@botharness/im-provider 4.32.0-botharness.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (423) hide show
  1. package/LICENSE +21 -0
  2. package/PROVENANCE.json +25 -0
  3. package/README.en.md +445 -0
  4. package/README.md +448 -0
  5. package/THIRD_PARTY_NOTICES.md +93 -0
  6. package/assets/dingtalk-menu-template.json +6 -0
  7. package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
  8. package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
  9. package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
  10. package/assets/logo-icon.png +0 -0
  11. package/assets/logo-plugin-message-link-gradient.webp +0 -0
  12. package/assets/logo-plugin-phone.png +0 -0
  13. package/assets/logo.png +0 -0
  14. package/assets/logo_cn.png +0 -0
  15. package/assets/screenshot-menu-card.png +0 -0
  16. package/cordis.patch.yml +3 -0
  17. package/lib/client.js +20330 -0
  18. package/lib/index.js +604 -0
  19. package/locale/en.json +5 -0
  20. package/locale/zh.json +5 -0
  21. package/package.json +181 -0
  22. package/plugin-src/client/access-policy-settings.js +362 -0
  23. package/plugin-src/client/agent-preset.js +119 -0
  24. package/plugin-src/client/bot-alias.js +169 -0
  25. package/plugin-src/client/build.mjs +38 -0
  26. package/plugin-src/client/channel-card-meta.js +132 -0
  27. package/plugin-src/client/channel-logos.js +190 -0
  28. package/plugin-src/client/channels/dingtalk/api.js +267 -0
  29. package/plugin-src/client/channels/dingtalk/index.js +954 -0
  30. package/plugin-src/client/channels/dingtalk/styles.js +136 -0
  31. package/plugin-src/client/channels/discord/api.js +11 -0
  32. package/plugin-src/client/channels/discord/index.js +25 -0
  33. package/plugin-src/client/channels/discord/styles.js +19 -0
  34. package/plugin-src/client/channels/email/api.js +52 -0
  35. package/plugin-src/client/channels/email/index.js +728 -0
  36. package/plugin-src/client/channels/email/styles.js +51 -0
  37. package/plugin-src/client/channels/feishu/api.js +405 -0
  38. package/plugin-src/client/channels/feishu/group-settings.js +581 -0
  39. package/plugin-src/client/channels/feishu/index.js +1583 -0
  40. package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
  41. package/plugin-src/client/channels/feishu/styles.js +573 -0
  42. package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
  43. package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
  44. package/plugin-src/client/channels/imessage/api.js +12 -0
  45. package/plugin-src/client/channels/imessage/index.js +46 -0
  46. package/plugin-src/client/channels/imessage/styles.js +19 -0
  47. package/plugin-src/client/channels/matrix/api.js +11 -0
  48. package/plugin-src/client/channels/matrix/index.js +151 -0
  49. package/plugin-src/client/channels/matrix/styles.js +36 -0
  50. package/plugin-src/client/channels/office/api.js +46 -0
  51. package/plugin-src/client/channels/office/index.js +153 -0
  52. package/plugin-src/client/channels/office/styles.js +50 -0
  53. package/plugin-src/client/channels/qq/api.js +171 -0
  54. package/plugin-src/client/channels/qq/index.js +593 -0
  55. package/plugin-src/client/channels/qq/styles.js +19 -0
  56. package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
  57. package/plugin-src/client/channels/shared/token-api.js +124 -0
  58. package/plugin-src/client/channels/shared/token-channel.js +495 -0
  59. package/plugin-src/client/channels/slack/api.js +11 -0
  60. package/plugin-src/client/channels/slack/index.js +131 -0
  61. package/plugin-src/client/channels/slack/styles.js +34 -0
  62. package/plugin-src/client/channels/telegram/api.js +11 -0
  63. package/plugin-src/client/channels/telegram/index.js +28 -0
  64. package/plugin-src/client/channels/telegram/styles.js +31 -0
  65. package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
  66. package/plugin-src/client/channels/wecom/api.js +160 -0
  67. package/plugin-src/client/channels/wecom/index.js +625 -0
  68. package/plugin-src/client/channels/wecom/styles.js +19 -0
  69. package/plugin-src/client/channels/wecom-app/api.js +132 -0
  70. package/plugin-src/client/channels/wecom-app/index.js +634 -0
  71. package/plugin-src/client/channels/wecom-app/styles.js +25 -0
  72. package/plugin-src/client/channels/weixin/api.js +211 -0
  73. package/plugin-src/client/channels/weixin/connection-error.js +1 -0
  74. package/plugin-src/client/channels/weixin/index.js +801 -0
  75. package/plugin-src/client/channels/weixin/styles.js +115 -0
  76. package/plugin-src/client/channels/whatsapp/api.js +152 -0
  77. package/plugin-src/client/channels/whatsapp/index.js +609 -0
  78. package/plugin-src/client/channels/whatsapp/styles.js +19 -0
  79. package/plugin-src/client/connection-error.js +87 -0
  80. package/plugin-src/client/context-enhancement.js +415 -0
  81. package/plugin-src/client/credential-binding.js +118 -0
  82. package/plugin-src/client/delivery-settings.js +905 -0
  83. package/plugin-src/client/global-settings.js +433 -0
  84. package/plugin-src/client/i18n.js +1314 -0
  85. package/plugin-src/client/index.js +624 -0
  86. package/plugin-src/client/interface-language.js +89 -0
  87. package/plugin-src/client/last-message-error.js +18 -0
  88. package/plugin-src/client/lifecycle.js +86 -0
  89. package/plugin-src/client/loopback-recovery.js +75 -0
  90. package/plugin-src/client/model-setting.js +172 -0
  91. package/plugin-src/client/panel-error-boundary.js +21 -0
  92. package/plugin-src/client/plugin-page.js +51 -0
  93. package/plugin-src/client/session-channel-logos.js +243 -0
  94. package/plugin-src/client/styles.js +770 -0
  95. package/plugin-src/client/update-panel.js +14 -0
  96. package/plugin-src/client/workspace-directory-picker.js +280 -0
  97. package/plugin-src/client/workspace-editor.js +69 -0
  98. package/plugin-src/client/workspace-snapshot-fence.js +28 -0
  99. package/plugin-src/host/build.mjs +52 -0
  100. package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
  101. package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
  102. package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
  103. package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
  104. package/plugin-src/host/channels/discord/index.mjs +33 -0
  105. package/plugin-src/host/channels/discord/production.mjs +18 -0
  106. package/plugin-src/host/channels/discord/rpc.mjs +21 -0
  107. package/plugin-src/host/channels/email/availability.mjs +60 -0
  108. package/plugin-src/host/channels/email/index.mjs +36 -0
  109. package/plugin-src/host/channels/email/production.mjs +58 -0
  110. package/plugin-src/host/channels/email/rpc.mjs +163 -0
  111. package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
  112. package/plugin-src/host/channels/feishu/controller.mjs +172 -0
  113. package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
  114. package/plugin-src/host/channels/feishu/index.mjs +69 -0
  115. package/plugin-src/host/channels/feishu/production.mjs +319 -0
  116. package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
  117. package/plugin-src/host/channels/imessage/index.mjs +21 -0
  118. package/plugin-src/host/channels/imessage/production.mjs +13 -0
  119. package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
  120. package/plugin-src/host/channels/matrix/index.mjs +31 -0
  121. package/plugin-src/host/channels/matrix/production.mjs +241 -0
  122. package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
  123. package/plugin-src/host/channels/office/index.mjs +14 -0
  124. package/plugin-src/host/channels/office/production.mjs +45 -0
  125. package/plugin-src/host/channels/office/rpc.mjs +51 -0
  126. package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
  127. package/plugin-src/host/channels/qq/index.mjs +28 -0
  128. package/plugin-src/host/channels/qq/production.mjs +181 -0
  129. package/plugin-src/host/channels/qq/rpc.mjs +250 -0
  130. package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
  131. package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
  132. package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
  133. package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
  134. package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
  135. package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
  136. package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
  137. package/plugin-src/host/channels/shared/production.mjs +239 -0
  138. package/plugin-src/host/channels/shared/rpc.mjs +226 -0
  139. package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
  140. package/plugin-src/host/channels/shared/startup.mjs +76 -0
  141. package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
  142. package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
  143. package/plugin-src/host/channels/slack/index.mjs +31 -0
  144. package/plugin-src/host/channels/slack/production.mjs +176 -0
  145. package/plugin-src/host/channels/slack/rpc.mjs +221 -0
  146. package/plugin-src/host/channels/telegram/index.mjs +33 -0
  147. package/plugin-src/host/channels/telegram/production.mjs +19 -0
  148. package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
  149. package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
  150. package/plugin-src/host/channels/wecom/index.mjs +34 -0
  151. package/plugin-src/host/channels/wecom/production.mjs +187 -0
  152. package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
  153. package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
  154. package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
  155. package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
  156. package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
  157. package/plugin-src/host/channels/weixin/index.mjs +44 -0
  158. package/plugin-src/host/channels/weixin/production.mjs +258 -0
  159. package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
  160. package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
  161. package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
  162. package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
  163. package/plugin-src/host/delivery-adapter.mjs +411 -0
  164. package/plugin-src/host/delivery-http.mjs +132 -0
  165. package/plugin-src/host/delivery-rpc.mjs +173 -0
  166. package/plugin-src/host/delivery-service.mjs +618 -0
  167. package/plugin-src/host/delivery-suggestions.mjs +198 -0
  168. package/plugin-src/host/harness-command-executor.mjs +48 -0
  169. package/plugin-src/host/harness-connection.mjs +20 -0
  170. package/plugin-src/host/harness-session-coordinator.mjs +183 -0
  171. package/plugin-src/host/host-language-rpc.mjs +71 -0
  172. package/plugin-src/host/host-language.mjs +157 -0
  173. package/plugin-src/host/image-input-rpc.mjs +24 -0
  174. package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
  175. package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
  176. package/plugin-src/host/inbound-ttl-service.mjs +179 -0
  177. package/plugin-src/host/index.mjs +229 -0
  178. package/plugin-src/host/injected-context.mjs +104 -0
  179. package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
  180. package/plugin-src/host/modern-harness-api.mjs +738 -0
  181. package/plugin-src/host/rpc-authority.mjs +12 -0
  182. package/plugin-src/host/session-sync-coordinator.mjs +233 -0
  183. package/plugin-src/host/session-title-prefix.mjs +122 -0
  184. package/plugin-src/host/update-policy.mjs +31 -0
  185. package/plugin-src/host/update-rpc.mjs +16 -0
  186. package/plugin-src/host/update-runtime.mjs +339 -0
  187. package/plugin-src/host/update-service.mjs +392 -0
  188. package/plugin-src/management-rpc.mjs +87 -0
  189. package/src/channels/dingtalk/config-store.mjs +284 -0
  190. package/src/channels/dingtalk/connection-error.mjs +292 -0
  191. package/src/channels/dingtalk/device-auth.mjs +240 -0
  192. package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
  193. package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
  194. package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
  195. package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
  196. package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
  197. package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
  198. package/src/channels/dingtalk/harness-client.mjs +19 -0
  199. package/src/channels/dingtalk/state-store.mjs +325 -0
  200. package/src/channels/discord/config-store.mjs +28 -0
  201. package/src/channels/discord/discord-api.mjs +423 -0
  202. package/src/channels/discord/discord-bridge.mjs +16 -0
  203. package/src/channels/discord/discord-controller.mjs +29 -0
  204. package/src/channels/discord/discord-runtime.mjs +1091 -0
  205. package/src/channels/discord/external-consumer.mjs +199 -0
  206. package/src/channels/discord/external-files.mjs +97 -0
  207. package/src/channels/discord/harness-client.mjs +11 -0
  208. package/src/channels/discord/history-reader.mjs +142 -0
  209. package/src/channels/discord/nearby-history.mjs +112 -0
  210. package/src/channels/discord/state-store.mjs +3 -0
  211. package/src/channels/email/config-store.mjs +194 -0
  212. package/src/channels/email/email-api.mjs +20 -0
  213. package/src/channels/email/email-bridge.mjs +17 -0
  214. package/src/channels/email/email-controller.mjs +824 -0
  215. package/src/channels/email/email-runtime.mjs +699 -0
  216. package/src/channels/email/harness-client.mjs +7 -0
  217. package/src/channels/email/mail-format.mjs +91 -0
  218. package/src/channels/email/state-store.mjs +176 -0
  219. package/src/channels/email/transport.mjs +64 -0
  220. package/src/channels/email/transports/agent-mail.mjs +604 -0
  221. package/src/channels/email/transports/agently-cli.mjs +288 -0
  222. package/src/channels/email/transports/imap-smtp.mjs +165 -0
  223. package/src/channels/feishu/bridge.mjs +6286 -0
  224. package/src/channels/feishu/config.mjs +71 -0
  225. package/src/channels/feishu/external-cards.mjs +87 -0
  226. package/src/channels/feishu/external-consumer.mjs +89 -0
  227. package/src/channels/feishu/external-files.mjs +115 -0
  228. package/src/channels/feishu/external-images.mjs +50 -0
  229. package/src/channels/feishu/external-names.mjs +99 -0
  230. package/src/channels/feishu/feishu-app.mjs +54 -0
  231. package/src/channels/feishu/feishu-cards.mjs +1285 -0
  232. package/src/channels/feishu/feishu-channel.mjs +651 -0
  233. package/src/channels/feishu/feishu-runtime.mjs +982 -0
  234. package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
  235. package/src/channels/feishu/group-response-mode.mjs +15 -0
  236. package/src/channels/feishu/harness-client.mjs +19 -0
  237. package/src/channels/feishu/history-reader.mjs +77 -0
  238. package/src/channels/feishu/live-cot.mjs +260 -0
  239. package/src/channels/feishu/message-utils.mjs +613 -0
  240. package/src/channels/feishu/multi-bot-controller.mjs +1619 -0
  241. package/src/channels/feishu/nearby-history.mjs +72 -0
  242. package/src/channels/feishu/plugin-config-store.mjs +216 -0
  243. package/src/channels/feishu/plugin-controller.mjs +254 -0
  244. package/src/channels/feishu/registration-manager.mjs +349 -0
  245. package/src/channels/feishu/repair-manager.mjs +138 -0
  246. package/src/channels/feishu/reply-context.mjs +22 -0
  247. package/src/channels/feishu/slash-command-panel.mjs +155 -0
  248. package/src/channels/feishu/slash-command-registry.mjs +495 -0
  249. package/src/channels/feishu/state-store.mjs +214 -0
  250. package/src/channels/feishu/step-push-mode.mjs +25 -0
  251. package/src/channels/feishu/voice-config.mjs +34 -0
  252. package/src/channels/feishu/voice.mjs +134 -0
  253. package/src/channels/imessage/config-store.mjs +24 -0
  254. package/src/channels/imessage/controller.mjs +37 -0
  255. package/src/channels/imessage/harness-client.mjs +7 -0
  256. package/src/channels/imessage/imessage-api.mjs +194 -0
  257. package/src/channels/imessage/imessage-bridge.mjs +16 -0
  258. package/src/channels/imessage/runtime.mjs +102 -0
  259. package/src/channels/imessage/state-store.mjs +3 -0
  260. package/src/channels/matrix/matrix-api.mjs +696 -0
  261. package/src/channels/matrix/matrix-bridge.mjs +20 -0
  262. package/src/channels/matrix/matrix-config-store.mjs +368 -0
  263. package/src/channels/matrix/matrix-controller.mjs +404 -0
  264. package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
  265. package/src/channels/matrix/matrix-crypto.mjs +1014 -0
  266. package/src/channels/matrix/matrix-harness-client.mjs +11 -0
  267. package/src/channels/matrix/matrix-normalize.mjs +357 -0
  268. package/src/channels/matrix/matrix-rich-text.mjs +313 -0
  269. package/src/channels/matrix/matrix-room-history.mjs +316 -0
  270. package/src/channels/matrix/matrix-runtime.mjs +1014 -0
  271. package/src/channels/office/config-store.mjs +107 -0
  272. package/src/channels/office/office-controller.mjs +178 -0
  273. package/src/channels/office/office-job-executor.mjs +391 -0
  274. package/src/channels/office/office-runtime.mjs +175 -0
  275. package/src/channels/office/office-transport.mjs +171 -0
  276. package/src/channels/office/protocol.mjs +43 -0
  277. package/src/channels/qq/config-store.mjs +173 -0
  278. package/src/channels/qq/harness-client.mjs +11 -0
  279. package/src/channels/qq/markdown-reply.mjs +446 -0
  280. package/src/channels/qq/qq-bridge.mjs +1507 -0
  281. package/src/channels/qq/qq-controller.mjs +514 -0
  282. package/src/channels/qq/qq-menu.mjs +208 -0
  283. package/src/channels/qq/qq-runtime.mjs +303 -0
  284. package/src/channels/qq/qr-auth.mjs +24 -0
  285. package/src/channels/qq/state-error.mjs +17 -0
  286. package/src/channels/qq/state-store.mjs +143 -0
  287. package/src/channels/shared/access-policy.mjs +210 -0
  288. package/src/channels/shared/agent-preset.mjs +76 -0
  289. package/src/channels/shared/batch-input.mjs +229 -0
  290. package/src/channels/shared/bot-alias.mjs +29 -0
  291. package/src/channels/shared/bot-workspace-store.mjs +2383 -0
  292. package/src/channels/shared/command-catalog.mjs +107 -0
  293. package/src/channels/shared/command-permission.mjs +32 -0
  294. package/src/channels/shared/compact-command.mjs +109 -0
  295. package/src/channels/shared/config-read-error.mjs +24 -0
  296. package/src/channels/shared/connection-error.mjs +191 -0
  297. package/src/channels/shared/connection-test.mjs +58 -0
  298. package/src/channels/shared/context-enhancement.mjs +372 -0
  299. package/src/channels/shared/control-command.mjs +111 -0
  300. package/src/channels/shared/conversation-state-store.mjs +165 -0
  301. package/src/channels/shared/default-workspace.mjs +31 -0
  302. package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
  303. package/src/channels/shared/deferred-delivery.mjs +161 -0
  304. package/src/channels/shared/deferred-state.mjs +53 -0
  305. package/src/channels/shared/diagnostic-details.mjs +95 -0
  306. package/src/channels/shared/editable-message-stream.mjs +100 -0
  307. package/src/channels/shared/exclusive-inbound-consumers.mjs +91 -0
  308. package/src/channels/shared/file-download.mjs +64 -0
  309. package/src/channels/shared/harness-approval.mjs +508 -0
  310. package/src/channels/shared/harness-client.mjs +2143 -0
  311. package/src/channels/shared/harness-mux.mjs +123 -0
  312. package/src/channels/shared/harness-question.mjs +95 -0
  313. package/src/channels/shared/harness-session-binding.mjs +119 -0
  314. package/src/channels/shared/history-command.mjs +193 -0
  315. package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
  316. package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
  317. package/src/channels/shared/i18n-en/discord.mjs +10 -0
  318. package/src/channels/shared/i18n-en/email.mjs +25 -0
  319. package/src/channels/shared/i18n-en/feishu.mjs +404 -0
  320. package/src/channels/shared/i18n-en/image-input.mjs +18 -0
  321. package/src/channels/shared/i18n-en/matrix.mjs +85 -0
  322. package/src/channels/shared/i18n-en/office.mjs +23 -0
  323. package/src/channels/shared/i18n-en/qq.mjs +96 -0
  324. package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
  325. package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
  326. package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
  327. package/src/channels/shared/i18n-en/slack.mjs +27 -0
  328. package/src/channels/shared/i18n-en/telegram.mjs +27 -0
  329. package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
  330. package/src/channels/shared/i18n-en/wecom.mjs +62 -0
  331. package/src/channels/shared/i18n-en/weixin.mjs +88 -0
  332. package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
  333. package/src/channels/shared/i18n-en.mjs +45 -0
  334. package/src/channels/shared/i18n.mjs +78 -0
  335. package/src/channels/shared/im-source-guidance.mjs +65 -0
  336. package/src/channels/shared/image-input-policy.mjs +35 -0
  337. package/src/channels/shared/image-input-settings-store.mjs +60 -0
  338. package/src/channels/shared/image-input.mjs +124 -0
  339. package/src/channels/shared/image-prompt.mjs +360 -0
  340. package/src/channels/shared/inbound-access.mjs +43 -0
  341. package/src/channels/shared/inbound-file.mjs +323 -0
  342. package/src/channels/shared/inbound-ttl-store.mjs +110 -0
  343. package/src/channels/shared/inbound-ttl.mjs +22 -0
  344. package/src/channels/shared/injected-context.mjs +362 -0
  345. package/src/channels/shared/interface-language-store.mjs +127 -0
  346. package/src/channels/shared/interface-language.mjs +51 -0
  347. package/src/channels/shared/message-failure.mjs +257 -0
  348. package/src/channels/shared/model-command.mjs +741 -0
  349. package/src/channels/shared/model-setting.mjs +145 -0
  350. package/src/channels/shared/preset-command.mjs +308 -0
  351. package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
  352. package/src/channels/shared/semantic/artifact.mjs +750 -0
  353. package/src/channels/shared/semantic/delivery.mjs +193 -0
  354. package/src/channels/shared/semantic/reply-reference.mjs +148 -0
  355. package/src/channels/shared/session-binding-lock.mjs +40 -0
  356. package/src/channels/shared/session-channel-labels.mjs +28 -0
  357. package/src/channels/shared/session-reply-recovery.mjs +104 -0
  358. package/src/channels/shared/session-sync-registry.mjs +22 -0
  359. package/src/channels/shared/session-title.mjs +74 -0
  360. package/src/channels/shared/status-reaction.mjs +107 -0
  361. package/src/channels/shared/text-harness-bridge.mjs +1623 -0
  362. package/src/channels/shared/token-bot-controller.mjs +529 -0
  363. package/src/channels/shared/token-config-store.mjs +208 -0
  364. package/src/channels/shared/video-media.mjs +9 -0
  365. package/src/channels/shared/workspace-command.mjs +532 -0
  366. package/src/channels/shared/workspace-session.mjs +196 -0
  367. package/src/channels/slack/config-store.mjs +177 -0
  368. package/src/channels/slack/external-consumer.mjs +93 -0
  369. package/src/channels/slack/external-files.mjs +90 -0
  370. package/src/channels/slack/harness-client.mjs +11 -0
  371. package/src/channels/slack/history-reader.mjs +203 -0
  372. package/src/channels/slack/manifest.mjs +37 -0
  373. package/src/channels/slack/slack-api.mjs +644 -0
  374. package/src/channels/slack/slack-bridge.mjs +20 -0
  375. package/src/channels/slack/slack-controller.mjs +468 -0
  376. package/src/channels/slack/slack-runtime.mjs +895 -0
  377. package/src/channels/slack/state-store.mjs +3 -0
  378. package/src/channels/telegram/config-store.mjs +89 -0
  379. package/src/channels/telegram/harness-client.mjs +11 -0
  380. package/src/channels/telegram/state-store.mjs +3 -0
  381. package/src/channels/telegram/telegram-api.mjs +486 -0
  382. package/src/channels/telegram/telegram-bridge.mjs +81 -0
  383. package/src/channels/telegram/telegram-controller.mjs +52 -0
  384. package/src/channels/telegram/telegram-http.mjs +21 -0
  385. package/src/channels/telegram/telegram-rich-message.mjs +149 -0
  386. package/src/channels/telegram/telegram-runtime.mjs +1471 -0
  387. package/src/channels/wecom/config-store.mjs +172 -0
  388. package/src/channels/wecom/harness-client.mjs +11 -0
  389. package/src/channels/wecom/qr-auth.mjs +95 -0
  390. package/src/channels/wecom/send-error.mjs +31 -0
  391. package/src/channels/wecom/state-store.mjs +107 -0
  392. package/src/channels/wecom/wecom-bridge.mjs +1833 -0
  393. package/src/channels/wecom/wecom-cards.mjs +101 -0
  394. package/src/channels/wecom/wecom-controller.mjs +530 -0
  395. package/src/channels/wecom/wecom-runtime.mjs +269 -0
  396. package/src/channels/wecom-app/callback-server.mjs +471 -0
  397. package/src/channels/wecom-app/config-store.mjs +242 -0
  398. package/src/channels/wecom-app/harness-client.mjs +11 -0
  399. package/src/channels/wecom-app/state-store.mjs +107 -0
  400. package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
  401. package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
  402. package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
  403. package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
  404. package/src/channels/weixin/config-store.mjs +194 -0
  405. package/src/channels/weixin/connection-error.en.mjs +137 -0
  406. package/src/channels/weixin/connection-error.mjs +153 -0
  407. package/src/channels/weixin/diagnostic-details.mjs +1 -0
  408. package/src/channels/weixin/external-consumer.mjs +160 -0
  409. package/src/channels/weixin/external-files.mjs +84 -0
  410. package/src/channels/weixin/external-typing.mjs +120 -0
  411. package/src/channels/weixin/harness-client.mjs +19 -0
  412. package/src/channels/weixin/state-store.mjs +316 -0
  413. package/src/channels/weixin/weixin-api.mjs +1009 -0
  414. package/src/channels/weixin/weixin-bridge.mjs +1537 -0
  415. package/src/channels/weixin/weixin-controller.mjs +779 -0
  416. package/src/channels/weixin/weixin-runtime.mjs +507 -0
  417. package/src/channels/whatsapp/config-store.mjs +210 -0
  418. package/src/channels/whatsapp/harness-client.mjs +11 -0
  419. package/src/channels/whatsapp/state-store.mjs +3 -0
  420. package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
  421. package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
  422. package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
  423. package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
@@ -0,0 +1,1285 @@
1
+ /**
2
+ * Feishu interactive-card builders for the dsh-im menu / session-list /
3
+ * workspace-list UX. All builders return the JSON string the
4
+ * `im.message.create` API expects as `content` for `msg_type: interactive`
5
+ * (card schema 2.0; callback buttons live inside a column_set/column layout).
6
+ *
7
+ * The session list lays each row out as a `column_set` (fixed-width ⭐
8
+ * watch-toggle column + weighted session-button column), which is how V2
9
+ * expresses a row of buttons.
10
+ *
11
+ * Buttons carry a small `{ action }` value object that `card.action.trigger`
12
+ * events echo back (when the app subscribes that event); every numbered
13
+ * button also has a numeric label so the number-reply fallback stays usable
14
+ * without button callbacks.
15
+ */
16
+
17
+ import { t } from '../shared/i18n.mjs';
18
+
19
+ export const MENU_PAGE_SIZE = 10;
20
+
21
+ /** 预设下拉中「跟随默认」(null) 的哨兵值,供 initial_index 命中与回调识别。 */
22
+ export const PRESET_FOLLOW_DEFAULT_SENTINEL = '__preset_follow_default__';
23
+
24
+ function plainText(content) {
25
+ return { tag: 'plain_text', content: String(content) };
26
+ }
27
+
28
+ function markdown(content) {
29
+ return { tag: 'lark_md', content: String(content) };
30
+ }
31
+
32
+ /** Full-width button wrapped in a column_set. */
33
+ function button(content, actionValue) {
34
+ return {
35
+ tag: 'column_set',
36
+ flex_mode: 'none',
37
+ columns: [{
38
+ tag: 'column',
39
+ width: 'weighted',
40
+ weight: 1,
41
+ elements: [{
42
+ tag: 'button',
43
+ text: plainText(content),
44
+ type: 'default',
45
+ width: 'fill',
46
+ behaviors: [{ type: 'callback', value: { action: actionValue } }],
47
+ }],
48
+ }],
49
+ };
50
+ }
51
+
52
+ /** The raw button element (without the full-width column_set wrapper). */
53
+ function buttonElement(content, actionValue) {
54
+ return {
55
+ tag: 'button',
56
+ text: plainText(content),
57
+ type: 'default',
58
+ width: 'fill',
59
+ behaviors: [{ type: 'callback', value: { action: actionValue } }],
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Two buttons side by side in a `column_set`.
65
+ * `leftContent` / `leftAction` and `rightContent` / `rightAction` define
66
+ * each button's label and callback action value.
67
+ */
68
+ function buttonPair(leftContent, leftAction, rightContent, rightAction) {
69
+ return {
70
+ tag: 'column_set',
71
+ flex_mode: 'none',
72
+ columns: [
73
+ { tag: 'column', width: 'weighted', weight: 1, elements: [buttonElement(leftContent, leftAction)] },
74
+ { tag: 'column', width: 'weighted', weight: 1, elements: [buttonElement(rightContent, rightAction)] },
75
+ ],
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Feishu schema 2.0 single-select (`select_static`) does NOT support a
81
+ * `selected` field on options (that triggers 230099 parse json err). The
82
+ * supported way to show a default value is `initial_index` (1-based option
83
+ * order; 0 = show none). Build it from the option array + current value.
84
+ */
85
+ function initialIndex(options, currentValue) {
86
+ const idx = options.findIndex((o) => o.value === currentValue);
87
+ return idx >= 0 ? idx + 1 : 0;
88
+ }
89
+
90
+ function safeTitle(value) {
91
+ const title = String(value ?? '').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ').replace(/\s+/gu, ' ').trim();
92
+ return title || t('暂无标题');
93
+ }
94
+
95
+ function cardWith(headerText, elements) {
96
+ return JSON.stringify({
97
+ schema: '2.0',
98
+ header: { title: plainText(headerText), template: 'blue' },
99
+ body: { elements },
100
+ });
101
+ }
102
+
103
+ // ── Shared helper: a "back to menu" button ────────────────────────────────
104
+
105
+ function backButton() {
106
+ return button(t('🔙 返回菜单'), 'back_to_menu');
107
+ }
108
+
109
+ // ── Main menu card ────────────────────────────────────────────────────────
110
+
111
+ /**
112
+ * The hub menu card — a single entry point covering every command, organized
113
+ * by operating flow:
114
+ * 1. 会话 · 工作区(高频率)→ 会话下拉 · 工作区下拉 · 新会话 · 全部会话
115
+ * 2. 任务控制 → 停止 · 压缩 · 补充指令下拉
116
+ * 3. 配置 → 预设下拉 · 模型下拉 · 归档切换
117
+ * 4. 系统 → 状态 · 帮助
118
+ * `ctx` bundle:
119
+ * - workspaces: string[] (工作区下拉选项)
120
+ * - currentWorkspace: string|null (当前工作区,下拉高亮)
121
+ * - currentSession: {id,title}|null (当前绑定会话,续写目标)
122
+ * - sessions: {id,title}[] (最近会话,供会话下拉切换)
123
+ * - archiveVisible: boolean (归档显隐开关当前值)
124
+ * - presetCatalog: object|null (预设目录, {items,defaultId,_currentId})
125
+ * - modelCatalog: object|null (模型目录, {groups,current})
126
+ * Number fallback: 1=续写 2=新会话 3=会话列表 4=状态
127
+ * 5=补全权限 6=帮助.
128
+ */
129
+ export function menuCard(ctx) {
130
+ const {
131
+ workspaces = [],
132
+ currentWorkspace = null,
133
+ currentSession = null,
134
+ sessions = [],
135
+ archiveVisible = false,
136
+ presetCatalog = null,
137
+ modelCatalog = null,
138
+ } = ctx || {};
139
+
140
+ // currentSession 提供 id/title;为兼容旧调用,也接受 currentSessionTitle
141
+ const currentSessionId = currentSession?.id ?? null;
142
+ const currentSessionTitle = currentSession?.title ?? ctx?.currentSessionTitle ?? null;
143
+
144
+ const sessionOptions = (Array.isArray(sessions) ? sessions : []).slice(0, 20);
145
+ const hasSessions = sessionOptions.length > 0;
146
+ const hasWorkspaces = Array.isArray(workspaces) && workspaces.length > 0;
147
+ const elements = [];
148
+
149
+ // ── 设置区 ──────────────────────────────────────────────────
150
+ elements.push({ tag: 'div', text: markdown(t('**设置**')) });
151
+
152
+ // ── 四个下拉菜单 2×2 网格 ────────────────────────────────────
153
+
154
+ // 第 1 行:会话 + 工作区
155
+ let sessionDropdown = null;
156
+ if (hasSessions) {
157
+ const sessionPickOptions = sessionOptions.map((s) => ({
158
+ text: { tag: 'plain_text', content: `${s.id === currentSessionId ? '✓ ' : ''}${safeTitle(s.title)}` },
159
+ value: s.id,
160
+ }));
161
+ sessionDropdown = {
162
+ tag: 'select_static',
163
+ name: 'session_pick',
164
+ placeholder: {
165
+ tag: 'plain_text',
166
+ content: currentSessionId ? t('切换会话') : t('选择会话(当前未绑定)'),
167
+ },
168
+ initial_index: initialIndex(sessionPickOptions, currentSessionId),
169
+ options: sessionPickOptions,
170
+ behaviors: [{ type: 'callback', value: { action: 'session_pick' } }],
171
+ };
172
+ }
173
+
174
+ let workspaceDropdown = null;
175
+ if (hasWorkspaces) {
176
+ const wsOptions = workspaces.slice(0, 20).map((path) => ({
177
+ text: { tag: 'plain_text', content: `${path === currentWorkspace ? '✓ ' : ''}${path}` },
178
+ value: path,
179
+ }));
180
+ workspaceDropdown = {
181
+ tag: 'select_static',
182
+ name: 'workspace_pick',
183
+ placeholder: { tag: 'plain_text', content: t('切换工作区') },
184
+ initial_index: initialIndex(wsOptions, currentWorkspace),
185
+ options: wsOptions,
186
+ behaviors: [{ type: 'callback', value: { action: 'workspace_pick' } }],
187
+ };
188
+ }
189
+
190
+ // 第 2 行:预设 + 模型
191
+ const presetItems = Array.isArray(presetCatalog?.items) ? presetCatalog.items : [];
192
+ const curPresetId = presetCatalog?._currentId ?? null;
193
+ const presetFollowDefault = curPresetId === null;
194
+ let presetDropdown = null;
195
+ if (presetItems.length >= 1) {
196
+ const setPresetOptions = presetItems.slice(0, 30).map((item) => ({
197
+ text: { tag: 'plain_text', content: `${item.id === curPresetId ? '✓ ' : ''}${item.label}` },
198
+ value: item.id,
199
+ }));
200
+ const presetSelected = presetFollowDefault ? PRESET_FOLLOW_DEFAULT_SENTINEL : curPresetId;
201
+ setPresetOptions.unshift({
202
+ text: { tag: 'plain_text', content: `${presetFollowDefault ? '✓ ' : ''}${t('跟随默认')}` },
203
+ value: PRESET_FOLLOW_DEFAULT_SENTINEL,
204
+ });
205
+ presetDropdown = {
206
+ tag: 'select_static',
207
+ name: 'preset_pick',
208
+ placeholder: { tag: 'plain_text', content: t('切换预设') },
209
+ initial_index: initialIndex(setPresetOptions, presetSelected),
210
+ options: setPresetOptions,
211
+ behaviors: [{ type: 'callback', value: { action: 'preset_pick' } }],
212
+ };
213
+ }
214
+
215
+ const groups = Array.isArray(modelCatalog?.groups) ? modelCatalog.groups : [];
216
+ const curModel = modelCatalog?.current;
217
+ const curModelId = curModel ? `${curModel.provider}/${curModel.model}` : null;
218
+ const flat = [];
219
+ for (const group of groups) {
220
+ for (const model of (group.models || [])) flat.push({ id: `${group.id}/${model.id}`, name: `${group.name} - ${model.name}` });
221
+ }
222
+ let modelDropdown = null;
223
+ if (flat.length > 1) {
224
+ const setModelOptions = flat.slice(0, 30).map((opt) => ({
225
+ text: { tag: 'plain_text', content: `${opt.id === curModelId ? '✓ ' : ''}${opt.name}` },
226
+ value: opt.id,
227
+ }));
228
+ modelDropdown = {
229
+ tag: 'select_static',
230
+ name: 'model_pick',
231
+ placeholder: { tag: 'plain_text', content: t('切换模型') },
232
+ initial_index: initialIndex(setModelOptions, curModelId),
233
+ options: setModelOptions,
234
+ behaviors: [{ type: 'callback', value: { action: 'model_pick' } }],
235
+ };
236
+ }
237
+
238
+ // 渲染 2×2 网格:图标 + 下拉并列
239
+ // 每一行用 4 列 column_set:图标 | 下拉 | 图标 | 下拉
240
+ function iconCol(icon) {
241
+ return { tag: 'column', width: 'weighted', weight: 0.1, vertical_align: 'center', elements: [{ tag: 'div', text: { tag: 'plain_text', content: icon } }] };
242
+ }
243
+ function dropdownCol(el) {
244
+ return { tag: 'column', width: 'weighted', weight: 1, elements: [el] };
245
+ }
246
+
247
+ const row1 = [];
248
+ if (sessionDropdown) row1.push(sessionDropdown);
249
+ if (workspaceDropdown) row1.push(workspaceDropdown);
250
+ if (row1.length === 2) {
251
+ elements.push({
252
+ tag: 'column_set', flex_mode: 'none',
253
+ columns: [iconCol('💬'), dropdownCol(row1[0]), iconCol('📂'), dropdownCol(row1[1])],
254
+ });
255
+ } else if (row1[0]) {
256
+ elements.push(row1[0]);
257
+ }
258
+ if (!hasSessions) {
259
+ elements.push({ tag: 'div', text: markdown(t('当前工作区暂无可用会话。')) });
260
+ }
261
+
262
+ const row2 = [];
263
+ const presetBtn = button(t('🤖 切换预设'), 'presets');
264
+ const modelBtn = button(t('🧠 切换模型'), 'models');
265
+ if (presetDropdown) row2.push(presetDropdown); else row2.push(presetBtn);
266
+ if (modelDropdown) row2.push(modelDropdown); else row2.push(modelBtn);
267
+ elements.push({
268
+ tag: 'column_set', flex_mode: 'none',
269
+ columns: [iconCol('🤖'), dropdownCol(row2[0]), iconCol('🧠'), dropdownCol(row2[1])],
270
+ });
271
+
272
+ // 新会话 + 全部会话按钮
273
+ elements.push(buttonPair(t('🆕 新会话'), 'new', t('📋 会话/关注'), 'sessions'));
274
+ if (!hasSessions && !hasWorkspaces) {
275
+ elements.push(button(t('🗂 工作区列表'), 'workspaces'));
276
+ }
277
+ elements.push({ tag: 'hr' });
278
+
279
+ // ── 任务控制(对运行中任务的操作)────────────────────────
280
+ elements.push({ tag: 'div', text: markdown(t('**任务控制**')) });
281
+ elements.push(buttonPair(t('⏹ 停止'), 'stop', t('📐 压缩'), 'compact'));
282
+ elements.push({ tag: 'hr' });
283
+
284
+ // ── 补充指令 + 归档切换(并列)────────────────────────────
285
+ elements.push({
286
+ tag: 'column_set', flex_mode: 'none',
287
+ columns: [
288
+ {
289
+ tag: 'column', width: 'weighted', weight: 1,
290
+ elements: [
291
+ { tag: 'div', text: markdown(t('**补充指令**')) },
292
+ {
293
+ tag: 'select_static',
294
+ name: 'steer_pick',
295
+ placeholder: { tag: 'plain_text', content: t('选择补充指令') },
296
+ initial_index: 0,
297
+ options: [
298
+ ...QUICK_STEER_OPTIONS.map((source) => ({
299
+ text: { tag: 'plain_text', content: t(source) },
300
+ value: t(source),
301
+ })),
302
+ { text: { tag: 'plain_text', content: t('✏️ 更多 / 自定义…') }, value: 'custom' },
303
+ ],
304
+ behaviors: [{ type: 'callback', value: { action: 'steer_pick' } }],
305
+ },
306
+ ],
307
+ },
308
+ {
309
+ tag: 'column', width: 'weighted', weight: 1,
310
+ elements: [
311
+ { tag: 'div', text: markdown(t('🗄 归档:{state}', {
312
+ state: archiveVisible ? t('已显示') : t('已隐藏'),
313
+ })) },
314
+ button(t('切换归档显示'), 'archive_toggle'),
315
+ ],
316
+ },
317
+ ],
318
+ });
319
+ elements.push({ tag: 'hr' });
320
+
321
+ // ── 底部操作(系统功能)────────────────────────────────────
322
+ elements.push(buttonPair(t('📊 状态'), 'status', t('📖 帮助'), 'help'));
323
+
324
+ // 命令与数字兜底说明
325
+ elements.push({ tag: 'div', text: markdown(t(
326
+ '**数字兜底**\n**1**工作区列表 · **2**新会话 · **3**会话列表 · **4**状态\n**5**🔧补全权限 · **6**帮助',
327
+ )) });
328
+ return cardWith(t('🤖 助手中心'), elements);
329
+ }
330
+
331
+ // ── Preset management card ────────────────────────────────────────────────
332
+
333
+ /**
334
+ * Preset selection card with a dropdown of available presets.
335
+ * The catalog comes from `harness.agentPresetSettings()`.
336
+ */
337
+ export function presetCard(catalog) {
338
+ const { items, defaultId } = catalog;
339
+ const current = catalog._currentId; // injected by the caller
340
+ const currentItem = items.find((i) => i.id === current);
341
+ const defaultItem = items.find((i) => i.id === defaultId);
342
+
343
+ const currentText = current === null
344
+ ? t('跟随 Host 默认{default}', { default: defaultItem ? `(${defaultItem.label})` : '' })
345
+ : currentItem
346
+ ? `${currentItem.label}(${currentItem.id})`
347
+ : t('{id}(已不可用)', { id: current });
348
+
349
+ const elements = [
350
+ { tag: 'div', text: markdown(t('**当前**:{value}', { value: currentText })) },
351
+ { tag: 'div', text: markdown(t('**Host 默认**:{value}', {
352
+ value: defaultItem ? `${defaultItem.label}(${defaultItem.id})` : t('未设置'),
353
+ })) },
354
+ { tag: 'hr' },
355
+ ];
356
+
357
+ if (items.length >= 1) {
358
+ const presetCardOptions = items.map((item) => ({
359
+ text: { tag: 'plain_text', content: `${item.label}(${item.id})${item.id === current ? ' ✓' : ''}` },
360
+ value: item.id,
361
+ }));
362
+ elements.push(
363
+ {
364
+ tag: 'select_static',
365
+ name: 'preset_pick',
366
+ placeholder: { tag: 'plain_text', content: t('选择预设') },
367
+ initial_index: current === null ? 0 : initialIndex(presetCardOptions, current),
368
+ options: presetCardOptions,
369
+ behaviors: [{ type: 'callback', value: { action: 'preset_pick' } }],
370
+ },
371
+ { tag: 'hr' },
372
+ buttonPair(t('🔄 跟随默认'), 'preset_default', t('🔙 返回菜单'), 'back_to_menu'),
373
+ );
374
+ } else {
375
+ elements.push(
376
+ { tag: 'div', text: markdown(t('当前没有可选择的预设。')) },
377
+ backButton(),
378
+ );
379
+ }
380
+ return cardWith(t('🤖 预设列表'), elements);
381
+ }
382
+
383
+ // ── Model management card ─────────────────────────────────────────────────
384
+
385
+ /**
386
+ * Model selection card with a dropdown of available models.
387
+ * The catalog comes from `harness.listModels()` or `session.models()`.
388
+ * Groups are shown as text, then a flat dropdown for selection.
389
+ */
390
+ export function modelCard(catalog) {
391
+ const { groups, current } = catalog;
392
+ const currentId = current ? `${current.provider}/${current.model}` : null;
393
+
394
+ const elements = [
395
+ { tag: 'div', text: markdown(t('**当前模型**:{model}', { model: currentId || t('未设置') })) },
396
+ { tag: 'hr' },
397
+ ];
398
+
399
+ // Count total models
400
+ let total = 0;
401
+ for (const group of groups) total += group.models.length;
402
+
403
+ if (total === 0) {
404
+ elements.push(
405
+ { tag: 'div', text: markdown(t('当前没有可用模型。')) },
406
+ backButton(),
407
+ );
408
+ } else {
409
+ // Show groups as text
410
+ for (const group of groups) {
411
+ const modelLines = group.models.map((m) => {
412
+ const id = `${group.id}/${m.id}`;
413
+ return `${id}${id === currentId ? ' ✓' : ''}`;
414
+ });
415
+ elements.push(
416
+ { tag: 'div', text: markdown(`**${group.name}**\n${modelLines.join('\n')}`) },
417
+ );
418
+ }
419
+
420
+ // Flatten all models into a dropdown
421
+ const allOptions = [];
422
+ for (const group of groups) {
423
+ for (const model of group.models) {
424
+ allOptions.push({
425
+ value: `${group.id}/${model.id}`,
426
+ text: { tag: 'plain_text', content: `${group.name} - ${model.name}` },
427
+ });
428
+ }
429
+ }
430
+
431
+ elements.push(
432
+ { tag: 'hr' },
433
+ {
434
+ tag: 'select_static',
435
+ name: 'model_pick',
436
+ placeholder: { tag: 'plain_text', content: t('选择模型') },
437
+ initial_index: currentId === null ? 0 : initialIndex(allOptions, currentId),
438
+ options: allOptions.map((opt) => ({
439
+ text: { tag: 'plain_text', content: `${opt.text.content}${opt.value === currentId ? ' ✓' : ''}` },
440
+ value: opt.value,
441
+ })),
442
+ behaviors: [{ type: 'callback', value: { action: 'model_pick' } }],
443
+ },
444
+ { tag: 'hr' },
445
+ backButton(),
446
+ );
447
+ }
448
+ return cardWith(t('🧠 模型列表'), elements);
449
+ }
450
+
451
+ // ── Status card ───────────────────────────────────────────────────────────
452
+
453
+ /**
454
+ * System status card showing connection, workspace, preset, model and session
455
+ * count. `info` is an object with keys:
456
+ * - connected: boolean
457
+ * - workspace: string | null
458
+ * - preset: string | null
459
+ * - model: string | null
460
+ * - sessionCount: number
461
+ */
462
+ export function statusCard(info) {
463
+ const elements = [
464
+ { tag: 'div', text: markdown(t('{icon} 飞书机器人{state}', {
465
+ icon: info.connected ? '✅' : '❌',
466
+ state: info.connected ? t('已连接') : t('未连接'),
467
+ })) },
468
+ { tag: 'div', text: markdown(t('📂 工作区:`{workspace}`', { workspace: info.workspace || t('未设置') })) },
469
+ { tag: 'div', text: markdown(t('🤖 预设:{preset}', { preset: info.preset || t('未设置') })) },
470
+ { tag: 'div', text: markdown(t('🧠 模型:{model}', { model: info.model || t('未设置') })) },
471
+ { tag: 'div', text: markdown(t('💬 会话:{count} 个', { count: info.sessionCount })) },
472
+ { tag: 'hr' },
473
+ backButton(),
474
+ ];
475
+ return cardWith(t('📊 系统状态'), elements);
476
+ }
477
+
478
+ // ── Help card ─────────────────────────────────────────────────────────────
479
+
480
+ /**
481
+ * Plain-text command reference advertised when no interactive card is
482
+ * available (e.g. non-interactive clients), so every command stays
483
+ * discoverable without card callbacks.
484
+ */
485
+ export function menuHelpText() {
486
+ return [
487
+ '🤖 助手菜单(回复数字即可,无需记命令)',
488
+ '',
489
+ '📋 会话 / 工作区',
490
+ '/sessionlist 或 /sessions 列出工作区会话',
491
+ '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
492
+ '/session ID 绑定已有会话',
493
+ '/workspacelist 列出工作区',
494
+ '/workspace 工作区序号或绝对路径 切换工作区',
495
+ '/ws、/wsl、/workspaces 工作区命令别名',
496
+ '/new 开启全新会话',
497
+ '',
498
+ '📊 状态 / 压缩',
499
+ '/status 连接状态',
500
+ '/version 查看插件版本',
501
+ '/compact 压缩当前会话上下文',
502
+ '/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)',
503
+ '/archived on/off 会话列表显示/隐藏归档',
504
+ '',
505
+ '👁 关注',
506
+ '/watch ID 关注会话(完成后推送)',
507
+ '/watchlist 关注列表',
508
+ '/unwatch ID 取消关注',
509
+ '',
510
+ '🤖 预设 / 模型',
511
+ '/presetlist 或 /presets 列出可用 Agent Preset',
512
+ '/preset [序号或完整ID] 查看或设置当前机器人 Agent Preset',
513
+ '纯数字 ID:/preset id:<ID>',
514
+ '/preset --default 跟随 Host 默认',
515
+ '/models 列出模型',
516
+ '/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级',
517
+ '/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级',
518
+ '/model [序号或完整模型ID] [推理等级ID] 查看或切换当前会话模型',
519
+ '',
520
+ '📦 批量输入(仅私聊)',
521
+ '/batch 开始批量输入(仅私聊,最多 10 条文字)',
522
+ '/send 提交当前批次',
523
+ '/cancel 取消当前批次',
524
+ '',
525
+ '🎮 任务控制',
526
+ '/stop 停止当前任务',
527
+ '/steer 指令 给 Agent 补充指令',
528
+ '/repair 补全飞书权限与卡片回调',
529
+ ].map((line) => t(line)).join('\n');
530
+ }
531
+
532
+ /**
533
+ * Help card with all available commands and their descriptions.
534
+ */
535
+ const HELP_CARD_FEATURES = [
536
+ '**📋 卡片功能**',
537
+ '',
538
+ '1. 会话下拉 — 切换当前绑定会话',
539
+ '2. 工作区下拉 — 切换工作区',
540
+ '3. 🤖 预设下拉 — 切换 Agent 预设',
541
+ '4. 🧠 模型下拉 — 切换模型',
542
+ '5. 🆕 新会话 — 开启全新会话',
543
+ '6. 📋 会话/关注 — 查看/绑定会话,管理关注',
544
+ '7. ⏹ 停止 — 停止当前任务',
545
+ '8. 📐 压缩 — 压缩当前会话上下文',
546
+ '9. 补充指令 — 给 Agent 发送指令',
547
+ '10. 🗄 归档切换 — 显示/隐藏归档会话',
548
+ '11. 📊 状态 — 查看系统连接状态',
549
+ '12. 📖 帮助 — 查看本帮助',
550
+ ].join('\n');
551
+
552
+ const HELP_TEXT_COMMANDS = [
553
+ '**⌨️ 文本命令**',
554
+ '',
555
+ '`/m` — 打开菜单卡片',
556
+ '`/new` — 开启全新会话',
557
+ '`/session ID` — 绑定已有会话',
558
+ '`/sessionlist [工作区]` 或 `/sessions [工作区]` — 列出会话',
559
+ '`/sessionlist --limit N` 或 `/sessions --limit N` — 仅列出当前工作区前 N 个会话',
560
+ '`/workspace 工作区序号或绝对路径` — 切换工作区',
561
+ '`/workspacelist` — 列出工作区',
562
+ '`/status` — 查看连接状态',
563
+ '`/compact` — 压缩上下文',
564
+ '`/stop` — 停止当前任务',
565
+ '`/steer 指令` — 补充指令',
566
+ '`/watch ID` — 关注会话',
567
+ '`/watchlist` — 关注列表',
568
+ '`/unwatch ID` — 取消关注',
569
+ '`/archived on/off` — 归档显隐',
570
+ '`/presetlist` 或 `/presets` — 列出预设',
571
+ '`/preset [序号/ID]` — 切换预设',
572
+ '`/preset --default` — 跟随默认',
573
+ '`/models` — 列出模型',
574
+ '`/reasoninglist` 或 `/reasonings` — 按序号列出当前模型可用推理等级',
575
+ '`/reasoning [序号、等级ID或 --default]` — 查看或切换当前推理等级',
576
+ '`/model [序号或完整模型ID] [推理等级ID]` — 查看或切换当前会话模型',
577
+ '`/batch` — 开启批量输入(仅私聊,最多 10 条文字)',
578
+ '`/send` — 提交当前批次',
579
+ '`/cancel` — 取消当前批次',
580
+ '`/repair` — 补全飞书权限与卡片回调',
581
+ ].join('\n');
582
+
583
+ const HELP_NUMBER_FALLBACK = [
584
+ '**💡 数字兜底**',
585
+ '回复数字快速操作:',
586
+ '**1**工作区列表 · **2**新会话 · **3**会话/关注',
587
+ '**4**状态 · **5**补全权限 · **6**帮助',
588
+ ].join('\n');
589
+
590
+ export function helpCard(extraTextLines = []) {
591
+ const extraText = Array.isArray(extraTextLines) && extraTextLines.length > 0
592
+ ? ('\n' + extraTextLines.join('\n'))
593
+ : '';
594
+ const elements = [
595
+ { tag: 'div', text: markdown(t(HELP_CARD_FEATURES)) },
596
+ { tag: 'hr' },
597
+ { tag: 'div', text: markdown([
598
+ t(HELP_TEXT_COMMANDS),
599
+ t('/ws、/wsl、/workspaces 工作区命令别名'),
600
+ t('`/version` — 查看插件版本'),
601
+ t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'),
602
+ ].join('\n') + extraText) },
603
+ { tag: 'hr' },
604
+ { tag: 'div', text: markdown(t(HELP_NUMBER_FALLBACK)) },
605
+ { tag: 'hr' },
606
+ backButton(),
607
+ ];
608
+ return cardWith(t('📖 帮助'), elements);
609
+ }
610
+
611
+ // ── One-shot callback probe (repair verification) ─────────────────────────
612
+
613
+ /** One-shot callback probe used only after an existing app was re-authorized. */
614
+ export function cardActionProbeCard(nonce) {
615
+ if (typeof nonce !== 'string' || !/^[A-Za-z0-9_-]{16,128}$/.test(nonce)) {
616
+ throw new TypeError('A safe card-action probe nonce is required');
617
+ }
618
+ return cardWith(t('🧪 验证卡片按钮'), [
619
+ {
620
+ tag: 'div',
621
+ text: markdown(t('授权已提交。请点击下方按钮;机器人真实收到回调后才会判定修复成功。')),
622
+ },
623
+ {
624
+ tag: 'column_set',
625
+ flex_mode: 'none',
626
+ columns: [{
627
+ tag: 'column',
628
+ width: 'weighted',
629
+ weight: 1,
630
+ elements: [{
631
+ tag: 'button',
632
+ text: plainText(t('完成验证')),
633
+ type: 'primary',
634
+ width: 'fill',
635
+ behaviors: [{
636
+ type: 'callback',
637
+ value: { action: 'repair_verify', nonce },
638
+ }],
639
+ }],
640
+ }],
641
+ },
642
+ ]);
643
+ }
644
+
645
+ // ── Session list card (preserved, with back button) ───────────────────────
646
+
647
+ /**
648
+ * One page of the workspace's sessions. Each row is a `column_set` pair:
649
+ * the fixed-width ⭐ watch toggle (`⭐关注` / `⭐取关` for already-watched
650
+ * sessions) followed by the session button that carries the page-local
651
+ * number label (reply-number fallback = bind). Archived sessions are marked
652
+ * in the label. `watchedSessionIds` is a Set-like of ids this conversation
653
+ * already watches.
654
+ */
655
+ export function sessionListCard(workspace, sessions, page, total, watchedSessionIds = new Set()) {
656
+ const start = page * MENU_PAGE_SIZE;
657
+ const slice = sessions.slice(start, start + MENU_PAGE_SIZE);
658
+ const pageCount = Math.max(1, Math.ceil(total / MENU_PAGE_SIZE));
659
+ const watched = (id) => typeof watchedSessionIds?.has === 'function' && watchedSessionIds.has(id);
660
+ /** One row: fixed 90px watch toggle + the session button filling the rest. */
661
+ const row = (watchButton, sessionButton) => ({
662
+ tag: 'column_set',
663
+ flex_mode: 'none',
664
+ horizontal_spacing: 'default',
665
+ columns: [
666
+ { tag: 'column', width: '90px', vertical_align: 'center', elements: [watchButton] },
667
+ { tag: 'column', width: 'weighted', weight: 1, vertical_align: 'center', elements: [sessionButton] },
668
+ ],
669
+ });
670
+ const elements = [
671
+ { tag: 'div', text: markdown(t('**工作区**:{workspace}\n共 **{total}** 个会话{paging}', {
672
+ workspace: `\`${workspace}\``,
673
+ total,
674
+ paging: total > MENU_PAGE_SIZE
675
+ ? t('(第 {page}/{pageCount} 页)', { page: page + 1, pageCount })
676
+ : '',
677
+ })) },
678
+ ...slice.map((session, offset) => {
679
+ // Page-local numbering: number replies resolve against this page.
680
+ const label = `${offset + 1}. ${safeTitle(session.title)}${session.archived === true ? t('(已归档)') : ''}`;
681
+ const watching = watched(session.sessionId);
682
+ return row(
683
+ buttonElement(watching ? t('⭐ 取消关注') : t('☆ 关注'), watching ? `unwatch:${session.sessionId}` : `watch:${session.sessionId}`),
684
+ buttonElement(label, `use:${session.sessionId}`),
685
+ );
686
+ }),
687
+ ];
688
+ if (page > 0) elements.push(button(t('◀ 上一页'), `sessions:${page - 1}`));
689
+ if (page + 1 < pageCount) elements.push(button(t('下一页 ▶'), `sessions:${page + 1}`));
690
+ elements.push(
691
+ { tag: 'hr' },
692
+ buttonPair(t('🔙 返回菜单'), 'back_to_menu', t('🔍 关注列表'), 'watchlist'),
693
+ { tag: 'div', text: markdown(t('回复数字(1~N)绑定本页会话。')) },
694
+ );
695
+ return cardWith(t('📂 会话列表'), elements);
696
+ }
697
+
698
+ // ── Workspace list card (preserved, with back button) ─────────────────────
699
+
700
+ /** The workspace list card (switch-workspace buttons + reply fallback). */
701
+ export function workspaceListCard(paths, current) {
702
+ const elements = paths.length === 0
703
+ ? [
704
+ { tag: 'div', text: markdown(t('当前 Host 上没有已登记的工作区。')) },
705
+ backButton(),
706
+ ]
707
+ : [
708
+ { tag: 'div', text: markdown(t('回复数字切换工作区,或点击按钮:')) },
709
+ ...paths.map((path, index) => button(
710
+ `${index + 1}. ${path}${path === current ? t('(当前)') : ''}`,
711
+ `workspace:${path}`,
712
+ )),
713
+ { tag: 'hr' },
714
+ backButton(),
715
+ ];
716
+ return cardWith(t('🗂 工作区'), elements);
717
+ }
718
+
719
+ // ── Watch list card (multi-select add/remove + back button) ──────────────
720
+
721
+ /** Dropdown (multi-select) of sessions not yet watched, to add them in bulk. */
722
+ function watchAddSelect(entries, availableSessions) {
723
+ const watched = new Set(entries.map((e) => e.sessionId));
724
+ const options = (Array.isArray(availableSessions) ? availableSessions : [])
725
+ .filter((s) => s?.sessionId && !watched.has(s.sessionId))
726
+ .slice(0, 30)
727
+ .map((s) => ({
728
+ text: { tag: 'plain_text', content: safeTitle(s.title ?? s.sessionId) },
729
+ value: s.sessionId,
730
+ }));
731
+ if (options.length === 0) return null;
732
+ return {
733
+ tag: 'multi_select_static',
734
+ name: 'watch_add',
735
+ placeholder: { tag: 'plain_text', content: t('勾选要关注的会话') },
736
+ options,
737
+ behaviors: [{ type: 'callback', value: { action: 'watch_add', kind: 'multi' } }],
738
+ };
739
+ }
740
+
741
+ /** Dropdown (multi-select) of currently watched sessions, to remove in bulk. */
742
+ function watchRemoveSelect(entries) {
743
+ const options = entries.slice(0, 30).map((entry) => ({
744
+ text: { tag: 'plain_text', content: safeTitle(entry.title) },
745
+ value: entry.sessionId,
746
+ }));
747
+ if (options.length === 0) return null;
748
+ return {
749
+ tag: 'multi_select_static',
750
+ name: 'watch_remove',
751
+ placeholder: { tag: 'plain_text', content: t('勾选要取消关注的会话') },
752
+ options,
753
+ behaviors: [{ type: 'callback', value: { action: 'watch_remove', kind: 'multi' } }],
754
+ };
755
+ }
756
+
757
+ /** The watch list for one conversation (multi-select add/remove + buttons). */
758
+ export function watchListCard(entries, availableSessions) {
759
+ const watching = Array.isArray(entries) ? entries : [];
760
+ const addSelect = watchAddSelect(watching, availableSessions);
761
+ const removeSelect = watchRemoveSelect(watching);
762
+
763
+ const elements = [];
764
+ if (watching.length === 0) {
765
+ elements.push({ tag: 'div', text: markdown(t('当前没有关注的会话。任务完成会自动推送结果。')) });
766
+ } else {
767
+ elements.push({ tag: 'div', text: markdown(t('当前关注 **{count}** 个会话:', { count: watching.length })) });
768
+ }
769
+
770
+ if (addSelect) {
771
+ elements.push({ tag: 'hr' }, { tag: 'div', text: markdown(t('**➕ 添加关注**(多选下拉勾选)')) }, addSelect);
772
+ }
773
+ if (removeSelect) {
774
+ elements.push({ tag: 'hr' }, { tag: 'div', text: markdown(t('**➖ 取消关注**(多选下拉勾选)')) }, removeSelect);
775
+ }
776
+ elements.push({ tag: 'hr' }, buttonPair(t('📋 会话列表'), 'sessions', t('🔙 返回菜单'), 'back_to_menu'));
777
+ return cardWith(t('👁 关注列表'), elements);
778
+ }
779
+
780
+ // ── Completion push card ──────────────────────────────────────────────────
781
+
782
+ /**
783
+ * The completion push card. `title` is the session title, `reason` the
784
+ * turn-end kind (completed / stopped / aborted).
785
+ */
786
+ export function completionCard(sessionId, title, reason) {
787
+ const reasonText = reason === 'completed'
788
+ ? t('已完成')
789
+ : reason === 'stopped'
790
+ ? t('已停止')
791
+ : reason === 'aborted'
792
+ ? t('已中止')
793
+ : reason === 'cancelled'
794
+ ? t('已取消')
795
+ : t('已结束');
796
+ return cardWith(t('✅ 任务完成'), [
797
+ { tag: 'div', text: markdown(`**${safeTitle(title)}**\n\`${sessionId}\``) },
798
+ { tag: 'div', text: markdown(t('**状态**:{reason}', { reason: reasonText })) },
799
+ { tag: 'hr' },
800
+ buttonPair(t('📋 会话列表'), 'sessions', t('🔙 返回菜单'), 'back_to_menu'),
801
+ { tag: 'div', text: markdown(t('绑定该会话后可继续追问,输入文字即可。')) },
802
+ ]);
803
+ }
804
+
805
+ // ── Steer card (补充指令) ─────────────────────────────────────────────────
806
+
807
+ /** 常用补充指令的快捷选项,供下拉秒选。 */
808
+ const QUICK_STEER_OPTIONS = ['继续', '加速运行', '总结当前进展', '更简洁些', '更详细些'];
809
+
810
+ /** 快捷下拉的最后一项:切换到自定义输入卡片。 */
811
+ export const STEER_CUSTOM_SENTINEL = '__steer_custom__';
812
+
813
+ /** 补充指令卡片:单个下拉,快捷指令 + 「更多/自定义」。 */
814
+ export function steerCard({ hasSession }) {
815
+ const hint = hasSession
816
+ ? t('从下方下拉选择补充指令;最后一项可自定义输入。')
817
+ : t('当前没有绑定会话,请先绑定会话再补充指令。');
818
+ const options = QUICK_STEER_OPTIONS.map((source) => ({
819
+ text: { tag: 'plain_text', content: t(source) },
820
+ value: t(source),
821
+ }));
822
+ options.push({ text: { tag: 'plain_text', content: t('✏️ 更多 / 自定义…') }, value: STEER_CUSTOM_SENTINEL });
823
+ const elements = [
824
+ { tag: 'div', text: markdown(hint) },
825
+ { tag: 'hr' },
826
+ {
827
+ tag: 'select_static',
828
+ name: 'steer_quick',
829
+ placeholder: { tag: 'plain_text', content: t('选择补充指令') },
830
+ initial_index: 0,
831
+ options,
832
+ behaviors: [{ type: 'callback', value: { action: 'steer', source: 'quick' } }],
833
+ },
834
+ { tag: 'hr' },
835
+ button(t('🔙 返回菜单'), 'back_to_menu'),
836
+ ];
837
+ return cardWith(t('➕ 补充指令'), elements);
838
+ }
839
+
840
+ /** 自定义输入卡:输入框 + 提交(从下拉「更多/自定义」切过来)。 */
841
+ export function customSteerCard() {
842
+ const elements = [
843
+ { tag: 'div', text: markdown(t('输入补充指令后点「提交」,发送给当前运行的任务。')) },
844
+ { tag: 'hr' },
845
+ {
846
+ tag: 'form',
847
+ name: 'steer_form',
848
+ elements: [
849
+ {
850
+ tag: 'input',
851
+ name: 'steer_text',
852
+ placeholder: { tag: 'plain_text', content: t('输入你的补充指令') },
853
+ },
854
+ {
855
+ tag: 'button',
856
+ // Card 2.0 form controls need stable names so the client can
857
+ // construct a submit action (and expose action.name) reliably.
858
+ name: 'steer_submit',
859
+ text: { tag: 'plain_text', content: t('提交') },
860
+ type: 'primary',
861
+ width: 'fill',
862
+ form_action_type: 'submit',
863
+ behaviors: [{ type: 'callback', value: { action: 'steer', source: 'form' } }],
864
+ },
865
+ ],
866
+ },
867
+ { tag: 'hr' },
868
+ button(t('🔙 返回菜单'), 'back_to_menu'),
869
+ ];
870
+ return cardWith(t('➕ 自定义指令'), elements);
871
+ }
872
+
873
+ /**
874
+ * Interactive approval card with approve / reject buttons. Action values carry
875
+ * the approvalId so the card callback can submit the decision:
876
+ * approve:<approvalId> / reject:<approvalId>
877
+ * `requiresMention` is advisory; a button click is itself the operator's
878
+ * explicit intent, so it does not need an @ mention in groups.
879
+ */
880
+ export function approvalCard({ toolName, operation, reason, approvalId, resolvedText }) {
881
+ const elements = [];
882
+ if (toolName) {
883
+ elements.push({ tag: 'div', text: markdown(t('工具:{tool}', { tool: String(toolName) })) });
884
+ }
885
+ if (operation) {
886
+ // Cap the operation text so an oversized argument list cannot overflow the
887
+ // card (the plain-text path rejects >6000 chars; here we truncate so the
888
+ // approve/reject buttons still render).
889
+ const MAX_OPERATION_CHARS = 6_000;
890
+ const op = String(operation);
891
+ const shown = op.length > MAX_OPERATION_CHARS
892
+ ? `${op.slice(0, MAX_OPERATION_CHARS)}\n…(操作参数过长,已截断)`
893
+ : op;
894
+ elements.push({ tag: 'div', text: markdown(t('操作参数:\n{operation}', { operation: shown })) });
895
+ }
896
+ if (reason) {
897
+ elements.push({ tag: 'div', text: markdown(t('原因:{reason}', { reason: String(reason) })) });
898
+ }
899
+ elements.push(
900
+ { tag: 'hr' },
901
+ resolvedText
902
+ ? { tag: 'div', text: markdown(resolvedText) }
903
+ : buttonPair(t('✅ 批准'), `approve:${approvalId}`, t('❌ 拒绝'), `reject:${approvalId}`),
904
+ );
905
+ return cardWith(t('🔐 工具审批'), elements);
906
+ }
907
+
908
+ // ── Streaming step card (流式过程卡片) ────────────────────────────────────
909
+
910
+ /** One streaming step card carries at most this many JSON bytes after the
911
+ * card has been serialized (Feishu caps card content near 30KB; stay lower
912
+ * so headers and JSON escaping always fit). */
913
+ export const STEP_STREAM_CARD_MAX_BYTES = 24_000;
914
+
915
+ /**
916
+ * Build one streaming step card from the accumulated process blocks:
917
+ * { kind: 'message', text } — interim note / warning / context line
918
+ * { kind: 'tools', lines: string[] } — tool-call summary panel
919
+ * `status`: 'running' keeps panels expanded and ends with an italic status
920
+ * line; 'completed' / 'stopped' collapse the panels and swap the status text;
921
+ * 'sealed' is an overflow spill chunk with no status line at all. Finished
922
+ * turns (and sealed spill chunks) merge every tool/thinking panel into one
923
+ * collapsed "process details" panel so the sealed card stays compact.
924
+ */
925
+
926
+ export function stepStreamCard(rawBlocks, { status = 'running' } = {}) {
927
+ const running = status === 'running';
928
+ const elements = [];
929
+ const panelElements = [];
930
+ for (const block of Array.isArray(rawBlocks) ? rawBlocks : []) {
931
+ if (block?.kind === 'tools' || block?.kind === 'notes') {
932
+ const lines = (Array.isArray(block.lines) ? block.lines : [])
933
+ .filter((line) => typeof line === 'string' && line.trim());
934
+ if (lines.length === 0) continue;
935
+ const count = lines.length + (Number(block.omitted) || 0);
936
+ const panel = stepPanel(lines, {
937
+ title: block.kind === 'tools'
938
+ ? t('🛠️ 工具摘要({count})', { count })
939
+ : t('💭 思考过程({count})', { count }),
940
+ // Tool summaries stay visible while the turn runs; thinking notes
941
+ // remain folded at all times. Finished turns keep both panels but
942
+ // tuck them inside one collapsed "process details" wrapper.
943
+ expanded: block.kind === 'tools' && running,
944
+ });
945
+ if (running) elements.push(panel);
946
+ else panelElements.push(panel);
947
+ continue;
948
+ }
949
+ const text = typeof block?.text === 'string' ? block.text.trim() : '';
950
+ if (text) elements.push({ tag: 'markdown', content: text });
951
+ }
952
+ if (!running && panelElements.length > 0) {
953
+ // Finished turns: the tool/thinking panels nest inside one collapsed
954
+ // "process details" wrapper, so the sealed card shows a single line.
955
+ elements.push(processDetailsPanel(panelElements));
956
+ }
957
+ if (elements.length === 0) elements.push({ tag: 'markdown', content: ' ' });
958
+ if (status !== 'sealed') {
959
+ elements.push({ tag: 'markdown', content: `_${stepStatusText(status)}_` });
960
+ }
961
+ return JSON.stringify({
962
+ schema: '2.0',
963
+ header: { title: plainText(t('⚙️ 任务过程')), template: 'blue' },
964
+ body: { elements },
965
+ });
966
+ }
967
+
968
+ /** The collapsed wrapper that holds the per-kind panels on finished turns. */
969
+ function processDetailsPanel(children) {
970
+ return {
971
+ tag: 'collapsible_panel',
972
+ expanded: false,
973
+ background_color: 'grey-50',
974
+ border: { color: 'grey', corner_radius: '8px' },
975
+ padding: '8px 8px 8px 8px',
976
+ header: {
977
+ title: { tag: 'plain_text', content: t('📋 过程详情') },
978
+ vertical_align: 'center',
979
+ padding: '8px 8px 8px 8px',
980
+ icon: { tag: 'standard_icon', token: 'down-small-ccm_outlined', color: 'grey', size: '16px 16px' },
981
+ icon_position: 'right',
982
+ icon_expanded_angle: -180,
983
+ },
984
+ elements: children,
985
+ };
986
+ }
987
+
988
+ /** The collapsible grey panel used for tool summaries and thinking notes. */
989
+ function stepPanel(lines, { title, expanded }) {
990
+ return {
991
+ tag: 'collapsible_panel',
992
+ expanded: expanded === true,
993
+ background_color: 'grey-50',
994
+ border: { color: 'grey', corner_radius: '8px' },
995
+ padding: '8px 8px 8px 8px',
996
+ header: {
997
+ title: { tag: 'plain_text', content: title },
998
+ vertical_align: 'center',
999
+ padding: '8px 8px 8px 8px',
1000
+ icon: { tag: 'standard_icon', token: 'down-small-ccm_outlined', color: 'grey', size: '16px 16px' },
1001
+ icon_position: 'right',
1002
+ icon_expanded_angle: -180,
1003
+ },
1004
+ elements: [{ tag: 'markdown', content: lines.join('\n') }],
1005
+ };
1006
+ }
1007
+
1008
+ export function stepStatusText(status) {
1009
+ if (status === 'completed') return t('已完成');
1010
+ if (status === 'stopped') return t('已停止');
1011
+ return t('运行中');
1012
+ }
1013
+
1014
+ /**
1015
+ * A single card accepts only this many `table` elements. Feishu rejects the
1016
+ * whole write with `230099 / ErrCode 11310 card table number over limit`, which
1017
+ * leaves the card stuck on its previous content, so the reply never appears.
1018
+ *
1019
+ * The boundary was established by the maintainer against a live bot: five
1020
+ * tables in one card succeeded, six failed, and a folded process panel's tables
1021
+ * counted toward the total (3 folded + 2 in the body succeeded, 3 + 3 failed).
1022
+ */
1023
+ export const STEP_STREAM_CARD_MAX_TABLES = 5;
1024
+
1025
+ function hasClosingBacktickRun(text, start, length) {
1026
+ for (let index = start; index < text.length;) {
1027
+ if (text[index] !== '`') {
1028
+ index += 1;
1029
+ continue;
1030
+ }
1031
+ let end = index + 1;
1032
+ while (text[end] === '`') end += 1;
1033
+ if (end - index === length) return true;
1034
+ index = end;
1035
+ }
1036
+ return false;
1037
+ }
1038
+
1039
+ function gfmTableCells(line) {
1040
+ const normalized = line.endsWith('\r') ? line.slice(0, -1) : line;
1041
+ if (normalized.startsWith(' ') || normalized.startsWith('\t')) return null;
1042
+ const text = normalized.trim();
1043
+ if (!text) return null;
1044
+
1045
+ const cells = [];
1046
+ let cell = '';
1047
+ let separators = 0;
1048
+ let codeRun = 0;
1049
+ for (let index = 0; index < text.length;) {
1050
+ const character = text[index];
1051
+ if (character === '\\' && index + 1 < text.length) {
1052
+ cell += text.slice(index, index + 2);
1053
+ index += 2;
1054
+ continue;
1055
+ }
1056
+ if (character === '`') {
1057
+ let end = index + 1;
1058
+ while (text[end] === '`') end += 1;
1059
+ const length = end - index;
1060
+ if (codeRun === length) {
1061
+ codeRun = 0;
1062
+ } else if (codeRun === 0 && hasClosingBacktickRun(text, end, length)) {
1063
+ codeRun = length;
1064
+ }
1065
+ cell += text.slice(index, end);
1066
+ index = end;
1067
+ continue;
1068
+ }
1069
+ if (character === '|' && codeRun === 0) {
1070
+ cells.push(cell);
1071
+ cell = '';
1072
+ separators += 1;
1073
+ index += 1;
1074
+ continue;
1075
+ }
1076
+ cell += character;
1077
+ index += 1;
1078
+ }
1079
+ if (separators === 0) return null;
1080
+ cells.push(cell);
1081
+ if (cells[0].trim() === '') cells.shift();
1082
+ if (cells.at(-1)?.trim() === '') cells.pop();
1083
+ return cells.length > 0 ? cells : null;
1084
+ }
1085
+
1086
+ /** Locate table headers once for both counting and splitting. */
1087
+ function markdownTableStarts(text) {
1088
+ if (typeof text !== 'string' || !text) return [];
1089
+ const lines = text.split('\n');
1090
+ const offsets = [];
1091
+ let offset = 0;
1092
+ for (const line of lines) {
1093
+ offsets.push(offset);
1094
+ offset += line.length + 1;
1095
+ }
1096
+ const starts = [];
1097
+ let fence = null;
1098
+ for (let index = 0; index < lines.length; index += 1) {
1099
+ const line = lines[index].replace(/\r$/, '');
1100
+ if (fence) {
1101
+ const close = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(line);
1102
+ if (close && close[1][0] === fence[0] && close[1].length >= fence.length) fence = null;
1103
+ continue;
1104
+ }
1105
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
1106
+ if (opening && (opening[1][0] !== '`' || !opening[2].includes('`'))) {
1107
+ fence = opening[1];
1108
+ continue;
1109
+ }
1110
+ const header = gfmTableCells(line);
1111
+ const delimiter = gfmTableCells(lines[index + 1] ?? '');
1112
+ if (!header || !delimiter || header.length !== delimiter.length
1113
+ || !delimiter.every((cell) => /^\s*:?-+:?\s*$/.test(cell))) continue;
1114
+ starts.push(offsets[index]);
1115
+ index += 1;
1116
+ // A delimiter-looking data row is part of this table, not another header.
1117
+ while (index + 1 < lines.length && gfmTableCells(lines[index + 1])) index += 1;
1118
+ }
1119
+ return starts;
1120
+ }
1121
+
1122
+ export function countMarkdownTables(text) {
1123
+ return markdownTableStarts(text).length;
1124
+ }
1125
+
1126
+ function splitMarkdownByTableLimit(text, maxTables) {
1127
+ const starts = markdownTableStarts(text);
1128
+ const parts = [];
1129
+ let from = 0;
1130
+ for (let index = maxTables; index < starts.length; index += maxTables) {
1131
+ parts.push(text.slice(from, starts[index]));
1132
+ from = starts[index];
1133
+ }
1134
+ parts.push(text.slice(from));
1135
+ return parts;
1136
+ }
1137
+
1138
+ /** Count the Markdown that stepStreamCard actually renders. */
1139
+ function stepStreamCardTableCount(blocks) {
1140
+ return blocks.reduce((sum, block) => {
1141
+ const text = block?.kind === 'notes' || block?.kind === 'tools'
1142
+ ? (block.lines ?? []).filter((line) => typeof line === 'string' && line.trim()).join('\n')
1143
+ : block?.text;
1144
+ return sum + countMarkdownTables(text);
1145
+ }, 0);
1146
+ }
1147
+
1148
+ /** Split display copies; the bridge's logical blocks and answer indices stay intact. */
1149
+ export function splitBlockByTableLimit(block, maxTables = STEP_STREAM_CARD_MAX_TABLES) {
1150
+ if (!block || typeof block !== 'object' || !Number.isInteger(maxTables) || maxTables < 1) return [block];
1151
+ if (block.kind === 'notes' || block.kind === 'tools') {
1152
+ const lines = (block.lines ?? []).filter((line) => typeof line === 'string' && line.trim());
1153
+ if (countMarkdownTables(lines.join('\n')) <= maxTables) return [block];
1154
+ const groups = [];
1155
+ let current = [];
1156
+ for (const line of lines) {
1157
+ for (const part of splitMarkdownByTableLimit(line, maxTables)) {
1158
+ if (current.length && countMarkdownTables([...current, part].join('\n')) > maxTables) {
1159
+ groups.push(current);
1160
+ current = [];
1161
+ }
1162
+ current.push(part);
1163
+ }
1164
+ }
1165
+ if (current.length) groups.push(current);
1166
+ return groups.map((lines, index) => ({ ...block, lines, omitted: index === 0 ? block.omitted : 0 }));
1167
+ }
1168
+ if (typeof block.text !== 'string' || countMarkdownTables(block.text) <= maxTables) return [block];
1169
+ return splitMarkdownByTableLimit(block.text, maxTables).map((text) => ({ ...block, text }));
1170
+ }
1171
+
1172
+ /**
1173
+ * Split accumulated blocks into card-sized chunks at block boundaries,
1174
+ * budgeted by the encoded running-status card (the largest render) **and** by
1175
+ * the table count, because a card accepts only a handful of tables no matter
1176
+ * how small it is. Every chunk keeps at least one block so progress is never
1177
+ * dropped. The caller renders all but the last chunk as `sealed` and the last
1178
+ * one live.
1179
+ */
1180
+ export function splitStepStreamCardBlocks(
1181
+ blocks,
1182
+ limit = STEP_STREAM_CARD_MAX_BYTES,
1183
+ maxTables = STEP_STREAM_CARD_MAX_TABLES,
1184
+ ) {
1185
+ // A single block can carry more tables than a card accepts — one short answer
1186
+ // with six small tables — and splitting only between blocks cannot help. Each
1187
+ // block is broken at table boundaries first, so the walk below sees pieces it
1188
+ // can actually distribute.
1189
+ const list = (Array.isArray(blocks) ? blocks : [])
1190
+ .filter(Boolean)
1191
+ .flatMap((block) => splitBlockByTableLimit(block, maxTables));
1192
+ if (list.length === 0) return [];
1193
+ const chunks = [];
1194
+ let current = [];
1195
+ for (const block of list) {
1196
+ const tooLarge = Buffer.byteLength(stepStreamCard([...current, block]), 'utf8') > limit;
1197
+ const tooManyTables = stepStreamCardTableCount([...current, block]) > maxTables;
1198
+ if (current.length > 0 && (tooLarge || tooManyTables)) {
1199
+ chunks.push(current);
1200
+ current = [block];
1201
+ } else {
1202
+ current.push(block);
1203
+ }
1204
+ }
1205
+ if (current.length > 0) chunks.push(current);
1206
+ return chunks;
1207
+ }
1208
+
1209
+ /**
1210
+ * Interactive question card. When the question carries options, each option is
1211
+ * rendered as its own button; the selected option label is submitted via a
1212
+ * card callback. Multi-select questions fall back to the plain-text flow (the
1213
+ * caller decides), because a multi-select needs a confirm step.
1214
+ * A resolvedText replaces the buttons when an image ends the question flow.
1215
+ * Action: answer:<interactionId>:<optionLabel>
1216
+ */
1217
+ export function questionCard({ interactionId, header, question, detail, options, index, total, resolvedText }) {
1218
+ const elements = [];
1219
+ const progress = total > 1 ? `(${index + 1}/${total})` : '';
1220
+ if (header) elements.push({ tag: 'div', text: markdown(String(header)) });
1221
+ const qText = typeof question === 'string' && question.trim() ? question : t('请输入你的回答。');
1222
+ elements.push({ tag: 'div', text: markdown(String(qText)) });
1223
+ if (detail) elements.push({ tag: 'div', text: markdown(String(detail)) });
1224
+
1225
+ if (resolvedText) {
1226
+ elements.push({ tag: 'hr' }, { tag: 'div', text: markdown(resolvedText) });
1227
+ return cardWith(t('⏹ 提问已结束{progress}', { progress }), elements);
1228
+ }
1229
+
1230
+ if (Array.isArray(options) && options.length > 0) {
1231
+ elements.push({ tag: 'hr' });
1232
+ for (const option of options) {
1233
+ const label = typeof option?.label === 'string' ? option.label : '';
1234
+ if (!label) continue;
1235
+ const description = typeof option?.description === 'string' && option.description.trim()
1236
+ ? option.description.trim()
1237
+ : '';
1238
+ // Include the option description in the button so the user sees the full
1239
+ // meaning (mirrors the text form "1. label — description").
1240
+ const buttonText = description ? `${label}\n${description}` : label;
1241
+ // Action carries the question index so a stale card from a previous
1242
+ // question cannot be applied to the current one: answer:<interactionId>:<index>:<label>
1243
+ elements.push(button(buttonText, `answer:${interactionId}:${index}:${label}`));
1244
+ }
1245
+ // issue #162:自定义答案入口与 menuCard/steerCard 的「✏️ 更多 / 自定义…」
1246
+ // 对齐——文字流本就支持 custom 答案,卡片补上引导入口。
1247
+ elements.push(button(t('✏️ 其他答案…'), `answerCustom:${interactionId}:${index}`));
1248
+ }
1249
+ return cardWith(t('❓ 请补充信息{progress}', { progress }), elements);
1250
+ }
1251
+
1252
+ /**
1253
+ * issue #162:提问卡被回答后的已答状态卡——原卡整卡替换为该回执样式:
1254
+ * 保留问题与选项文本、标注已选项、不渲染任何按钮(重复点击从根源消失)。
1255
+ * 与 questionCard 一样返回 JSON 字符串,调用方直接作为卡 content 使用。
1256
+ */
1257
+ export function answeredQuestionCard({ interactionId, header, question, detail, options, chosen, index, total }) {
1258
+ const elements = [];
1259
+ const progress = total > 1 ? `(${index + 1}/${total})` : '';
1260
+ if (header) elements.push({ tag: 'div', text: markdown(String(header)) });
1261
+ const qText = typeof question === 'string' && question.trim() ? question : t('请输入你的回答。');
1262
+ elements.push({ tag: 'div', text: markdown(String(qText)) });
1263
+ if (detail) elements.push({ tag: 'div', text: markdown(String(detail)) });
1264
+ if (Array.isArray(options) && options.length > 0) {
1265
+ elements.push({ tag: 'hr' });
1266
+ let chosenShown = false;
1267
+ for (const option of options) {
1268
+ const label = typeof option?.label === 'string' ? option.label : '';
1269
+ if (!label) continue;
1270
+ if (label === chosen) chosenShown = true;
1271
+ elements.push({ tag: 'div', text: markdown(label === chosen
1272
+ ? t('✅ 已选择:{label}', { label })
1273
+ : label) });
1274
+ }
1275
+ // 自定义文本答案不在预设选项里——单独一行展示所选内容。
1276
+ if (!chosenShown && typeof chosen === 'string' && chosen.trim()) {
1277
+ elements.push({ tag: 'div', text: markdown(t('✅ 已选择:{label}', { label: chosen })) });
1278
+ }
1279
+ } else if (typeof chosen === 'string' && chosen.trim()) {
1280
+ elements.push({ tag: 'div', text: markdown(t('✅ 已选择:{label}', { label: chosen })) });
1281
+ }
1282
+ elements.push({ tag: 'hr' });
1283
+ elements.push({ tag: 'div', text: markdown(t('回答已提交,对话将继续。')) });
1284
+ return cardWith(t('✅ 已回答{progress}', { progress }), elements);
1285
+ }