@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,738 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ import { hasActiveHarnessInteractionOwner } from '../../src/channels/shared/harness-client.mjs';
4
+
5
+ const modernApis = new WeakMap();
6
+
7
+ function failureOf(error) {
8
+ const failure = error?.failure ?? (error?.isDSHRemoteError === true ? error : undefined);
9
+ if (failure && typeof failure === 'object'
10
+ && typeof failure.code === 'string'
11
+ && typeof failure.message === 'string') {
12
+ return {
13
+ code: failure.code,
14
+ message: failure.message,
15
+ details: failure.details && typeof failure.details === 'object' ? failure.details : {},
16
+ };
17
+ }
18
+ if (error?.name === 'AbortError' || error?.name === 'RemoteInvocationCancelled') {
19
+ return {
20
+ code: 'cancelled',
21
+ message: error instanceof Error ? error.message : 'Harness request was cancelled',
22
+ details: {},
23
+ };
24
+ }
25
+ return {
26
+ code: 'internal',
27
+ message: error instanceof Error ? error.message : String(error),
28
+ details: {},
29
+ };
30
+ }
31
+
32
+ function rpcResult(request, operation) {
33
+ return Promise.resolve().then(operation).then(
34
+ (value) => ({ rpcId: request.rpcId, result: { ok: true, value } }),
35
+ (error) => ({ rpcId: request.rpcId, result: { ok: false, error: failureOf(error) } }),
36
+ );
37
+ }
38
+
39
+ function remoteRequest(namespace, method, args, signal) {
40
+ return {
41
+ namespace,
42
+ method,
43
+ args,
44
+ ...(signal === undefined ? {} : { signal }),
45
+ };
46
+ }
47
+
48
+ function questionError(message, code) {
49
+ const error = new Error(message);
50
+ error.name = 'UserQuestionError';
51
+ error.code = code;
52
+ return error;
53
+ }
54
+
55
+ function sessionEvents(session) {
56
+ if (typeof session?.snapshotEvents === 'function') {
57
+ const events = session.snapshotEvents();
58
+ if (Array.isArray(events)) return events;
59
+ }
60
+ const events = session?.events;
61
+ return Array.isArray(events) ? events : null;
62
+ }
63
+
64
+ function matchesQuestions(value, pending) {
65
+ if (!value || typeof value !== 'object'
66
+ || value.sessionId !== pending.sessionId
67
+ || !value.answer || typeof value.answer !== 'object'
68
+ || !Array.isArray(value.answer.answers)
69
+ || value.answer.answers.length !== pending.questions.length) return false;
70
+ return value.answer.answers.every((answer, index) => {
71
+ const question = pending.questions[index];
72
+ if (!answer || typeof answer !== 'object'
73
+ || answer.id !== question.id
74
+ || !Array.isArray(answer.selected)
75
+ || answer.selected.some((label) => typeof label !== 'string')
76
+ || new Set(answer.selected).size !== answer.selected.length
77
+ || (answer.custom !== undefined && typeof answer.custom !== 'string')) return false;
78
+ const custom = answer.custom?.trim();
79
+ if (custom !== undefined && !custom) return false;
80
+ if (question.multiSelect !== true
81
+ && ((custom !== undefined && answer.selected.length > 0) || answer.selected.length > 1)) return false;
82
+ const labels = new Set(question.options?.map((option) => option.label) ?? []);
83
+ return answer.selected.every((label) => labels.has(label));
84
+ });
85
+ }
86
+
87
+ function expandChunkRecord(record) {
88
+ if (record?.type === 'event' && record.event && typeof record.event === 'object') {
89
+ return [{ event: record.event }];
90
+ }
91
+ const packed = record?.type === 'chunks' ? record.event : null;
92
+ if (!packed || typeof packed !== 'object') {
93
+ throw new Error('Harness returned an invalid session history record');
94
+ }
95
+ const { data } = packed;
96
+ const kind = packed.type;
97
+ const members = kind === 'chunkrow/tool-call-chunks' ? data?.args : data?.texts;
98
+ if (!data || !Array.isArray(members) || members.length === 0
99
+ || members.some((member) => typeof member !== 'string')
100
+ || !Array.isArray(data.dt) || data.dt.length !== members.length - 1) {
101
+ throw new Error('Harness returned an invalid packed session chunk');
102
+ }
103
+ let time = packed.time;
104
+ return members.map((member, index) => {
105
+ if (index > 0) time += data.dt[index - 1];
106
+ let chunk;
107
+ if (kind === 'chunkrow/text-chunks') {
108
+ chunk = { type: 'text-delta', index: data.index, text: member };
109
+ } else if (kind === 'chunkrow/reasoning-chunks') {
110
+ chunk = { type: 'reasoning-delta', index: data.index, text: member };
111
+ } else if (kind === 'chunkrow/tool-call-chunks') {
112
+ chunk = {
113
+ type: 'tool-call-delta',
114
+ index: data.index,
115
+ id: data.id,
116
+ ...(Object.hasOwn(data, 'name') ? { name: data.name } : {}),
117
+ argumentsDelta: member,
118
+ };
119
+ } else {
120
+ throw new Error(`Harness returned an unsupported packed session chunk: ${String(kind)}`);
121
+ }
122
+ return {
123
+ event: {
124
+ type: 'assistant/chunk',
125
+ seq: packed.seq + index,
126
+ time,
127
+ data: { turn: data.turn, step: data.step, chunk },
128
+ },
129
+ };
130
+ });
131
+ }
132
+
133
+ function historyEntries(records) {
134
+ if (!Array.isArray(records)) throw new Error('Harness returned invalid session history records');
135
+ return records.flatMap(expandChunkRecord);
136
+ }
137
+
138
+ class MuxSubscription {
139
+ #frames = [];
140
+ #waiting = null;
141
+ #closed = false;
142
+ #signal;
143
+ #onAbort;
144
+ #dispose;
145
+
146
+ constructor(signal, dispose) {
147
+ this.#signal = signal;
148
+ this.#dispose = dispose;
149
+ this.#onAbort = () => this.close();
150
+ signal?.addEventListener('abort', this.#onAbort, { once: true });
151
+ if (signal?.aborted) this.close();
152
+ }
153
+
154
+ push(frame) {
155
+ if (this.#closed) return;
156
+ if (this.#waiting) {
157
+ const resolve = this.#waiting;
158
+ this.#waiting = null;
159
+ resolve({ value: frame, done: false });
160
+ } else {
161
+ this.#frames.push(frame);
162
+ }
163
+ }
164
+
165
+ next() {
166
+ if (this.#frames.length > 0) {
167
+ return Promise.resolve({ value: this.#frames.shift(), done: false });
168
+ }
169
+ if (this.#closed) return Promise.resolve({ value: undefined, done: true });
170
+ return new Promise((resolve) => { this.#waiting = resolve; });
171
+ }
172
+
173
+ return() {
174
+ this.close();
175
+ return Promise.resolve({ value: undefined, done: true });
176
+ }
177
+
178
+ close() {
179
+ if (this.#closed) return;
180
+ this.#closed = true;
181
+ this.#signal?.removeEventListener('abort', this.#onAbort);
182
+ this.#dispose?.();
183
+ this.#dispose = null;
184
+ if (this.#waiting) {
185
+ const resolve = this.#waiting;
186
+ this.#waiting = null;
187
+ resolve({ value: undefined, done: true });
188
+ }
189
+ }
190
+
191
+ [Symbol.asyncIterator]() {
192
+ return this;
193
+ }
194
+ }
195
+
196
+ class ModernHarnessApi {
197
+ #gateway;
198
+ #scope;
199
+ #mux = new Set();
200
+ #pendingQuestions = new Map();
201
+ #pendingApprovals = new Map();
202
+ #sessionCursors = new Map();
203
+ #assistantStreams = new Map();
204
+ #disposers = [];
205
+ #disposed = false;
206
+
207
+ constructor(ctx, gateway, scope) {
208
+ this.#gateway = gateway;
209
+ this.#scope = scope;
210
+
211
+ this.host = Object.freeze({
212
+ describe: (request) => rpcResult(request, () => ({ ready: true, transport: 'typert' })),
213
+ });
214
+ this.workspace = Object.freeze({
215
+ list: (request, signal) => rpcResult(request, () => this.#workspaceList(signal)),
216
+ create: (request, signal) => rpcResult(request, () => this.#invoke(
217
+ 'workspace', 'create', { request: request.payload }, signal,
218
+ )),
219
+ });
220
+ this.sessions = Object.freeze({
221
+ list: (request, signal) => rpcResult(request, () => this.#invoke(
222
+ 'session', 'list', { _request: request.payload }, signal,
223
+ )),
224
+ create: (request, signal) => rpcResult(request, () => this.#invoke(
225
+ 'session', 'create', { request: request.payload }, signal,
226
+ )),
227
+ history: (request, signal) => rpcResult(request, () => this.#history(request.payload, signal)),
228
+ prompt: (request, signal) => rpcResult(request, () => this.#invoke(
229
+ 'session',
230
+ 'prompt',
231
+ { request: { requestId: request.rpcId, ...request.payload } },
232
+ signal,
233
+ )),
234
+ rename: (request, signal) => rpcResult(request, () => this.#invoke(
235
+ 'session', 'rename', { request: request.payload }, signal,
236
+ )),
237
+ cancel: (request, signal) => rpcResult(request, () => this.#invoke(
238
+ 'session', 'cancel', { request: { sessionId: request.payload.sessionId } }, signal,
239
+ )),
240
+ models: (request, signal) => rpcResult(request, () => this.#sessionModels(
241
+ request.payload.sessionId, signal,
242
+ )),
243
+ selectModel: (request, signal) => rpcResult(request, () => this.#invoke(
244
+ 'session', 'selectModel', { request: request.payload }, signal,
245
+ )),
246
+ });
247
+ this.llm = Object.freeze({
248
+ models: (request, signal) => rpcResult(request, async () => {
249
+ const catalog = await this.#modelCatalog(signal);
250
+ return { groups: catalog.groups, failures: catalog.failures };
251
+ }),
252
+ });
253
+ this.events = Object.freeze({
254
+ mux: (_request, signal) => this.#openMux(signal),
255
+ });
256
+ this.respond = (message) => Promise.resolve(this.#respond(message));
257
+
258
+ if (typeof ctx?.on === 'function') {
259
+ this.#disposers.push(ctx.on('session/event', (session, event) => {
260
+ const sessionId = session?.id;
261
+ if (typeof sessionId !== 'string' || !event || typeof event !== 'object') return;
262
+ if (Number.isSafeInteger(event.seq)) this.#rememberCursor(sessionId, event.seq);
263
+ this.#broadcast({ type: 'session/event', sessionId, event });
264
+ }, { global: true }));
265
+ this.#disposers.push(ctx.on('agent/assistant-stream', ({ agent, frame }) => {
266
+ this.#acceptAssistantStream(agent, frame);
267
+ }, { global: true }));
268
+ this.#disposers.push(ctx.on('agent/disposed', ({ agent }) => {
269
+ const sessionId = agent?.session?.id;
270
+ if (typeof sessionId === 'string') this.#assistantStreams.delete(sessionId);
271
+ }, { global: true }));
272
+ this.#disposers.push(ctx.on(
273
+ 'approval/request',
274
+ (request, next) => this.#requestApproval(request, next),
275
+ { global: true, prepend: true },
276
+ ));
277
+ this.#disposers.push(ctx.on(
278
+ 'user-questions/request',
279
+ (request, next) => this.#requestQuestion(request, next),
280
+ { global: true, prepend: true },
281
+ ));
282
+ }
283
+ }
284
+
285
+ async #invoke(namespace, method, args, signal) {
286
+ return this.#gateway.invoke(remoteRequest(namespace, method, args, signal));
287
+ }
288
+
289
+ async #streamFirst(namespace, method, args, signal) {
290
+ const controller = new AbortController();
291
+ const streamSignal = signal
292
+ ? AbortSignal.any([signal, controller.signal])
293
+ : controller.signal;
294
+ let iterator;
295
+ try {
296
+ const source = await this.#gateway.stream(remoteRequest(
297
+ namespace, method, args, streamSignal,
298
+ ));
299
+ iterator = source[Symbol.asyncIterator]();
300
+ const first = await iterator.next();
301
+ if (first.done) throw new Error(`Harness ${namespace}.${method} stream ended before its baseline`);
302
+ return first.value;
303
+ } finally {
304
+ controller.abort(new DOMException('Baseline received', 'AbortError'));
305
+ await Promise.resolve(iterator?.return?.()).catch(() => undefined);
306
+ }
307
+ }
308
+
309
+ async #workspaceList(signal) {
310
+ const frame = await this.#streamFirst('workspace', 'follow', {}, signal);
311
+ if (frame?.type !== 'baseline' || !frame.value || typeof frame.value !== 'object') {
312
+ throw new Error('Harness workspace.follow returned no baseline');
313
+ }
314
+ return frame.value;
315
+ }
316
+
317
+ async #sessionSnapshot(sessionId, maxMessages, signal) {
318
+ const frame = await this.#streamFirst('session', 'follow', {
319
+ request: {
320
+ address: { kind: 'session', sessionId },
321
+ maxMessages,
322
+ },
323
+ }, signal);
324
+ if (frame?.type !== 'snapshot' || !Number.isSafeInteger(frame.cursor)) {
325
+ throw new Error('Harness session.follow returned no snapshot');
326
+ }
327
+ this.#rememberCursor(sessionId, frame.cursor);
328
+ return frame;
329
+ }
330
+
331
+ async #history(payload, signal) {
332
+ const { sessionId, maxMessages = 50, beforeSeq } = payload;
333
+ let cursor = this.#sessionCursors.get(sessionId);
334
+ if (cursor === undefined) {
335
+ const snapshot = await this.#sessionSnapshot(sessionId, maxMessages, signal);
336
+ cursor = this.#sessionCursors.get(sessionId) ?? snapshot.cursor;
337
+ if (beforeSeq === undefined && cursor === snapshot.cursor) {
338
+ return {
339
+ events: this.#withAssistantStream(sessionId, historyEntries(snapshot.records)),
340
+ hasMore: snapshot.hasMore === true,
341
+ ...(snapshot.projections === undefined ? {} : { projections: snapshot.projections }),
342
+ };
343
+ }
344
+ }
345
+ const page = await this.#invoke('session', 'page', {
346
+ request: {
347
+ address: { kind: 'session', sessionId },
348
+ throughSeq: cursor,
349
+ maxMessages,
350
+ ...(beforeSeq === undefined ? {} : { beforeSeq }),
351
+ },
352
+ }, signal);
353
+ return {
354
+ events: beforeSeq === undefined
355
+ ? this.#withAssistantStream(sessionId, historyEntries(page.records))
356
+ : historyEntries(page.records),
357
+ hasMore: page.hasMore === true,
358
+ };
359
+ }
360
+
361
+ #acceptAssistantStream(agent, frame) {
362
+ const sessionId = agent?.session?.id;
363
+ if (typeof sessionId !== 'string' || !frame || typeof frame !== 'object') return;
364
+ if (frame.type === 'start') {
365
+ const nextSeq = agent?.session?.seq;
366
+ const startedAfterSeq = Number.isSafeInteger(nextSeq) && nextSeq >= 0
367
+ ? nextSeq - 1
368
+ : this.#sessionCursors.get(sessionId) ?? -1;
369
+ this.#assistantStreams.set(sessionId, {
370
+ attemptId: frame.attemptId,
371
+ turn: frame.turn,
372
+ step: frame.step,
373
+ startedAfterSeq,
374
+ entries: [],
375
+ });
376
+ return;
377
+ }
378
+ const stream = this.#assistantStreams.get(sessionId);
379
+ if (!stream || stream.attemptId !== frame.attemptId) return;
380
+ if (frame.type === 'end') {
381
+ this.#assistantStreams.delete(sessionId);
382
+ return;
383
+ }
384
+ if (frame.type !== 'chunk' || frame.index !== stream.entries.length) return;
385
+ const entry = {
386
+ type: 'transient',
387
+ event: {
388
+ type: 'assistant/chunk',
389
+ // Match DSH's Web client ordering: live chunks sit in the numeric gap
390
+ // before the durable assistant/message that replaces them.
391
+ seq: stream.startedAfterSeq + 1 - 1 / (frame.index + 2),
392
+ time: frame.time,
393
+ data: { turn: stream.turn, step: stream.step, chunk: frame.chunk },
394
+ },
395
+ };
396
+ stream.entries.push(entry);
397
+ // History only exposes these transient chunks while the attempt is open.
398
+ // Broadcast each one as it arrives so live IM renderers cannot miss a
399
+ // short reasoning phase that starts and commits between two history polls.
400
+ this.#broadcast({ type: 'session/event', sessionId, event: entry.event });
401
+ }
402
+
403
+ #withAssistantStream(sessionId, entries) {
404
+ const transient = this.#assistantStreams.get(sessionId)?.entries ?? [];
405
+ return transient.length === 0 ? entries : [...entries, ...transient];
406
+ }
407
+
408
+ #rememberCursor(sessionId, cursor) {
409
+ const previous = this.#sessionCursors.get(sessionId);
410
+ if (previous === undefined || cursor > previous) this.#sessionCursors.set(sessionId, cursor);
411
+ }
412
+
413
+ #modelCatalog(signal) {
414
+ return this.#invoke('session', 'modelCatalog', {}, signal);
415
+ }
416
+
417
+ async #sessionModels(sessionId, signal) {
418
+ const [catalog, list] = await Promise.all([
419
+ this.#modelCatalog(signal),
420
+ this.#invoke('session', 'list', { _request: {} }, signal),
421
+ ]);
422
+ const summary = list?.items?.find((item) => item?.sessionId === sessionId);
423
+ if (!summary) {
424
+ const error = new Error(`session "${sessionId}" not found`);
425
+ error.failure = {
426
+ code: 'session-not-found',
427
+ message: error.message,
428
+ details: { sessionId },
429
+ };
430
+ throw error;
431
+ }
432
+ const selection = summary.projections?.values?.modelSelection;
433
+ const current = selection?.next ?? selection?.lastUsed ?? catalog.default;
434
+ return {
435
+ current,
436
+ routable: catalog.routableProviders.includes(current.provider),
437
+ groups: catalog.groups,
438
+ failures: catalog.failures,
439
+ };
440
+ }
441
+
442
+ #openMux(signal) {
443
+ let subscription;
444
+ subscription = new MuxSubscription(signal, () => this.#mux.delete(subscription));
445
+ this.#mux.add(subscription);
446
+ for (const pending of this.#pendingQuestions.values()) subscription.push(this.#questionFrame(pending));
447
+ for (const pending of this.#pendingApprovals.values()) subscription.push(this.#approvalFrame(pending));
448
+ return subscription;
449
+ }
450
+
451
+ #broadcast(payload, rpcId = randomUUID()) {
452
+ const frame = { rpcId, payload };
453
+ for (const subscription of this.#mux) subscription.push(frame);
454
+ }
455
+
456
+ #claimableAgent(agent) {
457
+ const session = agent?.session;
458
+ const sessionId = session?.id ?? agent?.id;
459
+ const events = sessionEvents(session);
460
+ if (typeof sessionId !== 'string' || !events) return null;
461
+ return hasActiveHarnessInteractionOwner(
462
+ this.#scope,
463
+ sessionId,
464
+ events,
465
+ ) ? { sessionId, events } : null;
466
+ }
467
+
468
+ #questionFrame(pending) {
469
+ return {
470
+ rpcId: pending.rpcId,
471
+ payload: {
472
+ type: 'question/requested',
473
+ sessionId: pending.sessionId,
474
+ questions: pending.questions,
475
+ },
476
+ };
477
+ }
478
+
479
+ #requestQuestion(request, next) {
480
+ const owner = this.#claimableAgent(request?.agent);
481
+ if (!owner) return next();
482
+ const turnSignal = request.signal;
483
+ if (turnSignal?.aborted) {
484
+ return Promise.reject(questionError(
485
+ 'ask_user_question was aborted before the user answered', 'ASK_ABORTED',
486
+ ));
487
+ }
488
+ // Give this question a lifetime of its own instead of lending it the enclosing
489
+ // turn's. `dsh-agent-loop` mints one abort controller per turn and every tool
490
+ // call in that turn shares the one signal, and under PTC two consumers of it
491
+ // react to the abort EVENT rather than to `signal.aborted`: `run_code` flips its
492
+ // own program controller from an abort listener (dsh-tools `onOuterAbort`) and
493
+ // the worker code runtime retires the worker the same way
494
+ // (dsh-code-runtime-worker-thread `onAbort`). Retiring the Web card by firing
495
+ // that event therefore also killed the program that was merely waiting for this
496
+ // answer — `code run failed (abort)`. A private controller keeps the retirement
497
+ // below local: real upstream cancellation is forwarded into it, and every
498
+ // listener on this waterfall — the Remote/Web forwarder that renders the card,
499
+ // and our own IM pending — sees a lifetime that ends with this question rather
500
+ // than with the turn.
501
+ //
502
+ // Handing it downstream means replacing `request.signal`, because the Cordis
503
+ // waterfall passes the same request object to every remaining listener and
504
+ // `next()` takes no replacement arguments. The object is a per-call copy made by
505
+ // `UserQuestionService.ask`, and the signal it carried stays reachable here as
506
+ // `turnSignal`, so the caller's own view of the request is untouched.
507
+ const question = new AbortController();
508
+ const forwardTurnAbort = () => question.abort(turnSignal?.reason);
509
+ turnSignal?.addEventListener('abort', forwardTurnAbort, { once: true });
510
+ request.signal = question.signal;
511
+ // Race the IM answer against the host's own answerers (Web/CLI). Claiming the
512
+ // request exclusively used to keep the question out of Web entirely, leaving
513
+ // whoever happened to be looking at that Session with a card they could not
514
+ // answer. Racing keeps both surfaces usable: the first answer wins.
515
+ const im = this.#askThroughIm(request, owner);
516
+ let answeredByIm = false;
517
+ const native = Promise.resolve()
518
+ .then(() => next())
519
+ .catch((error) => {
520
+ // A pure-IM session has no client connected, so the host rejects with
521
+ // NO_PROVIDER — an expected state rather than a failure — and ASK_ABORTED
522
+ // is this adapter's own retire signal below. Any other error is real, so
523
+ // log it instead of swallowing it silently; the question still stays open
524
+ // for IM rather than being failed outright.
525
+ if (error?.code !== 'NO_PROVIDER' && error?.code !== 'ASK_ABORTED') {
526
+ console.warn(
527
+ '[dsh-im] the host user-question answerer failed; waiting for the IM answer:',
528
+ error?.message ?? error,
529
+ );
530
+ }
531
+ return new Promise(() => {});
532
+ });
533
+ return Promise.race([
534
+ native,
535
+ im.promise.then((value) => {
536
+ answeredByIm = true;
537
+ return value;
538
+ }),
539
+ ]).finally(() => {
540
+ // Losing side cleanup. A host answer already settled this request, so drop
541
+ // the IM pending: leaving it registered would let a late press answer a
542
+ // question the model has moved past. Settling is idempotent.
543
+ im.dismiss(new Error('another client answered this question'));
544
+ turnSignal?.removeEventListener('abort', forwardTurnAbort);
545
+ if (answeredByIm) {
546
+ // The host's own answerer (DSH Web) keeps its question card until its own
547
+ // pending settles, and a host-side adapter has no other handle on it. A Web
548
+ // client holds that pending through the lifetime this question handed
549
+ // downstream, so ending that lifetime makes the client drop a card whose
550
+ // answer was already given on IM — otherwise it keeps offering choices for a
551
+ // question the model has moved past.
552
+ //
553
+ // Ending it is `abort`, not a dispatched `abort` event: a listener that
554
+ // reads `signal.aborted` must see the same thing one that listens for the
555
+ // event does. Either way it reaches only this question's controller, so the
556
+ // turn and every other tool call in it — a waiting `run_code` program above
557
+ // all — keep running. The reason carries `ASK_ABORTED` so the host answerer
558
+ // rejecting alongside us stays an expected retirement rather than a logged
559
+ // failure.
560
+ question.abort(questionError('the question was answered on IM', 'ASK_ABORTED'));
561
+ }
562
+ });
563
+ }
564
+
565
+ /**
566
+ * Present one question to IM clients. Returns the answer promise plus a
567
+ * `dismiss` used to retire the pending when the host answers first.
568
+ */
569
+ #askThroughIm(request, owner) {
570
+ let pending = null;
571
+ const promise = new Promise((resolve, reject) => {
572
+ pending = {
573
+ rpcId: randomUUID(),
574
+ sessionId: owner.sessionId,
575
+ questions: request.questions,
576
+ signal: request.signal,
577
+ settle: (outcome, value) => {
578
+ if (!this.#pendingQuestions.delete(pending.rpcId)) return;
579
+ request.signal?.removeEventListener('abort', onAbort);
580
+ this.#broadcast({
581
+ type: 'question/resolved',
582
+ sessionId: pending.sessionId,
583
+ questionRpcId: pending.rpcId,
584
+ outcome,
585
+ });
586
+ if (outcome === 'answered') resolve(value);
587
+ else reject(value);
588
+ },
589
+ };
590
+ const onAbort = () => pending.settle('cancelled', questionError(
591
+ 'ask_user_question was aborted before the user answered', 'ASK_ABORTED',
592
+ ));
593
+ this.#pendingQuestions.set(pending.rpcId, pending);
594
+ request.signal?.addEventListener('abort', onAbort, { once: true });
595
+ this.#broadcast(this.#questionFrame(pending).payload, pending.rpcId);
596
+ });
597
+ return {
598
+ promise,
599
+ dismiss: (reason) => pending?.settle('cancelled', reason),
600
+ };
601
+ }
602
+
603
+ #approvalFrame(pending) {
604
+ return {
605
+ rpcId: pending.rpcId,
606
+ payload: {
607
+ type: 'approval/requested',
608
+ sessionId: pending.sessionId,
609
+ approvalId: pending.approvalId,
610
+ toolName: pending.toolName,
611
+ ...(pending.callId === undefined ? {} : { callId: pending.callId }),
612
+ ...(pending.reason === undefined ? {} : { reason: pending.reason }),
613
+ },
614
+ };
615
+ }
616
+
617
+ #requestApproval(request, next) {
618
+ const owner = this.#claimableAgent(request?.agent);
619
+ if (!owner) return next();
620
+ if (request.signal?.aborted) return Promise.resolve('cancelled');
621
+ const claimed = new Set([...this.#pendingApprovals.values()].map((entry) => entry.approvalId));
622
+ const decided = new Set();
623
+ let approvalId;
624
+ for (let index = owner.events.length - 1; index >= 0; index -= 1) {
625
+ const event = owner.events[index];
626
+ if (event.type === 'approval/decided') {
627
+ decided.add(event.data?.id);
628
+ } else if (event.type === 'approval/asked') {
629
+ const id = event.data?.id;
630
+ if (!id || decided.has(id) || claimed.has(id)) continue;
631
+ if ((request.callId ?? null) !== (event.data?.callId ?? null)) continue;
632
+ approvalId = id;
633
+ break;
634
+ }
635
+ }
636
+ if (approvalId === undefined) return next();
637
+ return new Promise((resolve) => {
638
+ const pending = {
639
+ rpcId: randomUUID(),
640
+ sessionId: owner.sessionId,
641
+ approvalId,
642
+ toolName: request.toolName,
643
+ callId: request.callId,
644
+ reason: request.reason,
645
+ settle: (outcome) => {
646
+ if (!this.#pendingApprovals.delete(pending.rpcId)) return;
647
+ request.signal?.removeEventListener('abort', onAbort);
648
+ this.#broadcast({
649
+ type: 'approval/resolved',
650
+ sessionId: pending.sessionId,
651
+ approvalId: pending.approvalId,
652
+ outcome,
653
+ });
654
+ resolve(outcome);
655
+ },
656
+ };
657
+ const onAbort = () => pending.settle('cancelled');
658
+ this.#pendingApprovals.set(pending.rpcId, pending);
659
+ request.signal?.addEventListener('abort', onAbort, { once: true });
660
+ this.#broadcast(this.#approvalFrame(pending).payload, pending.rpcId);
661
+ });
662
+ }
663
+
664
+ #respond(message) {
665
+ const approval = this.#pendingApprovals.get(message?.rpcId);
666
+ if (approval) {
667
+ const value = message?.result?.value;
668
+ if (message?.result?.ok !== true
669
+ || !value || typeof value !== 'object'
670
+ || value.sessionId !== approval.sessionId
671
+ || value.approvalId !== approval.approvalId
672
+ || (value.outcome !== 'allowed-once' && value.outcome !== 'rejected')) {
673
+ return { accepted: false, reason: 'bad-response' };
674
+ }
675
+ approval.settle(value.outcome);
676
+ return { accepted: true };
677
+ }
678
+ const question = this.#pendingQuestions.get(message?.rpcId);
679
+ if (!question) return { accepted: false, reason: 'not-pending' };
680
+ if (message?.result?.ok !== true) {
681
+ if (message?.result?.error?.code !== 'cancelled') {
682
+ return { accepted: false, reason: 'bad-response' };
683
+ }
684
+ question.settle('cancelled', questionError(
685
+ 'the user cancelled ask_user_question', 'ASK_CANCELLED',
686
+ ));
687
+ return { accepted: true };
688
+ }
689
+ if (!matchesQuestions(message.result.value, question)) {
690
+ return { accepted: false, reason: 'bad-response' };
691
+ }
692
+ const answer = {
693
+ answers: message.result.value.answer.answers.map((item) => ({
694
+ id: item.id,
695
+ selected: [...item.selected],
696
+ ...(item.custom === undefined ? {} : { custom: item.custom }),
697
+ })),
698
+ };
699
+ question.settle('answered', answer);
700
+ return { accepted: true };
701
+ }
702
+
703
+ dispose() {
704
+ if (this.#disposed) return;
705
+ this.#disposed = true;
706
+ for (const subscription of [...this.#mux]) subscription.close();
707
+ this.#assistantStreams.clear();
708
+ for (const pending of [...this.#pendingApprovals.values()]) pending.settle('cancelled');
709
+ for (const pending of [...this.#pendingQuestions.values()]) pending.settle(
710
+ 'cancelled',
711
+ questionError('dsh-im interaction adapter was disposed', 'ASK_ABORTED'),
712
+ );
713
+ for (const dispose of this.#disposers.splice(0).reverse()) dispose?.();
714
+ }
715
+ }
716
+
717
+ /** Create one modern compatibility API per Cordis Host root. */
718
+ export function modernHarnessApi(ctx) {
719
+ const scope = ctx?.root ?? ctx;
720
+ if (!scope || !['object', 'function'].includes(typeof scope)) {
721
+ throw new TypeError('dsh-im requires a Cordis Host context');
722
+ }
723
+ const cached = modernApis.get(scope);
724
+ if (cached) return cached;
725
+ const gateway = ctx?.typertGateway;
726
+ if (!gateway || typeof gateway.invoke !== 'function' || typeof gateway.stream !== 'function') {
727
+ throw new TypeError('dsh-im requires the modern Host Typert gateway');
728
+ }
729
+ const api = new ModernHarnessApi(ctx, gateway, scope);
730
+ modernApis.set(scope, api);
731
+ if (typeof ctx.effect === 'function') {
732
+ ctx.effect(() => () => {
733
+ if (modernApis.get(scope) === api) modernApis.delete(scope);
734
+ api.dispose();
735
+ }, 'dsh-im: modern Harness compatibility API');
736
+ }
737
+ return api;
738
+ }