@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,1009 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createHash,
5
+ randomBytes,
6
+ randomUUID,
7
+ } from 'node:crypto';
8
+
9
+ import { fetchImageBuffer } from '../shared/image-prompt.mjs';
10
+
11
+ export const WEIXIN_QR_BASE_URL = 'https://ilinkai.weixin.qq.com/';
12
+ export const WEIXIN_PROTOCOL_VERSION = '2.4.6';
13
+ export const DEFAULT_BOT_TYPE = '3';
14
+ export const WEIXIN_CDN_BASE_URL = 'https://novac2c.cdn.weixin.qq.com/c2c';
15
+ export const DEFAULT_WEIXIN_MAX_MESSAGE_CHARS = 1_800;
16
+
17
+ const WEIXIN_CDN_HOST = 'novac2c.cdn.weixin.qq.com';
18
+
19
+ const ILINK_APP_ID = 'bot';
20
+ const ILINK_CLIENT_VERSION = (2 << 16) | (4 << 8) | 6;
21
+ const DEFAULT_TIMEOUT_MS = 15_000;
22
+ const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
23
+ const WEIXIN_CDN_UPLOAD_RETRIES = 3;
24
+ const WEIXIN_CDN_UPLOAD_IDLE_TIMEOUT_MS = 60_000;
25
+ const WEIXIN_CDN_UPLOAD_CHUNK_BYTES = 64 * 1024;
26
+ const WEIXIN_MESSAGE_ID_TIMESTAMP_SHIFT = 22n;
27
+ const WEIXIN_MESSAGE_ID_MIN_TIMESTAMP_MS = Date.UTC(2020, 0, 1);
28
+ const WEIXIN_MESSAGE_ID_MAX_FUTURE_MS = 24 * 60 * 60 * 1_000;
29
+ const LOGIN_STATUSES = new Set([
30
+ 'wait',
31
+ 'scaned',
32
+ 'confirmed',
33
+ 'expired',
34
+ 'scaned_but_redirect',
35
+ 'need_verifycode',
36
+ 'verify_code_blocked',
37
+ 'binded_redirect',
38
+ ]);
39
+
40
+ export class WeixinApiError extends Error {
41
+ constructor(code, message, options = {}) {
42
+ super(message, options);
43
+ this.name = 'WeixinApiError';
44
+ this.code = code;
45
+ this.status = options.status;
46
+ this.providerCode = options.providerCode;
47
+ }
48
+ }
49
+
50
+ function nonEmptyString(value) {
51
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
52
+ }
53
+
54
+ function safeProviderCode(value) {
55
+ const code = value === undefined || value === null ? null : String(value).trim();
56
+ return code && /^-?[A-Za-z0-9_.:-]{1,160}$/.test(code) ? code : undefined;
57
+ }
58
+
59
+ function preserveArtifactMetadata(target, source) {
60
+ if (Number.isInteger(source?.status)) target.status = source.status;
61
+ if (source?.providerCode !== undefined) target.providerCode = source.providerCode;
62
+ return target;
63
+ }
64
+
65
+ function weixinArtifactError(cause, { fallback = 'artifact-provider-rejected' } = {}) {
66
+ if (cause?.code?.startsWith?.('artifact-')) return cause;
67
+ const status = Number(cause?.status);
68
+ const providerCode = safeProviderCode(cause?.providerCode);
69
+ const providerText = providerCode ?? '';
70
+ let code = fallback;
71
+ let message = 'Weixin could not prepare the file for delivery.';
72
+ if (status === 401 || status === 403 || providerCode === '401' || providerCode === '403'
73
+ || /(?:permission|forbidden|unauthor|access.?denied)/i.test(providerText)) {
74
+ code = 'artifact-permission-required';
75
+ message = 'Weixin denied permission to send the file.';
76
+ } else if (status === 413 || providerCode === '413'
77
+ || /(?:too.?large|size.?limit)/i.test(providerText)) {
78
+ code = 'artifact-too-large';
79
+ message = 'The file exceeds Weixin\'s size limit.';
80
+ } else if (status === 429 || providerCode === '429'
81
+ || /(?:rate.?limit|too.?many)/i.test(providerText)) {
82
+ code = 'artifact-rate-limited';
83
+ message = 'Weixin rate-limited file delivery.';
84
+ } else if (cause?.code === 'upload-timeout') {
85
+ code = 'artifact-upload-timeout';
86
+ message = 'Weixin file upload stalled; the file message was not sent.';
87
+ } else if (fallback === 'artifact-provider-rejected') {
88
+ message = 'Weixin rejected the file message.';
89
+ }
90
+ const error = new Error(message, { cause });
91
+ error.code = code;
92
+ return preserveArtifactMetadata(error, cause);
93
+ }
94
+
95
+ function uncertainWeixinDelivery(cause) {
96
+ const error = new Error('Weixin file delivery result is uncertain', { cause });
97
+ error.code = 'artifact-delivery-uncertain';
98
+ return preserveArtifactMetadata(error, cause);
99
+ }
100
+
101
+ export function rejectedProviderResponse(value, fields = ['ret', 'errcode']) {
102
+ if (!value || typeof value !== 'object') return null;
103
+ for (const field of fields) {
104
+ if (value[field] !== undefined && value[field] !== 0 && value[field] !== '0') {
105
+ return safeProviderCode(value[field]) ?? 'rejected';
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+
111
+ function classifyWeixinFinalDeliveryError(error, signal) {
112
+ if (signal?.aborted) throw abortError(signal);
113
+ const status = Number(error?.status);
114
+ if (error?.code === 'network-error' || error?.code === 'timeout'
115
+ || error?.code === 'invalid-response' || (status >= 500 && status < 600)) {
116
+ return uncertainWeixinDelivery(error);
117
+ }
118
+ return weixinArtifactError(error);
119
+ }
120
+
121
+ function strictBase64(value) {
122
+ const text = nonEmptyString(value);
123
+ if (!text || text.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(text)) return null;
124
+ return Buffer.from(text, 'base64');
125
+ }
126
+
127
+ /** Parse the two AES key encodings used by Weixin iLink image messages. */
128
+ export function parseWeixinImageAesKey(imageItem) {
129
+ const directHex = nonEmptyString(imageItem?.aeskey);
130
+ if (directHex) {
131
+ if (!/^[0-9a-fA-F]{32}$/.test(directHex)) {
132
+ throw new WeixinApiError('invalid-image-key', '微信图片的加密密钥无效。');
133
+ }
134
+ return Buffer.from(directHex, 'hex');
135
+ }
136
+
137
+ const encoded = strictBase64(imageItem?.media?.aes_key);
138
+ if (encoded?.length === 16) return encoded;
139
+ if (encoded?.length === 32 && /^[0-9a-fA-F]{32}$/.test(encoded.toString('ascii'))) {
140
+ return Buffer.from(encoded.toString('ascii'), 'hex');
141
+ }
142
+ throw new WeixinApiError('invalid-image-key', '微信图片的加密密钥无效。');
143
+ }
144
+
145
+ export function decryptWeixinImage(ciphertext, key) {
146
+ const encrypted = Buffer.from(ciphertext);
147
+ const aesKey = Buffer.from(key);
148
+ if (aesKey.length !== 16 || encrypted.length === 0 || encrypted.length % 16 !== 0) {
149
+ throw new WeixinApiError('invalid-image-ciphertext', '微信图片的加密数据无效。');
150
+ }
151
+ try {
152
+ const decipher = createDecipheriv('aes-128-ecb', aesKey, null);
153
+ return Buffer.concat([decipher.update(encrypted), decipher.final()]);
154
+ } catch (error) {
155
+ throw new WeixinApiError('image-decryption-failed', '微信图片解密失败。', { cause: error });
156
+ }
157
+ }
158
+
159
+ export function weixinImageDownloadUrl(media) {
160
+ const query = nonEmptyString(media?.encrypt_query_param);
161
+ if (query) {
162
+ return `${WEIXIN_CDN_BASE_URL}/download?encrypted_query_param=${encodeURIComponent(query)}`;
163
+ }
164
+
165
+ const fullUrl = nonEmptyString(media?.full_url);
166
+ if (!fullUrl) throw new WeixinApiError('missing-image-url', '微信图片没有可用的下载地址。');
167
+ let url;
168
+ try {
169
+ url = new URL(fullUrl);
170
+ } catch {
171
+ throw new WeixinApiError('invalid-image-url', '微信图片的下载地址无效。');
172
+ }
173
+ if (url.protocol !== 'https:' || url.hostname !== WEIXIN_CDN_HOST
174
+ || (url.port && url.port !== '443') || !url.pathname.startsWith('/c2c/')) {
175
+ throw new WeixinApiError('untrusted-image-url', '微信图片的下载地址不受信任。');
176
+ }
177
+ url.username = '';
178
+ url.password = '';
179
+ url.hash = '';
180
+ return url.toString();
181
+ }
182
+
183
+ /** Convert iLink image items into lazily downloaded, decrypted image references. */
184
+ export function extractWeixinImages(message, { fetchImpl = fetch } = {}) {
185
+ if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
186
+ const images = [];
187
+ for (const item of message?.item_list ?? []) {
188
+ const imageItem = item?.image_item;
189
+ if (!imageItem || typeof imageItem !== 'object') continue;
190
+ images.push({
191
+ name: images.length === 0 ? 'image' : `image-${images.length + 1}`,
192
+ load: async ({ signal, maxBytes }) => {
193
+ const key = parseWeixinImageAesKey(imageItem);
194
+ const url = weixinImageDownloadUrl(imageItem.media);
195
+ const ciphertext = await fetchImageBuffer(url, {
196
+ fetchImpl,
197
+ signal,
198
+ maxBytes: maxBytes + 16,
199
+ allowedHosts: [WEIXIN_CDN_HOST],
200
+ });
201
+ return decryptWeixinImage(ciphertext, key);
202
+ },
203
+ });
204
+ }
205
+ return images;
206
+ }
207
+
208
+ async function fetchWeixinFileCiphertext(url, { fetchImpl, signal, maxBytes }) {
209
+ const response = await fetchImpl(new URL(url), {
210
+ method: 'GET',
211
+ signal,
212
+ redirect: 'manual',
213
+ });
214
+ if (!response?.ok) {
215
+ await response?.body?.cancel?.().catch?.(() => undefined);
216
+ throw new WeixinApiError(
217
+ 'file-download-failed',
218
+ `微信文件下载失败(HTTP ${response?.status ?? 'unknown'})。`,
219
+ { status: response?.status },
220
+ );
221
+ }
222
+ const tooLarge = () => Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
223
+ const declared = Number(response.headers?.get?.('content-length'));
224
+ if (Number.isFinite(declared) && declared > maxBytes) {
225
+ await response.body?.cancel?.().catch(() => undefined);
226
+ throw tooLarge();
227
+ }
228
+ if (!response.body?.[Symbol.asyncIterator]) throw Object.assign(new Error('resource-unavailable'), { code: 'resource-unavailable' });
229
+ const chunks = [];
230
+ let size = 0;
231
+ try {
232
+ for await (const chunk of response.body) {
233
+ signal?.throwIfAborted();
234
+ size += chunk.byteLength;
235
+ if (size > maxBytes) throw tooLarge();
236
+ chunks.push(Buffer.from(chunk));
237
+ }
238
+ signal?.throwIfAborted();
239
+ return Buffer.concat(chunks, size);
240
+ } finally { await response.body.cancel?.().catch(() => undefined); }
241
+ }
242
+
243
+ /** Convert native iLink file items into lazily downloaded, decrypted file references. */
244
+ export function extractWeixinFiles(message, { fetchImpl = fetch } = {}) {
245
+ if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
246
+ const files = [];
247
+ for (const item of message?.item_list ?? []) {
248
+ const fileItem = item?.file_item;
249
+ if (!fileItem || typeof fileItem !== 'object') continue;
250
+ const declaredSize = Number(fileItem.len);
251
+ files.push({
252
+ name: nonEmptyString(fileItem.file_name) ?? (files.length === 0 ? 'file' : `file-${files.length + 1}`),
253
+ ...(Number.isFinite(declaredSize) && declaredSize >= 0 ? { size: declaredSize } : {}),
254
+ load: async ({ signal, maxBytes = 25 * 1024 * 1024 } = {}) => {
255
+ signal?.throwIfAborted();
256
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > 25 * 1024 * 1024) throw new TypeError('Invalid file byte limit');
257
+ if (Number.isFinite(declaredSize) && declaredSize > maxBytes) throw Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
258
+ const key = parseWeixinImageAesKey(fileItem);
259
+ const url = weixinImageDownloadUrl(fileItem.media);
260
+ const ciphertext = await fetchWeixinFileCiphertext(url, { fetchImpl, signal, maxBytes: maxBytes + 16 });
261
+ signal?.throwIfAborted();
262
+ const plaintext = decryptWeixinImage(ciphertext, key);
263
+ if (plaintext.length > maxBytes) throw Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
264
+ return plaintext;
265
+ },
266
+ });
267
+ }
268
+ return files;
269
+ }
270
+
271
+ function isWeixinHost(hostname) {
272
+ const normalized = hostname.toLowerCase().replace(/\.$/, '');
273
+ return normalized === 'weixin.qq.com' || normalized.endsWith('.weixin.qq.com')
274
+ || normalized === 'wechat.com' || normalized.endsWith('.wechat.com');
275
+ }
276
+
277
+ export function normalizeWeixinApiBaseUrl(value) {
278
+ let url;
279
+ try {
280
+ url = new URL(value);
281
+ } catch {
282
+ throw new WeixinApiError('invalid-base-url', '微信服务返回了无效的连接地址。');
283
+ }
284
+ if (url.protocol !== 'https:' || !isWeixinHost(url.hostname)
285
+ || (url.port !== '' && url.port !== '443')) {
286
+ throw new WeixinApiError('untrusted-base-url', '微信服务返回了不受信任的连接地址。');
287
+ }
288
+ url.username = '';
289
+ url.password = '';
290
+ url.search = '';
291
+ url.hash = '';
292
+ if (!url.pathname.endsWith('/')) url.pathname += '/';
293
+ return url.toString();
294
+ }
295
+
296
+ export function normalizeWeixinQrUrl(value) {
297
+ const text = nonEmptyString(value);
298
+ if (!text) throw new WeixinApiError('invalid-qr', '微信服务没有返回扫码地址。');
299
+ let url;
300
+ try {
301
+ url = new URL(text);
302
+ } catch {
303
+ throw new WeixinApiError('invalid-qr', '微信服务返回了无效的扫码地址。');
304
+ }
305
+ if (url.protocol !== 'https:' || !isWeixinHost(url.hostname)) {
306
+ throw new WeixinApiError('untrusted-qr', '微信服务返回了不受信任的扫码地址。');
307
+ }
308
+ return url.toString();
309
+ }
310
+
311
+ function commonHeaders() {
312
+ return {
313
+ 'iLink-App-Id': ILINK_APP_ID,
314
+ 'iLink-App-ClientVersion': String(ILINK_CLIENT_VERSION),
315
+ };
316
+ }
317
+
318
+ function authenticatedHeaders(token) {
319
+ const headers = {
320
+ ...commonHeaders(),
321
+ 'content-type': 'application/json',
322
+ AuthorizationType: 'ilink_bot_token',
323
+ 'X-WECHAT-UIN': Buffer.from(String(randomBytes(4).readUInt32BE(0)), 'utf8').toString('base64'),
324
+ };
325
+ if (nonEmptyString(token)) headers.Authorization = `Bearer ${token.trim()}`;
326
+ return headers;
327
+ }
328
+
329
+ function baseInfo() {
330
+ return {
331
+ channel_version: WEIXIN_PROTOCOL_VERSION,
332
+ bot_agent: 'DeepSeekHarness/1.1.0',
333
+ };
334
+ }
335
+
336
+ function aesEcbPaddedSize(size) {
337
+ return Math.ceil((size + 1) / 16) * 16;
338
+ }
339
+
340
+ function trustedWeixinCdnUploadUrl(value) {
341
+ let url;
342
+ try {
343
+ url = new URL(value);
344
+ } catch {
345
+ throw new WeixinApiError('invalid-upload-url', '微信服务返回了无效的文件上传地址。');
346
+ }
347
+ if (url.protocol !== 'https:' || url.hostname !== WEIXIN_CDN_HOST
348
+ || (url.port && url.port !== '443') || url.pathname !== '/c2c/upload'
349
+ || url.username || url.password) {
350
+ throw new WeixinApiError('untrusted-upload-url', '微信服务返回了不受信任的文件上传地址。');
351
+ }
352
+ url.hash = '';
353
+ return url;
354
+ }
355
+
356
+ function weixinCdnUploadUrl(response, fileKey) {
357
+ const fullUrl = nonEmptyString(response?.upload_full_url);
358
+ if (fullUrl) return trustedWeixinCdnUploadUrl(fullUrl);
359
+ const uploadParam = nonEmptyString(response?.upload_param);
360
+ if (!uploadParam) {
361
+ throw new WeixinApiError('missing-upload-url', '微信服务没有返回文件上传地址。');
362
+ }
363
+ const url = new URL(`${WEIXIN_CDN_BASE_URL}/upload`);
364
+ url.searchParams.set('encrypted_query_param', uploadParam);
365
+ url.searchParams.set('filekey', fileKey);
366
+ return trustedWeixinCdnUploadUrl(url);
367
+ }
368
+
369
+ async function* encryptWeixinUpload(bytes, key, { signal, onProgress }) {
370
+ const cipher = createCipheriv('aes-128-ecb', key, null);
371
+ // Let fetch backpressure drive encryption, without keeping whole-file
372
+ // ciphertext copies alongside a potentially large artifact buffer.
373
+ for (let offset = 0; offset < bytes.byteLength; offset += WEIXIN_CDN_UPLOAD_CHUNK_BYTES) {
374
+ signal.throwIfAborted();
375
+ const chunk = cipher.update(bytes.subarray(offset, offset + WEIXIN_CDN_UPLOAD_CHUNK_BYTES));
376
+ onProgress();
377
+ if (chunk.byteLength) yield chunk;
378
+ }
379
+ signal.throwIfAborted();
380
+ onProgress();
381
+ yield cipher.final();
382
+ }
383
+
384
+ async function uploadWeixinCdn(fetchImpl, url, bytes, key, { signal } = {}) {
385
+ let lastError;
386
+ for (let attempt = 1; attempt <= WEIXIN_CDN_UPLOAD_RETRIES; attempt += 1) {
387
+ signal?.throwIfAborted();
388
+ const idleController = new AbortController();
389
+ const uploadSignal = signal
390
+ ? AbortSignal.any([signal, idleController.signal])
391
+ : idleController.signal;
392
+ let timer;
393
+ let active = true;
394
+ const onProgress = () => {
395
+ if (!active) return;
396
+ clearTimeout(timer);
397
+ timer = setTimeout(() => idleController.abort(new WeixinApiError(
398
+ 'upload-timeout', '微信文件上传长时间没有进展,已超时。',
399
+ )), WEIXIN_CDN_UPLOAD_IDLE_TIMEOUT_MS);
400
+ };
401
+ const body = encryptWeixinUpload(bytes, key, { signal: uploadSignal, onProgress });
402
+ let response;
403
+ onProgress();
404
+ try {
405
+ response = await fetchImpl(url, {
406
+ method: 'POST',
407
+ headers: {
408
+ 'content-type': 'application/octet-stream',
409
+ 'content-length': String(aesEcbPaddedSize(bytes.byteLength)),
410
+ },
411
+ body,
412
+ duplex: 'half',
413
+ signal: uploadSignal,
414
+ redirect: 'error',
415
+ });
416
+ uploadSignal.throwIfAborted();
417
+ if (response.status >= 400 && response.status < 500) {
418
+ throw new WeixinApiError(
419
+ 'upload-rejected',
420
+ `微信文件上传被拒绝(HTTP ${response.status})。`,
421
+ { status: response.status },
422
+ );
423
+ }
424
+ if (response.status !== 200) {
425
+ throw new WeixinApiError(
426
+ 'upload-failed',
427
+ `微信文件上传失败(HTTP ${response.status})。`,
428
+ { status: response.status },
429
+ );
430
+ }
431
+ const downloadParam = nonEmptyString(response.headers.get('x-encrypted-param'));
432
+ if (!downloadParam) {
433
+ throw new WeixinApiError('invalid-upload-response', '微信文件上传响应缺少下载参数。');
434
+ }
435
+ return downloadParam;
436
+ } catch (error) {
437
+ if (signal?.aborted) throw abortError(signal);
438
+ if (idleController.signal.aborted) error = idleController.signal.reason;
439
+ if (error instanceof WeixinApiError
440
+ && (error.code === 'upload-rejected' || error.status < 500)) throw error;
441
+ lastError = error;
442
+ } finally {
443
+ active = false;
444
+ clearTimeout(timer);
445
+ await body.return();
446
+ await response?.body?.cancel?.().catch(() => undefined);
447
+ }
448
+ }
449
+ if (lastError instanceof WeixinApiError) throw lastError;
450
+ throw new WeixinApiError('upload-failed', '微信文件上传失败。', { cause: lastError });
451
+ }
452
+
453
+ function abortError(signal) {
454
+ if (signal?.reason instanceof Error) return signal.reason;
455
+ return new DOMException('The operation was aborted', 'AbortError');
456
+ }
457
+
458
+ async function requestJson(fetchImpl, {
459
+ method,
460
+ baseUrl,
461
+ endpoint,
462
+ body,
463
+ token,
464
+ timeoutMs = DEFAULT_TIMEOUT_MS,
465
+ signal,
466
+ authenticated = true,
467
+ }) {
468
+ const trustedBase = normalizeWeixinApiBaseUrl(baseUrl);
469
+ const url = new URL(endpoint, trustedBase);
470
+ if (!isWeixinHost(url.hostname)) {
471
+ throw new WeixinApiError('untrusted-endpoint', '拒绝访问不受信任的微信服务地址。');
472
+ }
473
+
474
+ const controller = new AbortController();
475
+ const startedAt = Date.now();
476
+ let timedOut = false;
477
+ const onAbort = () => controller.abort(signal?.reason);
478
+ if (signal?.aborted) throw abortError(signal);
479
+ signal?.addEventListener('abort', onAbort, { once: true });
480
+ const timer = timeoutMs > 0 ? setTimeout(() => {
481
+ timedOut = true;
482
+ controller.abort();
483
+ }, timeoutMs) : null;
484
+
485
+ try {
486
+ const response = await fetchImpl(url, {
487
+ method,
488
+ headers: authenticated ? authenticatedHeaders(token) : commonHeaders(),
489
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
490
+ signal: controller.signal,
491
+ });
492
+ if (!response.ok) {
493
+ throw new WeixinApiError(
494
+ 'http-error',
495
+ `微信服务请求失败(HTTP ${response.status})。`,
496
+ { status: response.status },
497
+ );
498
+ }
499
+ try {
500
+ // Native IDs may exceed Number.MAX_SAFE_INTEGER. Read their original JSON
501
+ // lexemes before numeric precision is lost; other protocol values keep
502
+ // their original types (ret/errcode and timestamps are not message IDs).
503
+ return JSON.parse(await response.text(), (key, value, context) => {
504
+ if ((key === 'message_id' || key === 'msg_id' || key === 'svr_id') && typeof value === 'number') {
505
+ if (!context?.source || !/^\d+$/.test(context.source)) {
506
+ throw new TypeError('Invalid native Weixin message ID');
507
+ }
508
+ return context.source;
509
+ }
510
+ return value;
511
+ });
512
+ } catch (error) {
513
+ throw new WeixinApiError('invalid-response', '微信服务返回了无法解析的响应。', { cause: error });
514
+ }
515
+ } catch (error) {
516
+ if (signal?.aborted) throw abortError(signal);
517
+ let failure;
518
+ if (timedOut) {
519
+ failure = new WeixinApiError('timeout', '微信服务请求超时。', { cause: error });
520
+ } else {
521
+ failure = error instanceof WeixinApiError ? error
522
+ : new WeixinApiError('network-error', '暂时无法访问微信服务。', { cause: error });
523
+ }
524
+ failure.durationMs = Date.now() - startedAt;
525
+ failure.timeoutMs = timeoutMs;
526
+ throw failure;
527
+ } finally {
528
+ if (timer) clearTimeout(timer);
529
+ signal?.removeEventListener('abort', onAbort);
530
+ }
531
+ }
532
+
533
+ function validateLoginResponse(value) {
534
+ if (!value || typeof value !== 'object' || !LOGIN_STATUSES.has(value.status)) {
535
+ throw new WeixinApiError('invalid-login-status', '微信服务返回了无法识别的扫码状态。');
536
+ }
537
+ return value;
538
+ }
539
+
540
+ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl } = {}) {
541
+ if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
542
+ if (typeof uploadFetchImpl !== 'function') throw new TypeError('uploadFetchImpl must be a function');
543
+
544
+ async function sendArtifact({
545
+ baseUrl,
546
+ token,
547
+ toUserId,
548
+ file,
549
+ contextToken,
550
+ runId,
551
+ signal,
552
+ beforeSend,
553
+ }, { mediaType, createItem }) {
554
+ const recipient = nonEmptyString(toUserId);
555
+ if (!recipient || !file || typeof file !== 'object'
556
+ || typeof file.fileName !== 'string' || !file.fileName
557
+ || !Buffer.isBuffer(file.bytes)) {
558
+ throw new TypeError('toUserId and a file are required');
559
+ }
560
+ signal?.throwIfAborted();
561
+ const fileKey = randomBytes(16).toString('hex');
562
+ const aesKey = randomBytes(16);
563
+ const rawMd5 = createHash('md5').update(file.bytes).digest('hex');
564
+ let upload;
565
+ try {
566
+ upload = await requestJson(fetchImpl, {
567
+ method: 'POST',
568
+ baseUrl,
569
+ endpoint: 'ilink/bot/getuploadurl',
570
+ token,
571
+ signal,
572
+ body: {
573
+ filekey: fileKey,
574
+ media_type: mediaType,
575
+ to_user_id: recipient,
576
+ rawsize: file.bytes.byteLength,
577
+ rawfilemd5: rawMd5,
578
+ filesize: aesEcbPaddedSize(file.bytes.byteLength),
579
+ no_need_thumb: true,
580
+ aeskey: aesKey.toString('hex'),
581
+ base_info: baseInfo(),
582
+ },
583
+ });
584
+ } catch (error) {
585
+ if (signal?.aborted) throw abortError(signal);
586
+ const status = Number(error?.status);
587
+ const fallback = error?.code === 'http-error' && status >= 400 && status < 500
588
+ ? 'artifact-provider-rejected'
589
+ : 'artifact-provider-failed';
590
+ throw weixinArtifactError(error, { fallback });
591
+ }
592
+ const uploadRejection = rejectedProviderResponse(upload);
593
+ if (uploadRejection) {
594
+ throw weixinArtifactError(new WeixinApiError(
595
+ 'upload-url-rejected',
596
+ '微信服务拒绝了文件上传请求。',
597
+ { providerCode: uploadRejection },
598
+ ));
599
+ }
600
+ const uploadUrl = weixinCdnUploadUrl(upload, fileKey);
601
+ const ciphertextSize = aesEcbPaddedSize(file.bytes.byteLength);
602
+ let downloadParam;
603
+ try {
604
+ downloadParam = await uploadWeixinCdn(uploadFetchImpl, uploadUrl, file.bytes, aesKey, { signal });
605
+ } catch (error) {
606
+ if (signal?.aborted) throw abortError(signal);
607
+ const status = Number(error?.status);
608
+ const fallback = error?.code === 'upload-rejected' || (status >= 400 && status < 500)
609
+ ? 'artifact-provider-rejected'
610
+ : 'artifact-provider-failed';
611
+ throw weixinArtifactError(error, { fallback });
612
+ }
613
+ signal?.throwIfAborted();
614
+ const deliverySeed = nonEmptyString(file.deliveryKey) ?? nonEmptyString(file.artifactId)
615
+ ?? randomUUID();
616
+ const clientIdSeed = mediaType === 3 ? deliverySeed : `${deliverySeed}\u0000${mediaType}`;
617
+ const clientId = `dsh-weixin-${createHash('sha256')
618
+ .update(clientIdSeed)
619
+ .digest('hex')
620
+ .slice(0, 32)}`;
621
+ const media = {
622
+ encrypt_query_param: downloadParam,
623
+ aes_key: Buffer.from(aesKey.toString('hex')).toString('base64'),
624
+ encrypt_type: 1,
625
+ };
626
+ await beforeSend?.();
627
+ signal?.throwIfAborted();
628
+ let response;
629
+ try {
630
+ response = await requestJson(fetchImpl, {
631
+ method: 'POST',
632
+ baseUrl,
633
+ endpoint: 'ilink/bot/sendmessage',
634
+ token,
635
+ signal,
636
+ body: {
637
+ msg: {
638
+ from_user_id: '',
639
+ to_user_id: recipient,
640
+ client_id: clientId,
641
+ message_type: 2,
642
+ message_state: 2,
643
+ item_list: [createItem({ file, media, ciphertextSize })],
644
+ ...(nonEmptyString(contextToken) ? { context_token: contextToken.trim() } : {}),
645
+ ...(nonEmptyString(runId) ? { run_id: runId.trim() } : {}),
646
+ },
647
+ base_info: baseInfo(),
648
+ },
649
+ });
650
+ } catch (error) {
651
+ throw classifyWeixinFinalDeliveryError(error, signal);
652
+ }
653
+ const sendRejection = rejectedProviderResponse(response);
654
+ if (sendRejection) {
655
+ throw weixinArtifactError(new WeixinApiError(
656
+ 'send-rejected',
657
+ '微信服务拒绝了文件消息。',
658
+ { providerCode: sendRejection },
659
+ ));
660
+ }
661
+ return { messageId: clientId };
662
+ }
663
+
664
+ return Object.freeze({
665
+ inboundImages(message) {
666
+ return extractWeixinImages(message, { fetchImpl });
667
+ },
668
+
669
+ inboundVideos(message) {
670
+ return extractWeixinFiles({ item_list: (message?.item_list ?? [])
671
+ .filter(item => item?.type === 5 && item.video_item?.media)
672
+ .map(item => ({ file_item: { media: item.video_item.media, file_name: 'video.mp4' } })) }, { fetchImpl });
673
+ },
674
+
675
+ inboundVoice(message) {
676
+ return extractWeixinFiles({ item_list: (message?.item_list ?? [])
677
+ .filter(item => item?.type === 3 && item.voice_item?.media)
678
+ .map(item => ({ file_item: { media: item.voice_item.media, file_name: 'voice',
679
+ ...(item.voice_item.len === undefined ? {} : { len: item.voice_item.len }) } })) }, { fetchImpl });
680
+ },
681
+ inboundFiles(message) {
682
+ return extractWeixinFiles(message, { fetchImpl });
683
+ },
684
+
685
+ async beginLogin({ localTokens = [], botType = DEFAULT_BOT_TYPE, signal } = {}) {
686
+ const tokens = [...new Set(localTokens.map(nonEmptyString).filter(Boolean))].slice(-10);
687
+ const response = await requestJson(fetchImpl, {
688
+ method: 'POST',
689
+ baseUrl: WEIXIN_QR_BASE_URL,
690
+ endpoint: `ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(botType)}`,
691
+ body: { local_token_list: tokens },
692
+ timeoutMs: 10_000,
693
+ signal,
694
+ });
695
+ const qrcode = nonEmptyString(response?.qrcode);
696
+ const providerCode = rejectedProviderResponse(response, ['errcode', 'ret']);
697
+ if (providerCode) throw new WeixinApiError('qr-request-rejected', '微信服务拒绝了二维码申请。', { providerCode });
698
+ if (!qrcode) throw new WeixinApiError('invalid-qr', '微信服务没有返回二维码令牌。');
699
+ return {
700
+ qrcode,
701
+ qrcodeUrl: normalizeWeixinQrUrl(response.qrcode_img_content),
702
+ };
703
+ },
704
+
705
+ async pollLogin({ qrcode, baseUrl = WEIXIN_QR_BASE_URL, verifyCode, signal }) {
706
+ const qr = nonEmptyString(qrcode);
707
+ if (!qr) throw new TypeError('qrcode is required');
708
+ let endpoint = `ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qr)}`;
709
+ if (nonEmptyString(verifyCode)) endpoint += `&verify_code=${encodeURIComponent(verifyCode.trim())}`;
710
+ const response = await requestJson(fetchImpl, {
711
+ method: 'GET',
712
+ baseUrl,
713
+ endpoint,
714
+ timeoutMs: DEFAULT_LONG_POLL_TIMEOUT_MS,
715
+ signal,
716
+ authenticated: false,
717
+ });
718
+ return validateLoginResponse(response);
719
+ },
720
+
721
+ async getUpdates({ baseUrl, token, getUpdatesBuf = '', timeoutMs, signal }) {
722
+ try {
723
+ return await requestJson(fetchImpl, {
724
+ method: 'POST',
725
+ baseUrl,
726
+ endpoint: 'ilink/bot/getupdates',
727
+ body: { get_updates_buf: getUpdatesBuf, base_info: baseInfo() },
728
+ token,
729
+ timeoutMs: timeoutMs ?? DEFAULT_LONG_POLL_TIMEOUT_MS,
730
+ signal,
731
+ });
732
+ } catch (error) {
733
+ if (error instanceof WeixinApiError && error.code === 'timeout') {
734
+ return { ret: 0, msgs: [], get_updates_buf: getUpdatesBuf };
735
+ }
736
+ throw error;
737
+ }
738
+ },
739
+
740
+ async getConfig({ baseUrl, token, toUserId, contextToken, signal }) {
741
+ const recipient = nonEmptyString(toUserId);
742
+ if (!recipient) throw new TypeError('toUserId is required');
743
+ const response = await requestJson(fetchImpl, {
744
+ method: 'POST',
745
+ baseUrl,
746
+ endpoint: 'ilink/bot/getconfig',
747
+ token,
748
+ signal,
749
+ timeoutMs: 10_000,
750
+ body: {
751
+ ilink_user_id: recipient,
752
+ ...(nonEmptyString(contextToken) ? { context_token: contextToken.trim() } : {}),
753
+ base_info: baseInfo(),
754
+ },
755
+ });
756
+ if (response?.ret !== undefined && response.ret !== 0) {
757
+ throw new WeixinApiError('config-rejected', '微信服务拒绝了机器人配置请求。');
758
+ }
759
+ return { typingTicket: nonEmptyString(response?.typing_ticket) };
760
+ },
761
+
762
+ async sendTyping({ baseUrl, token, toUserId, typingTicket, status, signal }) {
763
+ const recipient = nonEmptyString(toUserId);
764
+ const ticket = nonEmptyString(typingTicket);
765
+ if (!recipient || !ticket) throw new TypeError('toUserId and typingTicket are required');
766
+ if (status !== 1 && status !== 2) throw new TypeError('typing status must be 1 or 2');
767
+ const response = await requestJson(fetchImpl, {
768
+ method: 'POST',
769
+ baseUrl,
770
+ endpoint: 'ilink/bot/sendtyping',
771
+ token,
772
+ signal,
773
+ timeoutMs: 10_000,
774
+ body: {
775
+ ilink_user_id: recipient,
776
+ typing_ticket: ticket,
777
+ status,
778
+ base_info: baseInfo(),
779
+ },
780
+ });
781
+ if (response?.ret !== undefined && response.ret !== 0) {
782
+ throw new WeixinApiError('typing-rejected', '微信服务拒绝了输入状态请求。');
783
+ }
784
+ return true;
785
+ },
786
+
787
+ async sendText({ baseUrl, token, toUserId, text, contextToken, runId, signal }) {
788
+ const recipient = nonEmptyString(toUserId);
789
+ const content = nonEmptyString(text);
790
+ if (!recipient || !content) throw new TypeError('toUserId and text are required');
791
+ const clientId = `dsh-weixin-${randomUUID()}`;
792
+ const response = await requestJson(fetchImpl, {
793
+ method: 'POST',
794
+ baseUrl,
795
+ endpoint: 'ilink/bot/sendmessage',
796
+ token,
797
+ signal,
798
+ body: {
799
+ msg: {
800
+ from_user_id: '',
801
+ to_user_id: recipient,
802
+ client_id: clientId,
803
+ message_type: 2,
804
+ message_state: 2,
805
+ item_list: [{ type: 1, text_item: { text: content } }],
806
+ ...(nonEmptyString(contextToken) ? { context_token: contextToken.trim() } : {}),
807
+ ...(nonEmptyString(runId) ? { run_id: runId.trim() } : {}),
808
+ },
809
+ base_info: baseInfo(),
810
+ },
811
+ });
812
+ const sendRejection = rejectedProviderResponse(response);
813
+ if (sendRejection) {
814
+ throw new WeixinApiError(
815
+ 'send-rejected',
816
+ '微信服务拒绝了回复消息。',
817
+ { providerCode: sendRejection },
818
+ );
819
+ }
820
+ return {
821
+ ...(response && typeof response === 'object' ? response : {}),
822
+ providerMessageIds: [clientId],
823
+ };
824
+ },
825
+
826
+ async sendFile(request) {
827
+ return sendArtifact(request, {
828
+ mediaType: 3,
829
+ createItem: ({ file, media }) => ({
830
+ type: 4,
831
+ file_item: {
832
+ media,
833
+ file_name: file.fileName,
834
+ len: String(file.bytes.byteLength),
835
+ },
836
+ }),
837
+ });
838
+ },
839
+
840
+ async sendVideo(request) {
841
+ return sendArtifact(request, {
842
+ mediaType: 2,
843
+ createItem: ({ media, ciphertextSize }) => ({
844
+ type: 5, video_item: { media, video_size: ciphertextSize },
845
+ }),
846
+ });
847
+ },
848
+
849
+ async sendImage(request) {
850
+ return sendArtifact(request, {
851
+ mediaType: 1,
852
+ createItem: ({ media, ciphertextSize }) => ({
853
+ type: 2,
854
+ image_item: {
855
+ media,
856
+ mid_size: ciphertextSize,
857
+ },
858
+ }),
859
+ });
860
+ },
861
+
862
+ async notifyStart({ baseUrl, token, signal }) {
863
+ const response = await requestJson(fetchImpl, {
864
+ method: 'POST',
865
+ baseUrl,
866
+ endpoint: 'ilink/bot/msg/notifystart',
867
+ token,
868
+ signal,
869
+ timeoutMs: 10_000,
870
+ body: { base_info: baseInfo() },
871
+ });
872
+ const providerCode = rejectedProviderResponse(response, ['errcode', 'ret']);
873
+ if (providerCode) {
874
+ throw new WeixinApiError(providerCode === '-14' ? 'stale-token' : 'start-rejected', '微信账号连接启动失败。', { providerCode });
875
+ }
876
+ return response;
877
+ },
878
+
879
+ async notifyStop({ baseUrl, token, signal }) {
880
+ const response = await requestJson(fetchImpl, {
881
+ method: 'POST',
882
+ baseUrl,
883
+ endpoint: 'ilink/bot/msg/notifystop',
884
+ token,
885
+ signal,
886
+ timeoutMs: 10_000,
887
+ body: { base_info: baseInfo() },
888
+ });
889
+ const providerCode = rejectedProviderResponse(response, ['errcode', 'ret']);
890
+ if (providerCode) throw new WeixinApiError('stop-rejected', '微信服务未确认停止通知。', { providerCode });
891
+ return response;
892
+ },
893
+ });
894
+ }
895
+
896
+ export function extractWeixinText(message) {
897
+ for (const item of message?.item_list ?? []) {
898
+ if (item?.type === 1 && typeof item.text_item?.text === 'string') {
899
+ const text = item.text_item.text.trim();
900
+ if (text) return text;
901
+ }
902
+ if (item?.type === 3 && typeof item.voice_item?.text === 'string') {
903
+ const text = item.voice_item.text.trim();
904
+ if (text) return text;
905
+ }
906
+ }
907
+ return null;
908
+ }
909
+
910
+ function weixinReplyAttachment(item) {
911
+ if (item?.type === 2 || (item?.image_item && typeof item.image_item === 'object')) {
912
+ return { kind: 'image' };
913
+ }
914
+ if (item?.type === 3 || (item?.voice_item && typeof item.voice_item === 'object')) {
915
+ return { kind: 'audio' };
916
+ }
917
+ if (item?.type === 4 || (item?.file_item && typeof item.file_item === 'object')) {
918
+ const name = nonEmptyString(item?.file_item?.file_name);
919
+ return { kind: 'file', ...(name ? { name } : {}) };
920
+ }
921
+ if (item?.type === 5 || (item?.video_item && typeof item.video_item === 'object')) {
922
+ return { kind: 'video' };
923
+ }
924
+ return null;
925
+ }
926
+
927
+ function weixinQuotedText(item) {
928
+ const text = nonEmptyString(item?.text_item?.text);
929
+ if (text) return text;
930
+ return nonEmptyString(item?.voice_item?.text);
931
+ }
932
+
933
+ /** Extract the one-level reply snapshot embedded in an inbound iLink message item. */
934
+ export function extractWeixinReplyReference(message, { resolveContent, loadContent } = {}) {
935
+ const container = (message?.item_list ?? []).find((item) => (
936
+ item?.ref_msg && typeof item.ref_msg === 'object'
937
+ ));
938
+ if (!container) return null;
939
+ const ref = container.ref_msg;
940
+ const quotedItem = ref.message_item && typeof ref.message_item === 'object'
941
+ ? ref.message_item
942
+ : null;
943
+ const quotedText = weixinQuotedText(quotedItem);
944
+ let content = quotedText ?? nonEmptyString(ref.title);
945
+ const attachment = weixinReplyAttachment(quotedItem);
946
+ const messageId = quotedItem?.msg_id === undefined || quotedItem?.msg_id === null
947
+ ? null
948
+ : nonEmptyString(String(quotedItem.msg_id));
949
+ const referenceDetails = {
950
+ messageId,
951
+ createTimeMs: quotedItem?.create_time_ms ?? ref.create_time_ms,
952
+ updateTimeMs: quotedItem?.update_time_ms ?? ref.update_time_ms,
953
+ };
954
+ if (!content && !attachment && typeof resolveContent === 'function') {
955
+ content = nonEmptyString(resolveContent(referenceDetails));
956
+ }
957
+ const load = !content && !attachment && typeof loadContent === 'function'
958
+ ? (options) => loadContent(referenceDetails, options)
959
+ : null;
960
+ const knownType = quotedItem && [1, 2, 3, 4, 5, 8].includes(quotedItem.type);
961
+ return {
962
+ ...(messageId ? { messageId } : {}),
963
+ ...(content ? { content } : {}),
964
+ ...(attachment ? { attachments: [attachment] } : {}),
965
+ ...(load ? { load } : {}),
966
+ ...(!content && !attachment && !load
967
+ ? { unavailableReason: quotedItem && !knownType ? 'unsupported' : 'not-delivered' }
968
+ : {}),
969
+ };
970
+ }
971
+
972
+ /** Decode the millisecond timestamp carried by current 64-bit iLink message IDs. */
973
+ export function weixinMessageTimestampMs(messageId, { now = Date.now() } = {}) {
974
+ const value = messageId === undefined || messageId === null ? '' : String(messageId).trim();
975
+ if (!/^\d{16,20}$/u.test(value)) return null;
976
+ try {
977
+ const timestampMs = Number(BigInt(value) >> WEIXIN_MESSAGE_ID_TIMESTAMP_SHIFT);
978
+ if (!Number.isSafeInteger(timestampMs)
979
+ || timestampMs < WEIXIN_MESSAGE_ID_MIN_TIMESTAMP_MS
980
+ || timestampMs > now + WEIXIN_MESSAGE_ID_MAX_FUTURE_MS) return null;
981
+ return timestampMs;
982
+ } catch {
983
+ return null;
984
+ }
985
+ }
986
+
987
+ export function weixinMessageId(message) {
988
+ if (message?.message_id !== undefined && message.message_id !== null) {
989
+ if (typeof message.message_id === 'number' && !Number.isSafeInteger(message.message_id)) {
990
+ return null;
991
+ }
992
+ return String(message.message_id);
993
+ }
994
+ return nonEmptyString(message?.client_id);
995
+ }
996
+
997
+ export function splitWeixinText(text, maxChars = DEFAULT_WEIXIN_MAX_MESSAGE_CHARS) {
998
+ if (text.length <= maxChars) return [text];
999
+ const chunks = [];
1000
+ let remaining = text;
1001
+ while (remaining.length > maxChars) {
1002
+ let splitAt = remaining.lastIndexOf('\n', maxChars);
1003
+ if (splitAt < Math.floor(maxChars * 0.6)) splitAt = maxChars;
1004
+ chunks.push(remaining.slice(0, splitAt));
1005
+ remaining = remaining.slice(splitAt).replace(/^\n+/, '');
1006
+ }
1007
+ if (remaining) chunks.push(remaining);
1008
+ return chunks;
1009
+ }