@botharness/im-provider 4.32.0-botharness.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (412) hide show
  1. package/LICENSE +21 -0
  2. package/PROVENANCE.json +25 -0
  3. package/README.en.md +445 -0
  4. package/README.md +448 -0
  5. package/THIRD_PARTY_NOTICES.md +93 -0
  6. package/assets/dingtalk-menu-template.json +6 -0
  7. package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
  8. package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
  9. package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
  10. package/assets/logo-icon.png +0 -0
  11. package/assets/logo-plugin-message-link-gradient.webp +0 -0
  12. package/assets/logo-plugin-phone.png +0 -0
  13. package/assets/logo.png +0 -0
  14. package/assets/logo_cn.png +0 -0
  15. package/assets/screenshot-menu-card.png +0 -0
  16. package/cordis.patch.yml +3 -0
  17. package/lib/client.js +20330 -0
  18. package/lib/index.js +602 -0
  19. package/locale/en.json +5 -0
  20. package/locale/zh.json +5 -0
  21. package/package.json +181 -0
  22. package/plugin-src/client/access-policy-settings.js +362 -0
  23. package/plugin-src/client/agent-preset.js +119 -0
  24. package/plugin-src/client/bot-alias.js +169 -0
  25. package/plugin-src/client/build.mjs +38 -0
  26. package/plugin-src/client/channel-card-meta.js +132 -0
  27. package/plugin-src/client/channel-logos.js +190 -0
  28. package/plugin-src/client/channels/dingtalk/api.js +267 -0
  29. package/plugin-src/client/channels/dingtalk/index.js +954 -0
  30. package/plugin-src/client/channels/dingtalk/styles.js +136 -0
  31. package/plugin-src/client/channels/discord/api.js +11 -0
  32. package/plugin-src/client/channels/discord/index.js +25 -0
  33. package/plugin-src/client/channels/discord/styles.js +19 -0
  34. package/plugin-src/client/channels/email/api.js +52 -0
  35. package/plugin-src/client/channels/email/index.js +728 -0
  36. package/plugin-src/client/channels/email/styles.js +51 -0
  37. package/plugin-src/client/channels/feishu/api.js +405 -0
  38. package/plugin-src/client/channels/feishu/group-settings.js +581 -0
  39. package/plugin-src/client/channels/feishu/index.js +1583 -0
  40. package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
  41. package/plugin-src/client/channels/feishu/styles.js +573 -0
  42. package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
  43. package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
  44. package/plugin-src/client/channels/imessage/api.js +12 -0
  45. package/plugin-src/client/channels/imessage/index.js +46 -0
  46. package/plugin-src/client/channels/imessage/styles.js +19 -0
  47. package/plugin-src/client/channels/matrix/api.js +11 -0
  48. package/plugin-src/client/channels/matrix/index.js +151 -0
  49. package/plugin-src/client/channels/matrix/styles.js +36 -0
  50. package/plugin-src/client/channels/office/api.js +46 -0
  51. package/plugin-src/client/channels/office/index.js +153 -0
  52. package/plugin-src/client/channels/office/styles.js +50 -0
  53. package/plugin-src/client/channels/qq/api.js +171 -0
  54. package/plugin-src/client/channels/qq/index.js +593 -0
  55. package/plugin-src/client/channels/qq/styles.js +19 -0
  56. package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
  57. package/plugin-src/client/channels/shared/token-api.js +124 -0
  58. package/plugin-src/client/channels/shared/token-channel.js +495 -0
  59. package/plugin-src/client/channels/slack/api.js +11 -0
  60. package/plugin-src/client/channels/slack/index.js +131 -0
  61. package/plugin-src/client/channels/slack/styles.js +34 -0
  62. package/plugin-src/client/channels/telegram/api.js +11 -0
  63. package/plugin-src/client/channels/telegram/index.js +28 -0
  64. package/plugin-src/client/channels/telegram/styles.js +31 -0
  65. package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
  66. package/plugin-src/client/channels/wecom/api.js +160 -0
  67. package/plugin-src/client/channels/wecom/index.js +625 -0
  68. package/plugin-src/client/channels/wecom/styles.js +19 -0
  69. package/plugin-src/client/channels/wecom-app/api.js +132 -0
  70. package/plugin-src/client/channels/wecom-app/index.js +634 -0
  71. package/plugin-src/client/channels/wecom-app/styles.js +25 -0
  72. package/plugin-src/client/channels/weixin/api.js +211 -0
  73. package/plugin-src/client/channels/weixin/connection-error.js +1 -0
  74. package/plugin-src/client/channels/weixin/index.js +801 -0
  75. package/plugin-src/client/channels/weixin/styles.js +115 -0
  76. package/plugin-src/client/channels/whatsapp/api.js +152 -0
  77. package/plugin-src/client/channels/whatsapp/index.js +609 -0
  78. package/plugin-src/client/channels/whatsapp/styles.js +19 -0
  79. package/plugin-src/client/connection-error.js +87 -0
  80. package/plugin-src/client/context-enhancement.js +415 -0
  81. package/plugin-src/client/credential-binding.js +118 -0
  82. package/plugin-src/client/delivery-settings.js +905 -0
  83. package/plugin-src/client/global-settings.js +433 -0
  84. package/plugin-src/client/i18n.js +1314 -0
  85. package/plugin-src/client/index.js +624 -0
  86. package/plugin-src/client/interface-language.js +89 -0
  87. package/plugin-src/client/last-message-error.js +18 -0
  88. package/plugin-src/client/lifecycle.js +86 -0
  89. package/plugin-src/client/loopback-recovery.js +75 -0
  90. package/plugin-src/client/model-setting.js +172 -0
  91. package/plugin-src/client/panel-error-boundary.js +21 -0
  92. package/plugin-src/client/plugin-page.js +51 -0
  93. package/plugin-src/client/session-channel-logos.js +243 -0
  94. package/plugin-src/client/styles.js +770 -0
  95. package/plugin-src/client/update-panel.js +14 -0
  96. package/plugin-src/client/workspace-directory-picker.js +280 -0
  97. package/plugin-src/client/workspace-editor.js +69 -0
  98. package/plugin-src/client/workspace-snapshot-fence.js +28 -0
  99. package/plugin-src/host/build.mjs +52 -0
  100. package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
  101. package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
  102. package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
  103. package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
  104. package/plugin-src/host/channels/discord/index.mjs +33 -0
  105. package/plugin-src/host/channels/discord/production.mjs +17 -0
  106. package/plugin-src/host/channels/discord/rpc.mjs +21 -0
  107. package/plugin-src/host/channels/email/availability.mjs +60 -0
  108. package/plugin-src/host/channels/email/index.mjs +36 -0
  109. package/plugin-src/host/channels/email/production.mjs +58 -0
  110. package/plugin-src/host/channels/email/rpc.mjs +163 -0
  111. package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
  112. package/plugin-src/host/channels/feishu/controller.mjs +172 -0
  113. package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
  114. package/plugin-src/host/channels/feishu/index.mjs +69 -0
  115. package/plugin-src/host/channels/feishu/production.mjs +318 -0
  116. package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
  117. package/plugin-src/host/channels/imessage/index.mjs +21 -0
  118. package/plugin-src/host/channels/imessage/production.mjs +13 -0
  119. package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
  120. package/plugin-src/host/channels/matrix/index.mjs +31 -0
  121. package/plugin-src/host/channels/matrix/production.mjs +241 -0
  122. package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
  123. package/plugin-src/host/channels/office/index.mjs +14 -0
  124. package/plugin-src/host/channels/office/production.mjs +45 -0
  125. package/plugin-src/host/channels/office/rpc.mjs +51 -0
  126. package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
  127. package/plugin-src/host/channels/qq/index.mjs +28 -0
  128. package/plugin-src/host/channels/qq/production.mjs +181 -0
  129. package/plugin-src/host/channels/qq/rpc.mjs +250 -0
  130. package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
  131. package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
  132. package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
  133. package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
  134. package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
  135. package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
  136. package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
  137. package/plugin-src/host/channels/shared/production.mjs +237 -0
  138. package/plugin-src/host/channels/shared/rpc.mjs +226 -0
  139. package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
  140. package/plugin-src/host/channels/shared/startup.mjs +76 -0
  141. package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
  142. package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
  143. package/plugin-src/host/channels/slack/index.mjs +31 -0
  144. package/plugin-src/host/channels/slack/production.mjs +176 -0
  145. package/plugin-src/host/channels/slack/rpc.mjs +221 -0
  146. package/plugin-src/host/channels/telegram/index.mjs +33 -0
  147. package/plugin-src/host/channels/telegram/production.mjs +19 -0
  148. package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
  149. package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
  150. package/plugin-src/host/channels/wecom/index.mjs +34 -0
  151. package/plugin-src/host/channels/wecom/production.mjs +187 -0
  152. package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
  153. package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
  154. package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
  155. package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
  156. package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
  157. package/plugin-src/host/channels/weixin/index.mjs +44 -0
  158. package/plugin-src/host/channels/weixin/production.mjs +257 -0
  159. package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
  160. package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
  161. package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
  162. package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
  163. package/plugin-src/host/delivery-adapter.mjs +388 -0
  164. package/plugin-src/host/delivery-http.mjs +132 -0
  165. package/plugin-src/host/delivery-rpc.mjs +173 -0
  166. package/plugin-src/host/delivery-service.mjs +552 -0
  167. package/plugin-src/host/delivery-suggestions.mjs +198 -0
  168. package/plugin-src/host/harness-command-executor.mjs +48 -0
  169. package/plugin-src/host/harness-connection.mjs +20 -0
  170. package/plugin-src/host/harness-session-coordinator.mjs +183 -0
  171. package/plugin-src/host/host-language-rpc.mjs +71 -0
  172. package/plugin-src/host/host-language.mjs +157 -0
  173. package/plugin-src/host/image-input-rpc.mjs +24 -0
  174. package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
  175. package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
  176. package/plugin-src/host/inbound-ttl-service.mjs +179 -0
  177. package/plugin-src/host/index.mjs +224 -0
  178. package/plugin-src/host/injected-context.mjs +104 -0
  179. package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
  180. package/plugin-src/host/modern-harness-api.mjs +738 -0
  181. package/plugin-src/host/rpc-authority.mjs +12 -0
  182. package/plugin-src/host/session-sync-coordinator.mjs +233 -0
  183. package/plugin-src/host/session-title-prefix.mjs +122 -0
  184. package/plugin-src/host/update-policy.mjs +31 -0
  185. package/plugin-src/host/update-rpc.mjs +16 -0
  186. package/plugin-src/host/update-runtime.mjs +339 -0
  187. package/plugin-src/host/update-service.mjs +392 -0
  188. package/plugin-src/management-rpc.mjs +87 -0
  189. package/src/channels/dingtalk/config-store.mjs +284 -0
  190. package/src/channels/dingtalk/connection-error.mjs +292 -0
  191. package/src/channels/dingtalk/device-auth.mjs +240 -0
  192. package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
  193. package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
  194. package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
  195. package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
  196. package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
  197. package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
  198. package/src/channels/dingtalk/harness-client.mjs +19 -0
  199. package/src/channels/dingtalk/state-store.mjs +325 -0
  200. package/src/channels/discord/config-store.mjs +25 -0
  201. package/src/channels/discord/discord-api.mjs +347 -0
  202. package/src/channels/discord/discord-bridge.mjs +16 -0
  203. package/src/channels/discord/discord-controller.mjs +16 -0
  204. package/src/channels/discord/discord-runtime.mjs +974 -0
  205. package/src/channels/discord/harness-client.mjs +11 -0
  206. package/src/channels/discord/state-store.mjs +3 -0
  207. package/src/channels/email/config-store.mjs +194 -0
  208. package/src/channels/email/email-api.mjs +20 -0
  209. package/src/channels/email/email-bridge.mjs +17 -0
  210. package/src/channels/email/email-controller.mjs +824 -0
  211. package/src/channels/email/email-runtime.mjs +699 -0
  212. package/src/channels/email/harness-client.mjs +7 -0
  213. package/src/channels/email/mail-format.mjs +91 -0
  214. package/src/channels/email/state-store.mjs +176 -0
  215. package/src/channels/email/transport.mjs +64 -0
  216. package/src/channels/email/transports/agent-mail.mjs +604 -0
  217. package/src/channels/email/transports/agently-cli.mjs +288 -0
  218. package/src/channels/email/transports/imap-smtp.mjs +165 -0
  219. package/src/channels/feishu/bridge.mjs +6286 -0
  220. package/src/channels/feishu/config.mjs +71 -0
  221. package/src/channels/feishu/external-consumer.mjs +77 -0
  222. package/src/channels/feishu/external-files.mjs +111 -0
  223. package/src/channels/feishu/feishu-app.mjs +54 -0
  224. package/src/channels/feishu/feishu-cards.mjs +1285 -0
  225. package/src/channels/feishu/feishu-channel.mjs +651 -0
  226. package/src/channels/feishu/feishu-runtime.mjs +950 -0
  227. package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
  228. package/src/channels/feishu/group-response-mode.mjs +15 -0
  229. package/src/channels/feishu/harness-client.mjs +19 -0
  230. package/src/channels/feishu/history-reader.mjs +77 -0
  231. package/src/channels/feishu/live-cot.mjs +260 -0
  232. package/src/channels/feishu/message-utils.mjs +613 -0
  233. package/src/channels/feishu/multi-bot-controller.mjs +1588 -0
  234. package/src/channels/feishu/nearby-history.mjs +72 -0
  235. package/src/channels/feishu/plugin-config-store.mjs +216 -0
  236. package/src/channels/feishu/plugin-controller.mjs +254 -0
  237. package/src/channels/feishu/registration-manager.mjs +349 -0
  238. package/src/channels/feishu/repair-manager.mjs +138 -0
  239. package/src/channels/feishu/reply-context.mjs +22 -0
  240. package/src/channels/feishu/slash-command-panel.mjs +155 -0
  241. package/src/channels/feishu/slash-command-registry.mjs +495 -0
  242. package/src/channels/feishu/state-store.mjs +214 -0
  243. package/src/channels/feishu/step-push-mode.mjs +25 -0
  244. package/src/channels/feishu/voice-config.mjs +34 -0
  245. package/src/channels/feishu/voice.mjs +134 -0
  246. package/src/channels/imessage/config-store.mjs +24 -0
  247. package/src/channels/imessage/controller.mjs +37 -0
  248. package/src/channels/imessage/harness-client.mjs +7 -0
  249. package/src/channels/imessage/imessage-api.mjs +194 -0
  250. package/src/channels/imessage/imessage-bridge.mjs +16 -0
  251. package/src/channels/imessage/runtime.mjs +102 -0
  252. package/src/channels/imessage/state-store.mjs +3 -0
  253. package/src/channels/matrix/matrix-api.mjs +696 -0
  254. package/src/channels/matrix/matrix-bridge.mjs +20 -0
  255. package/src/channels/matrix/matrix-config-store.mjs +368 -0
  256. package/src/channels/matrix/matrix-controller.mjs +404 -0
  257. package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
  258. package/src/channels/matrix/matrix-crypto.mjs +1014 -0
  259. package/src/channels/matrix/matrix-harness-client.mjs +11 -0
  260. package/src/channels/matrix/matrix-normalize.mjs +357 -0
  261. package/src/channels/matrix/matrix-rich-text.mjs +313 -0
  262. package/src/channels/matrix/matrix-room-history.mjs +316 -0
  263. package/src/channels/matrix/matrix-runtime.mjs +1014 -0
  264. package/src/channels/office/config-store.mjs +107 -0
  265. package/src/channels/office/office-controller.mjs +178 -0
  266. package/src/channels/office/office-job-executor.mjs +391 -0
  267. package/src/channels/office/office-runtime.mjs +175 -0
  268. package/src/channels/office/office-transport.mjs +171 -0
  269. package/src/channels/office/protocol.mjs +43 -0
  270. package/src/channels/qq/config-store.mjs +173 -0
  271. package/src/channels/qq/harness-client.mjs +11 -0
  272. package/src/channels/qq/markdown-reply.mjs +446 -0
  273. package/src/channels/qq/qq-bridge.mjs +1507 -0
  274. package/src/channels/qq/qq-controller.mjs +514 -0
  275. package/src/channels/qq/qq-menu.mjs +208 -0
  276. package/src/channels/qq/qq-runtime.mjs +303 -0
  277. package/src/channels/qq/qr-auth.mjs +24 -0
  278. package/src/channels/qq/state-error.mjs +17 -0
  279. package/src/channels/qq/state-store.mjs +143 -0
  280. package/src/channels/shared/access-policy.mjs +210 -0
  281. package/src/channels/shared/agent-preset.mjs +76 -0
  282. package/src/channels/shared/batch-input.mjs +229 -0
  283. package/src/channels/shared/bot-alias.mjs +29 -0
  284. package/src/channels/shared/bot-workspace-store.mjs +2383 -0
  285. package/src/channels/shared/command-catalog.mjs +107 -0
  286. package/src/channels/shared/command-permission.mjs +32 -0
  287. package/src/channels/shared/compact-command.mjs +109 -0
  288. package/src/channels/shared/config-read-error.mjs +24 -0
  289. package/src/channels/shared/connection-error.mjs +191 -0
  290. package/src/channels/shared/connection-test.mjs +58 -0
  291. package/src/channels/shared/context-enhancement.mjs +372 -0
  292. package/src/channels/shared/control-command.mjs +111 -0
  293. package/src/channels/shared/conversation-state-store.mjs +165 -0
  294. package/src/channels/shared/default-workspace.mjs +31 -0
  295. package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
  296. package/src/channels/shared/deferred-delivery.mjs +161 -0
  297. package/src/channels/shared/deferred-state.mjs +53 -0
  298. package/src/channels/shared/diagnostic-details.mjs +95 -0
  299. package/src/channels/shared/editable-message-stream.mjs +100 -0
  300. package/src/channels/shared/exclusive-inbound-consumers.mjs +71 -0
  301. package/src/channels/shared/file-download.mjs +64 -0
  302. package/src/channels/shared/harness-approval.mjs +508 -0
  303. package/src/channels/shared/harness-client.mjs +2143 -0
  304. package/src/channels/shared/harness-mux.mjs +123 -0
  305. package/src/channels/shared/harness-question.mjs +95 -0
  306. package/src/channels/shared/harness-session-binding.mjs +119 -0
  307. package/src/channels/shared/history-command.mjs +193 -0
  308. package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
  309. package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
  310. package/src/channels/shared/i18n-en/discord.mjs +10 -0
  311. package/src/channels/shared/i18n-en/email.mjs +25 -0
  312. package/src/channels/shared/i18n-en/feishu.mjs +404 -0
  313. package/src/channels/shared/i18n-en/image-input.mjs +18 -0
  314. package/src/channels/shared/i18n-en/matrix.mjs +85 -0
  315. package/src/channels/shared/i18n-en/office.mjs +23 -0
  316. package/src/channels/shared/i18n-en/qq.mjs +96 -0
  317. package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
  318. package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
  319. package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
  320. package/src/channels/shared/i18n-en/slack.mjs +27 -0
  321. package/src/channels/shared/i18n-en/telegram.mjs +27 -0
  322. package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
  323. package/src/channels/shared/i18n-en/wecom.mjs +62 -0
  324. package/src/channels/shared/i18n-en/weixin.mjs +88 -0
  325. package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
  326. package/src/channels/shared/i18n-en.mjs +45 -0
  327. package/src/channels/shared/i18n.mjs +78 -0
  328. package/src/channels/shared/im-source-guidance.mjs +65 -0
  329. package/src/channels/shared/image-input-policy.mjs +35 -0
  330. package/src/channels/shared/image-input-settings-store.mjs +60 -0
  331. package/src/channels/shared/image-input.mjs +124 -0
  332. package/src/channels/shared/image-prompt.mjs +360 -0
  333. package/src/channels/shared/inbound-access.mjs +43 -0
  334. package/src/channels/shared/inbound-file.mjs +323 -0
  335. package/src/channels/shared/inbound-ttl-store.mjs +110 -0
  336. package/src/channels/shared/inbound-ttl.mjs +22 -0
  337. package/src/channels/shared/injected-context.mjs +362 -0
  338. package/src/channels/shared/interface-language-store.mjs +127 -0
  339. package/src/channels/shared/interface-language.mjs +51 -0
  340. package/src/channels/shared/message-failure.mjs +257 -0
  341. package/src/channels/shared/model-command.mjs +741 -0
  342. package/src/channels/shared/model-setting.mjs +145 -0
  343. package/src/channels/shared/preset-command.mjs +308 -0
  344. package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
  345. package/src/channels/shared/semantic/artifact.mjs +750 -0
  346. package/src/channels/shared/semantic/delivery.mjs +193 -0
  347. package/src/channels/shared/semantic/reply-reference.mjs +148 -0
  348. package/src/channels/shared/session-binding-lock.mjs +40 -0
  349. package/src/channels/shared/session-channel-labels.mjs +28 -0
  350. package/src/channels/shared/session-reply-recovery.mjs +104 -0
  351. package/src/channels/shared/session-sync-registry.mjs +22 -0
  352. package/src/channels/shared/session-title.mjs +74 -0
  353. package/src/channels/shared/status-reaction.mjs +107 -0
  354. package/src/channels/shared/text-harness-bridge.mjs +1623 -0
  355. package/src/channels/shared/token-bot-controller.mjs +417 -0
  356. package/src/channels/shared/token-config-store.mjs +208 -0
  357. package/src/channels/shared/workspace-command.mjs +532 -0
  358. package/src/channels/shared/workspace-session.mjs +196 -0
  359. package/src/channels/slack/config-store.mjs +177 -0
  360. package/src/channels/slack/external-consumer.mjs +80 -0
  361. package/src/channels/slack/external-files.mjs +90 -0
  362. package/src/channels/slack/harness-client.mjs +11 -0
  363. package/src/channels/slack/history-reader.mjs +203 -0
  364. package/src/channels/slack/manifest.mjs +37 -0
  365. package/src/channels/slack/slack-api.mjs +636 -0
  366. package/src/channels/slack/slack-bridge.mjs +20 -0
  367. package/src/channels/slack/slack-controller.mjs +468 -0
  368. package/src/channels/slack/slack-runtime.mjs +879 -0
  369. package/src/channels/slack/state-store.mjs +3 -0
  370. package/src/channels/telegram/config-store.mjs +89 -0
  371. package/src/channels/telegram/harness-client.mjs +11 -0
  372. package/src/channels/telegram/state-store.mjs +3 -0
  373. package/src/channels/telegram/telegram-api.mjs +486 -0
  374. package/src/channels/telegram/telegram-bridge.mjs +81 -0
  375. package/src/channels/telegram/telegram-controller.mjs +52 -0
  376. package/src/channels/telegram/telegram-http.mjs +21 -0
  377. package/src/channels/telegram/telegram-rich-message.mjs +149 -0
  378. package/src/channels/telegram/telegram-runtime.mjs +1471 -0
  379. package/src/channels/wecom/config-store.mjs +172 -0
  380. package/src/channels/wecom/harness-client.mjs +11 -0
  381. package/src/channels/wecom/qr-auth.mjs +95 -0
  382. package/src/channels/wecom/send-error.mjs +31 -0
  383. package/src/channels/wecom/state-store.mjs +107 -0
  384. package/src/channels/wecom/wecom-bridge.mjs +1833 -0
  385. package/src/channels/wecom/wecom-cards.mjs +101 -0
  386. package/src/channels/wecom/wecom-controller.mjs +530 -0
  387. package/src/channels/wecom/wecom-runtime.mjs +269 -0
  388. package/src/channels/wecom-app/callback-server.mjs +471 -0
  389. package/src/channels/wecom-app/config-store.mjs +242 -0
  390. package/src/channels/wecom-app/harness-client.mjs +11 -0
  391. package/src/channels/wecom-app/state-store.mjs +107 -0
  392. package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
  393. package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
  394. package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
  395. package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
  396. package/src/channels/weixin/config-store.mjs +192 -0
  397. package/src/channels/weixin/connection-error.en.mjs +137 -0
  398. package/src/channels/weixin/connection-error.mjs +153 -0
  399. package/src/channels/weixin/diagnostic-details.mjs +1 -0
  400. package/src/channels/weixin/harness-client.mjs +19 -0
  401. package/src/channels/weixin/state-store.mjs +291 -0
  402. package/src/channels/weixin/weixin-api.mjs +949 -0
  403. package/src/channels/weixin/weixin-bridge.mjs +1537 -0
  404. package/src/channels/weixin/weixin-controller.mjs +669 -0
  405. package/src/channels/weixin/weixin-runtime.mjs +416 -0
  406. package/src/channels/whatsapp/config-store.mjs +210 -0
  407. package/src/channels/whatsapp/harness-client.mjs +11 -0
  408. package/src/channels/whatsapp/state-store.mjs +3 -0
  409. package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
  410. package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
  411. package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
  412. package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
@@ -0,0 +1,3 @@
1
+ import { ConversationStateStore } from '../shared/conversation-state-store.mjs';
2
+
3
+ export class SlackStateStore extends ConversationStateStore {}
@@ -0,0 +1,89 @@
1
+ import { t } from '../shared/i18n.mjs';
2
+ import {
3
+ deriveTokenBotIdentity,
4
+ maskPlatformId,
5
+ TokenBotConfigStore,
6
+ } from '../shared/token-config-store.mjs';
7
+
8
+ const IDENTITY_OPTIONS = Object.freeze({
9
+ botPrefix: 'telegram',
10
+ tokenRefPrefix: 'DSH_TELEGRAM_BOT_TOKEN',
11
+ });
12
+
13
+ export const TELEGRAM_ACCESS_MODES = Object.freeze({
14
+ compatible: 'compatible',
15
+ privateAllowlist: 'private-allowlist',
16
+ });
17
+
18
+ const TELEGRAM_USER_ID = /^[1-9]\d{0,15}$/;
19
+
20
+ export function normalizeTelegramAllowedUsers(value) {
21
+ if (value === undefined) return Object.freeze([]);
22
+ if (!Array.isArray(value)) {
23
+ throw new TypeError('allowedUsers must be an array of numeric Telegram User IDs');
24
+ }
25
+ const normalized = value.map((entry) => {
26
+ const userId = typeof entry === 'number' && Number.isSafeInteger(entry)
27
+ ? String(entry) : typeof entry === 'string' ? entry.trim() : '';
28
+ if (!TELEGRAM_USER_ID.test(userId)) {
29
+ throw new TypeError('allowedUsers contains an invalid Telegram User ID');
30
+ }
31
+ return userId;
32
+ });
33
+ return Object.freeze([...new Set(normalized)]);
34
+ }
35
+
36
+ export function normalizeTelegramAccessPolicy(value = {}) {
37
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
38
+ throw new TypeError('Telegram access policy must be an object');
39
+ }
40
+ const accessMode = value.accessMode ?? TELEGRAM_ACCESS_MODES.compatible;
41
+ if (!Object.values(TELEGRAM_ACCESS_MODES).includes(accessMode)) {
42
+ throw new TypeError('Telegram accessMode must be compatible or private-allowlist');
43
+ }
44
+ return Object.freeze({
45
+ accessMode,
46
+ allowedUsers: normalizeTelegramAllowedUsers(value.allowedUsers),
47
+ });
48
+ }
49
+
50
+ function normalizeTelegramBotExtension(value) {
51
+ const hasAccessMode = Object.hasOwn(value, 'accessMode');
52
+ const hasAllowedUsers = Object.hasOwn(value, 'allowedUsers');
53
+ const hasThinkingTraces = Object.hasOwn(value, 'thinkingTraces');
54
+ if (!hasAccessMode && !hasAllowedUsers && !hasThinkingTraces) return {};
55
+ try {
56
+ const policy = normalizeTelegramAccessPolicy(value);
57
+ return {
58
+ ...(hasAccessMode ? { accessMode: policy.accessMode } : {}),
59
+ ...(hasAllowedUsers || hasAccessMode ? { allowedUsers: policy.allowedUsers } : {}),
60
+ // Explicit field is kept; an absent field stays absent.
61
+ ...(hasThinkingTraces ? { thinkingTraces: value.thinkingTraces === true } : {}),
62
+ };
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+
68
+ export function deriveTelegramBotIdentity(platformId) {
69
+ return deriveTokenBotIdentity(platformId, IDENTITY_OPTIONS);
70
+ }
71
+
72
+ export function maskTelegramBotId(platformId) {
73
+ return maskPlatformId(platformId, t('Telegram机器人'));
74
+ }
75
+
76
+ export class TelegramConfigStore extends TokenBotConfigStore {
77
+ constructor(path) {
78
+ super(path, {
79
+ channel: 'Telegram',
80
+ ...IDENTITY_OPTIONS,
81
+ normalizeBotExtension: normalizeTelegramBotExtension,
82
+ });
83
+ }
84
+
85
+ async save(value) {
86
+ const previous = value?.platformId ? this.getByPlatformId(String(value.platformId)) : null;
87
+ return super.save({ ...previous, ...value });
88
+ }
89
+ }
@@ -0,0 +1,11 @@
1
+ import { HarnessClient } from '../shared/harness-client.mjs';
2
+
3
+ export class TelegramHarnessClient extends HarnessClient {
4
+ constructor(options) {
5
+ super({
6
+ ...options,
7
+ rpcIdPrefix: 'telegram',
8
+ logPrefix: 'dsh-telegram',
9
+ });
10
+ }
11
+ }
@@ -0,0 +1,3 @@
1
+ import { ConversationStateStore } from '../shared/conversation-state-store.mjs';
2
+
3
+ export class TelegramStateStore extends ConversationStateStore {}
@@ -0,0 +1,486 @@
1
+ import { fetchFileStream } from '../shared/file-download.mjs';
2
+ import { fetchImageBuffer } from '../shared/image-prompt.mjs';
3
+ import { t } from '../shared/i18n.mjs';
4
+
5
+ const DEFAULT_BASE_URL = 'https://api.telegram.org/';
6
+ const TELEGRAM_FILE_HOSTS = Object.freeze(['api.telegram.org']);
7
+ const DEFAULT_FILE_UPLOAD_TIMEOUT_MS = 120_000;
8
+
9
+ function cleanString(value) {
10
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
11
+ }
12
+
13
+ function requestSignal(signal, timeoutMs) {
14
+ const timeout = AbortSignal.timeout(timeoutMs);
15
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
16
+ }
17
+
18
+ function abortReason(signal) {
19
+ return signal?.reason instanceof Error
20
+ ? signal.reason
21
+ : new DOMException('The operation was aborted', 'AbortError');
22
+ }
23
+
24
+ function positiveTimeout(value, name) {
25
+ if (!Number.isInteger(value) || value < 1) throw new TypeError(`${name} must be a positive integer`);
26
+ return value;
27
+ }
28
+
29
+ function preserveProviderMetadata(target, source) {
30
+ if (source?.providerCode !== undefined) target.providerCode = source.providerCode;
31
+ if (source?.retry_after !== undefined) {
32
+ target.retry_after = source.retry_after;
33
+ target.retryAfter = source.retry_after;
34
+ }
35
+ if (Number.isInteger(source?.status)) target.status = source.status;
36
+ return target;
37
+ }
38
+
39
+ function inputRichMessage(value) {
40
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
41
+ throw new TypeError('A Telegram rich message is required');
42
+ }
43
+ const formats = ['markdown', 'html', 'blocks'].filter((key) => value[key] !== undefined);
44
+ if (formats.length !== 1) {
45
+ throw new TypeError('A Telegram rich message requires exactly one format');
46
+ }
47
+ const selected = formats[0];
48
+ if ((selected === 'markdown' || selected === 'html')
49
+ && (typeof value[selected] !== 'string' || !value[selected].trim())) {
50
+ throw new TypeError('Telegram rich message text is invalid');
51
+ }
52
+ if (selected === 'blocks' && !Array.isArray(value.blocks)) {
53
+ throw new TypeError('Telegram rich message blocks are invalid');
54
+ }
55
+ return value;
56
+ }
57
+
58
+ /** Telegram rejects callback_data longer than 64 bytes. */
59
+ const CALLBACK_DATA_MAX_BYTES = 64;
60
+
61
+ /** Validate an inline keyboard so no oversized or malformed payload is dispatched.
62
+ * An empty `inline_keyboard` is accepted: that is how Telegram removes a keyboard.
63
+ */
64
+ function inputReplyMarkup(value) {
65
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
66
+ throw new TypeError('A Telegram reply markup is required');
67
+ }
68
+ const rows = value.inline_keyboard;
69
+ if (!Array.isArray(rows)) {
70
+ throw new TypeError('Telegram reply markup requires inline_keyboard rows');
71
+ }
72
+ return {
73
+ inline_keyboard: rows.map((row) => {
74
+ if (!Array.isArray(row) || row.length === 0) {
75
+ throw new TypeError('Telegram inline keyboard rows must be non-empty arrays');
76
+ }
77
+ return row.map((button) => {
78
+ const text = cleanString(button?.text);
79
+ const data = cleanString(button?.callback_data);
80
+ if (!text || !data) {
81
+ throw new TypeError('Telegram inline keyboard buttons require text and callback_data');
82
+ }
83
+ if (Buffer.byteLength(data, 'utf8') > CALLBACK_DATA_MAX_BYTES) {
84
+ throw new TypeError(
85
+ `Telegram callback_data must be at most ${CALLBACK_DATA_MAX_BYTES} bytes`,
86
+ );
87
+ }
88
+ return { text, callback_data: data };
89
+ });
90
+ }),
91
+ };
92
+ }
93
+
94
+ function telegramArtifactProviderError(cause, mediaLabel = 'document') {
95
+ const providerCode = Number(cause?.providerCode);
96
+ const status = Number(cause?.status);
97
+ const message = cleanString(cause?.message) ?? '';
98
+ let code = 'artifact-provider-rejected';
99
+ let summary = `Telegram rejected the ${mediaLabel}.`;
100
+ if (providerCode === 401 || providerCode === 403 || status === 401 || status === 403) {
101
+ code = 'artifact-permission-required';
102
+ summary = `Telegram denied permission to send the ${mediaLabel}.`;
103
+ } else if (providerCode === 413 || status === 413
104
+ || /(?:file|request|entity).{0,20}(?:too (?:big|large)|size limit)|too (?:big|large)/i.test(message)) {
105
+ code = 'artifact-too-large';
106
+ summary = `The ${mediaLabel} exceeds Telegram's size limit.`;
107
+ } else if (providerCode === 429 || status === 429) {
108
+ code = 'artifact-rate-limited';
109
+ summary = `Telegram rate-limited ${mediaLabel} delivery.`;
110
+ } else if (providerCode >= 500 || status >= 500) {
111
+ code = 'artifact-delivery-uncertain';
112
+ summary = `Telegram ${mediaLabel} delivery result is uncertain.`;
113
+ }
114
+ const error = new Error(summary, { cause });
115
+ error.code = code;
116
+ return preserveProviderMetadata(error, cause);
117
+ }
118
+
119
+ function uncertainTelegramDelivery(cause, mediaLabel = 'document') {
120
+ const error = new Error(`Telegram ${mediaLabel} delivery result is uncertain`, { cause });
121
+ error.code = 'artifact-delivery-uncertain';
122
+ return preserveProviderMetadata(error, cause);
123
+ }
124
+
125
+ export function validTelegramToken(value) {
126
+ return typeof value === 'string' && /^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(value.trim());
127
+ }
128
+
129
+ const TELEGRAM_COMMAND_NAME = /^[a-z0-9_]{1,32}$/;
130
+
131
+ function validBotCommand(value) {
132
+ return Boolean(value)
133
+ && typeof value === 'object' && !Array.isArray(value)
134
+ && typeof value.command === 'string' && TELEGRAM_COMMAND_NAME.test(value.command)
135
+ && typeof value.description === 'string' && value.description.trim().length >= 1
136
+ && [...value.description].length <= 256;
137
+ }
138
+
139
+ export function validateTelegramCommands(commands, { allowEmpty = false } = {}) {
140
+ if (!Array.isArray(commands) || (!allowEmpty && commands.length === 0)
141
+ || commands.length > 100 || commands.some((command) => !validBotCommand(command))
142
+ || new Set(commands.map((item) => item.command)).size !== commands.length) {
143
+ throw new TypeError('Telegram bot commands are invalid');
144
+ }
145
+ }
146
+
147
+ export const COMMANDS_MENU_BUTTON = Object.freeze({ type: 'commands' });
148
+
149
+ export class TelegramApi {
150
+ #token;
151
+ #fetch;
152
+ #FormDataImpl;
153
+ #baseUrl;
154
+ #fileUploadTimeoutMs;
155
+
156
+ constructor({
157
+ token,
158
+ fetchImpl = fetch,
159
+ FormDataImpl = globalThis.FormData,
160
+ baseUrl = DEFAULT_BASE_URL,
161
+ fileUploadTimeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS,
162
+ }) {
163
+ if (!validTelegramToken(token)) throw new TypeError('Telegram Bot Token is invalid');
164
+ if (typeof fetchImpl !== 'function') throw new TypeError('TelegramApi requires fetch');
165
+ if (typeof FormDataImpl !== 'function') throw new TypeError('TelegramApi requires FormData');
166
+ this.#token = token.trim();
167
+ this.#fetch = fetchImpl;
168
+ this.#FormDataImpl = FormDataImpl;
169
+ this.#baseUrl = new URL(baseUrl);
170
+ this.#fileUploadTimeoutMs = positiveTimeout(fileUploadTimeoutMs, 'fileUploadTimeoutMs');
171
+ }
172
+
173
+ async getMe(options = {}) {
174
+ return this.#call('getMe', {}, options);
175
+ }
176
+
177
+ async getWebhookInfo(options = {}) {
178
+ return this.#call('getWebhookInfo', {}, options);
179
+ }
180
+
181
+ async getUpdates({ offset, timeout = 25, signal } = {}) {
182
+ const payload = {
183
+ timeout,
184
+ limit: 100,
185
+ allowed_updates: ['message', 'callback_query'],
186
+ ...(Number.isSafeInteger(offset) ? { offset } : {}),
187
+ };
188
+ return this.#call('getUpdates', payload, {
189
+ signal,
190
+ timeoutMs: Math.max(10_000, (timeout + 10) * 1_000),
191
+ });
192
+ }
193
+
194
+ async getFile({ fileId, signal } = {}) {
195
+ const id = cleanString(fileId);
196
+ if (!id || !/^[A-Za-z0-9_-]{1,512}$/.test(id)) {
197
+ throw new TypeError('Telegram file id is invalid');
198
+ }
199
+ return this.#call('getFile', { file_id: id }, { signal });
200
+ }
201
+
202
+ async downloadFile({ fileId, signal, maxBytes } = {}) {
203
+ const url = await this.#downloadUrl(fileId, signal);
204
+ return fetchImageBuffer(url, {
205
+ fetchImpl: this.#fetch,
206
+ signal,
207
+ maxBytes,
208
+ allowedHosts: TELEGRAM_FILE_HOSTS,
209
+ });
210
+ }
211
+
212
+ async downloadFileStream({ fileId, signal } = {}) {
213
+ const url = await this.#downloadUrl(fileId, signal);
214
+ return fetchFileStream(url, {
215
+ fetchImpl: this.#fetch,
216
+ signal,
217
+ allowedHosts: TELEGRAM_FILE_HOSTS,
218
+ });
219
+ }
220
+
221
+ async #downloadUrl(fileId, signal) {
222
+ const file = await this.getFile({ fileId, signal });
223
+ const filePath = cleanString(file?.file_path);
224
+ if (!filePath || filePath.startsWith('/') || filePath.includes('\\')
225
+ || filePath.includes('?') || filePath.includes('#')) {
226
+ throw new Error('Telegram returned an invalid file path');
227
+ }
228
+ let decodedSegments;
229
+ try {
230
+ decodedSegments = filePath.split('/').map((segment) => decodeURIComponent(segment));
231
+ } catch {
232
+ throw new Error('Telegram returned an invalid file path');
233
+ }
234
+ if (decodedSegments.some((segment) => !segment || segment === '.' || segment === '..')) {
235
+ throw new Error('Telegram returned an invalid file path');
236
+ }
237
+ const url = new URL(this.#baseUrl);
238
+ url.pathname = `/file/bot${this.#token}/${filePath}`;
239
+ return url;
240
+ }
241
+
242
+ async sendMessage({ chatId, text, replyToMessageId, messageThreadId, replyMarkup, signal }) {
243
+ return this.#call('sendMessage', {
244
+ chat_id: chatId,
245
+ text,
246
+ link_preview_options: { is_disabled: true },
247
+ ...(replyToMessageId ? {
248
+ reply_parameters: { message_id: replyToMessageId, allow_sending_without_reply: true },
249
+ } : {}),
250
+ ...(messageThreadId ? { message_thread_id: messageThreadId } : {}),
251
+ ...(replyMarkup === undefined ? {} : { reply_markup: inputReplyMarkup(replyMarkup) }),
252
+ }, { signal });
253
+ }
254
+
255
+ /** Acknowledge a button press so the client stops showing its progress spinner. */
256
+ async answerCallbackQuery({ callbackQueryId, text, signal }) {
257
+ const queryId = cleanString(callbackQueryId);
258
+ if (!queryId) throw new TypeError('Telegram callback query id is required');
259
+ const notice = cleanString(text);
260
+ return this.#call('answerCallbackQuery', {
261
+ callback_query_id: queryId,
262
+ ...(notice ? { text: notice } : {}),
263
+ }, { signal });
264
+ }
265
+
266
+ /** Replace only the keyboard of an existing message, keeping its text intact. */
267
+ async editMessageReplyMarkup({ chatId, messageId, replyMarkup, signal }) {
268
+ if (!Number.isSafeInteger(messageId)) {
269
+ throw new TypeError('Telegram message id must be a safe integer');
270
+ }
271
+ return this.#call('editMessageReplyMarkup', {
272
+ chat_id: chatId,
273
+ message_id: messageId,
274
+ ...(replyMarkup === undefined ? {} : { reply_markup: inputReplyMarkup(replyMarkup) }),
275
+ }, { signal });
276
+ }
277
+
278
+ async setMessageReaction({ chatId, messageId, emoji, signal, timeoutMs }) {
279
+ const normalizedEmoji = cleanString(emoji);
280
+ return this.#call('setMessageReaction', {
281
+ chat_id: chatId,
282
+ message_id: messageId,
283
+ reaction: normalizedEmoji ? [{ type: 'emoji', emoji: normalizedEmoji }] : [],
284
+ }, { signal, timeoutMs });
285
+ }
286
+
287
+ async sendRichMessage({
288
+ chatId,
289
+ richMessage,
290
+ replyToMessageId,
291
+ messageThreadId,
292
+ signal,
293
+ }) {
294
+ return this.#call('sendRichMessage', {
295
+ chat_id: chatId,
296
+ rich_message: inputRichMessage(richMessage),
297
+ ...(replyToMessageId ? {
298
+ reply_parameters: { message_id: replyToMessageId, allow_sending_without_reply: true },
299
+ } : {}),
300
+ ...(messageThreadId ? { message_thread_id: messageThreadId } : {}),
301
+ }, { signal });
302
+ }
303
+
304
+ async sendRichMessageDraft({ chatId, draftId, richMessage, messageThreadId, signal }) {
305
+ if (!Number.isSafeInteger(draftId) || draftId === 0) {
306
+ throw new TypeError('Telegram rich message draft id must be a non-zero integer');
307
+ }
308
+ return this.#call('sendRichMessageDraft', {
309
+ chat_id: chatId,
310
+ draft_id: draftId,
311
+ rich_message: inputRichMessage(richMessage),
312
+ ...(messageThreadId ? { message_thread_id: messageThreadId } : {}),
313
+ }, { signal });
314
+ }
315
+
316
+ async sendDocument({ chatId, file, replyToMessageId, messageThreadId, signal }) {
317
+ return this.#sendArtifact('sendDocument', 'document', 'document', {
318
+ chatId,
319
+ file,
320
+ replyToMessageId,
321
+ messageThreadId,
322
+ signal,
323
+ });
324
+ }
325
+
326
+ async sendPhoto({ chatId, file, replyToMessageId, messageThreadId, signal }) {
327
+ return this.#sendArtifact('sendPhoto', 'photo', 'photo', {
328
+ chatId,
329
+ file,
330
+ replyToMessageId,
331
+ messageThreadId,
332
+ signal,
333
+ });
334
+ }
335
+
336
+ async #sendArtifact(method, fieldName, mediaLabel, {
337
+ chatId,
338
+ file,
339
+ replyToMessageId,
340
+ messageThreadId,
341
+ signal,
342
+ }) {
343
+ if (!file || typeof file !== 'object'
344
+ || typeof file.fileName !== 'string' || !file.fileName
345
+ || !Buffer.isBuffer(file.bytes)) {
346
+ throw new TypeError(`A Telegram ${mediaLabel} is required`);
347
+ }
348
+ const payload = new this.#FormDataImpl();
349
+ payload.append('chat_id', String(chatId));
350
+ payload.append(
351
+ fieldName,
352
+ new Blob([file.bytes], { type: file.mediaType ?? 'application/octet-stream' }),
353
+ file.fileName,
354
+ );
355
+ if (replyToMessageId) {
356
+ payload.append('reply_parameters', JSON.stringify({
357
+ message_id: replyToMessageId,
358
+ allow_sending_without_reply: true,
359
+ }));
360
+ }
361
+ if (messageThreadId) payload.append('message_thread_id', String(messageThreadId));
362
+ if (signal?.aborted) throw abortReason(signal);
363
+ const uploadSignal = requestSignal(signal, this.#fileUploadTimeoutMs);
364
+ try {
365
+ return await this.#call(method, payload, {
366
+ signal: uploadSignal,
367
+ timeoutMs: this.#fileUploadTimeoutMs,
368
+ multipart: true,
369
+ });
370
+ } catch (error) {
371
+ if (signal?.aborted) throw abortReason(signal);
372
+ if (error?.deliveryOutcome === 'unknown') {
373
+ throw uncertainTelegramDelivery(error?.cause ?? error, mediaLabel);
374
+ }
375
+ if (error?.code?.startsWith?.('telegram-')) {
376
+ throw telegramArtifactProviderError(error, mediaLabel);
377
+ }
378
+ throw uncertainTelegramDelivery(error, mediaLabel);
379
+ }
380
+ }
381
+
382
+ async editMessageText({ chatId, messageId, text, richMessage, signal }) {
383
+ if ((text === undefined) === (richMessage === undefined)) {
384
+ throw new TypeError('Telegram message edit requires exactly one of text or richMessage');
385
+ }
386
+ return this.#call('editMessageText', {
387
+ chat_id: chatId,
388
+ message_id: messageId,
389
+ ...(text === undefined ? { rich_message: inputRichMessage(richMessage) } : {
390
+ text,
391
+ link_preview_options: { is_disabled: true },
392
+ }),
393
+ }, { signal });
394
+ }
395
+
396
+ async sendChatAction({ chatId, messageThreadId, signal }) {
397
+ return this.#call('sendChatAction', {
398
+ chat_id: chatId,
399
+ action: 'typing',
400
+ ...(messageThreadId ? { message_thread_id: messageThreadId } : {}),
401
+ }, { signal });
402
+ }
403
+
404
+ async setMyCommands({ commands, scope, languageCode, signal } = {}) {
405
+ validateTelegramCommands(commands);
406
+ return this.#call('setMyCommands', {
407
+ commands,
408
+ ...(scope ? { scope } : {}),
409
+ ...(cleanString(languageCode) ? { language_code: cleanString(languageCode) } : {}),
410
+ }, { signal });
411
+ }
412
+
413
+ async deleteMyCommands({ scope, languageCode, signal } = {}) {
414
+ return this.#call('deleteMyCommands', {
415
+ ...(scope ? { scope } : {}),
416
+ ...(cleanString(languageCode) ? { language_code: cleanString(languageCode) } : {}),
417
+ }, { signal });
418
+ }
419
+
420
+ async setChatMenuButton({ menuButton = COMMANDS_MENU_BUTTON, signal } = {}) {
421
+ if (!menuButton || typeof menuButton !== 'object' || Array.isArray(menuButton)) {
422
+ throw new TypeError('Telegram menu button is invalid');
423
+ }
424
+ return this.#call('setChatMenuButton', { menu_button: menuButton }, { signal });
425
+ }
426
+
427
+ async #call(method, payload, { signal, timeoutMs = 15_000, multipart = false } = {}) {
428
+ if (signal?.aborted) throw abortReason(signal);
429
+ const url = new URL(this.#baseUrl);
430
+ url.pathname = `${url.pathname.replace(/\/$/, '')}/bot${this.#token}/${method}`;
431
+ let response;
432
+ try {
433
+ response = await this.#fetch(url, {
434
+ method: 'POST',
435
+ ...(multipart ? {} : { headers: { 'content-type': 'application/json' } }),
436
+ body: multipart ? payload : JSON.stringify(payload),
437
+ signal: requestSignal(signal, timeoutMs),
438
+ redirect: 'error',
439
+ });
440
+ } catch (error) {
441
+ const transport = new Error(`Telegram ${method} transport failed`, { cause: error });
442
+ transport.code = error?.name === 'TimeoutError'
443
+ ? 'telegram-timeout'
444
+ : error?.name === 'AbortError'
445
+ ? 'telegram-aborted-after-dispatch'
446
+ : 'telegram-transport-error';
447
+ transport.deliveryOutcome = 'unknown';
448
+ throw transport;
449
+ }
450
+ let body;
451
+ try {
452
+ body = await response.json();
453
+ } catch (cause) {
454
+ const error = new Error(`Telegram ${method} returned invalid JSON`, { cause });
455
+ error.status = response?.status;
456
+ error.code = 'telegram-response-invalid';
457
+ error.deliveryOutcome = 'unknown';
458
+ throw error;
459
+ }
460
+ if (!response.ok || body?.ok !== true) {
461
+ const description = cleanString(body?.description);
462
+ const error = new Error(description ?? `Telegram ${method} failed`);
463
+ error.code = Number.isInteger(body?.error_code) ? `telegram-${body.error_code}` : 'telegram-api-error';
464
+ error.status = response.status;
465
+ if (Number.isInteger(body?.error_code)) error.providerCode = body.error_code;
466
+ const retryAfter = Number(body?.parameters?.retry_after);
467
+ if (Number.isFinite(retryAfter) && retryAfter >= 0) {
468
+ error.retry_after = retryAfter;
469
+ error.retryAfter = retryAfter;
470
+ }
471
+ throw error;
472
+ }
473
+ return body.result;
474
+ }
475
+ }
476
+
477
+ export async function inspectTelegramToken(token, options = {}) {
478
+ const api = new TelegramApi({ token, ...options });
479
+ const bot = await api.getMe();
480
+ if (!bot?.id || bot?.is_bot !== true) throw new Error('Telegram token does not belong to a bot');
481
+ return {
482
+ platformId: String(bot.id),
483
+ name: cleanString([bot.first_name, bot.last_name].filter(Boolean).join(' ')) ?? t('Telegram机器人'),
484
+ username: cleanString(bot.username),
485
+ };
486
+ }
@@ -0,0 +1,81 @@
1
+ import { harnessQuestionText } from '../shared/harness-question.mjs';
2
+ import { TextHarnessBridge, createTextBridgeStatus } from '../shared/text-harness-bridge.mjs';
3
+
4
+ export const TELEGRAM_DESCRIPTOR = Object.freeze({
5
+ key: 'telegram',
6
+ label: 'Telegram',
7
+ connectionLabel: ' Bot API 长轮询',
8
+ reactions: Object.freeze({ processing: '👀', success: '👍', error: '👎' }),
9
+ });
10
+
11
+ /** One keyboard row per option; beyond this the list stops being scannable. */
12
+ const MAX_CARD_OPTIONS = 8;
13
+
14
+ /**
15
+ * Encode a press. Carries the presentation nonce so a keyboard left over from an
16
+ * earlier question cannot answer a later one — a new request restarts its indexes
17
+ * at zero, so the index alone would collide. Still far under Telegram's 64-byte
18
+ * callback_data budget, so no server-side id table is needed.
19
+ */
20
+ function cardCallbackData(nonce, questionIndex, optionIndex) {
21
+ return `q|${nonce}|${questionIndex}|${optionIndex}`;
22
+ }
23
+
24
+ /** Parse a press produced by {@link cardCallbackData}; null for foreign payloads. */
25
+ export function parseTelegramCardCallback(data) {
26
+ const match = typeof data === 'string'
27
+ ? /^q\|([A-Za-z0-9_-]{1,16})\|(\d{1,4})\|(\d{1,4})$/u.exec(data)
28
+ : null;
29
+ if (!match) return null;
30
+ return {
31
+ nonce: match[1],
32
+ questionIndex: Number(match[2]),
33
+ optionIndex: Number(match[3]),
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Inline-keyboard presentation for single-choice questions.
39
+ *
40
+ * Returns null — leaving the plain-text flow in charge — when a keyboard cannot
41
+ * express every answer the request allows: no options, an unusable button label,
42
+ * more options than fit, or multi-select (which needs an accumulating keyboard
43
+ * plus a submit action this channel does not have yet).
44
+ */
45
+ export const TELEGRAM_INTERACTION_CARD = Object.freeze({
46
+ render(question, { questionIndex = 0, total = 1, requiresMention = false, nonce } = {}) {
47
+ // Without an identity the press could not be attributed to this presentation.
48
+ if (typeof nonce !== 'string' || !nonce) return null;
49
+ const options = Array.isArray(question?.options) ? question.options : [];
50
+ if (options.length === 0 || options.length > MAX_CARD_OPTIONS) return null;
51
+ if (question.multiSelect === true) return null;
52
+ if (options.some((option) => typeof option?.label !== 'string' || !option.label.trim())) {
53
+ return null;
54
+ }
55
+ return {
56
+ text: harnessQuestionText(question, questionIndex, total, {
57
+ requiresMention,
58
+ hasButtons: true,
59
+ }),
60
+ markup: {
61
+ inline_keyboard: options.map((option, optionIndex) => [{
62
+ text: option.label,
63
+ callback_data: cardCallbackData(nonce, questionIndex, optionIndex),
64
+ }]),
65
+ },
66
+ };
67
+ },
68
+ parse: parseTelegramCardCallback,
69
+ });
70
+
71
+ export class TelegramHarnessBridge extends TextHarnessBridge {
72
+ constructor(options) {
73
+ super({
74
+ descriptor: TELEGRAM_DESCRIPTOR,
75
+ interactionCard: TELEGRAM_INTERACTION_CARD,
76
+ ...options,
77
+ });
78
+ }
79
+ }
80
+
81
+ export { createTextBridgeStatus as createTelegramBridgeStatus };