@yuriai/web 0.2.27-beta.8 → 0.2.27

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 (196) hide show
  1. package/dist/assets/{AgentAvatar-BJ42lGZD.js → AgentAvatar-DNm_jMna.js} +1 -1
  2. package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
  3. package/dist/assets/{AssistantUnreadBadge-QwhBfXpC.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
  4. package/dist/assets/{AssistantView-D7ryIKL0.js → AssistantView-CxQv-9Ms.js} +1 -1
  5. package/dist/assets/{DiagramView-ERrGEBDp.js → DiagramView-DPpG0fwx.js} +1 -1
  6. package/dist/assets/{FadeInOnReveal-Bu2GvaM9.js → FadeInOnReveal-S6UbimjB.js} +1 -1
  7. package/dist/assets/{GuiPluginSurface-MzQgEZNr.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
  8. package/dist/assets/{GuiPluginWindow-DZMmlQzx.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
  9. package/dist/assets/{Icon-Dj4CCqCP.js → Icon-BE4mEwzV.js} +1 -1
  10. package/dist/assets/{ImageLoadingPlaceholder-BnFXgUuO.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
  11. package/dist/assets/{LoadingImage-PBnivDKv.js → LoadingImage-NLq7_P-i.js} +1 -1
  12. package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
  13. package/dist/assets/{MarkdownRendererImpl-CfyXL4rg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
  14. package/dist/assets/{MarkstreamRendererImpl-BGadklK1.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
  15. package/dist/assets/{MobileDetailNavigation-DqajQdB4.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
  16. package/dist/assets/{MobileResizableSheet-BvdUgwA3.js → MobileResizableSheet-Deidw1br.js} +1 -1
  17. package/dist/assets/{MobileShareBridge-3oPoYnry.js → MobileShareBridge-CO_OWEfq.js} +2 -2
  18. package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
  19. package/dist/assets/{MultiRunWindow-yhs0Ih5_.js → MultiRunWindow-DtVW9NTV.js} +1 -1
  20. package/dist/assets/{OnboardingScreen-Bi1VWFQC.js → OnboardingScreen-C8ld4wO7.js} +1 -1
  21. package/dist/assets/{OverlayScrollbar-BBDwGvGO.js → OverlayScrollbar-B3auC2WH.js} +1 -1
  22. package/dist/assets/{SettingsView-BSf-SJUA.js → SettingsView-Cm7woZWl.js} +14 -14
  23. package/dist/assets/{SettingsWindow-BvSXVMTm.js → SettingsWindow-CdL4PFxW.js} +1 -1
  24. package/dist/assets/{TerminalView-DhL01N7e.js → TerminalView-CwRB6Yyr.js} +1 -1
  25. package/dist/assets/{ToolOutputDialog-C8lnH4Ky.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
  26. package/dist/assets/{YuriLogo-D8asj1CS.js → YuriLogo-BOx0s0Ue.js} +1 -1
  27. package/dist/assets/{appThemeRegistry-C-maYSdv.js → appThemeRegistry-B6woJIX5.js} +1 -1
  28. package/dist/assets/{button-vXOdzd8x.js → button-BXxwtxsG.js} +1 -1
  29. package/dist/assets/{capgoAdapter-DJ_h2x5D.js → capgoAdapter-C5HFS-rx.js} +1 -1
  30. package/dist/assets/{collapsible-DwDQs3Wa.js → collapsible-BEm0787p.js} +1 -1
  31. package/dist/assets/{context-menu-BabBujQ-.js → context-menu-DUwvVUDY.js} +1 -1
  32. package/dist/assets/device-BcRP6Tjd.js +2 -0
  33. package/dist/assets/{diagram-HwgrQxY5.js → diagram-DyY8dxjZ.js} +1 -1
  34. package/dist/assets/{dialog-Dnf626tb.js → dialog-CLca6ojn.js} +1 -1
  35. package/dist/assets/{dropdown-menu.styles-CBc_a-Nv.js → dropdown-menu.styles-DGaALKP0.js} +1 -1
  36. package/dist/assets/{es-BQkO-Odr.js → es-CrsHvgue.js} +2 -2
  37. package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
  38. package/dist/assets/{fileMentionTouchSelection-CKPnEetl.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
  39. package/dist/assets/{fileReferenceActions-g7KZLi_G.js → fileReferenceActions-CrIAce3K.js} +1 -1
  40. package/dist/assets/{fr-C852roK5.js → fr-CEgiRlfa.js} +2 -2
  41. package/dist/assets/{gitApi-CVq5oKCd.js → gitApi-D2G9ny2O.js} +1 -1
  42. package/dist/assets/{gitApiHttp-BYOIbYIh.js → gitApiHttp-B7vYwgBh.js} +4 -4
  43. package/dist/assets/{gui-M_Rbwkyu.js → gui-CJjEj3l4.js} +1 -1
  44. package/dist/assets/host-CnVx34Dh.js +1 -0
  45. package/dist/assets/{input-BtM712b1.js → input-D59Q2pm8.js} +1 -1
  46. package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
  47. package/dist/assets/{ja-BqC39qK6.js → ja-CX-_p9jZ.js} +2 -2
  48. package/dist/assets/{ko-BMaChAWh.js → ko-D5xlLYJM.js} +2 -2
  49. package/dist/assets/main-CxpUooVS.js +2 -0
  50. package/dist/assets/{main-Mey7bCWf.js → main-Dpm4KxWX.js} +12 -12
  51. package/dist/assets/{markdownHeightCache-Bf8iisO4.js → markdownHeightCache-D2VWb_4E.js} +1 -1
  52. package/dist/assets/{mcpQueries-DpXqegX5.js → mcpQueries-DQ3KthDF.js} +1 -1
  53. package/dist/assets/miniChat-CTdj8Ug9.js +2 -0
  54. package/dist/assets/mobile-ChbA3Q8j.js +2 -0
  55. package/dist/assets/{mobileBackNavigation-DZcI7aZg.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
  56. package/dist/assets/{multirun-hzspPepd.js → multirun-BILeETbd.js} +1 -1
  57. package/dist/assets/{native-H7K64Ulc.js → native-BYMhr-xH.js} +1 -1
  58. package/dist/assets/{native-config-CddZtLQ1.js → native-config-BIY0Cr-l.js} +1 -1
  59. package/dist/assets/{persistence-BT8045Ue.js → persistence-CWuLIq1J.js} +2 -2
  60. package/dist/assets/{pl-Ubs8p28T.js → pl-BjH81A_q.js} +2 -2
  61. package/dist/assets/{projectMeta-CEf0QPmD.js → projectMeta-B9_Uh8YH.js} +1 -1
  62. package/dist/assets/{pt-BR-8rAOjJrs.js → pt-BR-Dp5oK2x3.js} +2 -2
  63. package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
  64. package/dist/assets/{readiness-Dyr7314z.js → readiness-BNIgH81X.js} +1 -1
  65. package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
  66. package/dist/assets/renderMobileApp-DAfque7-.js +28 -0
  67. package/dist/assets/{runtimeConfig-B8VHHNxj.js → runtimeConfig-BX8JirIc.js} +1 -1
  68. package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
  69. package/dist/assets/{scheduledTaskNavigation-Zm87Nydi.js → scheduledTaskNavigation-EomDNVu2.js} +1 -1
  70. package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
  71. package/dist/assets/{sortable-tabs-strip-D4pVoodN.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
  72. package/dist/assets/{speechSettingsQueries-RlCLMBtr.js → speechSettingsQueries-CC0fusUo.js} +2 -2
  73. package/dist/assets/src-BMKjN2ip.css +2 -0
  74. package/dist/assets/{store-ME7oHni1.js → store-CkIHVrmT.js} +4 -3
  75. package/dist/assets/{terminalApi-BSaclMDJ.js → terminalApi-rl9mZAlB.js} +1 -1
  76. package/dist/assets/{textarea-B98rsLs7.js → textarea-7eTptEtD.js} +1 -1
  77. package/dist/assets/{tooltip-B9810jbK.js → tooltip-BPwoSTzO.js} +1 -1
  78. package/dist/assets/types-CUtSV1V8.js +2 -0
  79. package/dist/assets/{uk-LzwzUApL.js → uk-BEfkaLtM.js} +2 -2
  80. package/dist/assets/{useAppFontEffects-D2C1sBYM.js → useAppFontEffects-Ck2PdQRx.js} +37 -37
  81. package/dist/assets/{useAssistantUIStore-TUN_ycy5.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
  82. package/dist/assets/useDesktopWindowControlsLayout-DxxOUZj1.js +1 -0
  83. package/dist/assets/useEffectiveDirectory-CNCQfN_x.js +1 -0
  84. package/dist/assets/{useFontPreferences-BlhlCJCX.js → useFontPreferences-DeqW9nRx.js} +1 -1
  85. package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
  86. package/dist/assets/{useUIStore-DRx6OgCp.js → useUIStore-C6CE42oh.js} +1 -1
  87. package/dist/assets/{useWorkerHighlightedLines-D093jNsH.js → useWorkerHighlightedLines-CN_RGaSw.js} +1 -1
  88. package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
  89. package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
  90. package/dist/assets/{vendor-opencode-plugin-BBOP6WNx.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
  91. package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
  92. package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
  93. package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
  94. package/dist/assets/{zh-CN-D-FVCeks.js → zh-CN-DipfA56P.js} +2 -2
  95. package/dist/assets/{zh-TW-B9iH_NXL.js → zh-TW-B7pXMVjt.js} +2 -2
  96. package/dist/index.html +12 -12
  97. package/dist/mini-chat.html +12 -12
  98. package/dist/mobile.html +12 -12
  99. package/package.json +1 -1
  100. package/server/index.js +2 -145
  101. package/server/lib/assistants/DOCUMENTATION.md +56 -10
  102. package/server/lib/assistants/cards.js +1 -1
  103. package/server/lib/assistants/channel-image.js +92 -0
  104. package/server/lib/assistants/channel-image.test.js +76 -0
  105. package/server/lib/assistants/channel-output-store.test.js +41 -0
  106. package/server/lib/assistants/channel-output.integration.test.js +114 -0
  107. package/server/lib/assistants/channel-output.js +90 -0
  108. package/server/lib/assistants/channel-output.test.js +79 -0
  109. package/server/lib/assistants/channels/DOCUMENTATION.md +52 -14
  110. package/server/lib/assistants/channels/PROTOCOLS.md +23 -1
  111. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +19 -7
  112. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +8 -0
  113. package/server/lib/assistants/channels/routes.js +12 -0
  114. package/server/lib/assistants/channels/routes.test.js +34 -0
  115. package/server/lib/assistants/channels/runtime.js +117 -26
  116. package/server/lib/assistants/channels/runtime.test.js +179 -5
  117. package/server/lib/assistants/channels/sdk-adapters.js +15 -3
  118. package/server/lib/assistants/channels/sdk-adapters.test.js +17 -0
  119. package/server/lib/assistants/channels/store.js +9 -6
  120. package/server/lib/assistants/channels/store.test.js +21 -11
  121. package/server/lib/assistants/channels/transport.js +2 -1
  122. package/server/lib/assistants/channels/wecom-chat-adapter.js +16 -2
  123. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +21 -0
  124. package/server/lib/assistants/contact-store.js +9 -3
  125. package/server/lib/assistants/contact-store.test.js +27 -0
  126. package/server/lib/assistants/contact-tools.js +65 -75
  127. package/server/lib/assistants/contact-tools.test.js +114 -22
  128. package/server/lib/assistants/harness.js +79 -34
  129. package/server/lib/assistants/harness.test.js +52 -20
  130. package/server/lib/assistants/resource-reference.integration.test.js +284 -0
  131. package/server/lib/assistants/routes.js +0 -3
  132. package/server/lib/assistants/service.js +116 -69
  133. package/server/lib/assistants/service.test.js +31 -17
  134. package/server/lib/assistants/weixin/DOCUMENTATION.md +34 -9
  135. package/server/lib/assistants/weixin/api.js +43 -1
  136. package/server/lib/assistants/weixin/api.test.js +28 -0
  137. package/server/lib/assistants/weixin/chat-adapter.js +8 -2
  138. package/server/lib/assistants/weixin/inbound.js +5 -3
  139. package/server/lib/assistants/weixin/inbound.test.js +20 -0
  140. package/server/lib/assistants/weixin/runtime.js +27 -18
  141. package/server/lib/assistants/weixin/runtime.test.js +36 -0
  142. package/server/lib/assistants/weixin/store.js +8 -4
  143. package/server/lib/assistants/weixin/store.test.js +21 -0
  144. package/server/lib/assistants/yuri-project.http.test.js +9 -3
  145. package/server/lib/notifications/DOCUMENTATION.md +6 -0
  146. package/server/lib/notifications/runtime.js +26 -15
  147. package/server/lib/notifications/runtime.test.js +14 -13
  148. package/server/lib/opencode/DOCUMENTATION.md +9 -0
  149. package/server/lib/opencode/auth.d.ts +6 -2
  150. package/server/lib/opencode/core-routes.js +0 -1
  151. package/server/lib/opencode/feature-routes-runtime.js +0 -24
  152. package/server/lib/opencode/location-release.d.ts +5 -1
  153. package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
  154. package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
  155. package/server/lib/opencode/native-goal.js +15 -0
  156. package/server/lib/opencode/native-goal.test.js +17 -0
  157. package/server/lib/opencode/settings-helpers.js +0 -6
  158. package/server/lib/opencode/shutdown-runtime.js +0 -2
  159. package/server/lib/projects/project-config.js +3 -6
  160. package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
  161. package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
  162. package/server/lib/scheduled-tasks/routes.js +0 -26
  163. package/server/lib/scheduled-tasks/runtime.js +33 -257
  164. package/server/lib/scheduled-tasks/runtime.test.js +24 -65
  165. package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
  166. package/server/lib/session-metadata/routes.js +4 -38
  167. package/server/lib/session-metadata/routes.test.js +2 -2
  168. package/dist/assets/AssistantContactStatus-dtkObamV.js +0 -3
  169. package/dist/assets/MarkdownRenderer-BajF4gUU.js +0 -2
  170. package/dist/assets/MobileTabPageHeader-B6cRyIRH.js +0 -2
  171. package/dist/assets/device-BjRYYXNT.js +0 -2
  172. package/dist/assets/host-BW3FEJdU.js +0 -1
  173. package/dist/assets/insertionBoundaries-Dx3WAY6i.js +0 -1
  174. package/dist/assets/main-9uP2z1qT.js +0 -2
  175. package/dist/assets/miniChat-DqZvVkme.js +0 -2
  176. package/dist/assets/mobile-DXAWjYcN.js +0 -2
  177. package/dist/assets/renderElectronMiniChatApp-DoOq8Cuo.js +0 -2
  178. package/dist/assets/renderMobileApp-TTxtOb8b.js +0 -28
  179. package/dist/assets/runtimeEndpointReset-BC6XWntz.js +0 -149
  180. package/dist/assets/sessionLookup-De53jDwM.js +0 -1
  181. package/dist/assets/src-lE4uqaHS.css +0 -2
  182. package/dist/assets/types-DFf9vd1b.js +0 -2
  183. package/dist/assets/useDesktopWindowControlsLayout-BjKaHN0x.js +0 -1
  184. package/dist/assets/useEffectiveDirectory-TEvyiQSC.js +0 -1
  185. package/dist/assets/useMobileNavigationStore-DTvJV9s-.js +0 -23
  186. package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +0 -23
  187. package/dist/assets/vendor-solid-js-9wmPZH9g.js +0 -1
  188. package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
  189. package/server/lib/session-goal/DOCUMENTATION.md +0 -371
  190. package/server/lib/session-goal/capability.js +0 -57
  191. package/server/lib/session-goal/capability.test.js +0 -33
  192. package/server/lib/session-goal/objectives.js +0 -61
  193. package/server/lib/session-goal/routes.js +0 -274
  194. package/server/lib/session-goal/routes.test.js +0 -211
  195. package/server/lib/session-goal/runtime.js +0 -2452
  196. package/server/lib/session-goal/runtime.test.js +0 -2125
@@ -22,7 +22,7 @@ runtime resolution fallback.
22
22
 
23
23
  `transport.js` remains the owner of the small HTTP helpers
24
24
  (`channelError`, `requestJSON`, `officialURL`). Channel adapters use
25
- `requestJSON` for the two documented outbound REST calls and do **not** use the
25
+ `requestJSON` for documented outbound REST calls (JSON or multipart) and do **not** use the
26
26
  removed `socketLoop`; no adapter opens a raw WebSocket or decodes protobuf.
27
27
 
28
28
  ## Feishu
@@ -50,6 +50,12 @@ Wire evidence: `@larksuite/channel@0.7.1` and
50
50
  short row IDs verbatim and hashes longer ones to 40 hex characters.
51
51
  `tenant_access_token/internal` uses `{app_id, app_secret}` and caches until
52
52
  `expire - 180s`.
53
+ - Image output first uploads multipart `image_type=message` and `image` to
54
+ `POST /open-apis/im/v1/images`, then sends `msg_type: image` with
55
+ `content: {"image_key": ...}` and the same durable UUID policy. The app needs
56
+ `im:resource` or `im:resource:upload` in addition to message-send permission.
57
+ Upload failure never counts as a submitted chat message.
58
+ Reference: https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/image/create
53
59
 
54
60
  ACK durability: the Chat adapter's normalized `message` path is not awaited by
55
61
  the vendor dispatcher, so it cannot gate the ACK. `sdk-adapters.js` therefore
@@ -115,6 +121,11 @@ Wire evidence: official `https://github.com/WecomTeam/aibot-node-sdk`,
115
121
  outbox as sent (platform accepted, not proof the user read it). Nonzero ACKs are
116
122
  definite failures; timeout, cancellation or disconnection after submission are
117
123
  `delivery_unknown` and are never automatically resent.
124
+ - Native images use public `uploadMedia(buffer, {type:'image', filename})` and
125
+ `sendMediaMessage(chatid, 'image', media_id)` from the installed official SDK.
126
+ The SDK owns init/chunk/finish and the final message ACK; Yuri does not write
127
+ its own chunk framing. Local-WebSocket tests exercise the full SDK upload plus
128
+ final-ACK wait. Real-account acceptance/quotas still require platform testing.
118
129
  - A configured owner fixes the private recipient; otherwise the runtime's private
119
130
  durable `target.userID` supplies it. Missing recipients fail before sending.
120
131
  - Incoming messages preserve `msgid` for durable dedup, use standard Chat `Message`
@@ -129,6 +140,17 @@ Wire evidence: official `https://github.com/WecomTeam/aibot-node-sdk`,
129
140
 
130
141
  ## DingTalk
131
142
 
143
+ Image output uploads multipart `type=image`/`media` to the official legacy
144
+ `https://oapi.dingtalk.com/media/upload` endpoint, then uses the existing private
145
+ batch-send API with `msgKey: sampleImageMsg` and `msgParam: {photoURL: media_id}`.
146
+ The legacy upload API requires the access token in its query; it is ephemeral,
147
+ never persisted/logged or included in a transcript/error. Generated local images
148
+ need no publicly hosted URL. Platform size/format/permission failures remain
149
+ explicit delivery failures rather than a false text-only success. No automatic
150
+ lossy resize, new image dependency or public image-hosting service is introduced.
151
+ References: https://developers.dingtalk.com/document/app/upload-media-files and
152
+ https://open.dingtalk.com/document/orgapp/types-of-messages-sent-by-robots
153
+
132
154
  Wire evidence: `dingtalk-stream@2.1.5` `dist/client.mjs` and
133
155
  `src/client.ts` of `open-dingtalk/dingtalk-stream-sdk-nodejs`; OpenAPI metadata
134
156
  from `@alicloud/dingtalk@2.2.48` (`robot_1_0`, `oauth2_1_0`).
@@ -423,11 +423,11 @@ export class DingTalkChatAdapter {
423
423
  }
424
424
  }
425
425
 
426
- async send({ config, target, text, signal } = {}) {
426
+ async send({ config, target, text, image, signal, beforeSend } = {}) {
427
427
  const credentials = credentialsFrom(config);
428
428
  const userId = config.ownerID || target?.userID;
429
429
  if (!nonEmptyString(userId)) throw channelError('invalid_response');
430
- await this._sendText({ credentials, userId, text: typeof text === 'string' ? text : '', signal });
430
+ await this._sendText({ credentials, userId, text: typeof text === 'string' ? text : '', image, signal, beforeSend });
431
431
  }
432
432
 
433
433
  // ── internals ──────────────────────────────────────────────────────────
@@ -565,14 +565,26 @@ export class DingTalkChatAdapter {
565
565
  return json.accessToken;
566
566
  }
567
567
 
568
- async _sendText({ credentials, userId, text, signal } = {}) {
568
+ async _sendText({ credentials, userId, text, image, signal, beforeSend } = {}) {
569
569
  const token = await this._accessToken(credentials, { signal });
570
+ let mediaID;
571
+ if (image) {
572
+ const form = new FormData();
573
+ form.set('type', 'image');
574
+ form.set('media', new Blob([image.buffer], { type: image.mime }), image.filename);
575
+ const uploaded = await requestJSON(`https://oapi.dingtalk.com/media/upload?${new URLSearchParams({ access_token: token, type: 'image' })}`, {
576
+ body: form, signal, fetchImpl: this.fetchImpl,
577
+ });
578
+ if (uploaded?.errcode !== 0 || !nonEmptyString(uploaded?.media_id)) throw channelError('delivery_failed');
579
+ mediaID = uploaded.media_id;
580
+ }
581
+ beforeSend?.();
570
582
  const json = await requestJSON(`${DINGTALK_ORIGIN}${BATCH_SEND_PATH}`, {
571
583
  body: {
572
584
  robotCode: credentials.clientId,
573
585
  userIds: [userId],
574
- msgKey: 'sampleText',
575
- msgParam: JSON.stringify({ content: text }),
586
+ msgKey: image ? 'sampleImageMsg' : 'sampleText',
587
+ msgParam: JSON.stringify(image ? { photoURL: mediaID } : { content: text }),
576
588
  },
577
589
  headers: { 'x-acs-dingtalk-access-token': token },
578
590
  signal,
@@ -618,7 +630,7 @@ export function createDingtalkSdkAdapter(options = {}) {
618
630
  }
619
631
  },
620
632
 
621
- async send({ config, target, text, signal } = {}) {
633
+ async send({ config, target, text, image, signal, beforeSend } = {}) {
622
634
  if (!config) throw channelError('invalid_response');
623
635
  const adapter = new DingTalkChatAdapter({
624
636
  ...options,
@@ -627,7 +639,7 @@ export function createDingtalkSdkAdapter(options = {}) {
627
639
  ownerId: config.ownerID,
628
640
  tokenCache: tokens,
629
641
  });
630
- await adapter.send({ config, target, text, signal });
642
+ await adapter.send({ config, target, text, image, signal, beforeSend });
631
643
  },
632
644
  };
633
645
  }
@@ -92,6 +92,14 @@ afterEach(() => {
92
92
  });
93
93
 
94
94
  describe('dingtalk Chat SDK adapter', () => {
95
+ it('uploads local image bytes and sends sampleImageMsg only to the original private user', async () => {
96
+ const fetchImpl = vi.fn(async (url) => Response.json(String(url).includes('accessToken') ? { accessToken: 'token', expireIn: 7200 }
97
+ : String(url).includes('/media/upload') ? { errcode: 0, media_id: '@uploaded' } : {}));
98
+ const bridge = createDingtalkSdkAdapter({ fetchImpl });
99
+ await bridge.send({ config, image: { buffer: Buffer.from('image'), mime: 'image/png', filename: 'image.png' } });
100
+ expect(fetchImpl.mock.calls[1][1].body).toBeInstanceOf(FormData);
101
+ expect(JSON.parse(fetchImpl.mock.calls[2][1].body)).toEqual({ robotCode: config.clientID, userIds: [config.ownerID], msgKey: 'sampleImageMsg', msgParam: JSON.stringify({ photoURL: '@uploaded' }) });
102
+ });
95
103
  it('accepts platform-scoped private senders without a binding and replies to the persisted user', async () => {
96
104
  const h = harness();
97
105
  const controller = new AbortController();
@@ -17,6 +17,8 @@ const SAFE_ERRORS = new Set([
17
17
  'cancelled',
18
18
  'binding_changed',
19
19
  'connection_replaced',
20
+ 'owner_required',
21
+ 'discovery_timeout',
20
22
  ]);
21
23
 
22
24
  const failureStatus = (code) => code === 'channel_disabled' ? 403
@@ -43,5 +45,15 @@ export function registerAssistantChannelRoutes(app, runtime) {
43
45
  app.put(root, (req, res) => respond(res, () => runtime.save(req.params.assistantID, req.params.provider, req.body)));
44
46
  app.post(`${root}/retry`, (req, res) => respond(res, () => runtime.retry(req.params.assistantID, req.params.provider)));
45
47
  app.post(`${root}/transfer`, (req, res) => respond(res, () => runtime.transfer(req.params.assistantID, req.params.provider, req.body)));
48
+ app.post(`${root}/discover`, (req, res) => {
49
+ const controller = new AbortController();
50
+ const cancel = () => controller.abort();
51
+ res.once('close', cancel);
52
+ respond(res, async () => {
53
+ try {
54
+ return await runtime.discover(req.params.assistantID, req.params.provider, req.body, { signal: controller.signal });
55
+ } finally { res.off('close', cancel); }
56
+ });
57
+ });
46
58
  app.delete(root, (req, res) => respond(res, () => runtime.disconnect(req.params.assistantID, req.params.provider)));
47
59
  }
@@ -20,6 +20,7 @@ describe('authenticated enterprise channel routes', () => {
20
20
  await request(app).put(root).send({}).expect(403, { error: 'channel_disabled' });
21
21
  await request(app).post(`${root}/retry`).send({}).expect(403, { error: 'channel_disabled' });
22
22
  await request(app).post(`${root}/transfer`).send({}).expect(403, { error: 'channel_disabled' });
23
+ await request(app).post(`${root}/discover`).send({}).expect(403, { error: 'channel_disabled' });
23
24
  await request(app).delete(root).expect(403, { error: 'channel_disabled' });
24
25
  await runtime.close();
25
26
  });
@@ -41,6 +42,7 @@ describe('authenticated enterprise channel routes', () => {
41
42
  })),
42
43
  retry: vi.fn(async () => ({ provider: 'feishu', status: 'reconnecting', error: null })),
43
44
  transfer: vi.fn(async () => ({ provider: 'feishu', status: 'connecting', error: null })),
45
+ discover: vi.fn(async () => ({ ownerID: 'ou_user' })),
44
46
  disconnect: vi.fn(async () => ({ provider: 'feishu', status: 'disconnected', error: null })),
45
47
  };
46
48
  registerAssistantChannelRoutes(app, runtime);
@@ -61,6 +63,11 @@ describe('authenticated enterprise channel routes', () => {
61
63
  await request(app).post(`${root}/transfer`).auth('test-owner', { type: 'bearer' })
62
64
  .send({ sourceAssistantID: 'old', revision: 'r1' }).expect(200);
63
65
  expect(runtime.transfer).toHaveBeenCalledWith('bot', 'feishu', { sourceAssistantID: 'old', revision: 'r1' });
66
+ await request(app).post(`${root}/discover`).send({ clientID: 'client' }).expect(401);
67
+ expect(runtime.discover).not.toHaveBeenCalled();
68
+ await request(app).post(`${root}/discover`).auth('test-owner', { type: 'bearer' })
69
+ .send({ clientID: 'client', clientSecret: 'secret' }).expect('Cache-Control', 'no-store').expect(200, { ownerID: 'ou_user' });
70
+ expect(runtime.discover).toHaveBeenCalledWith('bot', 'feishu', { clientID: 'client', clientSecret: 'secret' }, { signal: expect.any(AbortSignal) });
64
71
  await request(app).delete(root).auth('test-owner', { type: 'bearer' }).expect(200);
65
72
  expect(runtime.disconnect).toHaveBeenCalledWith('bot', 'feishu');
66
73
  });
@@ -102,4 +109,31 @@ describe('authenticated enterprise channel routes', () => {
102
109
  await request(app).put(root).send({}).expect(409, { error: 'connection_replaced' });
103
110
  await request(app).post(`${root}/retry`).expect(409, { error: 'binding_changed' });
104
111
  });
112
+
113
+ it('aborts discovery when the HTTP caller closes the request', async () => {
114
+ const app = express();
115
+ app.use(express.json());
116
+ let signal;
117
+ registerAssistantChannelRoutes(app, {
118
+ discover: async (_assistantID, _provider, _body, options) => {
119
+ signal = options.signal;
120
+ return new Promise((_, reject) => signal.addEventListener('abort', () => reject(Object.assign(new Error('cancelled'), { code: 'cancelled' })), { once: true }));
121
+ },
122
+ });
123
+ const server = app.listen(0, '127.0.0.1');
124
+ try {
125
+ await new Promise((resolve) => server.once('listening', resolve));
126
+ const controller = new AbortController();
127
+ const pending = fetch(`http://127.0.0.1:${server.address().port}/api/yuri/assistants/bot/channels/wecom/discover`, {
128
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}', signal: controller.signal,
129
+ }).catch(() => {});
130
+ await vi.waitFor(() => expect(signal).toBeDefined());
131
+ controller.abort();
132
+ await pending;
133
+ await vi.waitFor(() => expect(signal.aborted).toBe(true));
134
+ } finally {
135
+ server.closeAllConnections();
136
+ await new Promise((resolve) => server.close(resolve));
137
+ }
138
+ });
105
139
  });
@@ -3,6 +3,7 @@ import { setTimeout as delay } from 'node:timers/promises';
3
3
  import { createAssistantChannelStore } from './store.js';
4
4
  import { encodeWeixinTOON } from '../weixin/toon.js';
5
5
  import { isMessageChannelTurn } from '../message-channel-origin.js';
6
+ import { prepareChannelOutput, readChannelDeliveryImage, channelImageFailure } from '../channel-output.js';
6
7
 
7
8
  const digest = (value) => createHash('sha256').update(value).digest('hex');
8
9
  const PROVIDER = /^[a-z][a-z0-9_]{1,31}$/;
@@ -10,7 +11,6 @@ const MAX_PLATFORM_ID = 256;
10
11
  const MAX_ACCOUNT_FIELD = 512;
11
12
  const MAX_SECRET = 4096;
12
13
  const MAX_TEXT = 20_000;
13
- const MAX_CHUNK = 3500;
14
14
  const MAX_TARGET_BYTES = 16_384;
15
15
  const BACKLOG_MAX = 100;
16
16
  const AUTH_ERRORS = new Set(['auth_failed', 'auth_expired']);
@@ -146,15 +146,6 @@ const parseTarget = (value) => {
146
146
  } catch { return undefined; }
147
147
  };
148
148
 
149
- const chunkText = (text) => {
150
- const chars = Array.from(text);
151
- const chunks = [];
152
- for (let index = 0; index < chars.length; index += MAX_CHUNK) {
153
- chunks.push(chars.slice(index, index + MAX_CHUNK).join(''));
154
- }
155
- return chunks;
156
- };
157
-
158
149
  /**
159
150
  * Generic Host-owned long-connection channel framework for WeCom, Feishu and
160
151
  * DingTalk. Platform wire behavior lives in injected adapters; this module owns
@@ -168,6 +159,7 @@ export function createAssistantChannelsRuntime({
168
159
  env = process.env,
169
160
  clock = Date.now,
170
161
  intervalMs = 2000,
162
+ discoveryTimeoutMs = 90_000,
171
163
  } = {}) {
172
164
  const configured = String(env.YURI_CHANNELS_ENABLED ?? '').trim().toLowerCase();
173
165
  const development = env.NODE_ENV === 'development'
@@ -191,7 +183,7 @@ export function createAssistantChannelsRuntime({
191
183
  hasSecret: false, transport: 'websocket',
192
184
  };
193
185
  },
194
- save: disabled, retry: disabled, disconnect: disabled, transfer: disabled,
186
+ save: disabled, retry: disabled, disconnect: disabled, transfer: disabled, discover: disabled,
195
187
  forget: async () => {}, onTurnEvent: () => {}, close: async () => {},
196
188
  };
197
189
  }
@@ -204,6 +196,8 @@ export function createAssistantChannelsRuntime({
204
196
  const operations = new Set();
205
197
  const recovered = new Set();
206
198
  const retiring = new Set();
199
+ const discoveries = new Map();
200
+ const pendingAccounts = new Set();
207
201
  const lifetime = new AbortController();
208
202
  let closed = false;
209
203
  let ownsLease = false;
@@ -438,25 +432,31 @@ export function createAssistantChannelsRuntime({
438
432
  }
439
433
  };
440
434
 
441
- const enqueuePage = (binding, page) => {
435
+ const enqueuePage = async (binding, page) => {
442
436
  if (!binding.owner_id && !binding.target) {
443
437
  store.collect(binding, page, [], clock());
444
438
  return;
445
439
  }
446
- const deliveries = page.messages.flatMap((message) => {
440
+ const deliveries = [];
441
+ const receiverSignal = receivers.get(channelKey(binding.assistant_id, binding.provider))?.controller.signal;
442
+ const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
443
+ const assertCurrent = () => {
444
+ if (!isCurrent(binding) || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== page.generation) throw new ChannelError('cancelled');
445
+ };
446
+ for (const message of page.messages) {
447
447
  const receipt = store.receipt(message.turnID, binding.epoch);
448
- if (isMessageChannelTurn(message.turnID) && !receipt) return [];
448
+ if (isMessageChannelTurn(message.turnID) && !receipt) continue;
449
449
  // A channel reply uses its own durable sender, not another later sender.
450
- if (receipt && !receipt.target && !binding.owner_id) return [];
451
- const text = message.status === 'error' ? feedback(binding.language, 'failed')
452
- : message.text?.trim() && !message.text.trim().startsWith('oc.settle.') ? message.text.trim()
453
- : message.cards.map((card) => card.title || card.name || '').filter(Boolean).join('\n');
454
- return chunkText(text).filter(Boolean).map((chunk, index) => ({
450
+ if (receipt && !receipt.target && !binding.owner_id) continue;
451
+ const output = await prepareChannelOutput(message, { service, assistantID: binding.assistant_id,
452
+ generation: page.generation, language: binding.language, failureText: feedback(binding.language, 'failed'), signal, assertCurrent });
453
+ deliveries.push(...output.map((part, index) => ({
455
454
  id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`,
456
- text: chunk,
455
+ ...part,
457
456
  ...(receipt ? { target: receipt.target || '' } : {}),
458
- }));
459
- });
457
+ })));
458
+ }
459
+ assertCurrent();
460
460
  store.collect(binding, page, deliveries, clock());
461
461
  };
462
462
 
@@ -475,9 +475,8 @@ export function createAssistantChannelsRuntime({
475
475
  if (!row || row.epoch !== binding.epoch || isSticky(row)) return;
476
476
  const delivery = store.nextDelivery(binding.epoch);
477
477
  if (!delivery) return;
478
- // Head-of-line ordering: unknown/blocked rows are never bypassed. retry
479
- // may re-queue a definitively failed row, but never an unknown one.
480
- if (delivery.state !== 'pending') return;
478
+ // Only pending output is eligible; failed/unknown rows stay durable without
479
+ // blocking later replies. Unknown sends are never automatically retried.
481
480
  if (!adapter) {
482
481
  store.patch(binding.epoch, { status: 'error', error: 'unsupported_provider', updated_at: clock() });
483
482
  return;
@@ -485,10 +484,18 @@ export function createAssistantChannelsRuntime({
485
484
  store.markDelivery(delivery.id, 'sending');
486
485
  const signal = AbortSignal.any([lifetime.signal, receiver.controller.signal]);
487
486
  try {
487
+ const image = await readChannelDeliveryImage(service, binding.assistant_id, delivery.image ? JSON.parse(delivery.image) : null, signal);
488
+ if (!isCurrent(binding) || signal.aborted
489
+ || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== row.generation) throw new ChannelError('cancelled');
488
490
  await adapter.send({
489
491
  config: configOf(row),
490
492
  target: parseTarget(delivery.target),
491
493
  text: delivery.text,
494
+ ...(image ? { image } : {}),
495
+ beforeSend: () => {
496
+ signal.throwIfAborted();
497
+ if (!isCurrent(binding) || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== row.generation) throw new ChannelError('cancelled');
498
+ },
492
499
  id: delivery.id,
493
500
  signal,
494
501
  });
@@ -525,6 +532,9 @@ export function createAssistantChannelsRuntime({
525
532
  store.patch(binding.epoch, { error: 'delivery_unknown', updated_at: clock() });
526
533
  } else {
527
534
  store.failDelivery(delivery.id);
535
+ if (delivery.image && delivery.attempts >= 2) {
536
+ store.enqueue(binding.epoch, `${delivery.id}:image-failed`, channelImageFailure(binding.language), delivery.target);
537
+ }
528
538
  // A send failure never proves the connection is ready/connected.
529
539
  store.patch(binding.epoch, {
530
540
  error: store.hasBlocked(binding.epoch) ? 'delivery_failed' : code,
@@ -549,7 +559,7 @@ export function createAssistantChannelsRuntime({
549
559
  throw error;
550
560
  }
551
561
  if (!isCurrent(binding)) return;
552
- enqueuePage(binding, page);
562
+ await enqueuePage(binding, page);
553
563
  const key = channelKey(binding.assistant_id, binding.provider);
554
564
  if (!inboundWork.has(key)) {
555
565
  const work = track(processIncoming(binding, page.generation)).catch((error) => setError(binding, error));
@@ -570,6 +580,7 @@ export function createAssistantChannelsRuntime({
570
580
  try {
571
581
  ownsLease = store.acquire(owner, clock());
572
582
  if (!ownsLease) {
583
+ for (const entry of discoveries.values()) entry.controller.abort();
573
584
  for (const key of [...receivers.keys()]) stopReceiver(key);
574
585
  return;
575
586
  }
@@ -642,6 +653,77 @@ export function createAssistantChannelsRuntime({
642
653
  };
643
654
  };
644
655
 
656
+ // Discovery is an explicit, bounded credential probe, never a saved binding
657
+ // or a second message execution pipeline. The first private sender is shown
658
+ // to the user for confirmation through the normal Save action.
659
+ const discover = async (assistantID, provider, input, { signal } = {}) => {
660
+ assertProvider(provider);
661
+ assertOwner();
662
+ const adapter = adapters[provider];
663
+ if (!adapter) throw new ChannelError('unsupported_provider');
664
+ service.channelPage(assistantID, { tipOnly: true });
665
+ const existing = store.get(assistantID, provider);
666
+ const field = exactField(input?.clientID, MAX_ACCOUNT_FIELD);
667
+ const secret = typeof input?.clientSecret === 'string' ? input.clientSecret.trim() : '';
668
+ if (field.invalid || !field.value || secret.length > MAX_SECRET) throw new ChannelError('validation_error');
669
+ const clientID = field.value;
670
+ const accountKey = JSON.stringify([provider, clientID]);
671
+ const clientSecret = secret || (existing?.client_id === clientID ? existing.client_secret : '');
672
+ if (!clientSecret) throw new ChannelError('validation_error');
673
+ const key = channelKey(assistantID, provider);
674
+ if (retiring.has(key)) throw new ChannelError('channel_in_use');
675
+ if (store.listAll().some((row) => row.provider === provider && row.client_id === clientID && row.assistant_id !== assistantID)
676
+ || pendingAccounts.has(accountKey)) {
677
+ throw new ChannelError('account_in_use');
678
+ }
679
+ const controller = new AbortController();
680
+ const active = AbortSignal.any([controller.signal, lifetime.signal, AbortSignal.timeout(discoveryTimeoutMs), ...(signal ? [signal] : [])]);
681
+ const entry = { assistantID, provider, clientID, controller, done: null };
682
+ discoveries.set(key, entry);
683
+ pendingAccounts.add(accountKey);
684
+ retiring.add(key);
685
+ entry.done = (async () => {
686
+ let connection;
687
+ let onAbort;
688
+ try {
689
+ await Promise.allSettled([stopReceiver(key), bindingWork.get(key), inboundWork.get(key)]);
690
+ assertOwner();
691
+ service.channelPage(assistantID, { tipOnly: true });
692
+ if (active.aborted) throw new ChannelError('cancelled');
693
+ return await new Promise((resolve, reject) => {
694
+ const fail = (error) => reject(new ChannelError(safeError(error)));
695
+ onAbort = () => reject(new ChannelError(active.reason?.name === 'TimeoutError' ? 'discovery_timeout' : 'cancelled'));
696
+ active.addEventListener('abort', onAbort, { once: true });
697
+ connection = Promise.resolve().then(() => adapter.connect({
698
+ config: { clientID, clientSecret, ownerID: '' }, signal: active,
699
+ onReady: () => {},
700
+ onMessage: async (message) => {
701
+ if (active.aborted) return false;
702
+ try {
703
+ assertOwner();
704
+ service.channelPage(assistantID, { tipOnly: true });
705
+ const sender = exactField(message?.senderID, MAX_ACCOUNT_FIELD);
706
+ if (message?.chatType !== 'private' || sender.invalid || !sender.value) return false;
707
+ resolve({ ownerID: sender.value });
708
+ return true;
709
+ } catch (error) { fail(error); return false; }
710
+ },
711
+ onError: fail,
712
+ })).then(() => { if (!active.aborted) fail(new ChannelError('network_error')); }, fail);
713
+ });
714
+ } finally {
715
+ controller.abort();
716
+ if (onAbort) active.removeEventListener('abort', onAbort);
717
+ await connection;
718
+ discoveries.delete(key);
719
+ pendingAccounts.delete(accountKey);
720
+ retiring.delete(key);
721
+ if (!closed) void track(tick());
722
+ }
723
+ })();
724
+ return entry.done;
725
+ };
726
+
645
727
  const save = async (assistantID, provider, input) => {
646
728
  assertProvider(provider);
647
729
  assertOwner();
@@ -659,6 +741,7 @@ export function createAssistantChannelsRuntime({
659
741
  }
660
742
  const clientID = clientIDField.value;
661
743
  const ownerID = ownerIDField.value;
744
+ if (!ownerID) throw new ChannelError('owner_required');
662
745
  const accountChanged = Boolean(existing && existing.client_id !== clientID);
663
746
  // A new account must bring its own secret; never reuse a previous account's
664
747
  // credential after the client ID changes.
@@ -669,8 +752,11 @@ export function createAssistantChannelsRuntime({
669
752
  const expectedEpoch = existing?.epoch ?? null;
670
753
  const key = channelKey(assistantID, provider);
671
754
  if (retiring.has(key)) throw new ChannelError('channel_in_use');
755
+ const accountKey = JSON.stringify([provider, clientID]);
756
+ if (pendingAccounts.has(accountKey)) throw new ChannelError('account_in_use');
672
757
  const account = store.listAll().find((row) => row.provider === provider && row.client_id === clientID);
673
758
  if (account && account.assistant_id !== assistantID) throw new ChannelError('account_in_use');
759
+ pendingAccounts.add(accountKey);
674
760
  retiring.add(key);
675
761
  let bound = false;
676
762
  try {
@@ -704,6 +790,7 @@ export function createAssistantChannelsRuntime({
704
790
  bound = true;
705
791
  } finally {
706
792
  retiring.delete(key);
793
+ pendingAccounts.delete(accountKey);
707
794
  // Account conflict, a failed write or a stale binding must not strand the
708
795
  // previous receiver; resume it from its untouched row.
709
796
  if (!bound && !closed) void track(tick());
@@ -808,6 +895,9 @@ export function createAssistantChannelsRuntime({
808
895
  if (closed) return;
809
896
  if (!ownsLease) ownsLease = store.acquire(owner, clock());
810
897
  if (!ownsLease || !store.owns(owner, clock())) return;
898
+ const pendingDiscoveries = [...discoveries.values()].filter((entry) => entry.assistantID === assistantID);
899
+ for (const entry of pendingDiscoveries) entry.controller.abort();
900
+ await Promise.allSettled(pendingDiscoveries.map((entry) => entry.done));
811
901
  const rows = store.listByAssistant(assistantID);
812
902
  if (!rows.length) return;
813
903
  const keys = rows.map((row) => channelKey(assistantID, row.provider));
@@ -844,6 +934,7 @@ export function createAssistantChannelsRuntime({
844
934
 
845
935
  return {
846
936
  status,
937
+ discover: (assistantID, provider, input, options) => track(discover(assistantID, provider, input, options)),
847
938
  save: (assistantID, provider, input) => track(save(assistantID, provider, input)),
848
939
  transfer: (assistantID, provider, input) => track(transfer(assistantID, provider, input)),
849
940
  retry: (assistantID, provider) => track(retry(assistantID, provider)),