@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,1623 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ import { createDeferredDeliveryCoordinator, deferredOutcomeText } from './deferred-delivery-coordinator.mjs';
4
+ import { t } from './i18n.mjs';
5
+ import { commandHelpLines } from './command-catalog.mjs';
6
+ import {
7
+ COMMAND_PERMISSION_DENIED_MESSAGE,
8
+ evaluateInboundAccess,
9
+ } from './inbound-access.mjs';
10
+ import {
11
+ captureContextEnhancement,
12
+ captureContextEnhancementSource,
13
+ enhanceContextContent,
14
+ } from './context-enhancement.mjs';
15
+ import { runWorkspaceCommand } from './workspace-command.mjs';
16
+ import { runCompactCommand } from './compact-command.mjs';
17
+ import { isHistoryCommand, runHistoryCommand } from './history-command.mjs';
18
+ import {
19
+ isControlCommand,
20
+ runControlCommand,
21
+ } from './control-command.mjs';
22
+ import {
23
+ rememberConnectionTestTarget,
24
+ sendRememberedConnectionTest,
25
+ } from './connection-test.mjs';
26
+ import {
27
+ isModelCommand,
28
+ runModelCommand,
29
+ } from './model-command.mjs';
30
+ import {
31
+ isPresetCommand,
32
+ runPresetCommand,
33
+ } from './preset-command.mjs';
34
+ import { askInWorkspaceSession } from './workspace-session.mjs';
35
+ import { HarnessApprovalQueue } from './harness-approval.mjs';
36
+ import {
37
+ BatchInputManager,
38
+ batchInputBusyMessage,
39
+ batchInputGroupUnsupportedMessage,
40
+ isBatchInputCommand,
41
+ } from './batch-input.mjs';
42
+ import {
43
+ hasInboundImages,
44
+ imagePromptDiagnostic,
45
+ imagePromptUserMessage,
46
+ } from './image-prompt.mjs';
47
+ import {
48
+ hasInboundFiles,
49
+ inboundFileUserMessage,
50
+ } from './inbound-file.mjs';
51
+ import {
52
+ harnessAnswerForQuestion,
53
+ harnessQuestionText,
54
+ validHarnessQuestion,
55
+ } from './harness-question.mjs';
56
+ import { deliverOutboundArtifacts } from './semantic/artifact-delivery.mjs';
57
+ import {
58
+ hasReplyReference,
59
+ promptContentForInboundMessage,
60
+ } from './semantic/reply-reference.mjs';
61
+ import {
62
+ createDeliveryReceipt,
63
+ createTextDeliveryBlock,
64
+ providerMessageIdsFor,
65
+ } from './semantic/delivery.mjs';
66
+ import {
67
+ messageFailureDiagnostic,
68
+ channelDeliveryFailure,
69
+ clearLastMessageFailure,
70
+ messageFailureText,
71
+ setLastMessageFailure,
72
+ } from './message-failure.mjs';
73
+ import { beginStatusReaction } from './status-reaction.mjs';
74
+
75
+ const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
76
+ const FILE_ONLY_COMPLETION_TEXT = '任务已完成。';
77
+
78
+ /**
79
+ * How many times one inbound message may be re-delivered after a failed turn.
80
+ *
81
+ * A failure releases the message's `markSeen` so the next poll retries it, which
82
+ * would otherwise loop forever on a mail that always fails. After this many
83
+ * attempts the mark stays and the message is treated as handled.
84
+ */
85
+ const MAX_DELIVERY_ATTEMPTS = 3;
86
+
87
+ function cleanText(value) {
88
+ return typeof value === 'string' ? value.trim() : '';
89
+ }
90
+
91
+ function canClaimInteractionReply(message, pending, senderId) {
92
+ return pending.actor === senderId
93
+ && (message.kind !== 'group' || message.addressed === true)
94
+ && !hasInboundImages(message)
95
+ && !hasInboundFiles(message)
96
+ && Boolean(controlTextOf(message));
97
+ }
98
+
99
+ function artifactFailureText(fileName, error, descriptor) {
100
+ const name = String(fileName ?? t('结果文件'))
101
+ .replace(/[\r\n]+/g, ' ')
102
+ .trim()
103
+ .slice(0, 255) || t('结果文件');
104
+ switch (error?.code) {
105
+ case 'artifact-delivery-uncertain':
106
+ return t('结果文件「{name}」的发送结果未能确认,请先检查聊天内是否已收到,不要立即重试。', { name });
107
+ case 'artifact-permission-required':
108
+ if (descriptor?.key === 'slack') {
109
+ return t('结果文件「{name}」已生成,但 Slack 应用缺少 files:write 权限。请更新 Manifest、重新安装应用并重新连接机器人后重试。', { name });
110
+ }
111
+ if (descriptor?.key === 'discord') {
112
+ return t('结果文件「{name}」已生成,但机器人缺少 Discord 的 Send Messages、Attach Files 或 Read Message History 权限。', { name });
113
+ }
114
+ if (descriptor?.key === 'telegram') {
115
+ return t('结果文件「{name}」已生成,但 Telegram 不允许机器人在当前聊天发送文档,请检查聊天权限。', { name });
116
+ }
117
+ if (descriptor?.key === 'matrix') {
118
+ return t('结果文件「{name}」已生成,但 Matrix homeserver 拒绝了媒体上传,请检查其媒体大小限制与上传权限。', { name });
119
+ }
120
+ return t('结果文件「{name}」已生成,但当前机器人没有文件发送权限,请检查渠道权限。', { name });
121
+ case 'artifact-too-large':
122
+ return t('结果文件「{name}」超过当前渠道大小上限,未发送。', { name });
123
+ case 'artifact-empty':
124
+ return t('结果文件「{name}」为空,未发送。', { name });
125
+ case 'artifact-invalid':
126
+ case 'artifact-changed':
127
+ case 'artifact-unavailable':
128
+ return t('结果文件「{name}」暂时无法读取或准备发送,请确认文件仍可访问后重试。', { name });
129
+ case 'artifact-rate-limited':
130
+ return t('结果文件「{name}」暂时被当前渠道限流,未能发送,请稍后重试。', { name });
131
+ case 'artifact-provider-rejected':
132
+ return t('结果文件「{name}」已生成,但当前渠道拒绝了该文件或文件消息。', { name });
133
+ default:
134
+ return t('结果文件「{name}」已生成,但当前渠道暂时未能发送,请稍后重试。', { name });
135
+ }
136
+ }
137
+
138
+ export function createTextBridgeStatus() {
139
+ return {
140
+ messagesReceived: 0,
141
+ messagesReplied: 0,
142
+ messagesRejected: 0,
143
+ lastMessageAt: null,
144
+ lastReplyAt: null,
145
+ lastRejectedAt: null,
146
+ lastError: null,
147
+ lastMessageError: null,
148
+ reactionsAdded: 0,
149
+ reactionsRemoved: 0,
150
+ reactionErrors: 0,
151
+ };
152
+ }
153
+
154
+ /**
155
+ * The text a channel's control commands and approval decisions are parsed from.
156
+ *
157
+ * A channel may decorate `content` for the model — the email channel prepends
158
+ * the mail headers so a subject line reaches the model — while `controlText`
159
+ * keeps the undecorated body. Without this a decorated message made `/help`
160
+ * and "批准" unrecognisable.
161
+ */
162
+ function controlTextOf(message) {
163
+ return cleanText(message?.controlText ?? message?.content);
164
+ }
165
+
166
+ export class TextHarnessBridge {
167
+ #descriptor;
168
+ #bot;
169
+ #harness;
170
+ #state;
171
+ #deferred;
172
+ #contextEnhancement;
173
+ #accessPolicy;
174
+ #thinkingTraces;
175
+ #status;
176
+ #logger;
177
+ #replyTimeoutMs;
178
+ #signal;
179
+ #keepaliveIntervalMs;
180
+ #queues = new Map();
181
+ #pendingInteractions = new Map();
182
+ #interactionKeys = new Map();
183
+ // Keep the accepted configuration through the existing queue/reply lifecycle.
184
+ #acceptedMessageIds = new Map();
185
+ #approvalTasks = new Set();
186
+ #commandTasks = new Set();
187
+ #approvals;
188
+ #batches = new BatchInputManager();
189
+ #interactionCard;
190
+ // Delivery attempts per message id. A failed turn releases its `markSeen` so
191
+ // the next poll can retry, and this counter is what keeps that from becoming
192
+ // an infinite loop on a mail that always fails.
193
+ #deliveryAttempts = new Map();
194
+
195
+ constructor({
196
+ descriptor,
197
+ bot,
198
+ harness,
199
+ state,
200
+ contextEnhancement,
201
+ accessPolicy,
202
+ thinkingTraces = false,
203
+ status = createTextBridgeStatus(),
204
+ logger = console,
205
+ replyTimeoutMs = 600_000,
206
+ signal,
207
+ keepaliveIntervalMs = 4_000,
208
+ interactionCard = null,
209
+ }) {
210
+ if (!descriptor?.key || !descriptor?.label) throw new TypeError('A channel descriptor is required');
211
+ if (!bot || typeof bot.sendText !== 'function') throw new TypeError('A bot client is required');
212
+ if (!harness || !state) throw new TypeError('Harness client and state store are required');
213
+ this.#descriptor = descriptor;
214
+ this.#bot = bot;
215
+ this.#harness = harness;
216
+ this.#state = state;
217
+ this.#contextEnhancement = contextEnhancement;
218
+ this.#accessPolicy = accessPolicy;
219
+ this.#thinkingTraces = thinkingTraces;
220
+ this.#status = status;
221
+ this.#logger = logger;
222
+ this.#replyTimeoutMs = replyTimeoutMs;
223
+ this.#signal = signal;
224
+ this.#keepaliveIntervalMs = keepaliveIntervalMs;
225
+ this.#interactionCard = interactionCard ?? null;
226
+ this.#deferred = createDeferredDeliveryCoordinator({ harness, state, signal, logger,
227
+ deliver: (entry, outcome) => this.#deliverDeferredOutcome(entry, outcome),
228
+ });
229
+ this.#approvals = new HarnessApprovalQueue({
230
+ label: descriptor.key,
231
+ logger,
232
+ });
233
+ }
234
+
235
+ get status() {
236
+ return structuredClone(this.#status);
237
+ }
238
+
239
+ accept(message, { contextSnapshot, accessDecision } = {}) {
240
+ if (this.#signal?.aborted) return Promise.resolve();
241
+ const conversationId = cleanText(message?.conversationId);
242
+ const kind = message?.kind === 'group' ? 'group' : 'direct';
243
+ const normalized = { ...message, kind, conversationId };
244
+ const messageId = cleanText(normalized.messageId);
245
+ const senderId = cleanText(normalized.senderId);
246
+ if (!messageId || !senderId || !conversationId || normalized.senderIsBot === true
247
+ || this.#state.hasSeen(messageId) || this.#acceptedMessageIds.has(messageId)) {
248
+ return Promise.resolve();
249
+ }
250
+ // Preserve the channel trigger boundary. Access policy never turns an
251
+ // unaddressed group message into a denial reply.
252
+ if (kind === 'group' && normalized.addressed !== true) {
253
+ this.#status.messagesRejected += 1;
254
+ this.#status.lastRejectedAt = new Date().toISOString();
255
+ this.#acceptedMessageIds.set(messageId, null);
256
+ return this.#finishLocalMessage(normalized, messageId, null);
257
+ }
258
+ if (this.#accessPolicy || accessDecision) {
259
+ const hasImages = hasInboundImages(normalized);
260
+ const hasFiles = hasInboundFiles(normalized);
261
+ const decision = accessDecision ?? evaluateInboundAccess(this.#accessPolicy, {
262
+ conversationType: kind,
263
+ senderIds: [senderId, cleanText(normalized.senderAlternateId)].filter(Boolean),
264
+ // The same control text the command runner below parses. A channel may
265
+ // decorate `content` for the model (email prepends the mail headers), and
266
+ // a decorated body never looks like a command — so reading `content` here
267
+ // recognized no command at all and skipped the command-permission gate.
268
+ text: controlTextOf(normalized),
269
+ hasImages,
270
+ hasFiles,
271
+ });
272
+ if (!decision.allowed) {
273
+ this.#status.messagesRejected += 1;
274
+ this.#status.lastRejectedAt = new Date().toISOString();
275
+ // Mark policy denials so a webhook replay cannot repeat local work or
276
+ // a command-permission notice.
277
+ this.#acceptedMessageIds.set(messageId, null);
278
+ return this.#finishLocalMessage(
279
+ normalized,
280
+ messageId,
281
+ decision.reason === 'command-not-allowed'
282
+ ? t(COMMAND_PERMISSION_DENIED_MESSAGE)
283
+ : null,
284
+ { recordReceived: decision.reason === 'command-not-allowed' },
285
+ );
286
+ }
287
+ }
288
+ this.#acceptedMessageIds.set(messageId, contextSnapshot === undefined
289
+ ? captureContextEnhancement(this.#contextEnhancement, message?.kind)
290
+ : contextSnapshot);
291
+ const statusReaction = beginStatusReaction({
292
+ adapter: this.#bot,
293
+ target: normalized.kind === 'direct' || normalized.addressed === true
294
+ ? normalized.reactionTarget
295
+ : null,
296
+ reactions: this.#descriptor.reactions,
297
+ status: this.#status,
298
+ logger: this.#logger,
299
+ label: this.#descriptor.key,
300
+ });
301
+ normalized.statusReaction = statusReaction;
302
+
303
+ const processing = this.#acceptAcceptedMessage(normalized, messageId, senderId);
304
+ void processing.then(
305
+ () => statusReaction.success(),
306
+ () => statusReaction.error(),
307
+ );
308
+ return processing;
309
+ }
310
+
311
+ #acceptAcceptedMessage(normalized, messageId, senderId) {
312
+ if (normalized.kind === 'direct') {
313
+ rememberConnectionTestTarget(
314
+ this.#state,
315
+ normalized.connectionTestTarget ?? normalized.replyTarget,
316
+ );
317
+ }
318
+
319
+ const key = `${normalized.kind}:${normalized.conversationId}`;
320
+ const pending = this.#pendingInteractions.get(key);
321
+ const text = controlTextOf(normalized);
322
+ const batchCommand = isBatchInputCommand(text);
323
+ if (batchCommand && normalized.kind === 'group' && normalized.addressed === true) {
324
+ return this.#finishLocalMessage(
325
+ normalized,
326
+ messageId,
327
+ batchInputGroupUnsupportedMessage(),
328
+ );
329
+ }
330
+ if (batchCommand && normalized.kind === 'direct') {
331
+ const exactBatch = /^\/batch$/iu.test(text);
332
+ if (exactBatch && (
333
+ this.#queues.has(key)
334
+ || Boolean(pending)
335
+ || this.#approvals.hasPending(key)
336
+ )) {
337
+ return this.#finishLocalMessage(normalized, messageId, batchInputBusyMessage());
338
+ }
339
+ const batch = this.#batches.handle(key, text, {
340
+ plainText: Boolean(text)
341
+ && normalized.plainText !== false
342
+ && !hasInboundImages(normalized)
343
+ && !hasInboundFiles(normalized)
344
+ && !hasReplyReference(normalized),
345
+ });
346
+ if (batch.handled) {
347
+ if (batch.kind === 'submit') {
348
+ return this.#enqueueMessage({
349
+ ...normalized,
350
+ content: batch.prompt,
351
+ // The submission is exactly the collected text; a quote or an
352
+ // attachment on the command itself is not part of it.
353
+ replyTo: null,
354
+ images: [],
355
+ files: [],
356
+ batchSubmission: { token: batch.token, title: batch.title },
357
+ }, messageId, senderId, key);
358
+ }
359
+ return this.#finishLocalMessage(normalized, messageId, batch.message);
360
+ }
361
+ } else if (normalized.kind === 'direct'
362
+ && this.#batches.status(key).phase === 'collecting') {
363
+ const batch = this.#batches.handle(key, text, {
364
+ plainText: Boolean(text)
365
+ && normalized.plainText !== false
366
+ && !hasInboundImages(normalized)
367
+ && !hasInboundFiles(normalized)
368
+ && !hasReplyReference(normalized),
369
+ });
370
+ if (batch.handled) {
371
+ return this.#finishLocalMessage(normalized, messageId, batch.message);
372
+ }
373
+ }
374
+ const collectingBatch = normalized.kind === 'direct'
375
+ && this.#batches.status(key).phase === 'collecting';
376
+ const commandRunner = collectingBatch ? null : isHistoryCommand(text) ? runHistoryCommand
377
+ : hasInboundFiles(normalized) ? null : isControlCommand(text)
378
+ ? runControlCommand
379
+ : (isModelCommand(text)
380
+ ? runModelCommand
381
+ : (isPresetCommand(text) ? runPresetCommand : null));
382
+ if (commandRunner && (normalized.kind !== 'group' || normalized.addressed === true)) {
383
+ let task;
384
+ task = this.#processFastCommand(
385
+ normalized,
386
+ messageId,
387
+ key,
388
+ commandRunner,
389
+ senderId,
390
+ ).finally(() => {
391
+ this.#acceptedMessageIds.delete(messageId);
392
+ this.#commandTasks.delete(task);
393
+ });
394
+ this.#commandTasks.add(task);
395
+ return task;
396
+ }
397
+ const approval = this.#approvals.claimReply({
398
+ key,
399
+ actor: senderId,
400
+ messageId,
401
+ // Approval decisions are parsed from the control text, exactly like the
402
+ // commands above: a decorated `content` hid "批准" behind the mail headers,
403
+ // so a plain-body approval never claimed its pending request.
404
+ text: hasInboundImages(normalized) || hasInboundFiles(normalized)
405
+ ? ''
406
+ : controlTextOf(normalized),
407
+ addressed: normalized.kind !== 'group' || normalized.addressed === true,
408
+ hasPendingQuestion: Boolean(pending),
409
+ questionCompletion: pending?.submitting || pending?.claimedReplyMessageId
410
+ ? pending.queue
411
+ : null,
412
+ isQuestionPending: () => this.#pendingInteractions.has(key),
413
+ send: (text) => this.#bot.sendText(normalized.replyTarget, text),
414
+ });
415
+ if (approval) {
416
+ let task;
417
+ task = approval.process(async () => {
418
+ if (this.#state.hasSeen(messageId)) return false;
419
+ await this.#state.markSeen(messageId);
420
+ this.#status.messagesReceived += 1;
421
+ this.#status.lastMessageAt = new Date().toISOString();
422
+ return true;
423
+ })
424
+ .finally(() => {
425
+ this.#acceptedMessageIds.delete(messageId);
426
+ this.#approvalTasks.delete(task);
427
+ });
428
+ this.#approvalTasks.add(task);
429
+ return task;
430
+ }
431
+ if (pending && pending.actor !== senderId) {
432
+ return this.#enqueueMessage(normalized, messageId, senderId, key);
433
+ }
434
+ if (pending?.submitting || pending?.claimedReplyMessageId) {
435
+ return this.#enqueueMessage(normalized, messageId, senderId, key);
436
+ }
437
+ if (pending) {
438
+ if (canClaimInteractionReply(normalized, pending, senderId)) {
439
+ pending.claimedReplyMessageId = messageId;
440
+ }
441
+ const previous = pending.queue ?? Promise.resolve();
442
+ const current = previous
443
+ .catch(() => undefined)
444
+ .then(() => this.#processInteractionReply(
445
+ normalized,
446
+ messageId,
447
+ senderId,
448
+ key,
449
+ pending,
450
+ ))
451
+ .finally(() => {
452
+ this.#acceptedMessageIds.delete(messageId);
453
+ if (pending.claimedReplyMessageId === messageId) {
454
+ pending.claimedReplyMessageId = null;
455
+ }
456
+ if (pending.queue === current) pending.queue = null;
457
+ });
458
+ pending.queue = current;
459
+ return current;
460
+ }
461
+ return this.#enqueueMessage(normalized, messageId, senderId, key);
462
+ }
463
+
464
+ #finishLocalMessage(message, messageId, reply, { recordReceived = true } = {}) {
465
+ let task;
466
+ task = (async () => {
467
+ if (this.#state.hasSeen(messageId)) return;
468
+ await this.#state.markSeen(messageId);
469
+ if (recordReceived) {
470
+ this.#status.messagesReceived += 1;
471
+ this.#status.lastMessageAt = new Date().toISOString();
472
+ }
473
+ if (reply) await this.#bot.sendText(message.replyTarget, reply);
474
+ this.#status.lastError = null;
475
+ })().catch(async (error) => {
476
+ if (this.#signal?.aborted) {
477
+ message.statusReaction?.clear();
478
+ return;
479
+ }
480
+ message.statusReaction?.error();
481
+ this.#status.lastError = error?.message ?? String(error);
482
+ const failure = setLastMessageFailure(this.#status, error);
483
+ this.#logger.error?.(
484
+ `[dsh-im:${this.#descriptor.key}] failed to process a batch input message [${failure.referenceId}]:`,
485
+ messageFailureDiagnostic(error, failure),
486
+ );
487
+ }).finally(() => {
488
+ this.#acceptedMessageIds.delete(messageId);
489
+ this.#commandTasks.delete(task);
490
+ });
491
+ this.#commandTasks.add(task);
492
+ return task;
493
+ }
494
+
495
+ #enqueueMessage(message, messageId, senderId, key, {
496
+ releaseMessageId = true,
497
+ alreadyRecorded = false,
498
+ } = {}) {
499
+ const previous = this.#queues.get(key) ?? Promise.resolve();
500
+ const current = previous
501
+ .catch(() => undefined)
502
+ .then(() => this.#process(
503
+ message,
504
+ messageId,
505
+ senderId,
506
+ key,
507
+ { alreadyRecorded },
508
+ ))
509
+ .finally(() => {
510
+ if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
511
+ if (this.#queues.get(key) === current) this.#queues.delete(key);
512
+ });
513
+ this.#queues.set(key, current);
514
+ return current;
515
+ }
516
+
517
+ async #deliverDeferredOutcome(entry, outcome) {
518
+ const text = deferredOutcomeText(outcome);
519
+ return typeof this.#bot.sendDelivery === 'function'
520
+ ? this.#bot.sendDelivery(entry.target, createTextDeliveryBlock(text, outcome.found ? 'markdown' : 'plain'))
521
+ : this.#bot.sendText(entry.target, text);
522
+ }
523
+
524
+ async waitForIdle() {
525
+ await Promise.allSettled([
526
+ ...this.#queues.values(),
527
+ ...[...this.#pendingInteractions.values()].flatMap((pending) => (
528
+ pending.queue ? [pending.queue] : []
529
+ )),
530
+ ...this.#approvalTasks,
531
+ ...this.#commandTasks,
532
+ ]);
533
+ await this.#deferred.whenIdle();
534
+ }
535
+
536
+ async #processFastCommand(message, messageId, key, runner, senderId) {
537
+ if (this.#state.hasSeen(messageId)) return;
538
+ await this.#state.markSeen(messageId);
539
+ this.#status.messagesReceived += 1;
540
+ this.#status.lastMessageAt = new Date().toISOString();
541
+ const target = message.replyTarget;
542
+ try {
543
+ const result = await runner(
544
+ controlTextOf(message),
545
+ this.#harness,
546
+ this.#state,
547
+ key,
548
+ {
549
+ signal: this.#signal,
550
+ isDirect: message.kind === 'direct',
551
+ hasImages: hasInboundImages(message),
552
+ hasFiles: hasInboundFiles(message),
553
+ pendingInteraction: this.#pendingInteractions.has(key)
554
+ || this.#approvals.hasPending(key),
555
+ control: { owner: this, key },
556
+ deferredDelivery: this.#deferred,
557
+ enhancement: captureContextEnhancementSource(
558
+ this.#contextEnhancement,
559
+ message.kind,
560
+ () => {
561
+ const source = message.contextSource?.();
562
+ return {
563
+ channel: this.#descriptor.key,
564
+ senderId,
565
+ senderName: source?.senderName,
566
+ conversationTitle: source?.conversationTitle,
567
+ chatId: source?.chatId ?? message.conversationId,
568
+ threadId: source?.threadId,
569
+ };
570
+ },
571
+ ),
572
+ },
573
+ );
574
+ if (result?.stopped) {
575
+ await Promise.allSettled([
576
+ this.#cancelPendingInteraction(key),
577
+ this.#approvals.closeRoute(key),
578
+ ]);
579
+ }
580
+ for (const reply of result?.messages ?? [result?.message]) {
581
+ if (reply) await this.#bot.sendText(target, reply);
582
+ }
583
+ this.#status.lastError = null;
584
+ } catch (error) {
585
+ if (error?.code === 'turn-stopped' || this.#signal?.aborted) {
586
+ message.statusReaction?.clear();
587
+ return;
588
+ }
589
+ message.statusReaction?.error();
590
+ this.#status.lastError = error?.message ?? String(error);
591
+ const failure = setLastMessageFailure(this.#status, error);
592
+ this.#logger.error?.(
593
+ `[dsh-im:${this.#descriptor.key}] failed to process a command [${failure.referenceId}]:`,
594
+ messageFailureDiagnostic(error, failure),
595
+ );
596
+ await this.#bot.sendText(target, messageFailureText(failure)).catch(() => undefined);
597
+ }
598
+ }
599
+
600
+ sendConnectionTest(text) {
601
+ return sendRememberedConnectionTest({
602
+ state: this.#state,
603
+ text,
604
+ channelLabel: t('{label}机器人', { label: this.#descriptor.label }),
605
+ send: (target, message) => this.#bot.sendText(target, message),
606
+ });
607
+ }
608
+
609
+ sendProactiveText(target, text, { signal } = {}) {
610
+ signal?.throwIfAborted();
611
+ return this.#bot.sendText(target, text);
612
+ }
613
+
614
+ async #deliverArtifacts(target, replyTo, artifacts = [], baseReceipt) {
615
+ const delivery = await deliverOutboundArtifacts({
616
+ artifacts,
617
+ baseReceipt,
618
+ deliveryId: replyTo,
619
+ channelKey: this.#descriptor.key,
620
+ signal: this.#signal,
621
+ sendImage: typeof this.#bot.sendImage === 'function'
622
+ ? (file) => this.#bot.sendImage(target, file)
623
+ : undefined,
624
+ sendFile: typeof this.#bot.sendFile === 'function'
625
+ ? (file) => this.#bot.sendFile(target, file)
626
+ : undefined,
627
+ onFailure: (artifact, error) => setLastMessageFailure(this.#status, error, {
628
+ userMessage: artifactFailureText(artifact?.fileName, error, this.#descriptor),
629
+ reason: error?.code,
630
+ }),
631
+ sendFailureNotice: (_artifact, _error, failure) => this.#bot.sendText(
632
+ target,
633
+ messageFailureText(failure),
634
+ ),
635
+ logger: this.#logger,
636
+ });
637
+ this.#status.artifactsSent = (this.#status.artifactsSent ?? 0)
638
+ + delivery.artifactsSent;
639
+ this.#status.artifactSendErrors = (this.#status.artifactSendErrors ?? 0)
640
+ + delivery.artifactSendErrors;
641
+ return {
642
+ receipt: delivery.receipt,
643
+ userVisible: delivery.userVisible,
644
+ artifactSendErrors: delivery.artifactSendErrors,
645
+ };
646
+ }
647
+
648
+ async #process(message, messageId, senderId, conversationKey, {
649
+ alreadyRecorded = false,
650
+ } = {}) {
651
+ if (!alreadyRecorded) {
652
+ if (this.#state.hasSeen(messageId)) return;
653
+ await this.#state.markSeen(messageId);
654
+ this.#status.messagesReceived += 1;
655
+ this.#status.lastMessageAt = new Date().toISOString();
656
+ }
657
+
658
+ const target = message.replyTarget;
659
+ const text = controlTextOf(message);
660
+ const batchSubmission = message.batchSubmission;
661
+ let stream = null;
662
+ let semanticStream = false;
663
+ // Thinking streams accept the same delivery-block contract as semantic
664
+ // streams: finish() must receive { text, format } so a markdown answer
665
+ // renders rich instead of falling back to plain text.
666
+ let thinkingStream = false;
667
+ // A keepalive heartbeat keeps short-lived carriers (e.g. Telegram's
668
+ // private-chat Rich Draft) visible during long silent stretches such as a
669
+ // running tool call. Declared outside the try so every exit path (including
670
+ // pre-prompt failures like image parsing) clears the timer.
671
+ let keepaliveTimer = null;
672
+ const stopKeepalive = () => {
673
+ if (keepaliveTimer !== null) clearInterval(keepaliveTimer);
674
+ keepaliveTimer = null;
675
+ };
676
+ try {
677
+ this.#signal?.throwIfAborted();
678
+ if (message.kind === 'group' && message.addressed !== true) {
679
+ this.#status.messagesRejected += 1;
680
+ this.#status.lastRejectedAt = new Date().toISOString();
681
+ return;
682
+ }
683
+ const hasImages = hasInboundImages(message);
684
+ const hasFiles = hasInboundFiles(message);
685
+ const hasReply = hasReplyReference(message);
686
+ if (!text && !hasImages && !hasFiles && !hasReply) {
687
+ await this.#bot.sendText(target, t('目前支持文字、图片和文件消息。'));
688
+ return;
689
+ }
690
+ const command = text.toLowerCase();
691
+ if (!hasImages && !hasFiles && command === '/help') {
692
+ await this.#bot.sendText(target, [
693
+ t('{label}机器人已连接 DeepSeek Harness。', { label: this.#descriptor.label }),
694
+ '',
695
+ t('直接发送文字、图片或文件即可继续当前会话。'),
696
+ ...commandHelpLines(this.#descriptor.key),
697
+ ].join('\n'));
698
+ return;
699
+ }
700
+ if (!hasImages && !hasFiles && command === '/status') {
701
+ await this.#harness.ensureRunning({ signal: this.#signal });
702
+ await this.#bot.sendText(target, t('{label}机器人与 DeepSeek Harness 连接正常。', { label: this.#descriptor.label }));
703
+ return;
704
+ }
705
+ const workspaceCommand = !hasImages && !hasFiles
706
+ ? await runWorkspaceCommand(text, this.#harness, conversationKey)
707
+ : null;
708
+ if (workspaceCommand) {
709
+ for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
710
+ await this.#bot.sendText(target, reply);
711
+ }
712
+ return;
713
+ }
714
+ if (!hasImages && !hasFiles && command === '/new') {
715
+ await this.#state.clearSession(conversationKey);
716
+ await this.#bot.sendText(target, t('已开启新会话。请发送你的问题。'));
717
+ return;
718
+ }
719
+ const compactCommand = !hasImages && !hasFiles
720
+ ? await runCompactCommand(
721
+ text,
722
+ this.#harness,
723
+ this.#state,
724
+ conversationKey,
725
+ { signal: this.#signal },
726
+ )
727
+ : null;
728
+ if (compactCommand) {
729
+ await this.#bot.sendText(target, compactCommand.message);
730
+ return;
731
+ }
732
+
733
+ await this.#bot.sendTyping?.(target).catch((error) => {
734
+ this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] typing indicator failed:`, error);
735
+ });
736
+ let streamFinished = false;
737
+ if (this.#thinkingTraces && typeof this.#bot.openThinkingStream === 'function') {
738
+ try {
739
+ stream = await this.#bot.openThinkingStream(target);
740
+ thinkingStream = true;
741
+ } catch (error) {
742
+ stream = null;
743
+ this.#logger.warn?.(
744
+ `[dsh-im:${this.#descriptor.key}] unable to start a thinking stream; using final delivery:`,
745
+ error,
746
+ );
747
+ }
748
+ }
749
+ if (!stream) {
750
+ if (typeof this.#bot.openDeliveryStream === 'function') {
751
+ try {
752
+ stream = await this.#bot.openDeliveryStream(target);
753
+ semanticStream = true;
754
+ } catch (error) {
755
+ this.#logger.warn?.(
756
+ `[dsh-im:${this.#descriptor.key}] unable to start a semantic reply stream; using final delivery:`,
757
+ error,
758
+ );
759
+ }
760
+ } else if (typeof this.#bot.openStream === 'function') {
761
+ try {
762
+ stream = await this.#bot.openStream(target);
763
+ } catch (error) {
764
+ this.#logger.warn?.(
765
+ `[dsh-im:${this.#descriptor.key}] unable to start a streamed reply; using text:`,
766
+ error,
767
+ );
768
+ }
769
+ }
770
+ }
771
+ const thinkingMode = Boolean(stream
772
+ && this.#thinkingTraces
773
+ && typeof stream.sendToolTrace === 'function');
774
+ // What the model sees. A message may carry two texts: `controlText`, the
775
+ // plain body the parsers read, and `content`, the same body decorated for
776
+ // the model — the email channel prefixes the mail headers there, so a
777
+ // subject-only instruction is not silently dropped. Falling back to the
778
+ // parsed text kept commands working but lost that decoration entirely.
779
+ let content = hasImages || hasReply
780
+ ? await promptContentForInboundMessage(message, { signal: this.#signal, deferImages: true })
781
+ : cleanText(message.content) || undefined;
782
+ const snapshot = this.#acceptedMessageIds.get(messageId);
783
+ let contextEnhanced = false;
784
+ if (snapshot) {
785
+ const originalContent = content ?? text;
786
+ const contextSource = message.contextSource?.();
787
+ content = enhanceContextContent(originalContent, snapshot, () => ({
788
+ channel: this.#descriptor.key,
789
+ senderId,
790
+ senderName: contextSource?.senderName,
791
+ conversationTitle: contextSource?.conversationTitle,
792
+ chatId: contextSource?.chatId ?? message.conversationId,
793
+ threadId: contextSource?.threadId,
794
+ }));
795
+ contextEnhanced = content !== originalContent;
796
+ }
797
+ // Start the keepalive only after the inbound payload is ready, so a
798
+ // pre-prompt failure (image parsing, context building) cannot leave the
799
+ // timer running; the outermost finally below clears it on every path.
800
+ if (stream && stream.keepalive === true && typeof stream.refresh === 'function') {
801
+ let refreshing = false;
802
+ keepaliveTimer = setInterval(async () => {
803
+ // Skip ticks while the previous heartbeat is pending so redundant
804
+ // refreshes cannot queue ahead of the final answer on a slow network.
805
+ if (refreshing) return;
806
+ refreshing = true;
807
+ try {
808
+ await Promise.allSettled([
809
+ this.#bot.sendTyping?.(target),
810
+ stream.refresh(),
811
+ ]);
812
+ } catch {
813
+ // Keepalive is best-effort, including synchronous adapter failures.
814
+ } finally {
815
+ refreshing = false;
816
+ }
817
+ }, this.#keepaliveIntervalMs);
818
+ keepaliveTimer.unref?.();
819
+ }
820
+ const { answer, artifacts = [] } = await askInWorkspaceSession({
821
+ deferredDelivery: () => ({ coordinator: this.#deferred, target: this.#descriptor.key === 'whatsapp' ? { jid: target.jid, selfChat: target.selfChat } : target }),
822
+ harness: this.#harness,
823
+ state: this.#state,
824
+ key: conversationKey,
825
+ text,
826
+ content,
827
+ titleText: batchSubmission?.title,
828
+ sourceGuidance: snapshot?.config?.guidance,
829
+ contextEnhanced,
830
+ createOptions: this.#signal ? { signal: this.#signal } : undefined,
831
+ existsOptions: this.#signal ? { signal: this.#signal } : undefined,
832
+ askOptions: {
833
+ timeoutMs: this.#replyTimeoutMs,
834
+ signal: this.#signal,
835
+ control: { owner: this, key: conversationKey },
836
+ // Thinking mode needs every update (reasoning + tool calls) in
837
+ // order; latest mode filters as before. Only thinking mode subscribes
838
+ // to reasoning updates, so default-mode consumers on other channels
839
+ // never see them (their progress handlers would render update.text).
840
+ progressMode: thinkingMode ? 'all' : undefined,
841
+ reasoning: thinkingMode,
842
+ onUpdate: stream ? async (update) => {
843
+ if (thinkingMode) {
844
+ // Only the 💭 and 🔧 lines are surfaced; status/text updates
845
+ // and the assistant-message canonical text are not.
846
+ if (update.type === 'reasoning') {
847
+ await stream.sendThinking(update.text);
848
+ } else if (update.type === 'tool') {
849
+ await stream.sendToolTrace(update.name, update.arguments);
850
+ }
851
+ return;
852
+ }
853
+ if (update.type === 'reasoning') return;
854
+ const progress = update.type === 'text' ? update.text
855
+ : update.type === 'tool' ? t('正在使用{name}…', { name: update.name }) : update.text;
856
+ if (progress) {
857
+ const format = update.type === 'text' ? 'markdown' : 'plain';
858
+ await stream.update(semanticStream
859
+ ? createTextDeliveryBlock(progress, format)
860
+ : progress);
861
+ }
862
+ } : undefined,
863
+ onInteraction: async (interaction) => {
864
+ if (stream?.keepalive === true && typeof stream.stopPreview === 'function') {
865
+ stopKeepalive();
866
+ await stream.stopPreview();
867
+ }
868
+ return this.#handleInteraction(interaction, {
869
+ key: conversationKey,
870
+ actor: senderId,
871
+ target,
872
+ requiresMention: message.kind === 'group' && message.requiresMention !== false,
873
+ });
874
+ },
875
+ onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
876
+ files: message.files,
877
+ images: message.images,
878
+ },
879
+ });
880
+ stopKeepalive();
881
+ if (batchSubmission) {
882
+ this.#batches.complete(conversationKey, batchSubmission.token);
883
+ }
884
+ const fileOnlyCompletion = !cleanText(answer) && artifacts.length > 0;
885
+ const visibleAnswer = fileOnlyCompletion
886
+ ? t(FILE_ONLY_COMPLETION_TEXT)
887
+ : answer;
888
+ const answerFormat = fileOnlyCompletion ? 'plain' : 'markdown';
889
+ let textDeliveryError = null;
890
+ let textReceipt = null;
891
+ if (stream) {
892
+ try {
893
+ const result = await stream.finish(semanticStream || thinkingStream
894
+ ? createTextDeliveryBlock(visibleAnswer, answerFormat)
895
+ : visibleAnswer);
896
+ streamFinished = true;
897
+ textReceipt = createDeliveryReceipt({
898
+ deliveryId: messageId,
899
+ presentation: result?.presentation
900
+ ?? stream.presentation
901
+ ?? `${this.#descriptor.key}-stream`,
902
+ providerMessageIds: [
903
+ ...providerMessageIdsFor(stream),
904
+ ...providerMessageIdsFor(result),
905
+ ],
906
+ deliveryOutcome: result?.deliveryOutcome,
907
+ reason: result?.reason,
908
+ });
909
+ } catch (error) {
910
+ stream.cancel?.();
911
+ this.#logger.warn?.(
912
+ `[dsh-im:${this.#descriptor.key}] streamed reply finalization failed; using text:`,
913
+ error,
914
+ );
915
+ }
916
+ }
917
+ if (!streamFinished) {
918
+ try {
919
+ const result = typeof this.#bot.sendDelivery === 'function'
920
+ ? await this.#bot.sendDelivery(
921
+ target,
922
+ createTextDeliveryBlock(visibleAnswer, answerFormat),
923
+ )
924
+ : await this.#bot.sendText(target, visibleAnswer);
925
+ textReceipt = createDeliveryReceipt({
926
+ deliveryId: messageId,
927
+ presentation: result?.presentation ?? `${this.#descriptor.key}-text`,
928
+ providerMessageIds: providerMessageIdsFor(result),
929
+ deliveryOutcome: result?.deliveryOutcome,
930
+ reason: result?.reason,
931
+ });
932
+ } catch (error) {
933
+ textDeliveryError = channelDeliveryFailure(error);
934
+ }
935
+ }
936
+ const finalDeliveryUnknown = textReceipt?.deliveryOutcome === 'unknown';
937
+ if (textReceipt?.deliveryOutcome === 'failed') {
938
+ textDeliveryError = channelDeliveryFailure(
939
+ new Error(`Final text delivery failed (${textReceipt.reason ?? 'unknown'})`),
940
+ { uncertain: false },
941
+ );
942
+ } else if (finalDeliveryUnknown) {
943
+ textDeliveryError = channelDeliveryFailure(
944
+ new Error(`Final text delivery outcome is unknown (${textReceipt.reason ?? 'unknown'})`),
945
+ );
946
+ }
947
+ // A failed final text must not discard an already registered result file.
948
+ // Settle the independent attachment path before surfacing the text error.
949
+ const delivery = await this.#deliverArtifacts(target, messageId, artifacts, textReceipt);
950
+ if (textDeliveryError && (!delivery.userVisible || finalDeliveryUnknown)) {
951
+ textDeliveryError.deliveryReceipt = delivery.receipt;
952
+ throw textDeliveryError;
953
+ }
954
+ if (textDeliveryError && delivery.artifactSendErrors === 0) {
955
+ setLastMessageFailure(this.#status, textDeliveryError);
956
+ }
957
+ if (delivery.userVisible) {
958
+ this.#status.messagesReplied += 1;
959
+ this.#status.lastReplyAt = new Date().toISOString();
960
+ this.#status.lastError = null;
961
+ if (!textDeliveryError && delivery.artifactSendErrors === 0) {
962
+ clearLastMessageFailure(this.#status);
963
+ }
964
+ }
965
+ // The turn produced an answer, so its retry budget is spent and reset.
966
+ this.#deliveryAttempts.delete(messageId);
967
+ return delivery.receipt;
968
+ } catch (error) {
969
+ stopKeepalive();
970
+ const turnStopped = error?.code === 'turn-stopped';
971
+ if (batchSubmission && turnStopped) {
972
+ this.#batches.complete(conversationKey, batchSubmission.token);
973
+ }
974
+ const failedBatch = batchSubmission && !turnStopped
975
+ ? this.#batches.fail(conversationKey, batchSubmission.token)
976
+ : null;
977
+ if (turnStopped) {
978
+ message.statusReaction?.clear();
979
+ if (stream) {
980
+ try {
981
+ await stream.finish(t('已停止。'));
982
+ } catch {
983
+ stream.cancel?.();
984
+ }
985
+ }
986
+ return;
987
+ }
988
+ if (this.#signal?.aborted) {
989
+ message.statusReaction?.clear();
990
+ stream?.cancel?.();
991
+ return;
992
+ }
993
+ message.statusReaction?.error();
994
+ this.#status.lastError = error?.message ?? String(error);
995
+ const presentStreamFailure = async (text) => {
996
+ const method = typeof stream?.fail === 'function'
997
+ ? 'fail'
998
+ : (typeof stream?.finish === 'function' ? 'finish' : null);
999
+ if (!method) return false;
1000
+ try {
1001
+ const result = await stream[method](text);
1002
+ return method === 'fail'
1003
+ ? Boolean(result) && result.deliveryOutcome !== 'failed'
1004
+ : result !== false && result?.deliveryOutcome !== 'failed';
1005
+ } catch (streamError) {
1006
+ this.#logger.warn?.(
1007
+ `[dsh-im:${this.#descriptor.key}] unable to finalize the failed stream:`,
1008
+ streamError,
1009
+ );
1010
+ return false;
1011
+ }
1012
+ };
1013
+ const imageErrorMessage = imagePromptUserMessage(error);
1014
+ const fileErrorMessage = inboundFileUserMessage(error);
1015
+ const failure = setLastMessageFailure(this.#status, error, {
1016
+ userMessage: fileErrorMessage ?? imageErrorMessage,
1017
+ reason: imagePromptDiagnostic(error)?.reason,
1018
+ });
1019
+ const failureText = failedBatch?.retained
1020
+ ? `${messageFailureText(failure)}\n\n${failedBatch.message}`
1021
+ : messageFailureText(failure);
1022
+ this.#logger.error?.(
1023
+ `[dsh-im:${this.#descriptor.key}] failed to process a message [${failure.referenceId}]:`,
1024
+ messageFailureDiagnostic(error, failure),
1025
+ );
1026
+ if (await presentStreamFailure(failureText)) {
1027
+ return error.deliveryReceipt;
1028
+ }
1029
+ stream?.cancel?.();
1030
+ try {
1031
+ await this.#bot.sendText(target, failureText);
1032
+ } catch (sendError) {
1033
+ this.#logger.error?.(
1034
+ `[dsh-im:${this.#descriptor.key}] failed to send the safe error reply:`,
1035
+ sendError,
1036
+ );
1037
+ }
1038
+ // The turn produced no answer, so this id is "attempted", not "handled".
1039
+ // Releasing the mark lets the next poll retry it; `alreadyRecorded` means
1040
+ // an outer caller owns the mark, so it is left alone there.
1041
+ if (!alreadyRecorded) await this.#releaseFailedDelivery(messageId);
1042
+ return error.deliveryReceipt;
1043
+ } finally {
1044
+ stopKeepalive();
1045
+ await Promise.allSettled([
1046
+ this.#cancelPendingInteraction(conversationKey),
1047
+ this.#approvals.closeRoute(conversationKey),
1048
+ ]);
1049
+ }
1050
+ }
1051
+
1052
+ /**
1053
+ * Release the `markSeen` of a turn that failed without delivering anything,
1054
+ * so the next poll can pick the message up again.
1055
+ *
1056
+ * Bounded: a message is retried at most `MAX_DELIVERY_ATTEMPTS` times, after
1057
+ * which the mark stays and the id becomes a tombstone. That keeps a mail that
1058
+ * always fails from being re-executed forever, while a transient Harness
1059
+ * outage no longer drops it permanently.
1060
+ *
1061
+ * Returns true when the message was released and will be retried.
1062
+ */
1063
+ async #releaseFailedDelivery(messageId) {
1064
+ const attempts = (this.#deliveryAttempts.get(messageId) ?? 0) + 1;
1065
+ if (attempts >= MAX_DELIVERY_ATTEMPTS) {
1066
+ // Give up: keep the mark so the id is never replayed, and stop tracking
1067
+ // it. The sender has already been told the turn failed.
1068
+ this.#deliveryAttempts.delete(messageId);
1069
+ this.#logger.warn?.(
1070
+ `[dsh-im:${this.#descriptor.key}] giving up on a message after `
1071
+ + `${attempts} failed delivery attempts; it will not be retried.`,
1072
+ );
1073
+ return false;
1074
+ }
1075
+ this.#deliveryAttempts.set(messageId, attempts);
1076
+ if (typeof this.#state?.unmarkSeen !== 'function') return false;
1077
+ try {
1078
+ await this.#state.unmarkSeen(messageId);
1079
+ return true;
1080
+ } catch (error) {
1081
+ this.#logger.warn?.(
1082
+ `[dsh-im:${this.#descriptor.key}] unable to release a failed message for retry:`,
1083
+ error,
1084
+ );
1085
+ return false;
1086
+ }
1087
+ }
1088
+
1089
+ /**
1090
+ * Advance the pending interaction with one answer.
1091
+ *
1092
+ * `resolveAnswer` lets a caller that already knows the exact answer supply it
1093
+ * directly. A button press uses this: replaying its label as reply text would
1094
+ * re-parse a numeric label such as "2" as the second option, submitting a
1095
+ * different option than the one pressed.
1096
+ */
1097
+ async #processInteractionReply(
1098
+ message,
1099
+ messageId,
1100
+ senderId,
1101
+ key,
1102
+ expected,
1103
+ { resolveAnswer } = {},
1104
+ ) {
1105
+ if (this.#signal?.aborted) {
1106
+ message.statusReaction?.clear();
1107
+ return;
1108
+ }
1109
+ const current = this.#pendingInteractions.get(key);
1110
+ const claimed = expected.claimedReplyMessageId === messageId;
1111
+ if (!current || current !== expected || current.submitting) {
1112
+ if (claimed && (!current || current !== expected)) {
1113
+ return this.#discardResolvedInteractionReply(message, messageId);
1114
+ }
1115
+ return this.#enqueueMessage(message, messageId, senderId, key, {
1116
+ releaseMessageId: false,
1117
+ });
1118
+ }
1119
+ if (this.#state.hasSeen(messageId)) return;
1120
+ await this.#state.markSeen(messageId);
1121
+ this.#status.messagesReceived += 1;
1122
+ this.#status.lastMessageAt = new Date().toISOString();
1123
+
1124
+ if (message.kind === 'group' && message.addressed !== true) {
1125
+ this.#status.messagesRejected += 1;
1126
+ this.#status.lastRejectedAt = new Date().toISOString();
1127
+ return;
1128
+ }
1129
+
1130
+ const target = message.replyTarget;
1131
+ const text = controlTextOf(message);
1132
+ if (!text || hasInboundImages(message) || hasInboundFiles(message)) {
1133
+ try {
1134
+ await this.#bot.sendText(target, t('请用文字回答当前问题。'));
1135
+ } catch (error) {
1136
+ this.#logger.error?.(
1137
+ `[dsh-im:${this.#descriptor.key}] failed to reject a non-text interaction reply:`,
1138
+ error,
1139
+ );
1140
+ }
1141
+ return;
1142
+ }
1143
+
1144
+ const pending = this.#pendingInteractions.get(key);
1145
+ if (!pending || pending !== expected || pending.submitting) {
1146
+ if (claimed && (!pending || pending !== expected)) {
1147
+ return this.#discardResolvedInteractionReply(message, messageId, {
1148
+ alreadyRecorded: true,
1149
+ });
1150
+ }
1151
+ return this.#enqueueMessage(message, messageId, senderId, key, {
1152
+ releaseMessageId: false,
1153
+ alreadyRecorded: true,
1154
+ });
1155
+ }
1156
+ pending.target = target;
1157
+ if (pending.needsPresentation) {
1158
+ const presentationWasInFlight = pending.presentationTask !== null;
1159
+ try {
1160
+ await this.#presentInteraction(pending);
1161
+ } catch (error) {
1162
+ message.statusReaction?.error();
1163
+ this.#status.lastError = t('{label}交互问题发送失败。', { label: this.#descriptor.label });
1164
+ this.#logger.error?.(
1165
+ `[dsh-im:${this.#descriptor.key}] failed to retry an interaction question:`,
1166
+ error,
1167
+ );
1168
+ pending.interaction.reconnect?.();
1169
+ return;
1170
+ }
1171
+ const presented = this.#pendingInteractions.get(key);
1172
+ if (!presented || presented !== expected || presented.submitting) {
1173
+ if (claimed && (!presented || presented !== expected)) {
1174
+ return this.#discardResolvedInteractionReply(message, messageId, {
1175
+ alreadyRecorded: true,
1176
+ });
1177
+ }
1178
+ return this.#enqueueMessage(message, messageId, senderId, key, {
1179
+ releaseMessageId: false,
1180
+ alreadyRecorded: true,
1181
+ });
1182
+ }
1183
+ // A reply can arrive after the platform accepted the question message but
1184
+ // before its send promise settles. In that case it is already a valid
1185
+ // answer. A message which itself retried a failed presentation is not.
1186
+ if (!presentationWasInFlight) return;
1187
+ }
1188
+
1189
+ const question = pending.questions[pending.index];
1190
+ if (!question) return;
1191
+ const answer = typeof resolveAnswer === 'function'
1192
+ ? resolveAnswer(question)
1193
+ : harnessAnswerForQuestion(question, text);
1194
+ if (!answer) return;
1195
+ // Retire this question's keyboard before moving on: the answer is already in,
1196
+ // and a card left behind in the chat stays pressable after the batch advances.
1197
+ await this.#retireInteractionCard(pending.target, pending.cardMessageId);
1198
+ pending.cardMessageId = null;
1199
+ pending.answers.push(answer);
1200
+ pending.index += 1;
1201
+ if (pending.index < pending.questions.length) {
1202
+ if (pending.claimedReplyMessageId === messageId) {
1203
+ pending.claimedReplyMessageId = null;
1204
+ }
1205
+ pending.needsPresentation = true;
1206
+ try {
1207
+ await this.#presentInteraction(pending);
1208
+ } catch (error) {
1209
+ message.statusReaction?.error();
1210
+ this.#status.lastError = t('{label}交互问题发送失败。', { label: this.#descriptor.label });
1211
+ this.#logger.error?.(
1212
+ `[dsh-im:${this.#descriptor.key}] failed to send the next interaction question:`,
1213
+ error,
1214
+ );
1215
+ pending.interaction.reconnect?.();
1216
+ }
1217
+ return;
1218
+ }
1219
+
1220
+ pending.submitting = true;
1221
+ try {
1222
+ await pending.interaction.respond({
1223
+ ok: true,
1224
+ value: {
1225
+ sessionId: pending.sessionId,
1226
+ answer: { answers: pending.answers },
1227
+ },
1228
+ });
1229
+ this.#clearPendingInteraction(key, pending.interactionId);
1230
+ this.#status.lastError = null;
1231
+ } catch (error) {
1232
+ if (error?.code === 'interaction-not-pending') {
1233
+ this.#clearPendingInteraction(key, pending.interactionId);
1234
+ if (this.#signal?.aborted) {
1235
+ message.statusReaction?.clear();
1236
+ return;
1237
+ }
1238
+ try {
1239
+ await this.#bot.sendText(target, t(INTERACTION_RESOLVED_TEXT));
1240
+ } catch (sendError) {
1241
+ this.#logger.error?.(
1242
+ `[dsh-im:${this.#descriptor.key}] failed to send an expired interaction notice:`,
1243
+ sendError,
1244
+ );
1245
+ }
1246
+ return;
1247
+ }
1248
+ if (this.#signal?.aborted) {
1249
+ message.statusReaction?.clear();
1250
+ return;
1251
+ }
1252
+ if (this.#pendingInteractions.get(key) !== pending) {
1253
+ message.statusReaction?.clear();
1254
+ return;
1255
+ }
1256
+ message.statusReaction?.error();
1257
+ pending.submitting = false;
1258
+ pending.answers.pop();
1259
+ pending.index -= 1;
1260
+ this.#status.lastError = t('回答提交失败。');
1261
+ this.#logger.error?.(
1262
+ `[dsh-im:${this.#descriptor.key}] failed to answer a Harness interaction:`,
1263
+ error,
1264
+ );
1265
+ try {
1266
+ await this.#bot.sendText(target, t('回答提交失败,请重新发送当前问题的答案。'));
1267
+ } catch (sendError) {
1268
+ this.#logger.error?.(
1269
+ `[dsh-im:${this.#descriptor.key}] failed to send an interaction retry notice:`,
1270
+ sendError,
1271
+ );
1272
+ }
1273
+ }
1274
+ }
1275
+
1276
+ /** Acknowledge a press so the client stops its spinner; never fails the answer. */
1277
+ async #answerInteractionCallback(callback, text) {
1278
+ if (typeof this.#bot.answerInteractionCallback !== 'function') return;
1279
+ try {
1280
+ await this.#bot.answerInteractionCallback(callback.callbackQueryId, text);
1281
+ } catch (error) {
1282
+ this.#logger.warn?.(
1283
+ `[dsh-im:${this.#descriptor.key}] could not acknowledge a button press:`,
1284
+ error?.message ?? error,
1285
+ );
1286
+ }
1287
+ }
1288
+
1289
+ /** Drop a handled card's keyboard so the same press cannot be submitted twice. */
1290
+ async #retireInteractionCard(target, providerMessageId) {
1291
+ if (!providerMessageId || typeof this.#bot.updateInteractionCard !== 'function') return;
1292
+ try {
1293
+ await this.#bot.updateInteractionCard(target, providerMessageId, {
1294
+ markup: { inline_keyboard: [] },
1295
+ });
1296
+ } catch (error) {
1297
+ this.#logger.warn?.(
1298
+ `[dsh-im:${this.#descriptor.key}] could not retire an interaction card:`,
1299
+ error?.message ?? error,
1300
+ );
1301
+ }
1302
+ }
1303
+
1304
+ /**
1305
+ * Accept an inline-keyboard press. The press is replayed as the option label the
1306
+ * text flow already understands, so a button and a typed reply share one
1307
+ * submission path and cannot drift apart.
1308
+ */
1309
+ async acceptCallback(callback) {
1310
+ if (this.#signal?.aborted) return;
1311
+ const conversationId = cleanText(callback?.conversationId);
1312
+ const senderId = cleanText(callback?.senderId);
1313
+ const messageId = cleanText(callback?.messageId);
1314
+ if (!conversationId || !senderId || !messageId || callback?.senderIsBot === true) return;
1315
+ const kind = callback.kind === 'group' ? 'group' : 'direct';
1316
+ const key = `${kind}:${conversationId}`;
1317
+ const pending = this.#pendingInteractions.get(key);
1318
+ const notice = (text) => this.#answerInteractionCallback(callback, text);
1319
+ if (!pending) return notice(t('该问题已处理,无需再次选择。'));
1320
+ if (pending.actor !== senderId) {
1321
+ return notice(t('只有发起当前任务的用户可以处理这条问题。'));
1322
+ }
1323
+ // A press can arrive while an earlier one is still being submitted: the
1324
+ // acknowledgement round-trip is a real window, and a user who sees no feedback
1325
+ // presses again. Claim synchronously, before the first await, so the second
1326
+ // press cannot advance the same question twice.
1327
+ if (pending.submitting || pending.callbackClaimed) {
1328
+ return notice(t('正在提交你的选择,请稍候。'));
1329
+ }
1330
+
1331
+ const question = pending.questions[pending.index];
1332
+ const parsed = this.#interactionCard?.parse?.(callback.data) ?? null;
1333
+ const option = parsed && Array.isArray(question?.options)
1334
+ ? question.options[parsed.optionIndex]
1335
+ : undefined;
1336
+ if (!question || !parsed
1337
+ || !pending.cardNonce || parsed.nonce !== pending.cardNonce
1338
+ || parsed.questionIndex !== pending.index
1339
+ || !option || typeof option.label !== 'string') {
1340
+ return notice(t('这个选项已失效,请使用最新一条问题。'));
1341
+ }
1342
+ // Multi-select needs a keyboard that accumulates choices and a submit action;
1343
+ // until that exists the request keeps the text answer it has always accepted.
1344
+ if (question.multiSelect === true) {
1345
+ return notice(t('多选问题请直接回复文字。'));
1346
+ }
1347
+
1348
+ pending.callbackClaimed = true;
1349
+ // A press can beat the card's own send promise — Telegram delivers the update
1350
+ // as soon as its API accepted the keyboard. Wait for delivery so the card id
1351
+ // exists and the shared submission path can retire its keyboard.
1352
+ await pending.presentationTask?.catch(() => undefined);
1353
+ await notice(t('已选择:{label}', { label: option.label }));
1354
+ await this.#processInteractionReply(
1355
+ {
1356
+ kind,
1357
+ conversationId,
1358
+ messageId,
1359
+ senderId,
1360
+ addressed: true,
1361
+ content: option.label,
1362
+ replyTarget: callback.replyTarget ?? pending.target,
1363
+ statusReaction: null,
1364
+ },
1365
+ messageId,
1366
+ senderId,
1367
+ key,
1368
+ pending,
1369
+ // The press already identifies its option by index, so answer with that
1370
+ // exact label. Replaying the label as reply text would re-parse a numeric
1371
+ // label such as "2" as the second option and submit a different one.
1372
+ { resolveAnswer: (current) => ({ id: current.id, selected: [option.label] }) },
1373
+ ).catch((error) => {
1374
+ this.#logger.error?.(
1375
+ `[dsh-im:${this.#descriptor.key}] failed to submit a card answer:`,
1376
+ error,
1377
+ );
1378
+ }).finally(() => {
1379
+ // A failed submission rolls the question back, so let the user press again.
1380
+ if (this.#pendingInteractions.get(key) === pending) pending.callbackClaimed = false;
1381
+ });
1382
+ }
1383
+
1384
+ async #handleInteraction(interaction, {
1385
+ key,
1386
+ actor,
1387
+ target,
1388
+ requiresMention,
1389
+ }) {
1390
+ if (interaction?.kind === 'approval') {
1391
+ return this.#approvals.handleRequested(interaction, {
1392
+ key,
1393
+ actor,
1394
+ requiresMention,
1395
+ send: (text) => this.#bot.sendText(target, text),
1396
+ });
1397
+ }
1398
+ if (interaction?.kind !== 'question') return;
1399
+ const questions = interaction?.payload?.questions;
1400
+ const interactionId = cleanText(interaction?.interactionId) || cleanText(interaction?.rpcId);
1401
+ if (!cleanText(interaction?.rpcId)
1402
+ || !interactionId
1403
+ || !cleanText(interaction?.sessionId)
1404
+ || !Array.isArray(questions)
1405
+ || questions.length === 0
1406
+ || questions.some((question) => !validHarnessQuestion(question))) {
1407
+ this.#logger.warn?.(
1408
+ `[dsh-im:${this.#descriptor.key}] ignored an invalid Harness question interaction`,
1409
+ );
1410
+ return;
1411
+ }
1412
+
1413
+ if (interaction.recovered === true) {
1414
+ await this.#respondCancellation(
1415
+ interaction,
1416
+ `${this.#descriptor.label} safely cancelled an interaction left by an earlier client.`,
1417
+ );
1418
+ try {
1419
+ await this.#bot.sendText(
1420
+ target,
1421
+ t('检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。'),
1422
+ );
1423
+ } catch (error) {
1424
+ this.#logger.error?.(
1425
+ `[dsh-im:${this.#descriptor.key}] failed to send an interaction recovery notice:`,
1426
+ error,
1427
+ );
1428
+ }
1429
+ return;
1430
+ }
1431
+
1432
+ const existing = this.#pendingInteractions.get(key);
1433
+ if (existing?.interactionId === interactionId) {
1434
+ existing.interaction = interaction;
1435
+ if (existing.needsPresentation) await this.#presentInteraction(existing);
1436
+ return;
1437
+ }
1438
+ if (this.#interactionKeys.has(interactionId)) return;
1439
+ if (existing) {
1440
+ this.#logger.warn?.(
1441
+ `[dsh-im:${this.#descriptor.key}] cancelled a second pending Harness question`,
1442
+ );
1443
+ await this.#respondCancellation(
1444
+ interaction,
1445
+ `${this.#descriptor.label} is already handling another user interaction.`,
1446
+ );
1447
+ return;
1448
+ }
1449
+
1450
+ const pending = {
1451
+ kind: 'question',
1452
+ interactionId,
1453
+ sessionId: interaction.sessionId,
1454
+ interaction,
1455
+ actor,
1456
+ requiresMention,
1457
+ questions,
1458
+ answers: [],
1459
+ index: 0,
1460
+ target,
1461
+ queue: null,
1462
+ claimedReplyMessageId: null,
1463
+ submitting: false,
1464
+ needsPresentation: true,
1465
+ presentationTask: null,
1466
+ cardMessageId: null,
1467
+ // Identity of the keyboard currently on screen, and the guard that keeps two
1468
+ // presses of the same card from advancing one question twice.
1469
+ cardNonce: null,
1470
+ callbackClaimed: false,
1471
+ };
1472
+ this.#pendingInteractions.set(key, pending);
1473
+ this.#interactionKeys.set(interactionId, key);
1474
+ await this.#presentInteraction(pending);
1475
+ }
1476
+
1477
+ async #handleInteractionResolved(resolution) {
1478
+ if (resolution?.kind === 'approval') {
1479
+ await this.#approvals.handleResolved(resolution);
1480
+ return;
1481
+ }
1482
+ const interactionId = cleanText(resolution?.interactionId);
1483
+ if (resolution?.kind !== 'question' || !interactionId) return;
1484
+ const key = this.#interactionKeys.get(interactionId);
1485
+ if (!key) return;
1486
+ this.#clearPendingInteraction(key, interactionId);
1487
+ }
1488
+
1489
+ /** Build card content for the current question, or null to keep the text flow. */
1490
+ #interactionCardFor(pending, question) {
1491
+ if (!this.#interactionCard || typeof this.#interactionCard.render !== 'function') return null;
1492
+ if (typeof this.#bot.sendInteractionCard !== 'function') return null;
1493
+ if (pending.submitting) return null;
1494
+ let card = null;
1495
+ try {
1496
+ card = this.#interactionCard.render(question, {
1497
+ questionIndex: pending.index,
1498
+ total: pending.questions.length,
1499
+ requiresMention: pending.requiresMention,
1500
+ nonce: pending.cardNonce,
1501
+ });
1502
+ } catch (error) {
1503
+ this.#logger.warn?.(
1504
+ `[dsh-im:${this.#descriptor.key}] interaction card renderer failed:`,
1505
+ error,
1506
+ );
1507
+ return null;
1508
+ }
1509
+ if (!card || typeof card.text !== 'string' || !card.text || !card.markup) return null;
1510
+ return card;
1511
+ }
1512
+
1513
+ #presentInteraction(pending) {
1514
+ if (pending.presentationTask) return pending.presentationTask;
1515
+ const question = pending.questions[pending.index];
1516
+ if (!question) return Promise.resolve();
1517
+ const task = (async () => {
1518
+ // A fresh nonce per presentation: a later question restarts its indexes at
1519
+ // zero, so without one an old card's keyboard would answer the new question.
1520
+ pending.cardNonce = randomUUID().slice(0, 8);
1521
+ const card = this.#interactionCardFor(pending, question);
1522
+ if (card) {
1523
+ try {
1524
+ const sent = await this.#bot.sendInteractionCard(pending.target, {
1525
+ text: card.text,
1526
+ markup: card.markup,
1527
+ });
1528
+ pending.cardMessageId = sent?.providerMessageIds?.at(-1) ?? null;
1529
+ pending.needsPresentation = false;
1530
+ return;
1531
+ } catch (error) {
1532
+ // A platform that refuses the keyboard must not lose the question:
1533
+ // fall through to the plain-text flow this channel already had.
1534
+ pending.cardMessageId = null;
1535
+ this.#logger.warn?.(
1536
+ `[dsh-im:${this.#descriptor.key}] could not deliver an interaction card; `
1537
+ + 'falling back to plain text:',
1538
+ error?.message ?? error,
1539
+ );
1540
+ }
1541
+ }
1542
+ await this.#bot.sendText(
1543
+ pending.target,
1544
+ harnessQuestionText(
1545
+ question,
1546
+ pending.index,
1547
+ pending.questions.length,
1548
+ { requiresMention: pending.requiresMention },
1549
+ ),
1550
+ );
1551
+ pending.needsPresentation = false;
1552
+ })();
1553
+ pending.presentationTask = task;
1554
+ task.then(
1555
+ () => {
1556
+ if (pending.presentationTask === task) pending.presentationTask = null;
1557
+ },
1558
+ () => {
1559
+ if (pending.presentationTask === task) pending.presentationTask = null;
1560
+ },
1561
+ );
1562
+ return task;
1563
+ }
1564
+
1565
+ async #discardResolvedInteractionReply(message, messageId, {
1566
+ alreadyRecorded = false,
1567
+ } = {}) {
1568
+ if (!alreadyRecorded) {
1569
+ if (this.#state.hasSeen(messageId)) return;
1570
+ await this.#state.markSeen(messageId);
1571
+ this.#status.messagesReceived += 1;
1572
+ this.#status.lastMessageAt = new Date().toISOString();
1573
+ }
1574
+ try {
1575
+ await this.#bot.sendText(message.replyTarget, t(INTERACTION_RESOLVED_TEXT));
1576
+ } catch (error) {
1577
+ this.#logger.error?.(
1578
+ `[dsh-im:${this.#descriptor.key}] failed to send an expired interaction notice:`,
1579
+ error,
1580
+ );
1581
+ }
1582
+ }
1583
+
1584
+ #takePendingInteraction(key, interactionId) {
1585
+ const pending = this.#pendingInteractions.get(key);
1586
+ if (!pending
1587
+ || (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
1588
+ this.#pendingInteractions.delete(key);
1589
+ this.#interactionKeys.delete(pending.interactionId);
1590
+ return pending;
1591
+ }
1592
+
1593
+ #clearPendingInteraction(key, interactionId) {
1594
+ return this.#takePendingInteraction(key, interactionId) !== null;
1595
+ }
1596
+
1597
+ async #respondCancellation(interaction, message) {
1598
+ try {
1599
+ await interaction.respond({
1600
+ ok: false,
1601
+ error: { code: 'cancelled', message, details: {} },
1602
+ }, { signal: AbortSignal.timeout(5_000) });
1603
+ } catch (error) {
1604
+ if (error?.code !== 'interaction-not-pending') throw error;
1605
+ }
1606
+ }
1607
+
1608
+ async #cancelPendingInteraction(key) {
1609
+ const pending = this.#takePendingInteraction(key);
1610
+ if (!pending || pending.kind !== 'question') return;
1611
+ try {
1612
+ await this.#respondCancellation(
1613
+ pending.interaction,
1614
+ `The ${this.#descriptor.label} interaction ended before the user answered.`,
1615
+ );
1616
+ } catch (error) {
1617
+ this.#logger.warn?.(
1618
+ `[dsh-im:${this.#descriptor.key}] failed to cancel a pending Harness interaction:`,
1619
+ error,
1620
+ );
1621
+ }
1622
+ }
1623
+ }