@botharness/im-provider 4.32.0-botharness.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (412) hide show
  1. package/LICENSE +21 -0
  2. package/PROVENANCE.json +25 -0
  3. package/README.en.md +445 -0
  4. package/README.md +448 -0
  5. package/THIRD_PARTY_NOTICES.md +93 -0
  6. package/assets/dingtalk-menu-template.json +6 -0
  7. package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
  8. package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
  9. package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
  10. package/assets/logo-icon.png +0 -0
  11. package/assets/logo-plugin-message-link-gradient.webp +0 -0
  12. package/assets/logo-plugin-phone.png +0 -0
  13. package/assets/logo.png +0 -0
  14. package/assets/logo_cn.png +0 -0
  15. package/assets/screenshot-menu-card.png +0 -0
  16. package/cordis.patch.yml +3 -0
  17. package/lib/client.js +20330 -0
  18. package/lib/index.js +602 -0
  19. package/locale/en.json +5 -0
  20. package/locale/zh.json +5 -0
  21. package/package.json +181 -0
  22. package/plugin-src/client/access-policy-settings.js +362 -0
  23. package/plugin-src/client/agent-preset.js +119 -0
  24. package/plugin-src/client/bot-alias.js +169 -0
  25. package/plugin-src/client/build.mjs +38 -0
  26. package/plugin-src/client/channel-card-meta.js +132 -0
  27. package/plugin-src/client/channel-logos.js +190 -0
  28. package/plugin-src/client/channels/dingtalk/api.js +267 -0
  29. package/plugin-src/client/channels/dingtalk/index.js +954 -0
  30. package/plugin-src/client/channels/dingtalk/styles.js +136 -0
  31. package/plugin-src/client/channels/discord/api.js +11 -0
  32. package/plugin-src/client/channels/discord/index.js +25 -0
  33. package/plugin-src/client/channels/discord/styles.js +19 -0
  34. package/plugin-src/client/channels/email/api.js +52 -0
  35. package/plugin-src/client/channels/email/index.js +728 -0
  36. package/plugin-src/client/channels/email/styles.js +51 -0
  37. package/plugin-src/client/channels/feishu/api.js +405 -0
  38. package/plugin-src/client/channels/feishu/group-settings.js +581 -0
  39. package/plugin-src/client/channels/feishu/index.js +1583 -0
  40. package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
  41. package/plugin-src/client/channels/feishu/styles.js +573 -0
  42. package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
  43. package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
  44. package/plugin-src/client/channels/imessage/api.js +12 -0
  45. package/plugin-src/client/channels/imessage/index.js +46 -0
  46. package/plugin-src/client/channels/imessage/styles.js +19 -0
  47. package/plugin-src/client/channels/matrix/api.js +11 -0
  48. package/plugin-src/client/channels/matrix/index.js +151 -0
  49. package/plugin-src/client/channels/matrix/styles.js +36 -0
  50. package/plugin-src/client/channels/office/api.js +46 -0
  51. package/plugin-src/client/channels/office/index.js +153 -0
  52. package/plugin-src/client/channels/office/styles.js +50 -0
  53. package/plugin-src/client/channels/qq/api.js +171 -0
  54. package/plugin-src/client/channels/qq/index.js +593 -0
  55. package/plugin-src/client/channels/qq/styles.js +19 -0
  56. package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
  57. package/plugin-src/client/channels/shared/token-api.js +124 -0
  58. package/plugin-src/client/channels/shared/token-channel.js +495 -0
  59. package/plugin-src/client/channels/slack/api.js +11 -0
  60. package/plugin-src/client/channels/slack/index.js +131 -0
  61. package/plugin-src/client/channels/slack/styles.js +34 -0
  62. package/plugin-src/client/channels/telegram/api.js +11 -0
  63. package/plugin-src/client/channels/telegram/index.js +28 -0
  64. package/plugin-src/client/channels/telegram/styles.js +31 -0
  65. package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
  66. package/plugin-src/client/channels/wecom/api.js +160 -0
  67. package/plugin-src/client/channels/wecom/index.js +625 -0
  68. package/plugin-src/client/channels/wecom/styles.js +19 -0
  69. package/plugin-src/client/channels/wecom-app/api.js +132 -0
  70. package/plugin-src/client/channels/wecom-app/index.js +634 -0
  71. package/plugin-src/client/channels/wecom-app/styles.js +25 -0
  72. package/plugin-src/client/channels/weixin/api.js +211 -0
  73. package/plugin-src/client/channels/weixin/connection-error.js +1 -0
  74. package/plugin-src/client/channels/weixin/index.js +801 -0
  75. package/plugin-src/client/channels/weixin/styles.js +115 -0
  76. package/plugin-src/client/channels/whatsapp/api.js +152 -0
  77. package/plugin-src/client/channels/whatsapp/index.js +609 -0
  78. package/plugin-src/client/channels/whatsapp/styles.js +19 -0
  79. package/plugin-src/client/connection-error.js +87 -0
  80. package/plugin-src/client/context-enhancement.js +415 -0
  81. package/plugin-src/client/credential-binding.js +118 -0
  82. package/plugin-src/client/delivery-settings.js +905 -0
  83. package/plugin-src/client/global-settings.js +433 -0
  84. package/plugin-src/client/i18n.js +1314 -0
  85. package/plugin-src/client/index.js +624 -0
  86. package/plugin-src/client/interface-language.js +89 -0
  87. package/plugin-src/client/last-message-error.js +18 -0
  88. package/plugin-src/client/lifecycle.js +86 -0
  89. package/plugin-src/client/loopback-recovery.js +75 -0
  90. package/plugin-src/client/model-setting.js +172 -0
  91. package/plugin-src/client/panel-error-boundary.js +21 -0
  92. package/plugin-src/client/plugin-page.js +51 -0
  93. package/plugin-src/client/session-channel-logos.js +243 -0
  94. package/plugin-src/client/styles.js +770 -0
  95. package/plugin-src/client/update-panel.js +14 -0
  96. package/plugin-src/client/workspace-directory-picker.js +280 -0
  97. package/plugin-src/client/workspace-editor.js +69 -0
  98. package/plugin-src/client/workspace-snapshot-fence.js +28 -0
  99. package/plugin-src/host/build.mjs +52 -0
  100. package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
  101. package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
  102. package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
  103. package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
  104. package/plugin-src/host/channels/discord/index.mjs +33 -0
  105. package/plugin-src/host/channels/discord/production.mjs +17 -0
  106. package/plugin-src/host/channels/discord/rpc.mjs +21 -0
  107. package/plugin-src/host/channels/email/availability.mjs +60 -0
  108. package/plugin-src/host/channels/email/index.mjs +36 -0
  109. package/plugin-src/host/channels/email/production.mjs +58 -0
  110. package/plugin-src/host/channels/email/rpc.mjs +163 -0
  111. package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
  112. package/plugin-src/host/channels/feishu/controller.mjs +172 -0
  113. package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
  114. package/plugin-src/host/channels/feishu/index.mjs +69 -0
  115. package/plugin-src/host/channels/feishu/production.mjs +318 -0
  116. package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
  117. package/plugin-src/host/channels/imessage/index.mjs +21 -0
  118. package/plugin-src/host/channels/imessage/production.mjs +13 -0
  119. package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
  120. package/plugin-src/host/channels/matrix/index.mjs +31 -0
  121. package/plugin-src/host/channels/matrix/production.mjs +241 -0
  122. package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
  123. package/plugin-src/host/channels/office/index.mjs +14 -0
  124. package/plugin-src/host/channels/office/production.mjs +45 -0
  125. package/plugin-src/host/channels/office/rpc.mjs +51 -0
  126. package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
  127. package/plugin-src/host/channels/qq/index.mjs +28 -0
  128. package/plugin-src/host/channels/qq/production.mjs +181 -0
  129. package/plugin-src/host/channels/qq/rpc.mjs +250 -0
  130. package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
  131. package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
  132. package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
  133. package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
  134. package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
  135. package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
  136. package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
  137. package/plugin-src/host/channels/shared/production.mjs +237 -0
  138. package/plugin-src/host/channels/shared/rpc.mjs +226 -0
  139. package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
  140. package/plugin-src/host/channels/shared/startup.mjs +76 -0
  141. package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
  142. package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
  143. package/plugin-src/host/channels/slack/index.mjs +31 -0
  144. package/plugin-src/host/channels/slack/production.mjs +176 -0
  145. package/plugin-src/host/channels/slack/rpc.mjs +221 -0
  146. package/plugin-src/host/channels/telegram/index.mjs +33 -0
  147. package/plugin-src/host/channels/telegram/production.mjs +19 -0
  148. package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
  149. package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
  150. package/plugin-src/host/channels/wecom/index.mjs +34 -0
  151. package/plugin-src/host/channels/wecom/production.mjs +187 -0
  152. package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
  153. package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
  154. package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
  155. package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
  156. package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
  157. package/plugin-src/host/channels/weixin/index.mjs +44 -0
  158. package/plugin-src/host/channels/weixin/production.mjs +257 -0
  159. package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
  160. package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
  161. package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
  162. package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
  163. package/plugin-src/host/delivery-adapter.mjs +388 -0
  164. package/plugin-src/host/delivery-http.mjs +132 -0
  165. package/plugin-src/host/delivery-rpc.mjs +173 -0
  166. package/plugin-src/host/delivery-service.mjs +552 -0
  167. package/plugin-src/host/delivery-suggestions.mjs +198 -0
  168. package/plugin-src/host/harness-command-executor.mjs +48 -0
  169. package/plugin-src/host/harness-connection.mjs +20 -0
  170. package/plugin-src/host/harness-session-coordinator.mjs +183 -0
  171. package/plugin-src/host/host-language-rpc.mjs +71 -0
  172. package/plugin-src/host/host-language.mjs +157 -0
  173. package/plugin-src/host/image-input-rpc.mjs +24 -0
  174. package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
  175. package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
  176. package/plugin-src/host/inbound-ttl-service.mjs +179 -0
  177. package/plugin-src/host/index.mjs +224 -0
  178. package/plugin-src/host/injected-context.mjs +104 -0
  179. package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
  180. package/plugin-src/host/modern-harness-api.mjs +738 -0
  181. package/plugin-src/host/rpc-authority.mjs +12 -0
  182. package/plugin-src/host/session-sync-coordinator.mjs +233 -0
  183. package/plugin-src/host/session-title-prefix.mjs +122 -0
  184. package/plugin-src/host/update-policy.mjs +31 -0
  185. package/plugin-src/host/update-rpc.mjs +16 -0
  186. package/plugin-src/host/update-runtime.mjs +339 -0
  187. package/plugin-src/host/update-service.mjs +392 -0
  188. package/plugin-src/management-rpc.mjs +87 -0
  189. package/src/channels/dingtalk/config-store.mjs +284 -0
  190. package/src/channels/dingtalk/connection-error.mjs +292 -0
  191. package/src/channels/dingtalk/device-auth.mjs +240 -0
  192. package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
  193. package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
  194. package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
  195. package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
  196. package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
  197. package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
  198. package/src/channels/dingtalk/harness-client.mjs +19 -0
  199. package/src/channels/dingtalk/state-store.mjs +325 -0
  200. package/src/channels/discord/config-store.mjs +25 -0
  201. package/src/channels/discord/discord-api.mjs +347 -0
  202. package/src/channels/discord/discord-bridge.mjs +16 -0
  203. package/src/channels/discord/discord-controller.mjs +16 -0
  204. package/src/channels/discord/discord-runtime.mjs +974 -0
  205. package/src/channels/discord/harness-client.mjs +11 -0
  206. package/src/channels/discord/state-store.mjs +3 -0
  207. package/src/channels/email/config-store.mjs +194 -0
  208. package/src/channels/email/email-api.mjs +20 -0
  209. package/src/channels/email/email-bridge.mjs +17 -0
  210. package/src/channels/email/email-controller.mjs +824 -0
  211. package/src/channels/email/email-runtime.mjs +699 -0
  212. package/src/channels/email/harness-client.mjs +7 -0
  213. package/src/channels/email/mail-format.mjs +91 -0
  214. package/src/channels/email/state-store.mjs +176 -0
  215. package/src/channels/email/transport.mjs +64 -0
  216. package/src/channels/email/transports/agent-mail.mjs +604 -0
  217. package/src/channels/email/transports/agently-cli.mjs +288 -0
  218. package/src/channels/email/transports/imap-smtp.mjs +165 -0
  219. package/src/channels/feishu/bridge.mjs +6286 -0
  220. package/src/channels/feishu/config.mjs +71 -0
  221. package/src/channels/feishu/external-consumer.mjs +77 -0
  222. package/src/channels/feishu/external-files.mjs +111 -0
  223. package/src/channels/feishu/feishu-app.mjs +54 -0
  224. package/src/channels/feishu/feishu-cards.mjs +1285 -0
  225. package/src/channels/feishu/feishu-channel.mjs +651 -0
  226. package/src/channels/feishu/feishu-runtime.mjs +950 -0
  227. package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
  228. package/src/channels/feishu/group-response-mode.mjs +15 -0
  229. package/src/channels/feishu/harness-client.mjs +19 -0
  230. package/src/channels/feishu/history-reader.mjs +77 -0
  231. package/src/channels/feishu/live-cot.mjs +260 -0
  232. package/src/channels/feishu/message-utils.mjs +613 -0
  233. package/src/channels/feishu/multi-bot-controller.mjs +1588 -0
  234. package/src/channels/feishu/nearby-history.mjs +72 -0
  235. package/src/channels/feishu/plugin-config-store.mjs +216 -0
  236. package/src/channels/feishu/plugin-controller.mjs +254 -0
  237. package/src/channels/feishu/registration-manager.mjs +349 -0
  238. package/src/channels/feishu/repair-manager.mjs +138 -0
  239. package/src/channels/feishu/reply-context.mjs +22 -0
  240. package/src/channels/feishu/slash-command-panel.mjs +155 -0
  241. package/src/channels/feishu/slash-command-registry.mjs +495 -0
  242. package/src/channels/feishu/state-store.mjs +214 -0
  243. package/src/channels/feishu/step-push-mode.mjs +25 -0
  244. package/src/channels/feishu/voice-config.mjs +34 -0
  245. package/src/channels/feishu/voice.mjs +134 -0
  246. package/src/channels/imessage/config-store.mjs +24 -0
  247. package/src/channels/imessage/controller.mjs +37 -0
  248. package/src/channels/imessage/harness-client.mjs +7 -0
  249. package/src/channels/imessage/imessage-api.mjs +194 -0
  250. package/src/channels/imessage/imessage-bridge.mjs +16 -0
  251. package/src/channels/imessage/runtime.mjs +102 -0
  252. package/src/channels/imessage/state-store.mjs +3 -0
  253. package/src/channels/matrix/matrix-api.mjs +696 -0
  254. package/src/channels/matrix/matrix-bridge.mjs +20 -0
  255. package/src/channels/matrix/matrix-config-store.mjs +368 -0
  256. package/src/channels/matrix/matrix-controller.mjs +404 -0
  257. package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
  258. package/src/channels/matrix/matrix-crypto.mjs +1014 -0
  259. package/src/channels/matrix/matrix-harness-client.mjs +11 -0
  260. package/src/channels/matrix/matrix-normalize.mjs +357 -0
  261. package/src/channels/matrix/matrix-rich-text.mjs +313 -0
  262. package/src/channels/matrix/matrix-room-history.mjs +316 -0
  263. package/src/channels/matrix/matrix-runtime.mjs +1014 -0
  264. package/src/channels/office/config-store.mjs +107 -0
  265. package/src/channels/office/office-controller.mjs +178 -0
  266. package/src/channels/office/office-job-executor.mjs +391 -0
  267. package/src/channels/office/office-runtime.mjs +175 -0
  268. package/src/channels/office/office-transport.mjs +171 -0
  269. package/src/channels/office/protocol.mjs +43 -0
  270. package/src/channels/qq/config-store.mjs +173 -0
  271. package/src/channels/qq/harness-client.mjs +11 -0
  272. package/src/channels/qq/markdown-reply.mjs +446 -0
  273. package/src/channels/qq/qq-bridge.mjs +1507 -0
  274. package/src/channels/qq/qq-controller.mjs +514 -0
  275. package/src/channels/qq/qq-menu.mjs +208 -0
  276. package/src/channels/qq/qq-runtime.mjs +303 -0
  277. package/src/channels/qq/qr-auth.mjs +24 -0
  278. package/src/channels/qq/state-error.mjs +17 -0
  279. package/src/channels/qq/state-store.mjs +143 -0
  280. package/src/channels/shared/access-policy.mjs +210 -0
  281. package/src/channels/shared/agent-preset.mjs +76 -0
  282. package/src/channels/shared/batch-input.mjs +229 -0
  283. package/src/channels/shared/bot-alias.mjs +29 -0
  284. package/src/channels/shared/bot-workspace-store.mjs +2383 -0
  285. package/src/channels/shared/command-catalog.mjs +107 -0
  286. package/src/channels/shared/command-permission.mjs +32 -0
  287. package/src/channels/shared/compact-command.mjs +109 -0
  288. package/src/channels/shared/config-read-error.mjs +24 -0
  289. package/src/channels/shared/connection-error.mjs +191 -0
  290. package/src/channels/shared/connection-test.mjs +58 -0
  291. package/src/channels/shared/context-enhancement.mjs +372 -0
  292. package/src/channels/shared/control-command.mjs +111 -0
  293. package/src/channels/shared/conversation-state-store.mjs +165 -0
  294. package/src/channels/shared/default-workspace.mjs +31 -0
  295. package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
  296. package/src/channels/shared/deferred-delivery.mjs +161 -0
  297. package/src/channels/shared/deferred-state.mjs +53 -0
  298. package/src/channels/shared/diagnostic-details.mjs +95 -0
  299. package/src/channels/shared/editable-message-stream.mjs +100 -0
  300. package/src/channels/shared/exclusive-inbound-consumers.mjs +71 -0
  301. package/src/channels/shared/file-download.mjs +64 -0
  302. package/src/channels/shared/harness-approval.mjs +508 -0
  303. package/src/channels/shared/harness-client.mjs +2143 -0
  304. package/src/channels/shared/harness-mux.mjs +123 -0
  305. package/src/channels/shared/harness-question.mjs +95 -0
  306. package/src/channels/shared/harness-session-binding.mjs +119 -0
  307. package/src/channels/shared/history-command.mjs +193 -0
  308. package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
  309. package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
  310. package/src/channels/shared/i18n-en/discord.mjs +10 -0
  311. package/src/channels/shared/i18n-en/email.mjs +25 -0
  312. package/src/channels/shared/i18n-en/feishu.mjs +404 -0
  313. package/src/channels/shared/i18n-en/image-input.mjs +18 -0
  314. package/src/channels/shared/i18n-en/matrix.mjs +85 -0
  315. package/src/channels/shared/i18n-en/office.mjs +23 -0
  316. package/src/channels/shared/i18n-en/qq.mjs +96 -0
  317. package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
  318. package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
  319. package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
  320. package/src/channels/shared/i18n-en/slack.mjs +27 -0
  321. package/src/channels/shared/i18n-en/telegram.mjs +27 -0
  322. package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
  323. package/src/channels/shared/i18n-en/wecom.mjs +62 -0
  324. package/src/channels/shared/i18n-en/weixin.mjs +88 -0
  325. package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
  326. package/src/channels/shared/i18n-en.mjs +45 -0
  327. package/src/channels/shared/i18n.mjs +78 -0
  328. package/src/channels/shared/im-source-guidance.mjs +65 -0
  329. package/src/channels/shared/image-input-policy.mjs +35 -0
  330. package/src/channels/shared/image-input-settings-store.mjs +60 -0
  331. package/src/channels/shared/image-input.mjs +124 -0
  332. package/src/channels/shared/image-prompt.mjs +360 -0
  333. package/src/channels/shared/inbound-access.mjs +43 -0
  334. package/src/channels/shared/inbound-file.mjs +323 -0
  335. package/src/channels/shared/inbound-ttl-store.mjs +110 -0
  336. package/src/channels/shared/inbound-ttl.mjs +22 -0
  337. package/src/channels/shared/injected-context.mjs +362 -0
  338. package/src/channels/shared/interface-language-store.mjs +127 -0
  339. package/src/channels/shared/interface-language.mjs +51 -0
  340. package/src/channels/shared/message-failure.mjs +257 -0
  341. package/src/channels/shared/model-command.mjs +741 -0
  342. package/src/channels/shared/model-setting.mjs +145 -0
  343. package/src/channels/shared/preset-command.mjs +308 -0
  344. package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
  345. package/src/channels/shared/semantic/artifact.mjs +750 -0
  346. package/src/channels/shared/semantic/delivery.mjs +193 -0
  347. package/src/channels/shared/semantic/reply-reference.mjs +148 -0
  348. package/src/channels/shared/session-binding-lock.mjs +40 -0
  349. package/src/channels/shared/session-channel-labels.mjs +28 -0
  350. package/src/channels/shared/session-reply-recovery.mjs +104 -0
  351. package/src/channels/shared/session-sync-registry.mjs +22 -0
  352. package/src/channels/shared/session-title.mjs +74 -0
  353. package/src/channels/shared/status-reaction.mjs +107 -0
  354. package/src/channels/shared/text-harness-bridge.mjs +1623 -0
  355. package/src/channels/shared/token-bot-controller.mjs +417 -0
  356. package/src/channels/shared/token-config-store.mjs +208 -0
  357. package/src/channels/shared/workspace-command.mjs +532 -0
  358. package/src/channels/shared/workspace-session.mjs +196 -0
  359. package/src/channels/slack/config-store.mjs +177 -0
  360. package/src/channels/slack/external-consumer.mjs +80 -0
  361. package/src/channels/slack/external-files.mjs +90 -0
  362. package/src/channels/slack/harness-client.mjs +11 -0
  363. package/src/channels/slack/history-reader.mjs +203 -0
  364. package/src/channels/slack/manifest.mjs +37 -0
  365. package/src/channels/slack/slack-api.mjs +636 -0
  366. package/src/channels/slack/slack-bridge.mjs +20 -0
  367. package/src/channels/slack/slack-controller.mjs +468 -0
  368. package/src/channels/slack/slack-runtime.mjs +879 -0
  369. package/src/channels/slack/state-store.mjs +3 -0
  370. package/src/channels/telegram/config-store.mjs +89 -0
  371. package/src/channels/telegram/harness-client.mjs +11 -0
  372. package/src/channels/telegram/state-store.mjs +3 -0
  373. package/src/channels/telegram/telegram-api.mjs +486 -0
  374. package/src/channels/telegram/telegram-bridge.mjs +81 -0
  375. package/src/channels/telegram/telegram-controller.mjs +52 -0
  376. package/src/channels/telegram/telegram-http.mjs +21 -0
  377. package/src/channels/telegram/telegram-rich-message.mjs +149 -0
  378. package/src/channels/telegram/telegram-runtime.mjs +1471 -0
  379. package/src/channels/wecom/config-store.mjs +172 -0
  380. package/src/channels/wecom/harness-client.mjs +11 -0
  381. package/src/channels/wecom/qr-auth.mjs +95 -0
  382. package/src/channels/wecom/send-error.mjs +31 -0
  383. package/src/channels/wecom/state-store.mjs +107 -0
  384. package/src/channels/wecom/wecom-bridge.mjs +1833 -0
  385. package/src/channels/wecom/wecom-cards.mjs +101 -0
  386. package/src/channels/wecom/wecom-controller.mjs +530 -0
  387. package/src/channels/wecom/wecom-runtime.mjs +269 -0
  388. package/src/channels/wecom-app/callback-server.mjs +471 -0
  389. package/src/channels/wecom-app/config-store.mjs +242 -0
  390. package/src/channels/wecom-app/harness-client.mjs +11 -0
  391. package/src/channels/wecom-app/state-store.mjs +107 -0
  392. package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
  393. package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
  394. package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
  395. package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
  396. package/src/channels/weixin/config-store.mjs +192 -0
  397. package/src/channels/weixin/connection-error.en.mjs +137 -0
  398. package/src/channels/weixin/connection-error.mjs +153 -0
  399. package/src/channels/weixin/diagnostic-details.mjs +1 -0
  400. package/src/channels/weixin/harness-client.mjs +19 -0
  401. package/src/channels/weixin/state-store.mjs +291 -0
  402. package/src/channels/weixin/weixin-api.mjs +949 -0
  403. package/src/channels/weixin/weixin-bridge.mjs +1537 -0
  404. package/src/channels/weixin/weixin-controller.mjs +669 -0
  405. package/src/channels/weixin/weixin-runtime.mjs +416 -0
  406. package/src/channels/whatsapp/config-store.mjs +210 -0
  407. package/src/channels/whatsapp/harness-client.mjs +11 -0
  408. package/src/channels/whatsapp/state-store.mjs +3 -0
  409. package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
  410. package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
  411. package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
  412. package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
@@ -0,0 +1,950 @@
1
+ import { qualifyExternalReply } from './reply-context.mjs';
2
+ import { readExternalHistory } from './history-reader.mjs';
3
+ import { externalAttachments, readExternalFile, replyExternalFile } from './external-files.mjs';
4
+ import { createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { FeishuHarnessBridge } from './bridge.mjs';
7
+ import { cardActionProbeCard } from './feishu-cards.mjs';
8
+ import { VerifiedFeishuChannel } from './feishu-channel.mjs';
9
+ import { normalizeFeishuGroupResponseMode } from './group-response-mode.mjs';
10
+ import { normalizeFeishuStepPushMode } from './step-push-mode.mjs';
11
+ import { createVoice } from './voice.mjs';
12
+ import {
13
+ syncSlashCommands,
14
+ SLASH_COMMAND_MANIFEST,
15
+ } from './slash-command-registry.mjs';
16
+ import { normalizeSlashPanelConfig } from './slash-command-panel.mjs';
17
+ import {
18
+ connectionTestTargetUnavailable,
19
+ sendRememberedConnectionTest,
20
+ } from '../shared/connection-test.mjs';
21
+ import { t } from '../shared/i18n.mjs';
22
+
23
+ const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
24
+ const CALLBACK_PROBE_SUCCESS_NOTICE = '✅ 修复完成:已实测收到 card.action.trigger,菜单按钮现在可用。';
25
+ const CALLBACK_PROBE_TIMEOUT_NOTICE = '⚠️ 修复验证超时:未收到测试卡按钮的 card.action.trigger,不能确认按钮已修复。请不要重复授权;先检查飞书开放平台的卡片回调配置,确认后再发送 /repair。';
26
+ const CALLBACK_PROBE_SEND_FAILURE_NOTICE = '⚠️ 修复验证失败:无法发送专用测试卡,不能确认 card.action.trigger 已恢复。请不要重复授权;先检查机器人消息权限和连接状态。';
27
+ const CALLBACK_PROBE_ABORT_NOTICE = '⚠️ 修复验证中断:Runtime 已停止,未完成 card.action.trigger 实测,不能确认修复成功。请不要重复授权;先等待机器人恢复连接。';
28
+ const REUSABLE_WS_STATES = new Set(['connected', 'connecting', 'reconnecting']);
29
+
30
+ function nonEmptyString(value) {
31
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
32
+ }
33
+
34
+ function strictCardOperatorOpenId(event) {
35
+ return nonEmptyString(event?.operator?.open_id)
36
+ ?? nonEmptyString(event?.operator?.operator_id?.open_id);
37
+ }
38
+
39
+ function websocketState(wsClient, fallback) {
40
+ try {
41
+ const state = wsClient?.getConnectionStatus?.()?.state;
42
+ return typeof state === 'string' && state ? state : fallback;
43
+ } catch {
44
+ return fallback;
45
+ }
46
+ }
47
+
48
+ function probeError(code, message) {
49
+ const error = new Error(message);
50
+ error.code = code;
51
+ return error;
52
+ }
53
+
54
+ function httpInstanceWithTimeout(httpInstance, timeoutMs) {
55
+ if (!httpInstance || typeof httpInstance.request !== 'function') return undefined;
56
+ const optionsWithTimeout = (options) => ({
57
+ ...(options ?? {}),
58
+ timeout: options?.timeout ?? timeoutMs,
59
+ });
60
+ return {
61
+ request: (options) => httpInstance.request(optionsWithTimeout(options)),
62
+ get: (url, options) => httpInstance.get(url, optionsWithTimeout(options)),
63
+ delete: (url, options) => httpInstance.delete(url, optionsWithTimeout(options)),
64
+ head: (url, options) => httpInstance.head(url, optionsWithTimeout(options)),
65
+ options: (url, options) => httpInstance.options(url, optionsWithTimeout(options)),
66
+ post: (url, data, options) => httpInstance.post(url, data, optionsWithTimeout(options)),
67
+ put: (url, data, options) => httpInstance.put(url, data, optionsWithTimeout(options)),
68
+ patch: (url, data, options) => httpInstance.patch(url, data, optionsWithTimeout(options)),
69
+ };
70
+ }
71
+
72
+ export function createBridgeStatus({ allowedSenderCount = 1 } = {}) {
73
+ return {
74
+ startedAt: null,
75
+ ready: false,
76
+ feishuLongConnectionState: 'idle',
77
+ harnessReachable: false,
78
+ messagesReceived: 0,
79
+ messagesReplied: 0,
80
+ messagesRejected: 0,
81
+ reactionsAdded: 0,
82
+ reactionsRemoved: 0,
83
+ reactionErrors: 0,
84
+ streamResponses: 0,
85
+ streamUpdates: 0,
86
+ streamFallbacks: 0,
87
+ streamErrors: 0,
88
+ cardActionsReceived: 0,
89
+ cardActionProbesVerified: 0,
90
+ lastMessageAt: null,
91
+ lastReplyAt: null,
92
+ lastRejectedAt: null,
93
+ lastCardActionAt: null,
94
+ lastError: null,
95
+ agentPreset: 'standard',
96
+ authorizationMode: 'sender-open-id-allowlist',
97
+ allowedSenderCount,
98
+ slashCommandRegistration: 'idle',
99
+ slashCommandsRegistered: 0,
100
+ slashCommandsExisting: 0,
101
+ slashCommandsFailed: 0,
102
+ slashCommandsRemoved: 0,
103
+ slashCommandsError: null,
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Owns one live Feishu long connection and the already-tested bridge stack.
109
+ * The class intentionally receives the SDK and Harness dependencies so the
110
+ * plugin can run it in-process while tests exercise the lifecycle without a
111
+ * real Feishu tenant.
112
+ */
113
+ export class FeishuRuntime {
114
+ #lark;
115
+ #botId;
116
+ #appId;
117
+ #appSecret;
118
+ #domain;
119
+ #botOpenId;
120
+ #groupResponseMode;
121
+ #mentionTopicReply;
122
+ #stepPush;
123
+ #stepPushMode;
124
+ #voice = null;
125
+ #sessionSyncTargetsFor;
126
+ #ownerOpenIds;
127
+ #harness;
128
+ #state;
129
+ #contextEnhancement;
130
+ #accessPolicy;
131
+ #replyTimeoutMs;
132
+ #connectTimeoutMs;
133
+ #requestTimeoutMs;
134
+ #wsAgent;
135
+ #logger;
136
+ #diagnostics;
137
+ #repair;
138
+ #client = null;
139
+ #bridge = null;
140
+ #consumerMode;
141
+ #acceptExternal;
142
+ #wsClient = null;
143
+ #starting = null;
144
+ #stopping = null;
145
+ #abortController = null;
146
+ #pendingCardActionProbes = new Map();
147
+ #status;
148
+ #slashCommands = true;
149
+ /** Which commands the "/" panel should offer, and in which order. */
150
+ #slashPanel = null;
151
+ /** HTTP instance kept for panel re-syncs after startup. */
152
+ #slashHttpInstance = null;
153
+ /**
154
+ * Bumped on every panel change: a sync started for an older config stops at
155
+ * its next checkpoint instead of racing the newer one (last writer wins).
156
+ */
157
+ #slashSyncEpoch = 0;
158
+ /** Cancels the panel sync in flight; it stops before its next request. */
159
+ #slashSyncCancel = null;
160
+ /** Panel syncs run one after another, so two plans never interleave. */
161
+ #slashSyncQueue = Promise.resolve();
162
+
163
+ constructor({
164
+ lark,
165
+ consumerMode = 'standalone',
166
+ acceptExternal,
167
+ botId,
168
+ appId,
169
+ appSecret,
170
+ domain = 'feishu',
171
+ botOpenId,
172
+ groupResponseMode,
173
+ mentionTopicReply = true,
174
+ stepPush = false,
175
+ stepPushMode = 'post',
176
+ voice = null,
177
+ sessionSyncTargetsFor = null,
178
+ ownerOpenId,
179
+ ownerOpenIds,
180
+ harness,
181
+ state,
182
+ contextEnhancement,
183
+ accessPolicy,
184
+ repair,
185
+ replyTimeoutMs = 600000,
186
+ connectTimeoutMs = 15000,
187
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
188
+ slashCommands = true,
189
+ slashPanel = null,
190
+ wsAgent,
191
+ logger = console,
192
+ }) {
193
+ if (!lark) throw new Error('FeishuRuntime requires the Feishu SDK');
194
+ if (!appId || !appSecret) throw new Error('FeishuRuntime requires app credentials');
195
+ const allowedOwners = Array.isArray(ownerOpenIds) ? ownerOpenIds : [ownerOpenId];
196
+ const normalizedOwners = [...new Set(allowedOwners.filter((value) => typeof value === 'string' && value))];
197
+ if (normalizedOwners.length === 0) throw new Error('FeishuRuntime requires at least one owner open_id');
198
+ if (!harness) throw new Error('FeishuRuntime requires a Harness client');
199
+ if (!state) throw new Error('FeishuRuntime requires a state store');
200
+ if (repair !== undefined && repair !== null && !nonEmptyString(botId)) {
201
+ throw new TypeError('FeishuRuntime repair capability requires a botId');
202
+ }
203
+ if (!Number.isFinite(requestTimeoutMs) || requestTimeoutMs <= 0) {
204
+ throw new TypeError('FeishuRuntime requestTimeoutMs must be a positive number');
205
+ }
206
+
207
+ this.#consumerMode = consumerMode;
208
+ this.#acceptExternal = acceptExternal;
209
+ this.#lark = lark;
210
+ this.#botId = nonEmptyString(botId);
211
+ this.#appId = appId;
212
+ this.#appSecret = appSecret;
213
+ this.#domain = domain;
214
+ this.#botOpenId = nonEmptyString(botOpenId);
215
+ this.#groupResponseMode = normalizeFeishuGroupResponseMode(groupResponseMode);
216
+ this.#mentionTopicReply = mentionTopicReply !== false;
217
+ this.#stepPush = stepPush === true;
218
+ this.#stepPushMode = normalizeFeishuStepPushMode(stepPushMode);
219
+ // voice 为 { config, secret } 来源;凭据缺失时 createVoice 返回禁用对象,
220
+ // 桥接层完全跳过语音路径,不影响连接。
221
+ this.#voice = voice == null
222
+ ? null
223
+ : createVoice({ settings: voice.config, secret: voice.secret, logger });
224
+ this.#sessionSyncTargetsFor = typeof sessionSyncTargetsFor === 'function'
225
+ ? sessionSyncTargetsFor
226
+ : null;
227
+ this.#ownerOpenIds = normalizedOwners;
228
+ this.#harness = harness;
229
+ this.#state = state;
230
+ this.#contextEnhancement = contextEnhancement;
231
+ this.#accessPolicy = accessPolicy;
232
+ this.#repair = repair ?? null;
233
+ this.#replyTimeoutMs = replyTimeoutMs;
234
+ this.#connectTimeoutMs = connectTimeoutMs;
235
+ this.#requestTimeoutMs = requestTimeoutMs;
236
+ this.#slashCommands = consumerMode !== 'external-consumer' && Boolean(slashCommands);
237
+ this.#slashPanel = normalizeSlashPanelConfig(slashPanel);
238
+ this.#wsAgent = wsAgent;
239
+ this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'feishu', logger });
240
+ this.#status = createBridgeStatus({ allowedSenderCount: normalizedOwners.length });
241
+ }
242
+
243
+ get status() {
244
+ return structuredClone(this.#status);
245
+ }
246
+
247
+ setGroupResponseMode(value) {
248
+ this.#groupResponseMode = normalizeFeishuGroupResponseMode(value);
249
+ this.#bridge?.setGroupResponseMode(this.#groupResponseMode);
250
+ }
251
+
252
+ setMentionTopicReply(value) {
253
+ this.#mentionTopicReply = value !== false;
254
+ this.#bridge?.setMentionTopicReply(this.#mentionTopicReply);
255
+ }
256
+
257
+ setStepPush(value) {
258
+ this.#stepPush = value === true;
259
+ this.#bridge?.setStepPush(this.#stepPush);
260
+ }
261
+
262
+ setStepPushMode(value) {
263
+ this.#stepPushMode = normalizeFeishuStepPushMode(value);
264
+ this.#bridge?.setStepPushMode(this.#stepPushMode);
265
+ }
266
+
267
+ setVoice(source) {
268
+ this.#voice = source == null
269
+ ? null
270
+ : createVoice({ settings: source.config, secret: source.secret, logger: this.#logger });
271
+ this.#bridge?.setVoice(this.#voice);
272
+ }
273
+
274
+ /**
275
+ * Record which commands the "/" panel should offer. The panel itself lives on
276
+ * Feishu's side, so a connected bot re-syncs it in the background; the newer
277
+ * config wins and any sync still running for the older one stops.
278
+ */
279
+ setSlashPanel(value) {
280
+ this.#slashPanel = normalizeSlashPanelConfig(value);
281
+ this.#slashSyncEpoch += 1;
282
+ this.#scheduleSlashPanelSync();
283
+ }
284
+
285
+ async start() {
286
+ while (true) {
287
+ while (this.#stopping) await this.#stopping;
288
+ if (this.#starting) return this.#starting;
289
+
290
+ const wsClient = this.#wsClient;
291
+ if (wsClient) {
292
+ const state = websocketState(wsClient, this.#status.feishuLongConnectionState);
293
+ if (REUSABLE_WS_STATES.has(state)) return this.status;
294
+
295
+ await this.stop({ preserveError: state === 'failed' });
296
+ continue;
297
+ }
298
+
299
+ // A partial/failed attempt may have created resources before its
300
+ // WSClient became observable. Drain them before assigning a new attempt.
301
+ if (this.#client || this.#bridge || this.#abortController) {
302
+ await this.stop({
303
+ preserveError: this.#status.feishuLongConnectionState === 'failed',
304
+ });
305
+ continue;
306
+ }
307
+
308
+ break;
309
+ }
310
+
311
+ let starting;
312
+ starting = this.#start().finally(() => {
313
+ if (this.#starting === starting) this.#starting = null;
314
+ });
315
+ this.#starting = starting;
316
+ return starting;
317
+ }
318
+
319
+ async #start() {
320
+ const abortController = new AbortController();
321
+ this.#abortController = abortController;
322
+ const { signal } = abortController;
323
+ const abortError = () => (
324
+ signal.reason ?? new DOMException('Feishu runtime stopped', 'AbortError')
325
+ );
326
+ const isCurrentStart = () => (
327
+ !signal.aborted && this.#abortController === abortController
328
+ );
329
+ const assertCurrentStart = () => {
330
+ if (!isCurrentStart()) throw abortError();
331
+ };
332
+ this.#status.startedAt = new Date().toISOString();
333
+ this.#status.feishuLongConnectionState = 'connecting';
334
+ this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
335
+
336
+ try {
337
+ await atConnectionStage('harness.check', () => this.#harness.ensureRunning({ signal }));
338
+ assertCurrentStart();
339
+ this.#status.harnessReachable = true;
340
+
341
+ const sdkDomain = this.#domain === 'lark'
342
+ ? this.#lark.Domain.Lark
343
+ : this.#lark.Domain.Feishu;
344
+ const larkConfig = {
345
+ appId: this.#appId,
346
+ appSecret: this.#appSecret,
347
+ domain: sdkDomain,
348
+ };
349
+ const httpInstance = httpInstanceWithTimeout(
350
+ this.#lark.defaultHttpInstance,
351
+ this.#requestTimeoutMs,
352
+ );
353
+ if (httpInstance) larkConfig.httpInstance = httpInstance;
354
+ const client = new this.#lark.Client(larkConfig);
355
+ this.#client = client;
356
+ const channel = new VerifiedFeishuChannel({
357
+ client,
358
+ initialText: t('已连接 DeepSeek Harness,正在思考…'),
359
+ });
360
+ const bridge = this.#consumerMode === 'external-consumer' ? null : new FeishuHarnessBridge({
361
+ client,
362
+ channel,
363
+ harness: this.#harness,
364
+ state: this.#state,
365
+ contextEnhancement: this.#contextEnhancement,
366
+ accessPolicy: this.#accessPolicy,
367
+ status: this.#status,
368
+ allowedSenderOpenIds: new Set(this.#ownerOpenIds),
369
+ botId: this.#botId,
370
+ appId: this.#appId,
371
+ botOpenId: this.#botOpenId,
372
+ groupResponseMode: this.#groupResponseMode,
373
+ mentionTopicReply: this.#mentionTopicReply,
374
+ stepPush: this.#stepPush,
375
+ stepPushMode: this.#stepPushMode,
376
+ voice: this.#voice,
377
+ sessionSyncTargetsFor: this.#sessionSyncTargetsFor,
378
+ repair: this.#repair,
379
+ replyTimeoutMs: this.#replyTimeoutMs,
380
+ // Interaction cards (approval/question buttons) are on by default.
381
+ // Set DSH_IM_INTERACTION_CARDS=0 to fall back to plain-text replies.
382
+ interactionCards: !['0', 'false', 'no', 'off'].includes(
383
+ String(process.env.DSH_IM_INTERACTION_CARDS ?? '').trim().toLowerCase(),
384
+ ),
385
+ signal,
386
+ logger: this.#logger,
387
+ });
388
+ this.#bridge = bridge;
389
+
390
+ const dispatcher = new this.#lark.EventDispatcher({}).register({
391
+ 'im.message.receive_v1': (event) => {
392
+ if (this.#consumerMode === 'external-consumer') {
393
+ assertCurrentStart();
394
+ if (typeof this.#acceptExternal !== 'function')
395
+ throw Object.assign(new Error('consumer-unavailable'), { code: 'consumer-unavailable' });
396
+ return this.#acceptExternal(event, { signal });
397
+ }
398
+ if (isCurrentStart()) void bridge.accept(event);
399
+ },
400
+ 'im.message.reaction.created_v1': () => undefined,
401
+ 'im.message.reaction.deleted_v1': () => undefined,
402
+ // Interactive-card button callbacks (only delivered when the app
403
+ // subscribes card.action.trigger; the number-reply fallback covers
404
+ // apps that do not).
405
+ 'card.action.trigger': (event) => {
406
+ if (!isCurrentStart() || this.#consumerMode === 'external-consumer') return;
407
+ this.#status.cardActionsReceived += 1;
408
+ this.#status.lastCardActionAt = new Date().toISOString();
409
+ if (!this.#consumeCardActionProbe(event)) void bridge.onCardAction(event);
410
+ },
411
+ });
412
+
413
+ let settleReady;
414
+ let settleError;
415
+ const ready = new Promise((resolve, reject) => {
416
+ let settled = false;
417
+ const onAbort = () => {
418
+ settleError(abortError());
419
+ };
420
+ const settle = (callback, value) => {
421
+ if (settled) return;
422
+ settled = true;
423
+ clearTimeout(timer);
424
+ signal.removeEventListener('abort', onAbort);
425
+ callback(value);
426
+ };
427
+ const timer = setTimeout(() => {
428
+ settle(
429
+ reject,
430
+ new Error(`Feishu WebSocket handshake timed out after ${this.#connectTimeoutMs}ms`),
431
+ );
432
+ }, this.#connectTimeoutMs);
433
+ settleReady = () => {
434
+ settle(resolve);
435
+ };
436
+ settleError = (error) => {
437
+ settle(reject, error);
438
+ };
439
+ signal.addEventListener('abort', onAbort, { once: true });
440
+ if (signal.aborted) onAbort();
441
+ });
442
+ // The SDK constructor can throw before Promise.all attaches below.
443
+ // Keep the abort-driven rejection observed in that path as well.
444
+ void ready.catch(() => undefined);
445
+
446
+ const wsClient = new this.#lark.WSClient({
447
+ ...larkConfig,
448
+ ...(this.#wsAgent ? { agent: this.#wsAgent } : {}),
449
+ loggerLevel: this.#lark.LoggerLevel.info,
450
+ handshakeTimeoutMs: this.#connectTimeoutMs,
451
+ onReady: () => {
452
+ if (!isCurrentStart()) return;
453
+ this.#status.feishuLongConnectionState = 'connected';
454
+ this.#status.ready = true;
455
+ this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
456
+ settleReady();
457
+ },
458
+ onError: (error) => {
459
+ if (!isCurrentStart()) return;
460
+ this.#status.feishuLongConnectionState = 'failed';
461
+ this.#status.ready = false;
462
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#botId, automatic: true }).publicError;
463
+ this.#status.lastError = this.#status.error.message;
464
+
465
+ settleError(error);
466
+ },
467
+ onReconnecting: () => {
468
+ if (!isCurrentStart()) return;
469
+ this.#status.feishuLongConnectionState = 'reconnecting';
470
+ this.#status.ready = false;
471
+ },
472
+ onReconnected: () => {
473
+ if (!isCurrentStart()) return;
474
+ this.#status.feishuLongConnectionState = 'connected';
475
+ this.#status.ready = true;
476
+ this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
477
+ },
478
+ });
479
+ this.#wsClient = wsClient;
480
+ const wsStarted = Promise.resolve()
481
+ .then(() => wsClient.start({ eventDispatcher: dispatcher }))
482
+ .catch((error) => {
483
+ settleError(error);
484
+ throw error;
485
+ });
486
+ await Promise.all([wsStarted, ready]);
487
+ assertCurrentStart();
488
+ // Register the native Slash Command panel best-effort and asynchronously
489
+ // so it never blocks the long-connection startup. The panel is only a
490
+ // client-side convenience; failure here must not take the bot down. The
491
+ // HTTP instance is kept so a later panel change can re-sync while running.
492
+ if (this.#slashCommands && httpInstance) {
493
+ this.#slashHttpInstance = httpInstance;
494
+ this.#scheduleSlashPanelSync();
495
+ }
496
+ return this.status;
497
+ } catch (error) {
498
+ // stop() owns the terminal idle state for an explicitly aborted start.
499
+ // In particular, do not let the rejected handshake waiter overwrite it.
500
+ if (signal.aborted) throw error;
501
+ this.#status.ready = false;
502
+ this.#status.feishuLongConnectionState = 'failed';
503
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.restore', reuse: true, botId: this.#botId, automatic: true }).publicError;
504
+ this.#status.lastError = this.#status.error.message;
505
+ await this.#cleanup({ preserveError: true, abortController });
506
+ throw error;
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Send a one-shot callback card and resolve only after Feishu delivers the
512
+ * exact message/nonce/operator tuple over card.action.trigger. The controller
513
+ * uses this as the final proof for both browser- and chat-initiated repairs.
514
+ */
515
+ async beginCardActionProbe({ expectedOperatorOpenId, timeoutMs = 90_000 } = {}) {
516
+ if (!this.#status.ready || !this.#client) {
517
+ throw probeError('card_action_probe_unavailable', '飞书机器人尚未连接');
518
+ }
519
+ const operatorOpenId = nonEmptyString(expectedOperatorOpenId);
520
+ if (!operatorOpenId || operatorOpenId === '*') {
521
+ throw new TypeError('A precise Feishu operator open_id is required');
522
+ }
523
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 10 * 60_000) {
524
+ throw new TypeError('Card-action probe timeout must be between 1 and 600000ms');
525
+ }
526
+
527
+ const nonce = randomUUID().replaceAll('-', '');
528
+ let response;
529
+ try {
530
+ response = await this.#client.im.v1.message.create({
531
+ params: { receive_id_type: 'open_id' },
532
+ data: {
533
+ receive_id: operatorOpenId,
534
+ msg_type: 'interactive',
535
+ content: cardActionProbeCard(nonce),
536
+ },
537
+ });
538
+ } catch {
539
+ void this.#sendCardActionProbeNotice(
540
+ operatorOpenId,
541
+ t(CALLBACK_PROBE_SEND_FAILURE_NOTICE),
542
+ 'failure',
543
+ );
544
+ throw probeError('card_action_probe_send_failed', '无法发送飞书卡片回调测试');
545
+ }
546
+ if (response?.code && response.code !== 0) {
547
+ void this.#sendCardActionProbeNotice(
548
+ operatorOpenId,
549
+ t(CALLBACK_PROBE_SEND_FAILURE_NOTICE),
550
+ 'failure',
551
+ );
552
+ throw probeError('card_action_probe_send_failed', '无法发送飞书卡片回调测试');
553
+ }
554
+ const messageId = nonEmptyString(response?.data?.message_id)
555
+ ?? nonEmptyString(response?.message_id);
556
+ if (!messageId) {
557
+ void this.#sendCardActionProbeNotice(
558
+ operatorOpenId,
559
+ t(CALLBACK_PROBE_SEND_FAILURE_NOTICE),
560
+ 'failure',
561
+ );
562
+ throw probeError('card_action_probe_send_failed', '飞书未返回测试卡片的消息 ID');
563
+ }
564
+
565
+ return new Promise((resolve, reject) => {
566
+ const timeout = setTimeout(() => {
567
+ const current = this.#pendingCardActionProbes.get(messageId);
568
+ if (!current || current.nonce !== nonce) return;
569
+ this.#pendingCardActionProbes.delete(messageId);
570
+ void this.#sendCardActionProbeNotice(
571
+ operatorOpenId,
572
+ t(CALLBACK_PROBE_TIMEOUT_NOTICE),
573
+ 'timeout',
574
+ );
575
+ reject(probeError(
576
+ 'card_action_probe_timeout',
577
+ '在规定时间内未收到飞书卡片按钮回调',
578
+ ));
579
+ }, timeoutMs);
580
+ timeout.unref?.();
581
+ this.#pendingCardActionProbes.set(messageId, {
582
+ messageId,
583
+ nonce,
584
+ expectedOperatorOpenId: operatorOpenId,
585
+ timeout,
586
+ resolve,
587
+ reject,
588
+ });
589
+ });
590
+ }
591
+
592
+ #consumeCardActionProbe(event) {
593
+ const messageId = nonEmptyString(event?.context?.open_message_id);
594
+ if (!messageId) return false;
595
+ const probe = this.#pendingCardActionProbes.get(messageId);
596
+ if (!probe) return false;
597
+ const value = event?.action?.value;
598
+ const operatorOpenId = strictCardOperatorOpenId(event);
599
+ if (value?.action !== 'repair_verify'
600
+ || value?.nonce !== probe.nonce
601
+ || operatorOpenId !== probe.expectedOperatorOpenId) {
602
+ return false;
603
+ }
604
+ clearTimeout(probe.timeout);
605
+ this.#pendingCardActionProbes.delete(messageId);
606
+ this.#status.cardActionProbesVerified += 1;
607
+ // Start the terminal notification before resolving the controller-facing
608
+ // probe. A repair may rotate the App Secret and immediately replace this
609
+ // runtime after resolution; initiating the send here keeps chat and web
610
+ // repair flows equally observable. Notification failure never invalidates
611
+ // the callback proof itself.
612
+ void this.#sendCardActionProbeNotice(
613
+ operatorOpenId,
614
+ t(CALLBACK_PROBE_SUCCESS_NOTICE),
615
+ 'success',
616
+ ).finally(() => {
617
+ probe.resolve({
618
+ verified: true,
619
+ messageId,
620
+ operatorOpenId,
621
+ });
622
+ });
623
+ return true;
624
+ }
625
+
626
+ #sendCardActionProbeNotice(operatorOpenId, text, outcome) {
627
+ const client = this.#client;
628
+ if (!client) {
629
+ this.#logger.warn?.(`[dsh-feishu] unable to send the callback repair ${outcome} notice`);
630
+ return Promise.resolve(false);
631
+ }
632
+ return Promise.resolve().then(async () => {
633
+ const response = await client.im.v1.message.create({
634
+ params: { receive_id_type: 'open_id' },
635
+ data: {
636
+ receive_id: operatorOpenId,
637
+ msg_type: 'text',
638
+ content: JSON.stringify({ text }),
639
+ },
640
+ });
641
+ if (response?.code && response.code !== 0) {
642
+ throw new Error('Feishu callback repair notice failed');
643
+ }
644
+ return true;
645
+ }).catch(() => {
646
+ this.#logger.warn?.(`[dsh-feishu] unable to send the callback repair ${outcome} notice`);
647
+ return false;
648
+ });
649
+ }
650
+
651
+ async sendConnectionTest(text) {
652
+ if (!this.#status.ready || !this.#client) {
653
+ const error = new Error('飞书机器人尚未连接');
654
+ error.code = 'test-target-unavailable';
655
+ throw error;
656
+ }
657
+ if (typeof text !== 'string' || !text.trim()) {
658
+ throw new TypeError('Feishu connection test text is required');
659
+ }
660
+ const send = async (receiveIdType, receiveId, content) => {
661
+ const response = await this.#client.im.v1.message.create({
662
+ params: { receive_id_type: receiveIdType },
663
+ data: {
664
+ receive_id: receiveId,
665
+ msg_type: 'text',
666
+ content: JSON.stringify({ text: content }),
667
+ },
668
+ });
669
+ if (response?.code && response.code !== 0) {
670
+ throw new Error(`Feishu connection test failed: ${response.msg || response.code}`);
671
+ }
672
+ };
673
+
674
+ const ownerOpenId = this.#ownerOpenIds.find((value) => value !== '*');
675
+ if (ownerOpenId) {
676
+ await send('open_id', ownerOpenId, text);
677
+ return { sent: true };
678
+ }
679
+
680
+ return sendRememberedConnectionTest({
681
+ state: this.#state,
682
+ text,
683
+ channelLabel: t('飞书机器人'),
684
+ send: async (target, content) => {
685
+ const chatId = typeof target?.chatId === 'string' ? target.chatId.trim() : '';
686
+ if (!chatId) throw connectionTestTargetUnavailable(t('飞书机器人'));
687
+ await send('chat_id', chatId, content);
688
+ },
689
+ });
690
+ }
691
+
692
+ async sendProactiveText(target, text, { signal, format = 'plain', receipt = false } = {}) {
693
+ if (!this.#status.ready || !this.#client) {
694
+ const error = new Error('飞书机器人尚未连接');
695
+ error.code = 'bot-not-connected';
696
+ throw error;
697
+ }
698
+ const receiveIdType = target?.kind === 'user' ? 'open_id'
699
+ : target?.kind === 'group' ? 'chat_id' : null;
700
+ const receiveId = target?.kind === 'user'
701
+ ? nonEmptyString(target?.route?.openId)
702
+ : target?.kind === 'group'
703
+ ? nonEmptyString(target?.route?.chatId)
704
+ : null;
705
+ if (!receiveIdType || !receiveId) {
706
+ const error = new TypeError('Invalid Feishu proactive delivery target');
707
+ error.code = 'invalid-target';
708
+ throw error;
709
+ }
710
+ if (format !== 'plain' && format !== 'markdown') {
711
+ const error = new TypeError('Message format must be plain or markdown');
712
+ error.code = 'bad-request';
713
+ throw error;
714
+ }
715
+ if (typeof receipt !== 'boolean' || (receipt && target.kind !== 'group'))
716
+ throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
717
+ signal?.throwIfAborted();
718
+ // Use the same native Markdown element as chat, without opening a stream
719
+ // or retrying as plain text after a possibly accepted delivery.
720
+ const content = format === 'markdown'
721
+ ? { schema: '2.0', body: { elements: [{ tag: 'markdown', content: text }] } }
722
+ : { text };
723
+ const response = await this.#client.im.v1.message.create({
724
+ params: { receive_id_type: receiveIdType },
725
+ data: {
726
+ receive_id: receiveId,
727
+ msg_type: format === 'markdown' ? 'interactive' : 'text',
728
+ content: JSON.stringify(content),
729
+ },
730
+ });
731
+ if (response?.code && response.code !== 0) {
732
+ const error = new Error(`Feishu proactive delivery failed: ${response.msg || response.code}`);
733
+ error.code = 'target-rejected';
734
+ throw error;
735
+ }
736
+ if (!receipt) return { sent: true };
737
+ const messageId = response?.data?.message_id;
738
+ const conversationId = response?.data?.chat_id;
739
+ if (typeof messageId !== 'string' || !messageId || messageId.length > 512 || conversationId !== receiveId)
740
+ throw Object.assign(new Error('send-result-unknown'), { code: 'send-result-unknown' });
741
+ return { sent: true, receipt: { version: 1, messageId, conversationId } };
742
+ }
743
+
744
+ async historyChecked(identity, route, query, { signal } = {}) {
745
+ const client = this.#client;
746
+ if (!client || this.#consumerMode !== 'external-consumer')
747
+ throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
748
+ const result = await readExternalHistory(client, identity, route, query, signal);
749
+ signal?.throwIfAborted();
750
+ if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
751
+ return result;
752
+ }
753
+
754
+ async enrichExternal(evidence, { signal } = {}) {
755
+ const client = this.#client;
756
+ if (!client || this.#consumerMode !== 'external-consumer') throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
757
+ const result = await externalAttachments(client, evidence, signal);
758
+ signal?.throwIfAborted();
759
+ if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
760
+ return result;
761
+ }
762
+
763
+ async externalFileChecked(route, value, { signal, reply = false } = {}) {
764
+ const client = this.#client;
765
+ const assertCurrent = () => {
766
+ signal?.throwIfAborted();
767
+ if (!client || this.#client !== client || this.#consumerMode !== 'external-consumer')
768
+ throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
769
+ };
770
+ assertCurrent();
771
+ return reply ? replyExternalFile(client, route, value, { signal, assertCurrent })
772
+ : readExternalFile(client, route, value, { signal, assertCurrent });
773
+ }
774
+
775
+ async qualifyReplyChecked(route, { signal } = {}) {
776
+ const client = this.#client;
777
+ if (!client || this.#consumerMode !== 'external-consumer')
778
+ throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
779
+ const result = await qualifyExternalReply(client, route, signal);
780
+ signal?.throwIfAborted();
781
+ if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
782
+ return result;
783
+ }
784
+
785
+ async replyChecked(route, text, { signal, receipt = false, beforeSend } = {}) {
786
+ if (!route || typeof route.messageId !== 'string' || typeof route.conversationId !== 'string'
787
+ || typeof route.actorId !== 'string' || typeof text !== 'string' || !text.trim() || text.length > 4000)
788
+ throw Object.assign(new Error('bad-request'), { code: 'bad-request' });
789
+ const client = this.#client;
790
+ if (!client || this.#consumerMode !== 'external-consumer')
791
+ throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
792
+ signal?.throwIfAborted();
793
+ const current = await client.im.v1.message.get({ path: { message_id: route.messageId } });
794
+ const source = current?.data?.items?.find(item => item.message_id === route.messageId);
795
+ if (current?.code || !source || source.deleted === true || source.chat_id !== route.conversationId
796
+ || source.sender?.sender_type !== 'user' || source.sender?.id_type !== 'open_id'
797
+ || source.sender?.id !== route.actorId || (source.thread_id || undefined) !== route.threadId
798
+ || (source.root_id || undefined) !== route.rootId || (source.parent_id || undefined) !== route.parentId)
799
+ throw Object.assign(new Error('stale-route'), { code: 'stale-route' });
800
+ signal?.throwIfAborted();
801
+ if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
802
+ if (beforeSend !== undefined && (typeof beforeSend !== 'function' || beforeSend() !== true))
803
+ throw Object.assign(new Error('stale-route'), { code: 'stale-route' });
804
+ signal?.throwIfAborted();
805
+ const response = await client.im.v1.message.reply({
806
+ path: { message_id: route.messageId },
807
+ data: { msg_type: 'text', content: JSON.stringify({ text }), reply_in_thread: Boolean(route.threadId) },
808
+ });
809
+ const messageId = response?.data?.message_id;
810
+ if (response?.code || typeof messageId !== 'string' || !messageId)
811
+ throw Object.assign(new Error('reply-result-unknown'), { code: 'reply-result-unknown' });
812
+ if (receipt) {
813
+ if (messageId.length > 512 || response?.data?.chat_id !== route.conversationId)
814
+ throw Object.assign(new Error('reply-result-unknown'), { code: 'reply-result-unknown' });
815
+ return { sent: true, receipt: { version: 1, messageId, conversationId: route.conversationId } };
816
+ }
817
+ return { sent: true, messageId };
818
+ }
819
+
820
+ /**
821
+ * Queue one panel sync for the current config.
822
+ *
823
+ * Two saves in a row used to run two syncs concurrently, and the older one
824
+ * kept deleting and creating commands from a plan nobody wanted anymore. Here
825
+ * the run in flight is cancelled first — it stops at its next checkpoint while
826
+ * requests already sent are left to finish — and the new run starts only once
827
+ * it has settled, so the panel converges to the newest config.
828
+ */
829
+ #scheduleSlashPanelSync() {
830
+ const httpInstance = this.#slashHttpInstance;
831
+ const connectionSignal = this.#abortController?.signal;
832
+ if (!this.#slashCommands || !httpInstance || !connectionSignal || connectionSignal.aborted) return;
833
+ const epoch = this.#slashSyncEpoch;
834
+ this.#slashSyncCancel?.();
835
+ const controller = new AbortController();
836
+ const cancel = () => controller.abort();
837
+ const forwardAbort = () => cancel();
838
+ this.#slashSyncCancel = cancel;
839
+ connectionSignal.addEventListener('abort', forwardAbort, { once: true });
840
+ if (connectionSignal.aborted) cancel();
841
+ const run = this.#slashSyncQueue.then(() => this.#registerSlashCommands(
842
+ httpInstance,
843
+ () => !connectionSignal.aborted && this.#abortController?.signal === connectionSignal,
844
+ controller.signal,
845
+ epoch,
846
+ ));
847
+ const settled = run.then(() => {}, () => {});
848
+ this.#slashSyncQueue = settled;
849
+ void settled.then(() => {
850
+ connectionSignal.removeEventListener('abort', forwardAbort);
851
+ if (this.#slashSyncCancel === cancel) this.#slashSyncCancel = null;
852
+ });
853
+ }
854
+
855
+ async #registerSlashCommands(httpInstance, isCurrentStart, signal, epoch = this.#slashSyncEpoch) {
856
+ this.#status.slashCommandRegistration = 'registering';
857
+ this.#status.slashCommandsError = null;
858
+ try {
859
+ const result = await syncSlashCommands({
860
+ appId: this.#appId,
861
+ appSecret: this.#appSecret,
862
+ domain: this.#domain,
863
+ httpInstance,
864
+ signal,
865
+ manifest: SLASH_COMMAND_MANIFEST,
866
+ config: this.#slashPanel,
867
+ });
868
+ // A newer panel config took over while this sync was running: its own run
869
+ // reports the outcome, so this one only stops.
870
+ if (!isCurrentStart() || epoch !== this.#slashSyncEpoch || result.superseded === true) return;
871
+ this.#status.slashCommandRegistration = 'done';
872
+ this.#status.slashCommandsRegistered = result.created.length;
873
+ this.#status.slashCommandsExisting = result.existing.length;
874
+ this.#status.slashCommandsFailed = result.failed.length;
875
+ this.#status.slashCommandsRemoved = result.deleted.length;
876
+ this.#status.slashCommandsError = result.failed.length > 0
877
+ ? result.failed.map((f) => `/${f.command}: ${f.error?.message ?? String(f.error)}`).join('; ')
878
+ : null;
879
+ if (result.created.length > 0 || result.deleted.length > 0) {
880
+ this.#logger.info?.(
881
+ `[dsh-feishu] slash panel synced: ${result.created.length} added, ${result.deleted.length} removed`,
882
+ );
883
+ }
884
+ if (result.failed.length > 0) {
885
+ this.#logger.warn?.(
886
+ `[dsh-feishu] ${result.failed.length} slash command(s) failed to register: ${this.#status.slashCommandsError}`,
887
+ );
888
+ }
889
+ } catch (error) {
890
+ if (!isCurrentStart()) return;
891
+ this.#status.slashCommandRegistration = 'failed';
892
+ this.#status.slashCommandsError = error?.message ?? String(error);
893
+ this.#logger.warn?.(
894
+ `[dsh-feishu] slash command registration skipped: ${this.#status.slashCommandsError}`,
895
+ );
896
+ }
897
+ }
898
+
899
+ stop(options = {}) {
900
+ if (this.#stopping) return this.#stopping;
901
+
902
+ let stopping;
903
+ stopping = this.#stop(options).finally(() => {
904
+ if (this.#stopping === stopping) this.#stopping = null;
905
+ });
906
+ this.#stopping = stopping;
907
+ return stopping;
908
+ }
909
+
910
+ async #stop({ preserveError = false } = {}) {
911
+ const abortController = this.#abortController;
912
+ if (this.#abortController === abortController) this.#abortController = null;
913
+ abortController?.abort(new DOMException('Feishu runtime stopped', 'AbortError'));
914
+
915
+ const starting = this.#starting;
916
+ if (starting) await starting.catch(() => undefined);
917
+ return this.#cleanup({ preserveError, abortController });
918
+ }
919
+
920
+ async #cleanup({ preserveError = false, abortController } = {}) {
921
+ const error = preserveError ? this.#status.lastError : null;
922
+ const diagnostic = preserveError ? this.#status.error : null;
923
+ if (this.#abortController === abortController) this.#abortController = null;
924
+ abortController?.abort(new DOMException('Feishu runtime stopped', 'AbortError'));
925
+ for (const probe of this.#pendingCardActionProbes.values()) {
926
+ clearTimeout(probe.timeout);
927
+ void this.#sendCardActionProbeNotice(
928
+ probe.expectedOperatorOpenId,
929
+ t(CALLBACK_PROBE_ABORT_NOTICE),
930
+ 'abort',
931
+ );
932
+ probe.reject(probeError('abort', '飞书运行时已停止'));
933
+ }
934
+ this.#pendingCardActionProbes.clear();
935
+ this.#status.ready = false;
936
+ const wsClient = this.#wsClient;
937
+ this.#wsClient = null;
938
+ wsClient?.close({ force: true });
939
+ const bridge = this.#bridge;
940
+ this.#bridge = null;
941
+ if (bridge) await bridge.waitForIdle();
942
+ this.#client = null;
943
+ this.#status.feishuLongConnectionState = preserveError ? 'failed' : 'idle';
944
+ this.#status.slashCommandRegistration = 'idle';
945
+ this.#status.error = diagnostic;
946
+ this.#status.lastError = error;
947
+ if (!preserveError) this.#diagnostics.clear();
948
+ return this.status;
949
+ }
950
+ }