@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,372 @@
1
+ // Shared by the Host and settings UI; keep this module browser-compatible.
2
+ export const CONTEXT_ENHANCEMENT_FIELDS = Object.freeze([
3
+ 'channel', 'conversationType', 'senderId', 'senderName', 'conversationTitle',
4
+ 'chatId', 'threadId', 'botId', 'sentAt',
5
+ ]);
6
+
7
+ /**
8
+ * Tag grammar of the injected context prefix. The producer here and the
9
+ * Host-side splitter in `injected-context.mjs` share these literals, so the
10
+ * prefix a channel writes can never drift from the parser that pairs it.
11
+ */
12
+ export const INJECTED_CONTEXT_TAGS = Object.freeze({
13
+ sourceOpen: '<dsh_im_source>',
14
+ sourceClose: '</dsh_im_source>',
15
+ guidanceOpen: '<dsh_im_source_guidance>',
16
+ guidanceClose: '</dsh_im_source_guidance>',
17
+ replyOpen: '<dsh_im_reply_to>',
18
+ replyClose: '</dsh_im_reply_to>',
19
+ });
20
+
21
+ /** Separator the producer joins prefix blocks with, and the splitter consumes. */
22
+ export const INJECTED_CONTEXT_SEPARATOR = '\n\n';
23
+
24
+ export const CONTEXT_ENHANCEMENT_GUIDANCE_MAX_LENGTH = 8_000;
25
+ export const CONTEXT_GROUP_GUIDANCE_EXAMPLE = `仅依据当前消息的 <dsh_im_source> 中实际提供的字段理解来源;没有提供的字段不要猜测或补全。
26
+ 当前消息来自群聊,请使用严肃、克制、简洁的表达方式。`;
27
+ export const CONTEXT_DIRECT_GUIDANCE_EXAMPLE = `仅依据当前消息的 <dsh_im_source> 中实际提供的字段理解来源;没有提供的字段不要猜测或补全。
28
+ 当前消息来自私聊,可以使用更轻松、幽默、详细的表达方式。`;
29
+
30
+ // Kept for integrations that imported the original combined example.
31
+ export const CONTEXT_GUIDANCE_EXAMPLE = `仅依据当前消息的 <dsh_im_source> 中实际提供的字段理解来源;没有提供的字段不要猜测或补全。
32
+ conversationType是群聊时回复严肃一点,conversationType是私聊时回复一定要幽默搞笑,像周星驰的电影一样搞笑`;
33
+
34
+ // Kept as an alias for integrations that imported the original template name.
35
+ export const DEFAULT_CONTEXT_GUIDANCE = CONTEXT_GUIDANCE_EXAMPLE;
36
+
37
+ export const DEFAULT_CONTEXT_ENHANCEMENT_CONFIG = Object.freeze({
38
+ group: Object.freeze({
39
+ enabled: false,
40
+ fields: Object.freeze(['senderId']),
41
+ guidance: '',
42
+ }),
43
+ direct: Object.freeze({
44
+ enabled: false,
45
+ fields: Object.freeze(['senderId']),
46
+ guidance: '',
47
+ }),
48
+ });
49
+
50
+ const CONFIG_KEYS = ['group', 'direct'];
51
+ const SCOPE_KEYS = ['enabled', 'fields', 'guidance'];
52
+ const LEGACY_CONFIG_KEYS = ['groupEnabled', 'directEnabled', 'fields', 'guidance'];
53
+ const CHANNELS = new Set([
54
+ 'wecom', 'weixin', 'feishu', 'dingtalk', 'qq',
55
+ 'slack', 'telegram', 'discord', 'whatsapp',
56
+ ]);
57
+ const SOURCE_LIMITS = {
58
+ channel: 16, conversationType: 6, senderId: 256, senderName: 256,
59
+ conversationTitle: 256, chatId: 256, threadId: 256, botId: 128, sentAt: 32,
60
+ };
61
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
62
+
63
+ function invalidConfig(message) {
64
+ const error = new TypeError(message);
65
+ error.code = 'context-enhancement-invalid';
66
+ return error;
67
+ }
68
+
69
+ function hasExactKeys(input, keys) {
70
+ return input && typeof input === 'object' && !Array.isArray(input)
71
+ && [Object.prototype, null].includes(Object.getPrototypeOf(input))
72
+ && Reflect.ownKeys(input).length === keys.length
73
+ && keys.every((key) => Object.hasOwn(input, key));
74
+ }
75
+
76
+ function validateContextEnhancementScope(input) {
77
+ if (!hasExactKeys(input, SCOPE_KEYS)) {
78
+ throw invalidConfig('请提交完整的上下文增强设置。');
79
+ }
80
+ const { enabled, fields, guidance } = input;
81
+ if (typeof enabled !== 'boolean') {
82
+ throw invalidConfig('群聊和私聊开关必须是布尔值。');
83
+ }
84
+ if (!Array.isArray(fields) || ![...fields].every((field) => CONTEXT_ENHANCEMENT_FIELDS.includes(field))) {
85
+ throw invalidConfig('来源字段只能选择已定义的字段。');
86
+ }
87
+ if (typeof guidance !== 'string' || guidance.length > CONTEXT_ENHANCEMENT_GUIDANCE_MAX_LENGTH) {
88
+ throw invalidConfig(`增强提示词不得超过 ${CONTEXT_ENHANCEMENT_GUIDANCE_MAX_LENGTH} 个字符。`);
89
+ }
90
+ return Object.freeze({
91
+ enabled,
92
+ fields: Object.freeze(CONTEXT_ENHANCEMENT_FIELDS.filter((field) => fields.includes(field))),
93
+ guidance: guidance.trim() ? guidance : '',
94
+ });
95
+ }
96
+
97
+ /** Validate the complete atomic save, preserving explicit empty selections/text. */
98
+ export function validateContextEnhancementConfig(input) {
99
+ if (!hasExactKeys(input, CONFIG_KEYS)) {
100
+ throw invalidConfig('请提交完整的上下文增强设置。');
101
+ }
102
+ return Object.freeze({
103
+ group: validateContextEnhancementScope(input.group),
104
+ direct: validateContextEnhancementScope(input.direct),
105
+ });
106
+ }
107
+
108
+ function migrateLegacyContextEnhancementConfig(input) {
109
+ if (!hasExactKeys(input, LEGACY_CONFIG_KEYS)) {
110
+ throw invalidConfig('请提交完整的上下文增强设置。');
111
+ }
112
+ return validateContextEnhancementConfig({
113
+ group: {
114
+ enabled: input.groupEnabled,
115
+ fields: input.fields,
116
+ guidance: input.guidance,
117
+ },
118
+ direct: {
119
+ enabled: input.directEnabled,
120
+ fields: input.fields,
121
+ guidance: input.guidance,
122
+ },
123
+ });
124
+ }
125
+
126
+ /** Missing or damaged enhancement settings must never break an existing bot. */
127
+ export function normalizeContextEnhancementConfig(input) {
128
+ try {
129
+ return validateContextEnhancementConfig(input);
130
+ } catch {
131
+ try {
132
+ return migrateLegacyContextEnhancementConfig(input);
133
+ } catch {
134
+ return DEFAULT_CONTEXT_ENHANCEMENT_CONFIG;
135
+ }
136
+ }
137
+ }
138
+
139
+ /** Capture before queueing. The off path reads only the applicable switch. */
140
+ export function captureContextEnhancement(provider, conversationType) {
141
+ if (conversationType !== 'group' && conversationType !== 'direct') return null;
142
+ try {
143
+ const settings = provider?.getSettings?.();
144
+ const legacyEnabledKey = conversationType === 'group' ? 'groupEnabled' : 'directEnabled';
145
+ const enabled = Object.hasOwn(settings ?? {}, conversationType)
146
+ ? settings?.[conversationType]?.enabled
147
+ : settings?.[legacyEnabledKey];
148
+ if (enabled !== true) return null;
149
+ const config = normalizeContextEnhancementConfig(settings);
150
+ const scope = config[conversationType];
151
+ if (scope.enabled !== true) return null;
152
+ return Object.freeze({ config: scope, botId: provider.botId, conversationType });
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Property a channel hangs its captured moment on, using `withSentAt`.
160
+ *
161
+ * It sits on the source factory instead of being read out of it, because a
162
+ * factory reads the inbound event's fields -- sometimes through throwing
163
+ * getters -- and only a prompt that actually renders a source block may do
164
+ * that. Local commands (`/help`, `/new`, `/steer`) take the enhancement to keep
165
+ * its privacy rules but never read a source, and that must stay true.
166
+ */
167
+ const SENT_AT = 'sentAt';
168
+
169
+ /** One-shot latch: a wiring bug is worth saying once, not once per message. */
170
+ let warnedMissingSentAt = false;
171
+
172
+ /**
173
+ * Wrap one channel source factory so it also publishes the moment of the
174
+ * message, without reading any of the message's fields yet.
175
+ *
176
+ * `value` may itself be a thunk: a channel that derives the moment from the
177
+ * inbound event (a `create_time_ms` field, a message-id decode) should pass one,
178
+ * because evaluating it here would read the inbound message even when the scope
179
+ * is disabled or the `sentAt` field is not selected -- and a disabled scope must
180
+ * read nothing at all.
181
+ *
182
+ * @param factory - the channel's source factory, or nothing.
183
+ * @param value - platform send time (epoch ms or ISO-8601), or a thunk
184
+ * returning one. It is evaluated only when a rendered block selects `sentAt`;
185
+ * an unusable value, or a thunk that throws, omits the field.
186
+ * @returns the same shape, plus `sentAt` when a usable value was supplied.
187
+ */
188
+ export function withSentAt(factory, value) {
189
+ const wrapped = typeof factory === 'function' ? (...args) => factory(...args) : () => factory;
190
+ const published = typeof value === 'function' ? value : () => value;
191
+ Object.defineProperty(wrapped, SENT_AT, { value: published, enumerable: false });
192
+ return wrapped;
193
+ }
194
+
195
+ /**
196
+ * Evaluate the moment a channel published, without invoking its source factory.
197
+ *
198
+ * Called only while a prompt is rendering a block that selected `sentAt` --
199
+ * never at capture time -- so an unselected field, a disabled scope, a missing
200
+ * provider or a local command never reads the inbound message's clock. A
201
+ * throwing accessor (for example a getter on the inbound event) is contained
202
+ * here: it costs this one field, not the message.
203
+ *
204
+ * @param source - a source factory carrying `sentAt`, or a plain source object.
205
+ * @returns `{ published, ms }`: whether a moment was published at all, and its
206
+ * epoch milliseconds when it was usable.
207
+ */
208
+ function readPublishedSentAt(source) {
209
+ const own = typeof source === 'function' || (source !== null && typeof source === 'object')
210
+ ? source?.[SENT_AT]
211
+ : undefined;
212
+ if (typeof own !== 'function') return { published: false, ms: undefined };
213
+ let value;
214
+ try {
215
+ value = own();
216
+ } catch {
217
+ return { published: true, ms: undefined };
218
+ }
219
+ return { published: true, ms: timestampMs(value) ?? undefined };
220
+ }
221
+
222
+ /**
223
+ * Capture the enhancement one prompt replays, together with the source factory
224
+ * that fills its selected fields.
225
+ *
226
+ * Ordinary messages snapshot this when they are accepted, so a queued message
227
+ * keeps the settings it arrived under. A control command is never queued, so it
228
+ * captures at the moment it runs -- and it must, because the source fields of a
229
+ * steering instruction belong to whoever issued it, not to the message that
230
+ * opened the turn.
231
+ *
232
+ * @param provider - the bot's enhancement provider.
233
+ * @param conversationType - the inbound message's scope.
234
+ * @param source - factory for the currently selected source fields; attach the
235
+ * moment with `withSentAt` to publish a platform send time.
236
+ * @returns the enhancement to apply, or null when the scope is off.
237
+ */
238
+ export function captureContextEnhancementSource(provider, conversationType, source) {
239
+ // No provider means enhancement is not configured for this channel at all, so
240
+ // there is nothing to capture -- and the thunk a channel published must not be
241
+ // evaluated. Answering null here is what lets every channel call this
242
+ // unconditionally, including bots with no enhancement settings.
243
+ if (typeof provider?.getSettings !== 'function') return null;
244
+ const snapshot = captureContextEnhancement(provider, conversationType);
245
+ if (snapshot === null) return null;
246
+ // Nothing is read here -- not the message's fields and not the moment a
247
+ // channel published through `withSentAt`. Local commands capture too (to keep
248
+ // the privacy rules for a later prompt) but never render, and a capture whose
249
+ // scope does not select `sentAt` must never touch the clock; the moment is
250
+ // evaluated only by the render that actually needs it.
251
+ return Object.freeze({ snapshot, source });
252
+ }
253
+
254
+ /** Accept a millisecond epoch or an ISO-8601 string; anything else yields null. */
255
+ function timestampMs(value) {
256
+ if (value === undefined || value === null || value === '') return null;
257
+ if (typeof value === 'bigint') value = Number(value);
258
+ if (typeof value === 'number') return Number.isSafeInteger(value) ? value : null;
259
+ if (typeof value === 'string') {
260
+ const parsed = Date.parse(value);
261
+ return Number.isSafeInteger(parsed) ? parsed : null;
262
+ }
263
+ return null;
264
+ }
265
+
266
+ /**
267
+ * Render one epoch instant as `YYYY-MM-DD HH:mm:ss` in local time. The zone is
268
+ * deliberately omitted: four independent components already carry the digits,
269
+ * and the guidance text is the place to name the timezone.
270
+ *
271
+ * Padding is spelled out per component instead of calling a module-level
272
+ * helper: `sourceBlock` can run while this module is still initializing, and
273
+ * reading a `const` declared below would throw a temporal-dead-zone error that
274
+ * the caller's catch silently swallows -- dropping the entire prefix.
275
+ */
276
+ function formatTimestamp(ms) {
277
+ const date = new Date(ms);
278
+ const year = date.getFullYear();
279
+ if (!Number.isInteger(year)) return undefined;
280
+ const pad = (value) => String(value).padStart(2, '0');
281
+ return `${year}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
282
+ + ` ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
283
+ }
284
+
285
+ function sourceString(value, field) {
286
+ if (field === 'senderId' && (typeof value === 'bigint' || Number.isFinite(value))) {
287
+ value = String(value);
288
+ }
289
+ if (typeof value !== 'string') return undefined;
290
+ const normalized = value.replace(CONTROL_CHARACTERS, '').trim().slice(0, SOURCE_LIMITS[field]);
291
+ if (!normalized || (field === 'channel' && !CHANNELS.has(normalized))) return undefined;
292
+ return normalized;
293
+ }
294
+
295
+ function sourceBlock(snapshot, sourceFactory) {
296
+ const { fields } = snapshot.config;
297
+ const needsSource = fields.some((field) => [
298
+ 'channel', 'senderId', 'senderName', 'conversationTitle', 'chatId', 'threadId',
299
+ ].includes(field));
300
+ const source = needsSource ? sourceFactory?.() : null;
301
+ const projected = {};
302
+ for (const field of fields) {
303
+ if (field === 'sentAt') {
304
+ // Only a channel that published a moment through `withSentAt` renders
305
+ // this field, and the moment is evaluated here, the first and only time
306
+ // it is needed. A field the factory returns is never read for it: a
307
+ // channel that did not wire a moment omits the field rather than fall
308
+ // back to the local clock, which the model could not tell apart.
309
+ const { published, ms } = readPublishedSentAt(sourceFactory);
310
+ const formatted = ms === undefined ? undefined : formatTimestamp(ms);
311
+ if (typeof formatted === 'string' && formatted) {
312
+ projected[field] = formatted.slice(0, SOURCE_LIMITS[field]);
313
+ } else if (published && !warnedMissingSentAt) {
314
+ // The channel did publish a moment but it was unusable or failed to
315
+ // read: say so once, because the omitted field is otherwise
316
+ // indistinguishable from a channel that supplies none.
317
+ warnedMissingSentAt = true;
318
+ console.warn('[dsh-im] a published sentAt was unusable and was omitted from the block');
319
+ }
320
+ continue;
321
+ }
322
+ const value = field === 'botId' || field === 'conversationType'
323
+ ? snapshot[field] : source?.[field];
324
+ const normalized = sourceString(value, field);
325
+ if (normalized !== undefined) projected[field] = normalized;
326
+ }
327
+ if (Object.keys(projected).length === 0) return '';
328
+ const json = JSON.stringify(projected).replace(/[<>&]/g, (character) => ({
329
+ '<': '\\u003c', '>': '\\u003e', '&': '\\u0026',
330
+ })[character]);
331
+ return `${INJECTED_CONTEXT_TAGS.sourceOpen}${json}${INJECTED_CONTEXT_TAGS.sourceClose}`;
332
+ }
333
+
334
+ function guidanceBlock(guidance) {
335
+ if (!guidance.trim()) return '';
336
+ const body = guidance.replace(/<\/?dsh_im_source_guidance\b[^>]*(?:>|$)/gi, (tag) => (
337
+ tag.replace(/</g, '&lt;').replace(/>/g, '&gt;')
338
+ ));
339
+ return `${INJECTED_CONTEXT_TAGS.guidanceOpen}\n${body}\n${INJECTED_CONTEXT_TAGS.guidanceClose}`;
340
+ }
341
+
342
+ /**
343
+ * Add one text prefix; never inspect sources, format or copy content when off.
344
+ *
345
+ * @param content - the message body the channel is about to send.
346
+ * @param snapshot - either a capture from `captureContextEnhancementSource`
347
+ * (which already carries the moment and its own source) or a bare scope
348
+ * snapshot from `captureContextEnhancement`.
349
+ * @param sourceFactory - the channel's source factory, when the caller holds it
350
+ * separately from the capture. Omit it for a capture: the capture's own
351
+ * factory and moment are used, so a `sentAt` selection cannot be lost by
352
+ * passing only its `.snapshot`.
353
+ */
354
+ export function enhanceContextContent(content, snapshot, sourceFactory) {
355
+ if (!snapshot) return content;
356
+ // A capture is `{snapshot, source}`; a bare scope is `{config, ...}`.
357
+ const scope = snapshot.config ? snapshot : snapshot.snapshot;
358
+ if (!scope?.config) return content;
359
+ const factory = sourceFactory ?? (snapshot.config ? undefined : snapshot.source);
360
+ try {
361
+ const blocks = [sourceBlock(scope, factory), guidanceBlock(scope.config.guidance)]
362
+ .filter(Boolean);
363
+ if (blocks.length === 0) return content;
364
+ const prefix = blocks.join(INJECTED_CONTEXT_SEPARATOR);
365
+ if (typeof content === 'string') return `${prefix}\n\n${content}`;
366
+ if (Array.isArray(content)) return [{ type: 'text', text: prefix }, ...content];
367
+ return content;
368
+ } catch {
369
+ // Only enhancement errors are isolated; the caller's original flow proceeds.
370
+ return content;
371
+ }
372
+ }
@@ -0,0 +1,111 @@
1
+ import { enhanceContextContent } from './context-enhancement.mjs';
2
+ import { t } from './i18n.mjs';
3
+ import manifest from '../../../package.json' with { type: 'json' };
4
+
5
+ const CONTROL_COMMAND = /^\/(?:stop|steer|version)(?=$|\s)/iu;
6
+ const STOP_COMMAND = /^\/stop(?=$|\s)/iu;
7
+ const VERSION_COMMAND = /^\/version(?=$|\s)/iu;
8
+ const STOP_USAGE = '用法:/stop(不带参数)';
9
+ const VERSION_USAGE = '用法:/version(不带参数)';
10
+ const STEER_USAGE = '用法:/steer <补充指令>';
11
+ const TEXT_ONLY = '控制命令仅支持纯文字,请移除图片后重试。';
12
+
13
+ function commandResult(message, extra = {}) {
14
+ return { message, ...extra };
15
+ }
16
+
17
+ function requestOptions(signal) {
18
+ return signal ? { signal } : {};
19
+ }
20
+
21
+ function boundSession(harness, state, key) {
22
+ if (typeof state?.sessionFor !== 'function') return null;
23
+ const sessionId = state.sessionFor(key);
24
+ if (typeof sessionId !== 'string' || !sessionId) return null;
25
+ if (typeof harness?.workspaceSession !== 'function') {
26
+ throw new TypeError('Harness does not support workspace sessions');
27
+ }
28
+ const session = harness.workspaceSession(sessionId, key);
29
+ if (!session || typeof session !== 'object') {
30
+ throw new TypeError('Harness returned an invalid workspace session');
31
+ }
32
+ return session;
33
+ }
34
+
35
+ export function isControlCommand(text) {
36
+ return typeof text === 'string' && CONTROL_COMMAND.test(text.trim());
37
+ }
38
+
39
+ export async function runControlCommand(text, harness, state, key, {
40
+ signal,
41
+ hasImages = false,
42
+ pendingInteraction = false,
43
+ control,
44
+ deferredDelivery,
45
+ enhancement,
46
+ } = {}) {
47
+ if (!isControlCommand(text)) return null;
48
+ const command = text.trim();
49
+ const stop = STOP_COMMAND.test(command);
50
+ const version = VERSION_COMMAND.test(command);
51
+
52
+ if (hasImages) return commandResult(t(TEXT_ONLY));
53
+
54
+ if (version) {
55
+ return /^\/version$/iu.test(command)
56
+ ? commandResult(`dsh-im v${manifest.version}`)
57
+ : commandResult(t(VERSION_USAGE));
58
+ }
59
+
60
+ if (stop) {
61
+ if (!/^\/stop$/iu.test(command)) return commandResult(t(STOP_USAGE));
62
+ const session = boundSession(harness, state, key);
63
+ if (!session) return commandResult(t('当前聊天没有正在运行的任务。'));
64
+ if (typeof session.stopActiveTurn !== 'function') {
65
+ throw new TypeError('Harness session does not support stopping active turns');
66
+ }
67
+ const stopped = await session.stopActiveTurn(control, requestOptions(signal));
68
+ if (!stopped && deferredDelivery) {
69
+ const background = await deferredDelivery.stop(key);
70
+ if (background === 'stopped') return commandResult(t('已请求停止后台任务。'), { stopped: true });
71
+ if (background === 'unavailable') {
72
+ return commandResult(t('无法安全停止后台任务,请在 Harness 中查看并停止对应任务。'));
73
+ }
74
+ }
75
+ return stopped
76
+ ? commandResult(t('已请求停止当前任务。'), { stopped: true })
77
+ : commandResult(t('当前聊天没有正在运行的任务。'));
78
+ }
79
+
80
+ const match = /^\/steer(?:\s+([\s\S]*))?$/iu.exec(command);
81
+ const instruction = match?.[1]?.trim() ?? '';
82
+ if (!instruction) return commandResult(t(STEER_USAGE));
83
+ if (pendingInteraction) {
84
+ return commandResult([
85
+ t('当前任务正在等待你的回答或审批。'),
86
+ '',
87
+ t('请先处理当前请求,或者发送 /stop 停止任务。'),
88
+ ].join('\n'));
89
+ }
90
+
91
+ const session = boundSession(harness, state, key);
92
+ if (!session) {
93
+ return commandResult(t('当前聊天没有绑定会话,无法补充指令。请先绑定会话。'));
94
+ }
95
+ if (typeof session.steerActiveTurn !== 'function') {
96
+ throw new TypeError('Harness session does not support steering active turns');
97
+ }
98
+ // A mid-turn correction carries the same provenance as the message that
99
+ // opened the turn, so a group member who steers is identified too.
100
+ const steering = enhancement
101
+ ? enhanceContextContent(instruction, enhancement.snapshot, enhancement.source)
102
+ : instruction;
103
+ const steered = await session.steerActiveTurn(
104
+ steering,
105
+ control,
106
+ requestOptions(signal),
107
+ );
108
+ return steered
109
+ ? commandResult(t('已提交补充指令,Agent 会在下一步读取。'))
110
+ : commandResult(t('任务已结束,没有正在运行的任务,无法补充指令。请直接发送消息开始新任务。'));
111
+ }
@@ -0,0 +1,165 @@
1
+ import { deferredStateAccess, normalizeDeferredState } from './deferred-state.mjs';
2
+ import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+
5
+ /**
6
+ * Additional persisted keys a subclass may own. Kept intentionally small and
7
+ * explicit: a subclass reads and writes them through extensionState().
8
+ */
9
+ const EXTENSION_KEYS = Object.freeze([
10
+ 'emailBindings', 'mailCursor', 'pendingAuth', 'threadIds',
11
+ ]);
12
+
13
+ const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [], cursor: null });
14
+
15
+ function normalizeState(value) {
16
+ if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
17
+ const sessions = {};
18
+ if (value.sessions && typeof value.sessions === 'object' && !Array.isArray(value.sessions)) {
19
+ for (const [key, sessionId] of Object.entries(value.sessions)) {
20
+ if (typeof key === 'string' && key && typeof sessionId === 'string' && sessionId) {
21
+ sessions[key] = sessionId;
22
+ }
23
+ }
24
+ }
25
+ const normalized = {
26
+ version: 1,
27
+ sessions,
28
+ ...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
29
+ seenMessageIds: Array.isArray(value.seenMessageIds)
30
+ ? value.seenMessageIds.filter((id) => typeof id === 'string' && id).slice(-1_000)
31
+ : [],
32
+ cursor: Number.isSafeInteger(value.cursor) && value.cursor >= 0 ? value.cursor : null,
33
+ };
34
+ // Channel-specific extensions survive a reload; each is normalized by the
35
+ // subclass that owns it (see extensionKeys()).
36
+ for (const key of EXTENSION_KEYS) {
37
+ if (Object.hasOwn(value, key)) normalized[key] = value[key];
38
+ }
39
+ return normalized;
40
+ }
41
+
42
+ export class ConversationStateStore {
43
+ #path;
44
+ #state = structuredClone(EMPTY_STATE);
45
+ #writeQueue = Promise.resolve();
46
+ #deferred = deferredStateAccess(() => this.#state, () => this.#persist());
47
+
48
+ constructor(path) {
49
+ this.#path = path;
50
+ }
51
+
52
+ async load() {
53
+ try {
54
+ this.#state = normalizeState(JSON.parse(await readFile(this.#path, 'utf8')));
55
+ } catch (error) {
56
+ if (error?.code !== 'ENOENT') throw error;
57
+ this.#state = structuredClone(EMPTY_STATE);
58
+ await this.#persist();
59
+ }
60
+ return this;
61
+ }
62
+
63
+ deferredEntries() { return this.#deferred.entries(); }
64
+ putDeferred(entry) { return this.#deferred.put(entry); }
65
+ patchDeferred(id, patch) { return this.#deferred.patch(id, patch); }
66
+ removeDeferred(id) { return this.#deferred.remove(id); }
67
+
68
+ sessionFor(key) {
69
+ return this.#state.sessions[key] ?? null;
70
+ }
71
+
72
+ async setSession(key, sessionId) {
73
+ this.#state.sessions[key] = sessionId;
74
+ await this.#persist();
75
+ }
76
+
77
+ async clearSession(key) {
78
+ delete this.#state.sessions[key];
79
+ await this.#persist();
80
+ }
81
+
82
+ async clearSessions() {
83
+ this.#state.sessions = {};
84
+ await this.#persist();
85
+ }
86
+
87
+ hasSeen(messageId) {
88
+ return this.#state.seenMessageIds.includes(messageId);
89
+ }
90
+
91
+ async markSeen(messageId) {
92
+ if (this.hasSeen(messageId)) return;
93
+ this.#state.seenMessageIds.push(messageId);
94
+ if (this.#state.seenMessageIds.length > 1_000) {
95
+ this.#state.seenMessageIds.splice(0, this.#state.seenMessageIds.length - 1_000);
96
+ }
97
+ await this.#persist();
98
+ }
99
+
100
+ /**
101
+ * Take back a `markSeen` whose delivery never happened.
102
+ *
103
+ * `markSeen` means "this message was handled". A turn that failed before
104
+ * producing anything is not handled, so keeping the mark makes the id a
105
+ * permanent tombstone: every later poll short-circuits on `hasSeen` and the
106
+ * mail is never retried. The bridge calls this to separate "attempted" from
107
+ * "done". A message that already succeeded is never unmarked.
108
+ */
109
+ async unmarkSeen(messageId) {
110
+ const index = this.#state.seenMessageIds.indexOf(messageId);
111
+ if (index === -1) return false;
112
+ this.#state.seenMessageIds.splice(index, 1);
113
+ await this.#persist();
114
+ return true;
115
+ }
116
+
117
+ cursor() {
118
+ return this.#state.cursor;
119
+ }
120
+
121
+ async setCursor(cursor) {
122
+ if (!Number.isSafeInteger(cursor) || cursor < 0) throw new TypeError('Invalid update cursor');
123
+ this.#state.cursor = cursor;
124
+ await this.#persist();
125
+ }
126
+
127
+ snapshot() {
128
+ return structuredClone(this.#state);
129
+ }
130
+
131
+ /**
132
+ * Live view of the private state for subclasses that persist their own keys.
133
+ * Returns the real object (not a clone) so an extension can be written in
134
+ * place; call persist() afterwards.
135
+ */
136
+ extensionState() {
137
+ return this.#state;
138
+ }
139
+
140
+ /** Flush the current state to disk after an extension write. */
141
+ persist() {
142
+ return this.#persist();
143
+ }
144
+
145
+ async remove() {
146
+ try {
147
+ await unlink(this.#path);
148
+ } catch (error) {
149
+ if (error?.code !== 'ENOENT') throw error;
150
+ }
151
+ this.#state = structuredClone(EMPTY_STATE);
152
+ }
153
+
154
+ async #persist() {
155
+ const snapshot = `${JSON.stringify(this.#state, null, 2)}\n`;
156
+ const operation = this.#writeQueue.then(async () => {
157
+ await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
158
+ const temporary = `${this.#path}.tmp`;
159
+ await writeFile(temporary, snapshot, { encoding: 'utf8', mode: 0o600 });
160
+ await rename(temporary, this.#path);
161
+ });
162
+ this.#writeQueue = operation.then(() => undefined, () => undefined);
163
+ await operation;
164
+ }
165
+ }
@@ -0,0 +1,31 @@
1
+ import { mkdir, realpath } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+
5
+ export function defaultImWorkspace(config = {}) {
6
+ const dshHome = config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh');
7
+ return resolve(dshHome, 'im');
8
+ }
9
+
10
+ export async function sameWorkspacePath(left, right) {
11
+ if (typeof left !== 'string' || typeof right !== 'string'
12
+ || !isAbsolute(left) || !isAbsolute(right)) return false;
13
+ if (resolve(left) === resolve(right)) return true;
14
+ try {
15
+ return resolve(await realpath(left)) === resolve(await realpath(right));
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+
21
+ export async function prepareBotWorkspace(config = {}) {
22
+ const ungroupedWorkspace = defaultImWorkspace(config);
23
+ const defaultWorkspace = resolve(config.workspace ?? ungroupedWorkspace);
24
+ return { defaultWorkspace, ungroupedWorkspace };
25
+ }
26
+
27
+ export async function ensureImWorkspaceDirectory(workspace, ungroupedWorkspace) {
28
+ if (await sameWorkspacePath(workspace, ungroupedWorkspace)) {
29
+ await mkdir(workspace, { recursive: true });
30
+ }
31
+ }