@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,241 @@
1
+ import { createDeferredDeliveryRegistry, extractCompletedTurnAnswer } from './deferred-delivery.mjs';
2
+ import { t } from './i18n.mjs';
3
+ import { channelDeliveryFailure } from './message-failure.mjs';
4
+
5
+ export function deferredOutcomeText(outcome) {
6
+ if (outcome.found && outcome.text) return outcome.text;
7
+ const reason = outcome.reason === 'stopped' ? t('已停止')
8
+ : ['aborted', 'cancelled'].includes(outcome.reason) ? t('已中止')
9
+ : outcome.reason === 'failed' ? t('任务失败') : t('已结束');
10
+ return t('后台任务已结束({reason}),没有可推送的最终结果。', { reason });
11
+ }
12
+
13
+ function orderedEvents(history) {
14
+ return (Array.isArray(history?.events) ? history.events : [])
15
+ .map((row) => row?.event ?? row)
16
+ .filter((event) => Number.isSafeInteger(event?.seq) && event.seq >= 0)
17
+ .sort((a, b) => a.seq - b.seq);
18
+ }
19
+
20
+ /** One coordinator per bot. All history reads, sends, removal and stops for a
21
+ * Session use the same queue. Queued work stores ids, never stale entry objects.
22
+ * Durable pending rows survive crashes; there is no persisted pre-send claim.
23
+ */
24
+ export function createDeferredDeliveryCoordinator({
25
+ harness, state, deliver, signal, logger = console,
26
+ retryDelayMs = 1_000, pollDelayMs = 30_000, watch = true,
27
+ } = {}) {
28
+ const enabled = ['deferredEntries', 'putDeferred', 'patchDeferred', 'removeDeferred']
29
+ .every((name) => typeof state?.[name] === 'function');
30
+ const controller = new AbortController();
31
+ const activeSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
32
+ const tails = new Map();
33
+ const timers = new Map();
34
+ const registry = createDeferredDeliveryRegistry({
35
+ listDeferred: async () => state.deferredEntries(),
36
+ putDeferred: (entry) => state.putDeferred(entry),
37
+ patchDeferred: (id, patch) => state.patchDeferred(id, patch),
38
+ removeDeferred: (id) => state.removeDeferred(id),
39
+ }, { logger });
40
+ const warn = (error) => { if (!activeSignal.aborted) logger.warn?.('[dsh-im] deferred delivery:', error?.message ?? String(error)); };
41
+ const pending = async (id) => (await registry.allPending()).find((entry) => entry.id === id);
42
+ const bound = (entry) => !activeSignal.aborted && state.sessionFor(entry.key) === entry.sessionId;
43
+ function enqueue(sessionId, operation) {
44
+ const previous = tails.get(sessionId) ?? Promise.resolve();
45
+ const task = previous.then(() => activeSignal.aborted ? undefined : operation());
46
+ const tail = task.catch(warn).finally(() => { if (tails.get(sessionId) === tail) tails.delete(sessionId); });
47
+ tails.set(sessionId, tail);
48
+ return task;
49
+ }
50
+ function schedule(entry, delay = pollDelayMs) {
51
+ if (activeSignal.aborted || timers.has(entry.id)) return;
52
+ const timer = setTimeout(() => {
53
+ timers.delete(entry.id);
54
+ void enqueue(entry.sessionId, () => process(entry.id)).catch(warn);
55
+ }, delay);
56
+ timer.unref?.();
57
+ timers.set(entry.id, timer);
58
+ }
59
+ function clearTimer(id) {
60
+ clearTimeout(timers.get(id));
61
+ timers.delete(id);
62
+ }
63
+ async function remove(entry) {
64
+ clearTimer(entry.id);
65
+ await registry.remove(entry);
66
+ }
67
+ async function readOutcome(entry) {
68
+ // A result may be older than the latest history page after a restart.
69
+ // Recover the whole target turn instead of treating a missing page as empty.
70
+ const events = new Map();
71
+ const historySignal = AbortSignal.any([activeSignal, AbortSignal.timeout(30_000)]);
72
+ let beforeSeq;
73
+ let targetTurn = Number.isSafeInteger(entry.turn) ? entry.turn : null;
74
+ for (let page = 0; page < 20; page += 1) {
75
+ historySignal.throwIfAborted();
76
+ const history = await harness.rpc('session.history', {
77
+ sessionId: entry.sessionId, maxMessages: 100,
78
+ ...(beforeSeq === undefined ? {} : { beforeSeq }),
79
+ }, 30_000, { signal: historySignal });
80
+ const batch = orderedEvents(history);
81
+ for (const event of batch) events.set(event.seq, event);
82
+ const ordered = [...events.values()].sort((a, b) => a.seq - b.seq);
83
+ if (targetTurn === null && entry.promptRpcId) {
84
+ let openTurn = null;
85
+ for (const event of ordered) {
86
+ if (event.type === 'turn/start') openTurn = event.data?.turn ?? null;
87
+ if (event.type === 'user/message' && event.data?.source?.rpcId === entry.promptRpcId) {
88
+ targetTurn = Number.isSafeInteger(event.data?.turn) ? event.data.turn : openTurn;
89
+ break;
90
+ }
91
+ if (event.type === 'turn/end') openTurn = null;
92
+ }
93
+ }
94
+ const reachedCursor = !history.hasMore || ordered[0]?.seq <= entry.afterSeq;
95
+ if (targetTurn === null && !entry.promptRpcId && reachedCursor) {
96
+ // Legacy #153 rows had no prompt identity. Never select a completion
97
+ // preceding the saved cursor, or a newer arbitrary completed turn.
98
+ targetTurn = ordered.find((event) => event.type === 'turn/end'
99
+ && event.seq > entry.afterSeq)?.data?.turn ?? null;
100
+ }
101
+ const outcome = targetTurn === null
102
+ ? { found: false, endSeq: -1, turn: null }
103
+ : extractCompletedTurnAnswer(ordered, { turn: targetTurn });
104
+ const hasStart = ordered.some((event) => event.type === 'turn/start' && event.data?.turn === targetTurn);
105
+ if (!history.hasMore || hasStart) return { ...outcome, turn: targetTurn };
106
+ const oldest = batch[0]?.seq;
107
+ if (!Number.isSafeInteger(oldest) || oldest === beforeSeq) break;
108
+ beforeSeq = oldest;
109
+ }
110
+ // Bounded reads cannot prove that a truncated answer is complete.
111
+ return { found: false, endSeq: -1, turn: targetTurn };
112
+ }
113
+ async function process(id, { stopping = false, urgent = false } = {}) {
114
+ let entry = await pending(id);
115
+ if (!entry || activeSignal.aborted) return 'none';
116
+ clearTimer(id);
117
+ if (!bound(entry)) { await remove(entry); return 'none'; }
118
+ let sending = false;
119
+ try {
120
+ const outcome = await readOutcome(entry);
121
+ // Binding, status and cancellation can change while the RPC is in flight.
122
+ entry = await pending(id);
123
+ if (!entry || activeSignal.aborted) return 'none';
124
+ if (!bound(entry)) { await remove(entry); return 'none'; }
125
+ if (outcome.endSeq === -1) {
126
+ if (Number.isSafeInteger(outcome.turn) && entry.turn !== outcome.turn) {
127
+ await state.patchDeferred(id, { turn: outcome.turn });
128
+ entry = { ...entry, turn: outcome.turn };
129
+ }
130
+ if (stopping) {
131
+ const session = harness.workspaceSession?.(entry.sessionId, entry.key);
132
+ const stopped = typeof session?.stopDeferredTurn === 'function'
133
+ ? await session.stopDeferredTurn({ turn: entry.turn, promptRpcId: entry.promptRpcId }, {
134
+ signal: activeSignal, isCurrent: () => bound(entry),
135
+ })
136
+ : typeof harness.stopDeferredTurn === 'function'
137
+ ? await harness.stopDeferredTurn(entry.sessionId, { turn: entry.turn, promptRpcId: entry.promptRpcId }, {
138
+ signal: activeSignal, isCurrent: () => bound(entry),
139
+ }) : false;
140
+ schedule(entry, retryDelayMs);
141
+ return stopped ? 'stopped' : 'unavailable';
142
+ }
143
+ schedule(entry, urgent ? retryDelayMs : pollDelayMs);
144
+ return 'waiting';
145
+ }
146
+ sending = true;
147
+ const result = await deliver(entry, outcome);
148
+ if (result === false || result?.deliveryOutcome === 'failed' || result?.deliveryOutcome === 'unknown') {
149
+ throw Object.assign(new Error('Deferred delivery was not confirmed'), {
150
+ deliveryOutcome: result?.deliveryOutcome ?? 'failed',
151
+ });
152
+ }
153
+ await remove(entry);
154
+ return 'delivered';
155
+ } catch (error) {
156
+ if (activeSignal.aborted) return 'none';
157
+ if (error?.code === 'session-not-found') { await remove(entry); return 'none'; }
158
+ const current = await pending(id);
159
+ if (!current) return 'none';
160
+ if (!sending) {
161
+ warn(error);
162
+ schedule(current);
163
+ return stopping ? 'unavailable' : 'waiting';
164
+ }
165
+ const uncertain = error?.deliveryOutcome === 'unknown'
166
+ || (error?.deliveryOutcome !== 'failed'
167
+ && channelDeliveryFailure(error).code === 'channel-delivery-uncertain');
168
+ if (uncertain) {
169
+ // The provider may already have accepted the message. Preserve the
170
+ // existing delivery-uncertain rule instead of retrying a possible copy.
171
+ await state.patchDeferred(id, { status: 'failed', deliveryOutcome: 'unknown', attempts: (current.attempts ?? 0) + 1 });
172
+ warn(error);
173
+ return stopping ? 'unavailable' : 'unknown';
174
+ }
175
+ const attempts = await registry.markFailedAttempt(current);
176
+ warn(error);
177
+ if (attempts < 3) schedule(current, retryDelayMs * 2 ** (attempts - 1));
178
+ return stopping ? 'unavailable' : 'retry';
179
+ }
180
+ }
181
+ async function resume() {
182
+ if (!enabled || activeSignal.aborted) return;
183
+ const entries = await registry.allPending();
184
+ await Promise.allSettled(entries.map((entry) => enqueue(entry.sessionId, () => process(entry.id))));
185
+ }
186
+ const startup = Promise.resolve().then(async () => {
187
+ if (!enabled || activeSignal.aborted) return;
188
+ if (watch && typeof harness.watchHarnessEvents === 'function') {
189
+ try {
190
+ Promise.resolve(harness.watchHarnessEvents({ signal: activeSignal,
191
+ onSessionEvent: (payload) => { void api.onEvent(payload).catch(warn); },
192
+ onReconnect: () => { void resume().catch(warn); },
193
+ })).catch(warn);
194
+ } catch (error) { warn(error); }
195
+ }
196
+ await resume();
197
+ }).catch(warn);
198
+ activeSignal.addEventListener('abort', () => {
199
+ for (const timer of timers.values()) clearTimeout(timer);
200
+ timers.clear();
201
+ }, { once: true });
202
+ const api = {
203
+ async trackTimeout(error, { key, sessionId, ...delivery }) {
204
+ if (!enabled || error?.code !== 'harness-reply-timeout' || activeSignal.aborted) return;
205
+ const details = error.details ?? {};
206
+ const target = details.sessionId ?? sessionId ?? state.sessionFor(key);
207
+ if (!target || state.sessionFor(key) !== target) return;
208
+ const entry = await registry.register({ key, sessionId: target,
209
+ turn: details.turn, promptRpcId: details.promptRpcId,
210
+ afterSeq: details.baselineSeq ?? details.lastSeq ?? -1,
211
+ ...delivery,
212
+ });
213
+ void enqueue(target, () => process(entry.id)).catch(warn);
214
+ },
215
+ async onEvent({ sessionId, event } = {}) {
216
+ if (!enabled || activeSignal.aborted || event?.type !== 'turn/end') return;
217
+ const entries = await registry.pendingForSession(sessionId);
218
+ await Promise.allSettled(entries
219
+ .filter((entry) => !Number.isSafeInteger(entry.turn) || entry.turn === event.data?.turn)
220
+ .map((entry) => enqueue(sessionId, () => process(entry.id, { urgent: true }))));
221
+ },
222
+ resume,
223
+ async stop(key) {
224
+ if (!enabled || activeSignal.aborted) return 'none';
225
+ const entries = await registry.pendingForKey(key);
226
+ let outcome = 'none';
227
+ for (const entry of entries) {
228
+ const result = await enqueue(entry.sessionId, () => process(entry.id, { stopping: true }));
229
+ if (result === 'stopped') outcome = 'stopped';
230
+ else if (result === 'unavailable' && outcome !== 'stopped') outcome = 'unavailable';
231
+ }
232
+ return outcome;
233
+ },
234
+ async whenIdle() {
235
+ await startup;
236
+ while (tails.size) await Promise.allSettled([...tails.values()]);
237
+ },
238
+ close() { controller.abort(); },
239
+ };
240
+ return api;
241
+ }
@@ -0,0 +1,161 @@
1
+ import { AssistantTextAccumulator } from './harness-client.mjs';
2
+
3
+ export const MAX_DEFERRED_PER_KEY = 4;
4
+
5
+ /** Classify one turn/end event into a terminal-reason label. */
6
+ export function terminalOutcomeOf(turnEndEvent) {
7
+ const raw = turnEndEvent?.data?.reason;
8
+ const kind = typeof raw === 'string'
9
+ ? raw
10
+ : typeof raw?.kind === 'string' ? raw.kind : null;
11
+ return { kind: kind ?? 'other' };
12
+ }
13
+
14
+ function eventOf(entry) {
15
+ return entry?.event ?? (entry?.type ? entry : null);
16
+ }
17
+
18
+ function orderedEvents(entries) {
19
+ return (Array.isArray(entries) ? entries : [])
20
+ .map(eventOf)
21
+ .filter(Boolean)
22
+ .sort((left, right) => (left.seq ?? -1) - (right.seq ?? -1));
23
+ }
24
+
25
+ function textFromContent(content) {
26
+ if (!Array.isArray(content)) return '';
27
+ return content
28
+ .flatMap((block) => (block?.type === 'text' && typeof block.text === 'string' ? [block.text] : []))
29
+ .join('\n')
30
+ .trim();
31
+ }
32
+
33
+ /**
34
+ * Extract the final answer of one completed turn from durable history events.
35
+ *
36
+ * Reuses HarnessReplyTracker text accumulation: chunk deltas accumulate per
37
+ * (step, part index); a canonical assistant/message replaces its step; steps
38
+ * join with a blank line. `turn` omitted → prefer the latest completed answer.
39
+ * Returns `{ found, turn, text, reason, endSeq }`; `found: false` when the
40
+ * turn ended without a completed final answer (stopped/failed/empty/
41
+ * interrupted) — `reason`/`endSeq` still identify the confirmed terminal.
42
+ */
43
+ export function extractCompletedTurnAnswer(entries, { turn } = {}) {
44
+ const events = orderedEvents(entries);
45
+ const wantTurn = Number.isSafeInteger(turn) ? turn : null;
46
+ function turnAnswer(turnEnd) {
47
+ const accumulator = new AssistantTextAccumulator();
48
+ let interrupted = false;
49
+ for (const event of events) {
50
+ if (event.seq > turnEnd.seq || event.data?.turn !== turnEnd.data.turn) continue;
51
+ if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'text-delta') {
52
+ accumulator.appendDelta(event.data.step, event.data.chunk.index, event.data.chunk.text);
53
+ } else if (event.type === 'assistant/message') {
54
+ accumulator.setCanonical(event.data.step, textFromContent(event.data.message?.content));
55
+ interrupted = event.data.interrupted === true;
56
+ }
57
+ }
58
+ return { text: accumulator.text, interrupted };
59
+ }
60
+
61
+ function scan(matchTurn, acceptAnyTerminal = false) {
62
+ for (let index = events.length - 1; index >= 0; index -= 1) {
63
+ const event = events[index];
64
+ if (event?.type !== 'turn/end' || !Number.isSafeInteger(event.data?.turn)) continue;
65
+ if (matchTurn !== null && event.data.turn !== matchTurn) continue;
66
+ const raw = event.data?.reason;
67
+ const reason = typeof raw === 'string' ? raw : typeof raw?.kind === 'string' ? raw.kind : null;
68
+ const answer = turnAnswer(event);
69
+ const hasAnswer = reason === 'completed' && !answer.interrupted;
70
+ const text = hasAnswer ? answer.text : null;
71
+ if (hasAnswer && text) {
72
+ return { found: true, turn: event.data.turn, text, reason, endSeq: event.seq ?? -1 };
73
+ }
74
+ if (matchTurn !== null || acceptAnyTerminal) {
75
+ return { found: false, turn: event.data.turn, text: null, reason, endSeq: event.seq ?? -1 };
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+
81
+ const completed = scan(wantTurn);
82
+ if (completed) return completed;
83
+ const anyTerminal = scan(wantTurn, true);
84
+ if (anyTerminal) return anyTerminal;
85
+ return { found: false, turn: wantTurn, text: null, reason: null, endSeq: -1 };
86
+ }
87
+
88
+ /**
89
+ * Registry over a tiny persistence interface:
90
+ * `listDeferred() / putDeferred(entry) / patchDeferred(id, patch) / removeDeferred(id)`.
91
+ * Entries are owned snapshots; prompt ids distinguish tasks even before turn/start.
92
+ */
93
+ export function createDeferredDeliveryRegistry(store, {
94
+ now = () => Date.now(),
95
+ maxPerKey = MAX_DEFERRED_PER_KEY,
96
+ logger = console,
97
+ } = {}) {
98
+ function deferredId(key, sessionId, turn) {
99
+ return `${key} ${sessionId} ${Number.isSafeInteger(turn) ? turn : 'any'}`;
100
+ }
101
+
102
+ return {
103
+ deferredId,
104
+ async register({
105
+ key, chatId = null, target = null, replyToMessageId = null, sessionId, turn = null, afterSeq = -1, promptRpcId = null,
106
+ }) {
107
+ if (typeof key !== 'string' || !key) throw new TypeError('key is required');
108
+ if ((!chatId || typeof chatId !== 'string') && (!target || typeof target !== 'object')) {
109
+ throw new TypeError('chatId or a channel target is required');
110
+ }
111
+ if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
112
+ const entry = {
113
+ id: promptRpcId ? `${key} ${sessionId} ${promptRpcId}` : deferredId(key, sessionId, turn),
114
+ key,
115
+ chatId,
116
+ ...(target ? { target: structuredClone(target) } : {}),
117
+ replyToMessageId: typeof replyToMessageId === 'string' ? replyToMessageId : null,
118
+ sessionId,
119
+ promptRpcId,
120
+ turn: Number.isSafeInteger(turn) ? turn : null,
121
+ afterSeq: Number.isSafeInteger(afterSeq) ? afterSeq : -1,
122
+ lastSeenEndSeq: -1,
123
+ attempts: 0,
124
+ status: 'pending',
125
+ createdAt: now(),
126
+ };
127
+ const sameKey = (await store.listDeferred())
128
+ .filter((candidate) => candidate.key === key && candidate.status === 'pending');
129
+ const existing = sameKey.find((candidate) => candidate.id === entry.id);
130
+ if (existing) return existing;
131
+ if (sameKey.length >= maxPerKey) {
132
+ logger?.warn?.('[dsh-im] deferred delivery limit reached for key; dropping the oldest entry');
133
+ await store.removeDeferred(sameKey[0].id);
134
+ }
135
+ await store.putDeferred(entry);
136
+ return entry;
137
+ },
138
+ async pendingForSession(sessionId) {
139
+ return (await store.listDeferred())
140
+ .filter((entry) => entry.status === 'pending' && entry.sessionId === sessionId);
141
+ },
142
+ async pendingForKey(key) {
143
+ return (await store.listDeferred())
144
+ .filter((entry) => entry.status === 'pending' && entry.key === key);
145
+ },
146
+ async allPending() {
147
+ return (await store.listDeferred()).filter((entry) => entry.status === 'pending');
148
+ },
149
+ async markFailedAttempt(entry) {
150
+ // Read fresh state: the caller's snapshot goes stale across attempts.
151
+ const current = (await store.listDeferred())
152
+ .find((candidate) => candidate.id === entry.id) ?? entry;
153
+ const attempts = (current.attempts ?? 0) + 1;
154
+ await store.patchDeferred(entry.id, { attempts, status: attempts >= 3 ? 'failed' : 'pending' });
155
+ return attempts;
156
+ },
157
+ async remove(entry) {
158
+ await store.removeDeferred(entry.id);
159
+ },
160
+ };
161
+ }
@@ -0,0 +1,53 @@
1
+ /** Shared durable outbox surface, stored alongside each bot's conversation state. */
2
+ export function validDeferredEntry(value) {
3
+ return value && typeof value === 'object'
4
+ && ['id', 'key', 'sessionId'].every((key) => typeof value[key] === 'string' && value[key])
5
+ && ['pending', 'failed'].includes(value.status);
6
+ }
7
+
8
+ export function normalizeDeferredState(value) {
9
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
10
+ return Object.fromEntries(Object.entries(value).flatMap(([key, rows]) => {
11
+ const entries = Array.isArray(rows)
12
+ ? rows.filter((entry) => validDeferredEntry(entry) && entry.key === key) : [];
13
+ return entries.length ? [[key, entries]] : [];
14
+ }));
15
+ }
16
+
17
+ export function deferredStateAccess(read, persist) {
18
+ const rows = () => Object.values(read().deferred ?? {}).flat().filter(validDeferredEntry);
19
+ return {
20
+ entries: () => structuredClone(rows()),
21
+ async put(entry) {
22
+ if (!validDeferredEntry(entry)) throw new TypeError('Invalid deferred delivery entry');
23
+ const state = read();
24
+ const groups = state.deferred ??= {};
25
+ const list = Object.hasOwn(groups, entry.key) ? groups[entry.key] : [];
26
+ const next = [...list];
27
+ const index = next.findIndex((candidate) => candidate.id === entry.id);
28
+ if (index < 0) next.push(structuredClone(entry));
29
+ else next[index] = structuredClone(entry);
30
+ Object.defineProperty(groups, entry.key, { value: next, enumerable: true, writable: true, configurable: true });
31
+ await persist();
32
+ },
33
+ async patch(id, patch) {
34
+ const current = rows().find((entry) => entry.id === id);
35
+ if (!current) return null;
36
+ const next = { ...current, ...patch, id: current.id, key: current.key };
37
+ await this.put(next);
38
+ return structuredClone(next);
39
+ },
40
+ async remove(id) {
41
+ const groups = read().deferred ?? {};
42
+ for (const [key, list] of Object.entries(groups)) {
43
+ if (!Array.isArray(list)) continue;
44
+ const next = list.filter((entry) => entry.id !== id);
45
+ if (next.length === list.length) continue;
46
+ if (next.length) groups[key] = next;
47
+ else delete groups[key];
48
+ await persist();
49
+ return;
50
+ }
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,95 @@
1
+ // Shared by Host and Client: only explicitly admitted diagnostic facts cross the UI boundary.
2
+ const OPERATIONS = new Set([
3
+ 'bot.bind-credentials', 'bot.bind-native', 'bot.bind-mailbox', 'bot.mailbox.update', 'bot.auth.start', 'bot.auth.poll',
4
+ 'permissions.status', 'bot.session-binding.get', 'bot.session-binding.set', 'bot.session.list', 'connection.test', 'message.receive', 'message.send',
5
+ 'connector.configure', 'connector.reconnect', 'connector.test', 'connector.remove', 'startup', 'connection.restore', 'connection.monitor', 'connection.close', 'connection.status',
6
+ 'provision.begin', 'provision.poll', 'provision.verify', 'provision.cancel', 'bot.reconnect', 'bot.delete',
7
+ 'bot.workspace.set', 'bot.model.set', 'bot.agent-preset.set', 'bot.context-enhancement.set', 'bot.access-policy.set', 'bot.alias.set',
8
+ ]);
9
+ const STAGES = new Set([
10
+ 'credential.verify', 'permission.check', 'sdk.load', 'operation', 'message.receive', 'message.send', 'connection.test', 'startup.load', 'qr.begin', 'qr.encode', 'qr.poll', 'qr.verify', 'qr.cancel', 'credential.read', 'credential.save', 'credential.remove',
11
+ 'account.save', 'account.remove', 'state.load', 'state.write', 'state.cleanup', 'workspace.write', 'workspace.cleanup',
12
+ 'runtime.prepare', 'activation', 'harness.check', 'connection.start', 'connection.poll', 'connection.stop', 'status.read', 'rollback', 'management.request',
13
+ ]);
14
+ const REASONS = new Set([
15
+ 'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT', 'EPIPE',
16
+ 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET',
17
+ 'CERT_HAS_EXPIRED', 'CERT_NOT_YET_VALID', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN',
18
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'ERR_TLS_CERT_ALTNAME_INVALID', 'ERR_SSL_WRONG_VERSION_NUMBER',
19
+ 'ENOENT', 'EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'ENOTDIR', 'EISDIR', 'EBUSY', 'EIO', 'EXDEV', 'EMFILE', 'ENFILE', 'EEXIST',
20
+ 'unknown', 'multiple-causes', 'timeout', 'http-error', 'provider-rejected', 'invalid-response', 'ERR_PROXY_CONNECTION_FAILED', 'ERR_TLS_HANDSHAKE_TIMEOUT', 'ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR', 'ERR_NETWORK_ACCESS_DENIED', 'AUTHENTICATIONFAILED', 'EAUTH', 'invalid-json', 'invalid-config', 'read-only',
21
+ ]);
22
+ const RESOURCES = new Set(['credential-store', 'account-config', 'account-state', 'workspace-config', 'workspace-directory']);
23
+ const CONFIG_FILES = new Set(['config.json', 'workspaces.json']);
24
+ export const CONFIG_ISSUE_LABELS = Object.freeze({
25
+ 'expected-object': '应为 JSON 对象。',
26
+ 'expected-array': '应为 JSON 数组。',
27
+ 'unsupported-version': '配置版本缺失或不受当前插件支持。',
28
+ 'invalid-string': '字段缺失或不是非空字符串。',
29
+ 'invalid-identifier': '标识符格式不符合要求。',
30
+ 'identity-mismatch': '标识符与 accountId 派生结果不一致。',
31
+ 'duplicate-identity': '账号标识重复。',
32
+ 'invalid-api-url': '微信服务地址不是有效 URL。',
33
+ 'untrusted-api-url': '微信服务地址必须使用受信任的 HTTPS 域名和端口。',
34
+ 'invalid-workspace-path': '工作区路径必须是当前操作系统的绝对路径。',
35
+ 'invalid-agent-preset': 'Agent Preset 标识无效。',
36
+ 'invalid-model-selection': '模型设置须包含有效的 provider、model 和可选 reasoningEffort。',
37
+ 'invalid-delivery-target': '投递目标的标识、结构或路由不符合当前配置版本要求。',
38
+ 'unexpected-field': '当前配置版本不允许此字段。',
39
+ });
40
+ // Only schema-owned field names and numeric entry positions may leave the Host.
41
+ // Map keys are replaced with zero-based positions to avoid exposing identities.
42
+ const CONFIG_FIELD = /^(?:\$|version|accounts(?:\[\d{1,10}\](?:\.(?:accountId|ownerUserId|botId|tokenRef|baseUrl))?)?|(?:workspaces|agentPresets|models)(?:\[\d{1,10}\]\.(?:key|value))?|deliveryTargets(?:\[\d{1,10}\]\.(?:key|targets(?:\[\d{1,10}\])?))?)$/;
43
+
44
+ export function normalizeDiagnosticDetails(value) {
45
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
46
+ const result = {};
47
+ for (const [field, allowed] of [['operation', OPERATIONS], ['stage', STAGES], ['reason', REASONS], ['resource', RESOURCES]]) {
48
+ if (allowed.has(value[field])) result[field] = value[field];
49
+ }
50
+ if (DIAGNOSTIC_CHANNELS.includes(value.channel)) result.channel = value.channel;
51
+ if (Array.isArray(value.reasons)) {
52
+ const reasons = [...new Set(value.reasons.filter(v => REASONS.has(v) && !['unknown', 'multiple-causes'].includes(v)))].slice(0, 16);
53
+ if (reasons.length) result.reasons = reasons;
54
+ }
55
+ for (const field of ['durationMs', 'timeoutMs']) if (Number.isFinite(value[field]) && value[field] >= 0) result[field] = Math.round(value[field]);
56
+ for (const field of ['nodeVersion', 'dshVersion']) if (typeof value[field] === 'string' && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value[field]) && value[field].length < 80) result[field] = value[field];
57
+ if (['darwin', 'linux', 'win32', 'freebsd'].includes(value.platform)) result.platform = value.platform;
58
+ if (['ilinkai.weixin.qq.com', 'oapi.dingtalk.com', 'api.dingtalk.com', 'api.telegram.org', 'discord.com', 'slack.com', 'open.feishu.cn', 'qyapi.weixin.qq.com'].includes(value.host)) result.host = value.host;
59
+ if (value.dependencies && typeof value.dependencies === 'object') {
60
+ const dependencies = {};
61
+ for (const name of ['dingtalkStream', 'axios', 'httpsProxyAgent', 'agentBase']) {
62
+ const version = value.dependencies[name];
63
+ if (typeof version === 'string' && /^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(version) && version.length <= 80) dependencies[name] = version;
64
+ }
65
+ if (Object.keys(dependencies).length) result.dependencies = dependencies;
66
+ }
67
+ if (typeof value.proxyConfigured === 'boolean') result.proxyConfigured = value.proxyConfigured;
68
+ if (value.truncated === true) result.truncated = true;
69
+ if (CONFIG_FILES.has(value.file)) result.file = value.file;
70
+ if (typeof value.field === 'string' && CONFIG_FIELD.test(value.field)) result.field = value.field;
71
+ if (typeof value.issue === 'string' && Object.hasOwn(CONFIG_ISSUE_LABELS, value.issue)) result.issue = value.issue;
72
+ if (/^(?:(?:WX|DT|IM)-CONN|MF)-[A-F0-9]{8}$/.test(value.referenceId ?? '')) result.referenceId = value.referenceId;
73
+ if (typeof value.occurredAt === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value.occurredAt)
74
+ && Number.isFinite(Date.parse(value.occurredAt))) result.occurredAt = value.occurredAt;
75
+ if (Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599) result.httpStatus = value.httpStatus;
76
+ const provider = typeof value.providerCode === 'number' && Number.isSafeInteger(value.providerCode)
77
+ ? String(value.providerCode) : value.providerCode;
78
+ if (typeof provider === 'string' && /^-?\d{1,12}$/.test(provider)) result.providerCode = provider;
79
+ if (typeof value.pluginVersion === 'string' && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value.pluginVersion)
80
+ && value.pluginVersion.length <= 64) result.pluginVersion = value.pluginVersion;
81
+ if (['succeeded', 'failed', 'not-attempted', 'unknown'].includes(value.rollback)) result.rollback = value.rollback;
82
+ if (typeof value.hint === 'string' && value.hint.trim()) result.hint = value.hint.trim().slice(0, 500);
83
+ return result;
84
+ }
85
+
86
+ export const DIAGNOSTIC_CHANNELS = Object.freeze(['weixin', 'feishu', 'dingtalk', 'wecom', 'qq', 'slack', 'telegram', 'discord', 'whatsapp', 'wecom-app', 'imessage', 'email', 'office']);
87
+
88
+ export function diagnosticFields(value) {
89
+ if (!value?.details) return {};
90
+ const details = normalizeDiagnosticDetails({ ...value?.details,
91
+ referenceId: value?.details?.referenceId ?? value?.referenceId,
92
+ hint: value?.details?.hint ?? value?.hint,
93
+ });
94
+ return Object.keys(details).length ? { details } : {};
95
+ }
@@ -0,0 +1,100 @@
1
+ import { t } from './i18n.mjs';
2
+
3
+ export function splitMessageText(value, limit) {
4
+ const text = typeof value === 'string' ? value.trim() : '';
5
+ if (!text) return [];
6
+ const chunks = [];
7
+ let remaining = text;
8
+ while (remaining.length > limit) {
9
+ let cut = remaining.lastIndexOf('\n', limit);
10
+ if (cut < Math.floor(limit * 0.55)) cut = remaining.lastIndexOf(' ', limit);
11
+ if (cut < Math.floor(limit * 0.55)) cut = limit;
12
+ chunks.push(remaining.slice(0, cut).trim());
13
+ remaining = remaining.slice(cut).trimStart();
14
+ }
15
+ if (remaining) chunks.push(remaining);
16
+ return chunks;
17
+ }
18
+
19
+ export function createEditableMessageStream({
20
+ initialText = t('正在处理…'),
21
+ limit,
22
+ updateIntervalMs = 800,
23
+ create,
24
+ edit,
25
+ sendRemainder,
26
+ messageIdForResult = () => null,
27
+ logger = console,
28
+ }) {
29
+ let messageId;
30
+ const providerMessageIds = [];
31
+ let pending = null;
32
+ let timer = null;
33
+ let inFlight = null;
34
+ let closed = false;
35
+ let lastSent = initialText;
36
+
37
+ const schedule = () => {
38
+ if (closed || timer !== null || inFlight || !pending) return;
39
+ timer = setTimeout(() => {
40
+ timer = null;
41
+ const text = pending;
42
+ pending = null;
43
+ const next = splitMessageText(text, limit)[0] ?? initialText;
44
+ inFlight = Promise.resolve(next === lastSent ? undefined : edit(messageId, next))
45
+ .then(() => { lastSent = next; })
46
+ .catch((error) => logger.warn?.('[dsh-im] streamed message update failed:', error))
47
+ .finally(() => {
48
+ inFlight = null;
49
+ schedule();
50
+ });
51
+ }, updateIntervalMs);
52
+ timer?.unref?.();
53
+ };
54
+
55
+ return {
56
+ get messageId() {
57
+ return messageId;
58
+ },
59
+ get providerMessageIds() {
60
+ return [...providerMessageIds];
61
+ },
62
+ async start() {
63
+ messageId = await create(initialText);
64
+ if ((typeof messageId === 'string' && messageId.trim()) || Number.isSafeInteger(messageId)) {
65
+ providerMessageIds.push(String(messageId));
66
+ }
67
+ return this;
68
+ },
69
+ update(text) {
70
+ if (closed || typeof text !== 'string' || !text.trim()) return;
71
+ pending = text;
72
+ schedule();
73
+ },
74
+ async finish(text) {
75
+ if (closed) throw new Error('Message stream is already closed');
76
+ closed = true;
77
+ if (timer !== null) clearTimeout(timer);
78
+ timer = null;
79
+ pending = null;
80
+ await inFlight?.catch(() => undefined);
81
+ const chunks = splitMessageText(text, limit);
82
+ const first = chunks[0] ?? t('处理完成。');
83
+ if (first !== lastSent) await edit(messageId, first);
84
+ lastSent = first;
85
+ for (const chunk of chunks.slice(1)) {
86
+ const result = await sendRemainder(chunk);
87
+ const id = messageIdForResult(result);
88
+ if ((typeof id === 'string' && id.trim()) || Number.isSafeInteger(id)) {
89
+ providerMessageIds.push(String(id));
90
+ }
91
+ }
92
+ },
93
+ cancel() {
94
+ closed = true;
95
+ pending = null;
96
+ if (timer !== null) clearTimeout(timer);
97
+ timer = null;
98
+ },
99
+ };
100
+ }