@yuriai/web 0.2.27-beta.6 → 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 (228) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-DNm_jMna.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
  5. package/dist/assets/AssistantView-CxQv-9Ms.js +1 -0
  6. package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-DPpG0fwx.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-S6UbimjB.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
  10. package/dist/assets/{Icon-t2xvbAyN.js → Icon-BE4mEwzV.js} +1 -1
  11. package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
  12. package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-NLq7_P-i.js} +1 -1
  13. package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
  14. package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
  16. package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
  17. package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-Deidw1br.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-CO_OWEfq.js} +2 -2
  19. package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
  20. package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-DtVW9NTV.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-C8ld4wO7.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-B3auC2WH.js} +1 -1
  23. package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-Cm7woZWl.js} +15 -15
  24. package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-CdL4PFxW.js} +1 -1
  25. package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-CwRB6Yyr.js} +1 -1
  26. package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
  27. package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-BOx0s0Ue.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-B6woJIX5.js} +1 -1
  29. package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
  30. package/dist/assets/{button-DinGM3tu.js → button-BXxwtxsG.js} +1 -1
  31. package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-C5HFS-rx.js} +1 -1
  32. package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-BEm0787p.js} +1 -1
  33. package/dist/assets/context-menu-DUwvVUDY.js +1 -0
  34. package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
  35. package/dist/assets/device-BcRP6Tjd.js +2 -0
  36. package/dist/assets/{diagram-BmG-7Jb4.js → diagram-DyY8dxjZ.js} +1 -1
  37. package/dist/assets/{dialog-BXssfGXA.js → dialog-CLca6ojn.js} +1 -1
  38. package/dist/assets/dropdown-menu.styles-DGaALKP0.js +1 -0
  39. package/dist/assets/{es-HP_Ise0X.js → es-CrsHvgue.js} +2 -2
  40. package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
  41. package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
  42. package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
  43. package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
  44. package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-CrIAce3K.js} +1 -1
  45. package/dist/assets/{fr-D0kJXJ6U.js → fr-CEgiRlfa.js} +2 -2
  46. package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-D2G9ny2O.js} +1 -1
  47. package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-B7vYwgBh.js} +4 -4
  48. package/dist/assets/{gui-9enrif_1.js → gui-CJjEj3l4.js} +1 -1
  49. package/dist/assets/host-CnVx34Dh.js +1 -0
  50. package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
  51. package/dist/assets/{input-v8-rVbo-.js → input-D59Q2pm8.js} +1 -1
  52. package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
  53. package/dist/assets/{ja-BjHKXazE.js → ja-CX-_p9jZ.js} +2 -2
  54. package/dist/assets/{ko-Llwnl876.js → ko-D5xlLYJM.js} +2 -2
  55. package/dist/assets/main-CxpUooVS.js +2 -0
  56. package/dist/assets/main-Dpm4KxWX.js +169 -0
  57. package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-D2VWb_4E.js} +1 -1
  58. package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DQ3KthDF.js} +1 -1
  59. package/dist/assets/miniChat-CTdj8Ug9.js +2 -0
  60. package/dist/assets/mobile-ChbA3Q8j.js +2 -0
  61. package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
  62. package/dist/assets/{multirun-BhWttsRQ.js → multirun-BILeETbd.js} +1 -1
  63. package/dist/assets/{native-DSvNnKAm.js → native-BYMhr-xH.js} +1 -1
  64. package/dist/assets/{native-config-DjdrW_9n.js → native-config-BIY0Cr-l.js} +1 -1
  65. package/dist/assets/{persistence-CfrHIiIS.js → persistence-CWuLIq1J.js} +2 -2
  66. package/dist/assets/{pl-BOd_idqn.js → pl-BjH81A_q.js} +2 -2
  67. package/dist/assets/projectMeta-B9_Uh8YH.js +1 -0
  68. package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-Dp5oK2x3.js} +2 -2
  69. package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
  70. package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
  71. package/dist/assets/react-DRe85o5s.js +1 -0
  72. package/dist/assets/readiness-BNIgH81X.js +1 -0
  73. package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
  74. package/dist/assets/renderMobileApp-DAfque7-.js +28 -0
  75. package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
  76. package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
  77. package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
  78. package/dist/assets/runtimeConfig-BX8JirIc.js +2 -0
  79. package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
  80. package/dist/assets/scheduledTaskNavigation-EomDNVu2.js +1 -0
  81. package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
  82. package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
  83. package/dist/assets/speechSettingsQueries-CC0fusUo.js +4 -0
  84. package/dist/assets/src-BMKjN2ip.css +2 -0
  85. package/dist/assets/{store-CUBymvAC.js → store-CkIHVrmT.js} +4 -3
  86. package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-rl9mZAlB.js} +1 -1
  87. package/dist/assets/{textarea-B39OCNPV.js → textarea-7eTptEtD.js} +1 -1
  88. package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-BPwoSTzO.js} +1 -1
  89. package/dist/assets/types-CUtSV1V8.js +2 -0
  90. package/dist/assets/{uk-BNd7CjVO.js → uk-BEfkaLtM.js} +2 -2
  91. package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-Ck2PdQRx.js} +52 -52
  92. package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
  93. package/dist/assets/useDesktopWindowControlsLayout-DxxOUZj1.js +1 -0
  94. package/dist/assets/useEffectiveDirectory-CNCQfN_x.js +1 -0
  95. package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-DeqW9nRx.js} +1 -1
  96. package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
  97. package/dist/assets/useUIStore-C6CE42oh.js +1 -0
  98. package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-CN_RGaSw.js} +1 -1
  99. package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
  100. package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
  101. package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
  102. package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
  103. package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
  104. package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
  105. package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-DipfA56P.js} +2 -2
  106. package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B7pXMVjt.js} +2 -2
  107. package/dist/index.html +18 -18
  108. package/dist/mini-chat.html +18 -18
  109. package/dist/mobile.html +18 -18
  110. package/package.json +6 -1
  111. package/server/index.js +2 -145
  112. package/server/lib/assistants/DOCUMENTATION.md +69 -11
  113. package/server/lib/assistants/cards.js +1 -1
  114. package/server/lib/assistants/channel-image.js +92 -0
  115. package/server/lib/assistants/channel-image.test.js +76 -0
  116. package/server/lib/assistants/channel-output-store.test.js +41 -0
  117. package/server/lib/assistants/channel-output.integration.test.js +114 -0
  118. package/server/lib/assistants/channel-output.js +90 -0
  119. package/server/lib/assistants/channel-output.test.js +79 -0
  120. package/server/lib/assistants/channels/DOCUMENTATION.md +329 -0
  121. package/server/lib/assistants/channels/PROTOCOLS.md +250 -0
  122. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +645 -0
  123. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +423 -0
  124. package/server/lib/assistants/channels/integration.test.js +44 -0
  125. package/server/lib/assistants/channels/routes.js +59 -0
  126. package/server/lib/assistants/channels/routes.test.js +139 -0
  127. package/server/lib/assistants/channels/runtime.js +958 -0
  128. package/server/lib/assistants/channels/runtime.test.js +897 -0
  129. package/server/lib/assistants/channels/sdk-adapters.js +383 -0
  130. package/server/lib/assistants/channels/sdk-adapters.test.js +384 -0
  131. package/server/lib/assistants/channels/store.js +249 -0
  132. package/server/lib/assistants/channels/store.test.js +296 -0
  133. package/server/lib/assistants/channels/transport.js +42 -0
  134. package/server/lib/assistants/channels/transport.test.js +23 -0
  135. package/server/lib/assistants/channels/wecom-chat-adapter.js +703 -0
  136. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +130 -0
  137. package/server/lib/assistants/contact-store.js +9 -3
  138. package/server/lib/assistants/contact-store.test.js +27 -0
  139. package/server/lib/assistants/contact-tools.js +65 -75
  140. package/server/lib/assistants/contact-tools.test.js +114 -22
  141. package/server/lib/assistants/harness.js +79 -34
  142. package/server/lib/assistants/harness.test.js +52 -20
  143. package/server/lib/assistants/message-channel-origin.js +7 -0
  144. package/server/lib/assistants/resource-reference.integration.test.js +284 -0
  145. package/server/lib/assistants/routes.js +14 -4
  146. package/server/lib/assistants/service.js +116 -69
  147. package/server/lib/assistants/service.test.js +31 -17
  148. package/server/lib/assistants/weixin/DOCUMENTATION.md +121 -14
  149. package/server/lib/assistants/weixin/api.js +45 -1
  150. package/server/lib/assistants/weixin/api.test.js +28 -0
  151. package/server/lib/assistants/weixin/chat-adapter.js +113 -0
  152. package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
  153. package/server/lib/assistants/weixin/inbound.js +149 -0
  154. package/server/lib/assistants/weixin/inbound.test.js +141 -0
  155. package/server/lib/assistants/weixin/media.js +79 -0
  156. package/server/lib/assistants/weixin/media.test.js +66 -0
  157. package/server/lib/assistants/weixin/runtime.js +105 -74
  158. package/server/lib/assistants/weixin/runtime.test.js +192 -4
  159. package/server/lib/assistants/weixin/store.js +16 -8
  160. package/server/lib/assistants/weixin/store.test.js +93 -0
  161. package/server/lib/assistants/weixin/toon.js +49 -0
  162. package/server/lib/assistants/weixin/toon.test.js +25 -0
  163. package/server/lib/assistants/yuri-project.http.test.js +9 -3
  164. package/server/lib/github/DOCUMENTATION.md +9 -8
  165. package/server/lib/llm/bridge-plugin.bundle.js +188 -188
  166. package/server/lib/notifications/DOCUMENTATION.md +6 -0
  167. package/server/lib/notifications/runtime.js +26 -15
  168. package/server/lib/notifications/runtime.test.js +14 -13
  169. package/server/lib/opencode/DOCUMENTATION.md +10 -1
  170. package/server/lib/opencode/auth.d.ts +6 -2
  171. package/server/lib/opencode/core-routes.js +0 -1
  172. package/server/lib/opencode/feature-routes-runtime.js +0 -24
  173. package/server/lib/opencode/location-release.d.ts +5 -1
  174. package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
  175. package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
  176. package/server/lib/opencode/native-goal.js +15 -0
  177. package/server/lib/opencode/native-goal.test.js +17 -0
  178. package/server/lib/opencode/settings-helpers.js +0 -6
  179. package/server/lib/opencode/shutdown-runtime.js +0 -2
  180. package/server/lib/projects/project-config.js +3 -6
  181. package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
  182. package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
  183. package/server/lib/scheduled-tasks/routes.js +0 -26
  184. package/server/lib/scheduled-tasks/runtime.js +33 -257
  185. package/server/lib/scheduled-tasks/runtime.test.js +24 -65
  186. package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
  187. package/server/lib/session-metadata/routes.js +4 -38
  188. package/server/lib/session-metadata/routes.test.js +2 -2
  189. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
  190. package/dist/assets/AssistantView-Br1iETTs.js +0 -1
  191. package/dist/assets/MarkdownRenderer-BlGxjOei.js +0 -2
  192. package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +0 -2
  193. package/dist/assets/context-menu-DpbkRkk1.js +0 -1
  194. package/dist/assets/device-BjRYYXNT.js +0 -2
  195. package/dist/assets/host-FR_grJxM.js +0 -1
  196. package/dist/assets/insertionBoundaries-CZz7TWJv.js +0 -1
  197. package/dist/assets/main-Bp9HHqTr.js +0 -2
  198. package/dist/assets/main-DOwAfmxJ.js +0 -169
  199. package/dist/assets/miniChat-BJDgCrfF.js +0 -2
  200. package/dist/assets/mobile-GM9931J_.js +0 -2
  201. package/dist/assets/projectMeta-31PobC-M.js +0 -1
  202. package/dist/assets/react-B9v0P7kT.js +0 -1
  203. package/dist/assets/readiness-CYNnsekT.js +0 -1
  204. package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +0 -2
  205. package/dist/assets/renderMobileApp-CU1ec6Ak.js +0 -28
  206. package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
  207. package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
  208. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
  209. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
  210. package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
  211. package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
  212. package/dist/assets/src-Bckdo2XS.css +0 -2
  213. package/dist/assets/types-BqFQhQTt.js +0 -2
  214. package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +0 -1
  215. package/dist/assets/useEffectiveDirectory-D8FFE5Yn.js +0 -1
  216. package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +0 -23
  217. package/dist/assets/useUIStore-BbYD420L.js +0 -1
  218. package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
  219. package/dist/assets/vendor-solid-js-0T254UHG.js +0 -1
  220. package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
  221. package/server/lib/session-goal/DOCUMENTATION.md +0 -371
  222. package/server/lib/session-goal/capability.js +0 -57
  223. package/server/lib/session-goal/capability.test.js +0 -33
  224. package/server/lib/session-goal/objectives.js +0 -61
  225. package/server/lib/session-goal/routes.js +0 -274
  226. package/server/lib/session-goal/routes.test.js +0 -211
  227. package/server/lib/session-goal/runtime.js +0 -2452
  228. package/server/lib/session-goal/runtime.test.js +0 -2125
@@ -0,0 +1,141 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { normalizeWeixinInput, prepareWeixinInput } from './inbound.js';
3
+
4
+ const image = { type: 2, image_item: { media: { encrypt_query_param: 'private-reference', aes_key: 'private-key' }, thumb_width: 100 } };
5
+ const prepare = async (message, overrides = {}) => {
6
+ const api = { downloadMedia: vi.fn(async () => ({ buffer: Buffer.from('bytes'), mime: 'image/png', filename: 'image.png' })) };
7
+ const service = { putAssistantContactAttachment: vi.fn(async (_bot, uploadID, { headers }) => ({ type: 'file', attachmentID: `att_${uploadID}`, mime: headers['content-type'], size: Number(headers['x-content-size']) })) };
8
+ const options = { api, service, assistantID: 'bot', assertCurrent: () => {}, ...overrides };
9
+ const receipt = { id: 'stable-id', ...normalizeWeixinInput(message) };
10
+ const parts = await prepareWeixinInput(receipt, options);
11
+ return { parts, ...options, receipt };
12
+ };
13
+
14
+ describe('WeChat rich input projection', () => {
15
+ it('keeps a real plain-text envelope as one text part without transport-only metadata', async () => {
16
+ const message = { message_id: 'message-id', root_id: 0, parent_id: 0,
17
+ item_list: [{ type: 1, create_time_ms: 123, update_time_ms: 123, is_completed: true,
18
+ msg_id: 'item-id', button_item_list: [], at_bot_username_list: [],
19
+ text_item: { text: 'https://mp.weixin.qq.com/s/example' } }] };
20
+ const result = await prepare(message);
21
+ expect(result.receipt.payload).toBe('');
22
+ expect(result.parts).toEqual([{ type: 'text', text: 'https://mp.weixin.qq.com/s/example' }]);
23
+ });
24
+
25
+ it('does not turn ordinary text item protocol IDs into a TOON message', async () => {
26
+ const message = { message_id: 'message-id', from_user_id: 'owner', create_time_ms: 123,
27
+ item_list: [{ type: 1, msg_id: 'item-id', create_time_ms: 123, text_item: { text: 'halo' } }] };
28
+ const result = await prepare(message);
29
+ expect(result.receipt.payload).toBe('');
30
+ expect(result.parts).toEqual([{ type: 'text', text: 'halo' }]);
31
+ });
32
+
33
+ it('keeps ordinary text byte-for-byte and accepts legacy text-only receipts', async () => {
34
+ const message = { context_token: 'private-context', message_id: 'id', item_list: [{ type: 1, text_item: { text: '你好' } }, { type: 1, text_item: { text: 'world' } }] };
35
+ expect(normalizeWeixinInput(message)).toEqual({ text: '你好\nworld', payload: '' });
36
+ const result = await prepare(message);
37
+ expect(result.parts).toEqual([{ type: 'text', text: '你好\nworld' }]);
38
+ expect(result.api.downloadMedia).not.toHaveBeenCalled();
39
+ });
40
+
41
+ it('omits private-only text fields but retains actual button and article content', async () => {
42
+ const plain = await prepare({ item_list: [{ type: 1, text_item: { text: 'hello' }, private_token: 'not-content' }] });
43
+ expect(plain.parts).toEqual([{ type: 'text', text: 'hello' }]);
44
+ const rich = await prepare({ root_id: 0, parent_id: 0, article: { title: 'Article', url: 'https://mp.weixin.qq.com/s/example' },
45
+ item_list: [{ type: 1, text_item: { text: 'hello' }, button_item_list: [{ title: 'Open article' }] }] });
46
+ expect(rich.parts.at(-1).text).toContain('Open article');
47
+ expect(rich.parts.at(-1).text).toContain('Article');
48
+ expect(rich.parts.at(-1).text).not.toMatch(/root_id|parent_id/);
49
+ });
50
+
51
+ it('keeps every mixed item, inline quote and article extension as data while stripping transport secrets', async () => {
52
+ const { parts } = await prepare({ context_token: 'private-context', bot_token: 'private-token', item_list: [
53
+ { type: 1, text_item: { text: '看看这篇' }, ref_msg: { title: '原消息', svr_id: 'quoted-id', message_item: { type: 1, text_item: { text: '引用文字' } } } },
54
+ image,
55
+ // Deliberately synthetic extension: no public iLink article-item schema exists.
56
+ { type: 99, article_item: { title: '公众号文章', description: '摘要', url: 'https://mp.weixin.qq.com/s?__biz=public&mid=123&token=private-token',
57
+ media: { aes_key: 'private-key' }, context_token: 'private-context' } },
58
+ ] });
59
+ const text = parts.filter((part) => part.type === 'text').map((part) => part.text).join('\n');
60
+ expect(text).toContain('看看这篇');
61
+ for (const expected of ['TOON', '公众号文章', '摘要', 'mp.weixin.qq.com', '__biz=public', '原消息', '引用文字', 'attached']) expect(text).toContain(expected);
62
+ expect(text).not.toMatch(/private-key|private-token|private-context|private-reference/);
63
+ expect(parts.filter((part) => part.type === 'file')).toHaveLength(1);
64
+ });
65
+
66
+ it('retains unknown text fields and handles thumbnail-only and URL-only image references without claiming a full-resolution image', async () => {
67
+ const result = await prepare({ item_list: [
68
+ { type: 99, text_item: { text: '分享的其他内容' } },
69
+ { type: 2, image_item: { thumb_media: image.image_item.media, aeskey: 'must-not-use-original-key' } },
70
+ { type: 2, image_item: { url: 'https://novac2c.cdn.weixin.qq.com/c2c/download?encrypted_query_param=private-reference' } },
71
+ ] });
72
+ expect(result.parts.at(-1).text).toContain('分享的其他内容');
73
+ expect(result.parts.at(-1).text).toContain('thumbnail');
74
+ expect(result.api.downloadMedia).toHaveBeenCalledTimes(2);
75
+ expect(result.api.downloadMedia.mock.calls[0][0].aeskey).toBeUndefined();
76
+ expect(result.api.downloadMedia.mock.calls[1][0].full_url).toContain('encrypted_query_param=private-reference');
77
+ expect(result.parts.at(-1).text).not.toContain('private-reference');
78
+ });
79
+
80
+ it('consumes platform voice transcripts without downloading audio, and preserves raw audio when no transcript is supplied', async () => {
81
+ const spoken = await prepare({ item_list: [{ type: 3, voice_item: { text: '帮我总结今天的工作', encode_type: 6, media: image.image_item.media } }] });
82
+ expect(spoken.parts.at(-1).text).toContain('帮我总结今天的工作');
83
+ expect(spoken.parts.at(-1).text).toContain('provided');
84
+ expect(spoken.api.downloadMedia).not.toHaveBeenCalled();
85
+ const raw = await prepare({ item_list: [{ type: 3, voice_item: { encode_type: 6, playtime: 3000, media: image.image_item.media } }] });
86
+ expect(raw.parts.at(-1).text).toContain('original_file_only_not_transcribed');
87
+ expect(raw.parts.at(-1).text).toContain('unavailable');
88
+ expect(raw.parts.filter((part) => part.type === 'file')).toHaveLength(1);
89
+ });
90
+
91
+ it('preserves XML/JSON share data, sanitizes embedded capabilities and never fetches article URLs', async () => {
92
+ const { parts, api } = await prepare({ item_list: [{ type: 98, appmsg: {
93
+ xml: '<appmsg><title>文章</title><url>https://mp.weixin.qq.com/s/public</url><aes_key>private-key</aes_key></appmsg>',
94
+ json: '{"title":"其他分享","context_token":"private-context"}',
95
+ } }] });
96
+ expect(parts.at(-1).text).toContain('文章');
97
+ expect(parts.at(-1).text).toContain('其他分享');
98
+ expect(parts.at(-1).text).not.toMatch(/private-key|private-context/);
99
+ expect(api.downloadMedia).not.toHaveBeenCalled();
100
+ });
101
+
102
+ it('continues with successful attachments/text when one media item fails, and uses stable upload identities', async () => {
103
+ const api = { downloadMedia: vi.fn().mockRejectedValueOnce(new Error('https://private-url private-key')).mockResolvedValue({ buffer: Buffer.from('good'), mime: 'text/plain', filename: 'note.txt' }) };
104
+ const message = { item_list: [{ type: 1, text_item: { text: '读取附件' } }, image, { type: 4, file_item: { file_name: 'note.txt', media: image.image_item.media } }] };
105
+ const result = await prepare(message, { api });
106
+ expect(result.parts.filter((part) => part.type === 'file')).toHaveLength(1);
107
+ expect(result.parts.at(-1).text).toContain('download_or_storage_failed');
108
+ expect(result.parts.at(-1).text).toContain('attached');
109
+ expect(JSON.stringify(result.parts)).not.toMatch(/private-url|private-key|private-reference/);
110
+ const retry = await prepare(message, { api: { downloadMedia: vi.fn(async () => ({ buffer: Buffer.from('good'), mime: 'text/plain', filename: 'note.txt' })) } });
111
+ expect(result.service.putAssistantContactAttachment.mock.calls[0][1]).toBe(retry.service.putAssistantContactAttachment.mock.calls[1][1]);
112
+ });
113
+
114
+ it('bounds metadata depth, strings, items and downloads, explicitly marking truncation', async () => {
115
+ const message = { item_list: Array.from({ length: 100 }, () => ({ ...image, extension: { title: '文'.repeat(20_000), nested: { a: { b: { c: { d: { e: 'too deep' } } } } } } })) };
116
+ const result = await prepare(message);
117
+ expect(result.parts.at(-1).text).toContain('truncated');
118
+ expect(result.parts.at(-1).text.length).toBeLessThan(40_000);
119
+ expect(result.api.downloadMedia).toHaveBeenCalledTimes(8);
120
+ expect(result.receipt.payload.length).toBeLessThan(45_000);
121
+ });
122
+
123
+ it('does not admit or upload a stale completion after disconnect, expiry/lease loss or cancellation', async () => {
124
+ let current = true;
125
+ const api = { downloadMedia: vi.fn(async () => { current = false; return { buffer: Buffer.from('bytes'), mime: 'image/png', filename: 'image.png' }; }) };
126
+ const service = { putAssistantContactAttachment: vi.fn() };
127
+ await expect(prepare({ item_list: [image] }, { api, service, assertCurrent: () => { if (!current) throw new Error('cancelled'); } })).rejects.toThrow('cancelled');
128
+ expect(service.putAssistantContactAttachment).not.toHaveBeenCalled();
129
+ });
130
+
131
+ it('keeps within the per-turn byte budget and does not charge failed uploads against successful attachments', async () => {
132
+ const api = { downloadMedia: vi.fn(async () => ({ buffer: Buffer.alloc(20 * 1024 * 1024), mime: 'application/octet-stream', filename: 'file.bin' })) };
133
+ const service = { putAssistantContactAttachment: vi.fn().mockRejectedValueOnce(new Error('storage failure'))
134
+ .mockResolvedValue({ type: 'file', attachmentID: 'att_file', mime: 'application/octet-stream', size: 20 * 1024 * 1024 }) };
135
+ const result = await prepare({ item_list: Array.from({ length: 4 }, () => ({ type: 4, file_item: { media: image.image_item.media } })) }, { api, service });
136
+ expect(result.parts.filter((part) => part.type === 'file')).toHaveLength(2);
137
+ expect(service.putAssistantContactAttachment).toHaveBeenCalledTimes(3);
138
+ expect(result.parts.at(-1).text).toContain('size_limit');
139
+ expect(result.parts.at(-1).text).toContain('download_or_storage_failed');
140
+ });
141
+ });
@@ -0,0 +1,79 @@
1
+ import { createDecipheriv } from 'node:crypto';
2
+ import path from 'node:path';
3
+ import { MAX_PROMPT_ATTACHMENT_BYTES } from '../../fs/prompt-attachment-store.js';
4
+
5
+ const CDN = 'https://novac2c.cdn.weixin.qq.com/c2c/download';
6
+ const fail = (code) => { throw Object.assign(new Error(code), { code }); };
7
+ const aesKey = (source) => {
8
+ if (source.aeskey) {
9
+ if (!/^[a-f\d]{32}$/i.test(source.aeskey)) fail('media_invalid_key');
10
+ return Buffer.from(source.aeskey, 'hex');
11
+ }
12
+ if (!source.aes_key) return null;
13
+ if (!/^[A-Za-z\d+/]+={0,2}$/.test(source.aes_key)) fail('media_invalid_key');
14
+ const decoded = Buffer.from(source.aes_key, 'base64');
15
+ if (decoded.length === 16) return decoded;
16
+ if (decoded.length === 32 && /^[a-f\d]{32}$/i.test(decoded.toString('ascii'))) return Buffer.from(decoded.toString('ascii'), 'hex');
17
+ fail('media_invalid_key');
18
+ };
19
+
20
+ const imageMime = (buffer) => {
21
+ if (buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png';
22
+ if (buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return 'image/jpeg';
23
+ if (/^GIF8[79]a$/.test(buffer.subarray(0, 6).toString('ascii'))) return 'image/gif';
24
+ if (buffer.subarray(0, 4).toString() === 'RIFF' && buffer.subarray(8, 12).toString() === 'WEBP') return 'image/webp';
25
+ if (buffer.subarray(0, 2).toString() === 'BM') return 'image/bmp';
26
+ if (buffer.subarray(4, 8).toString() === 'ftyp') {
27
+ const brand = buffer.subarray(8, 12).toString();
28
+ if (['avif', 'avis'].includes(brand)) return 'image/avif';
29
+ if (['heic', 'heix', 'hevc', 'hevx', 'mif1'].includes(brand)) return 'image/heic';
30
+ }
31
+ fail('media_invalid_image');
32
+ };
33
+
34
+ export async function downloadWeixinMedia(source, { fetchImpl = fetch, signal } = {}) {
35
+ const url = new URL(source.full_url || CDN);
36
+ if (!source.full_url) url.searchParams.set('encrypted_query_param', source.encrypt_query_param || '');
37
+ // Media references are capabilities, not arbitrary user-provided fetch targets.
38
+ if (url.protocol !== 'https:' || url.hostname !== 'novac2c.cdn.weixin.qq.com' || url.port
39
+ || url.username || url.password || url.hash || url.pathname !== '/c2c/download') fail('media_unsafe_url');
40
+ if (!source.full_url && !source.encrypt_query_param) fail('media_missing_reference');
41
+ const key = aesKey(source);
42
+ if (!key && source.kind !== 'image') fail('media_invalid_key');
43
+ const limit = Math.min(MAX_PROMPT_ATTACHMENT_BYTES, 20 * 1024 * 1024);
44
+ const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(20_000)]) : AbortSignal.timeout(20_000);
45
+ requestSignal.throwIfAborted();
46
+ const response = await fetchImpl(url.href, { redirect: 'error', signal: requestSignal });
47
+ if (!response.ok || !response.body) fail('media_download_failed');
48
+ if (Number(response.headers.get('content-length')) > limit + 16) {
49
+ await response.body.cancel(); fail('media_too_large');
50
+ }
51
+ const reader = response.body.getReader();
52
+ const chunks = [];
53
+ let size = 0;
54
+ try {
55
+ while (true) {
56
+ requestSignal.throwIfAborted();
57
+ const chunk = await reader.read();
58
+ if (chunk.done) break;
59
+ size += chunk.value.byteLength;
60
+ if (size > limit + 16) fail('media_too_large');
61
+ chunks.push(chunk.value);
62
+ }
63
+ } catch (error) { await reader.cancel().catch(() => {}); throw error; }
64
+ let buffer = Buffer.concat(chunks, size);
65
+ if (key) {
66
+ const decipher = createDecipheriv('aes-128-ecb', key, null);
67
+ buffer = Buffer.concat([decipher.update(buffer), decipher.final()]);
68
+ }
69
+ if (!buffer.length || buffer.length > limit) fail('media_too_large');
70
+ const originalName = typeof source.filename === 'string' ? path.posix.basename(source.filename.replace(/\\/g, '/')) : '';
71
+ const filename = originalName.replace(/[\x00-\x1f\x7f]/g, '').replace(/\.\./g, '_').slice(-128) || `weixin-${source.kind}`;
72
+ const fileMimes = { '.txt': 'text/plain', '.md': 'text/markdown', '.csv': 'text/csv', '.json': 'application/json',
73
+ '.pdf': 'application/pdf', '.xml': 'application/xml', '.html': 'text/html', '.zip': 'application/zip' };
74
+ const voiceMimes = { 1: 'audio/pcm', 2: 'audio/adpcm', 4: 'audio/speex', 5: 'audio/amr', 6: 'audio/silk', 7: 'audio/mpeg', 8: 'audio/ogg' };
75
+ const mime = source.kind === 'image' ? imageMime(buffer) : source.kind === 'video' ? 'video/mp4'
76
+ : source.kind === 'voice' ? voiceMimes[source.encode_type] || 'application/octet-stream'
77
+ : fileMimes[path.extname(filename).toLowerCase()] || 'application/octet-stream';
78
+ return { buffer, mime, filename };
79
+ }
@@ -0,0 +1,66 @@
1
+ import { createCipheriv } from 'node:crypto';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { downloadWeixinMedia } from './media.js';
4
+
5
+ const key = Buffer.from('0123456789abcdef');
6
+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6D/8AAAAASUVORK5CYII=', 'base64');
7
+ const encrypted = (bytes) => {
8
+ const cipher = createCipheriv('aes-128-ecb', key, null);
9
+ return Buffer.concat([cipher.update(bytes), cipher.final()]);
10
+ };
11
+ const source = { kind: 'image', encrypt_query_param: 'private capability', aes_key: key.toString('base64') };
12
+
13
+ describe('WeChat CDN media boundary', () => {
14
+ it.each([key.toString('base64'), Buffer.from(key.toString('hex')).toString('base64')])('downloads and decrypts both official AES key encodings', async (aes_key) => {
15
+ const fetchImpl = vi.fn(async () => new Response(encrypted(png)));
16
+ const result = await downloadWeixinMedia({ ...source, aes_key }, { fetchImpl });
17
+ expect(result.buffer).toEqual(png);
18
+ expect(result.mime).toBe('image/png');
19
+ const [url, init] = fetchImpl.mock.calls[0];
20
+ expect(new URL(url).searchParams.get('encrypted_query_param')).toBe('private capability');
21
+ expect(init).toMatchObject({ redirect: 'error' });
22
+ expect(init.headers).toBeUndefined();
23
+ });
24
+
25
+ it('prefers the image hex key and a validated full CDN URL; permits plaintext images only', async () => {
26
+ const full_url = 'https://novac2c.cdn.weixin.qq.com/c2c/download?encrypted_query_param=full';
27
+ const fetchImpl = vi.fn(async () => new Response(encrypted(png)));
28
+ await expect(downloadWeixinMedia({ ...source, full_url, aeskey: key.toString('hex'), aes_key: 'invalid' }, { fetchImpl }))
29
+ .resolves.toMatchObject({ buffer: png });
30
+ expect(fetchImpl.mock.calls[0][0]).toBe(full_url);
31
+ await expect(downloadWeixinMedia({ kind: 'image', full_url }, { fetchImpl: async () => new Response(png) })).resolves.toMatchObject({ buffer: png });
32
+ await expect(downloadWeixinMedia({ kind: 'voice', full_url }, { fetchImpl })).rejects.toMatchObject({ code: 'media_invalid_key' });
33
+ });
34
+
35
+ it.each(['http://novac2c.cdn.weixin.qq.com/c2c/download', 'https://127.0.0.1/c2c/download',
36
+ 'https://novac2c.cdn.weixin.qq.com.evil.example/c2c/download', 'https://user:pass@novac2c.cdn.weixin.qq.com/c2c/download',
37
+ 'https://novac2c.cdn.weixin.qq.com:8443/c2c/download', 'https://novac2c.cdn.weixin.qq.com/other'])('rejects SSRF/credential destinations before fetching %s', async (full_url) => {
38
+ const fetchImpl = vi.fn();
39
+ await expect(downloadWeixinMedia({ ...source, full_url }, { fetchImpl })).rejects.toMatchObject({ code: 'media_unsafe_url' });
40
+ expect(fetchImpl).not.toHaveBeenCalled();
41
+ });
42
+
43
+ it('bounds declared and streaming bytes, cancels oversized bodies and rejects invalid image bytes/padding', async () => {
44
+ await expect(downloadWeixinMedia(source, { fetchImpl: async () => new Response('x', { headers: { 'content-length': String(26 * 1024 * 1024) } }) }))
45
+ .rejects.toMatchObject({ code: 'media_too_large' });
46
+ const cancel = vi.fn();
47
+ const body = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(26 * 1024 * 1024)); }, cancel });
48
+ await expect(downloadWeixinMedia(source, { fetchImpl: async () => new Response(body) })).rejects.toMatchObject({ code: 'media_too_large' });
49
+ expect(cancel).toHaveBeenCalled();
50
+ await expect(downloadWeixinMedia(source, { fetchImpl: async () => new Response(encrypted(Buffer.from('<html>not an image</html>'))) }))
51
+ .rejects.toMatchObject({ code: 'media_invalid_image' });
52
+ await expect(downloadWeixinMedia(source, { fetchImpl: async () => new Response(Buffer.alloc(16)) })).rejects.toThrow();
53
+ });
54
+
55
+ it('honors cancellation and preserves files/audio/video with safe names and MIME metadata', async () => {
56
+ const controller = new AbortController();
57
+ controller.abort();
58
+ await expect(downloadWeixinMedia(source, { signal: controller.signal, fetchImpl: async () => new Response(encrypted(png)) })).rejects.toThrow();
59
+ const file = await downloadWeixinMedia({ ...source, kind: 'file', filename: '..\\..\\notes.md' }, { fetchImpl: async () => new Response(encrypted(Buffer.from('# hello'))) });
60
+ expect(file).toMatchObject({ filename: 'notes.md', mime: 'text/markdown' });
61
+ const voice = await downloadWeixinMedia({ ...source, kind: 'voice', encode_type: 6 }, { fetchImpl: async () => new Response(encrypted(Buffer.from('#!SILK_V3'))) });
62
+ expect(voice.mime).toBe('audio/silk');
63
+ const video = await downloadWeixinMedia({ ...source, kind: 'video' }, { fetchImpl: async () => new Response(encrypted(Buffer.from('video'))) });
64
+ expect(video.mime).toBe('video/mp4');
65
+ });
66
+ });
@@ -3,24 +3,21 @@ import { setTimeout as delay } from 'node:timers/promises';
3
3
  import { createWeixinAPI, WeixinError, weixinOrigin } from './api.js';
4
4
  import { createWeixinStore } from './store.js';
5
5
  import { createWeixinTyping } from './typing.js';
6
+ import { prepareWeixinInput } from './inbound.js';
7
+ import { createWeixinChatAdapter } from './chat-adapter.js';
8
+ import { isMessageChannelTurn } from '../message-channel-origin.js';
9
+ import { prepareChannelOutput, readChannelDeliveryImage, channelImageFailure } from '../channel-output.js';
6
10
 
7
11
  const digest = (value) => createHash('sha256').update(value).digest('hex');
8
- const messageID = (account, peer, id) => `weixin:${digest(JSON.stringify([account, peer, id]))}`;
9
- const chunks = (text) => {
10
- const chars = Array.from(text);
11
- const result = [];
12
- for (let index = 0; index < chars.length; index += 3500) result.push(chars.slice(index, index + 3500).join(''));
13
- return result;
14
- };
15
12
  const feedback = (language, kind) => {
16
13
  const messages = language.startsWith('zh') ? {
17
14
  interrupted: 'Yuri 主机已重启,上一条请求可能未完成。请先检查任务状态,再决定是否重试。',
18
15
  failed: '助理未能完成这条请求,请在 Yuri 中查看具体错误后重试。',
19
- textOnly: '当前微信通道仅支持文字,请发送文字消息。',
16
+ empty: '这条微信消息没有可读取的内容,请重发文字、图片或文章链接。',
20
17
  } : {
21
18
  interrupted: 'The Yuri host restarted. The previous request may be incomplete. Check its status before retrying.',
22
19
  failed: 'The bot could not complete this request. Check the error in Yuri before retrying.',
23
- textOnly: 'This WeChat connection currently accepts text messages only. Please send a text message.',
20
+ empty: 'This WeChat message has no readable content. Please resend text, an image, or an article link.',
24
21
  };
25
22
  return messages[kind];
26
23
  };
@@ -45,12 +42,12 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
45
42
  const logins = new Map();
46
43
  const receivers = new Map();
47
44
  const bindingWork = new Map();
45
+ const inboundWork = new Map();
48
46
  const operations = new Set();
49
47
  const recovered = new Set();
50
48
  const retiring = new Set();
51
49
  const lifetime = new AbortController();
52
50
  let closed = false;
53
- let ticking = false;
54
51
  let ownsLease = false;
55
52
  let closePromise;
56
53
  const track = (promise) => {
@@ -85,29 +82,32 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
85
82
 
86
83
  const receive = async (initial, signal) => {
87
84
  let failures = 0;
85
+ let messages = [];
86
+ const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(initial) ? store.get(initial.assistant_id) : null });
87
+ await adapter.initialize({ processMessage: async (_adapter, _threadID, message) => { messages.push(adapter.receipt(message)); } });
88
88
  while (!signal.aborted && isCurrent(initial)) {
89
89
  const binding = store.get(initial.assistant_id);
90
90
  if (!binding || binding.status === 'expired') return;
91
91
  if (store.backlog(binding.epoch) >= 100) { await pause(2000, signal); continue; }
92
92
  try {
93
- const response = await api.getUpdates(binding, signal);
93
+ const response = await adapter.poll(signal);
94
94
  if (signal.aborted || !isCurrent(binding)) return;
95
95
  if (store.get(binding.assistant_id)?.status === 'expired') return;
96
96
  const incoming = response.msgs ?? [];
97
97
  const cursor = response.get_updates_buf ?? binding.cursor;
98
98
  if (!Array.isArray(incoming) || incoming.length > 500 || typeof cursor !== 'string'
99
99
  || cursor.length > 512_000) throw new WeixinError('invalid_response');
100
- const messages = [];
100
+ messages = [];
101
101
  for (const msg of incoming) {
102
102
  if (!msg || typeof msg !== 'object') continue;
103
103
  // The QR-confirmed owner is the only principal allowed to execute tools.
104
104
  if (msg.message_type !== 1 || msg.from_user_id !== binding.peer_id || msg.group_id) continue;
105
- if (typeof msg.message_id !== 'string' || !msg.message_id || msg.message_id.length > 256) continue;
106
- const text = Array.isArray(msg.item_list) ? msg.item_list.filter((item) => item?.type === 1)
107
- .map((item) => typeof item.text_item?.text === 'string' ? item.text_item.text : '').join('\n').trim() : '';
108
- const context = typeof msg.context_token === 'string' && msg.context_token.length <= 65_536 ? msg.context_token : '';
109
- messages.push({ id: messageID(binding.account_id, binding.peer_id, msg.message_id), text: text.length <= 20_000 ? text : '', context });
105
+ const platformID = typeof msg.message_id === 'string' && msg.message_id ? msg.message_id
106
+ : Array.isArray(msg.item_list) ? msg.item_list.find((item) => typeof item?.msg_id === 'string' && item.msg_id)?.msg_id : '';
107
+ if (!platformID || platformID.length > 256) continue;
108
+ await adapter.dispatch(msg);
110
109
  }
110
+ if (signal.aborted || !isCurrent(binding)) return;
111
111
  // Persist receipt and context before acknowledging the platform cursor.
112
112
  store.accept(binding, cursor || binding.cursor, messages);
113
113
  if (messages.some((message) => message.context)) store.unblock(binding.epoch);
@@ -127,39 +127,28 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
127
127
  }
128
128
  };
129
129
 
130
- const processBinding = async (binding) => {
131
- if (!isCurrent(binding)) return;
132
- let page;
133
- try { page = service.channelPage(binding.assistant_id, { afterOrdinal: binding.ordinal, generation: binding.generation }); }
134
- catch (error) {
135
- if (error?.code === 'not_found') { await forget(binding.assistant_id); return; }
136
- throw error;
137
- }
138
- if (binding.status === 'expired') return;
139
- const deliveries = page.messages.flatMap((message) => {
140
- const text = message.status === 'error' ? feedback(binding.language, 'failed')
141
- : message.text?.trim() && !message.text.trim().startsWith('oc.settle.') ? message.text.trim()
142
- : message.cards.map((card) => card.title || card.name || '').filter(Boolean).join('\n');
143
- return chunks(text).map((chunk, index) => ({
144
- id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, text: chunk,
145
- }));
146
- });
147
- store.collect(binding, page, deliveries);
148
-
130
+ const processIncoming = async (binding, generation) => {
149
131
  for (const receipt of store.pending(binding.epoch)) {
150
132
  if (!isCurrent(binding)) return;
151
- if (!receipt.text) {
152
- store.enqueue(binding.epoch, `${receipt.id}:text-only`, feedback(binding.language, 'textOnly'));
133
+ if (!receipt.text && !receipt.payload) {
134
+ store.enqueue(binding.epoch, `${receipt.id}:empty`, feedback(binding.language, 'empty'));
153
135
  store.finishTurn(receipt.id);
154
136
  continue;
155
137
  }
156
- // Fence the crash gap. Never replay admitted tool side effects on restart.
157
- store.markInbox(receipt.id, 'admitted');
158
138
  try {
139
+ const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
140
+ const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
141
+ const assertCurrent = () => {
142
+ if (!isCurrent(binding) || signal.aborted || store.get(binding.assistant_id)?.status === 'expired'
143
+ || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== generation) throw new WeixinError('cancelled');
144
+ };
145
+ const parts = await prepareWeixinInput(receipt, { api, service, assistantID: binding.assistant_id, signal, assertCurrent });
159
146
  await refreshAllowedRoots();
160
- if (!isCurrent(binding)) return;
147
+ assertCurrent();
148
+ // Fence the crash gap. Never replay admitted tool side effects on restart.
149
+ store.markInbox(receipt.id, 'admitted');
161
150
  const result = await service.send(binding.assistant_id, {
162
- messageID: receipt.id, parts: [{ type: 'text', text: receipt.text }], language: binding.language,
151
+ messageID: receipt.id, parts, language: binding.language,
163
152
  });
164
153
  if (isCurrent(binding) && result.replayed) {
165
154
  store.enqueue(binding.epoch, `${receipt.id}:interrupted`, feedback(binding.language, 'interrupted'));
@@ -171,6 +160,40 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
171
160
  store.finishTurn(receipt.id);
172
161
  }
173
162
  }
163
+ };
164
+
165
+ const processBinding = async (binding) => {
166
+ if (!isCurrent(binding)) return;
167
+ let page;
168
+ try { page = service.channelPage(binding.assistant_id, { afterOrdinal: binding.ordinal, generation: binding.generation }); }
169
+ catch (error) {
170
+ if (error?.code === 'not_found') { await forget(binding.assistant_id); return; }
171
+ throw error;
172
+ }
173
+ if (binding.status === 'expired') return;
174
+ const deliveries = [];
175
+ const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
176
+ const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
177
+ const assertCurrent = () => {
178
+ if (!isCurrent(binding) || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== page.generation) throw new WeixinError('cancelled');
179
+ };
180
+ for (const message of page.messages) {
181
+ if (isMessageChannelTurn(message.turnID) && !store.hasReceipt(message.turnID, binding.epoch)) continue;
182
+ const output = await prepareChannelOutput(message, { service, assistantID: binding.assistant_id,
183
+ generation: page.generation, language: binding.language, failureText: feedback(binding.language, 'failed'), signal, assertCurrent });
184
+ deliveries.push(...output.map((part, index) => ({
185
+ id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, ...part,
186
+ })));
187
+ }
188
+ assertCurrent();
189
+ store.collect(binding, page, deliveries);
190
+ if (!inboundWork.has(binding.assistant_id)) {
191
+ const work = track(processIncoming(binding, page.generation)).catch((error) => setError(binding, error));
192
+ inboundWork.set(binding.assistant_id, work);
193
+ void work.finally(() => {
194
+ if (inboundWork.get(binding.assistant_id) === work) inboundWork.delete(binding.assistant_id);
195
+ }).catch(() => {});
196
+ }
174
197
  const current = store.get(binding.assistant_id);
175
198
  if (!isCurrent(binding) || current.status === 'expired' || !current.context_token) return;
176
199
  const delivery = store.nextDelivery(binding.epoch);
@@ -178,10 +201,18 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
178
201
  store.markDelivery(delivery.id, 'sending');
179
202
  try {
180
203
  const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
181
- await api.sendText(current, delivery, receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal);
204
+ const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(binding) ? store.get(binding.assistant_id) : null });
205
+ const threadID = await adapter.openDM(current.peer_id);
206
+ const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
207
+ const image = await readChannelDeliveryImage(service, binding.assistant_id, delivery.image ? JSON.parse(delivery.image) : null, signal);
208
+ assertCurrent();
209
+ signal.throwIfAborted();
210
+ await adapter.postMessage(threadID, image ? { raw: '', files: [{ data: image.buffer, mimeType: image.mime, filename: image.filename }] } : delivery.text,
211
+ { id: delivery.id, signal, beforeSend: assertCurrent });
182
212
  if (!isCurrent(binding) && !(retiring.has(binding.assistant_id) && canControl(binding))) return;
183
213
  store.sent(delivery.id);
184
- store.patch(binding.epoch, { error: null, updated_at: clock() });
214
+ store.patch(binding.epoch, { error: store.hasUnknown(binding.epoch) ? 'delivery_unknown'
215
+ : store.hasBlocked(binding.epoch) ? 'reply_unavailable' : null, updated_at: clock() });
185
216
  } catch (error) {
186
217
  if (!isCurrent(binding)) {
187
218
  if (retiring.has(binding.assistant_id) && canControl(binding)) {
@@ -195,6 +226,9 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
195
226
  }
196
227
  // Network ambiguity is user-retryable, not an automatic duplicate reply.
197
228
  store.markDelivery(delivery.id, error?.ambiguous ? 'unknown' : 'blocked');
229
+ if (delivery.image && !error?.ambiguous) {
230
+ store.enqueue(binding.epoch, `${delivery.id}:image-failed`, channelImageFailure(binding.language));
231
+ }
198
232
  setError(binding, error?.ambiguous ? new WeixinError('delivery_unknown') : error);
199
233
  }
200
234
  };
@@ -209,36 +243,33 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
209
243
  void track(typing.clear());
210
244
  return;
211
245
  }
212
- if (ticking) return;
213
- ticking = true;
214
- try {
215
- const bindings = store.list();
216
- const ids = new Set(bindings.map((binding) => binding.assistant_id));
217
- for (const id of receivers.keys()) if (!ids.has(id)) stopReceiver(id);
218
- for (const binding of bindings) {
219
- if (!recovered.has(binding.epoch)) {
220
- store.recover(binding.epoch, feedback(binding.language, 'interrupted'));
221
- if (store.hasUnknown(binding.epoch)) store.patch(binding.epoch, { error: 'delivery_unknown' });
222
- recovered.add(binding.epoch);
223
- }
224
- if (binding.status !== 'expired' && !retiring.has(binding.assistant_id) && !receivers.has(binding.assistant_id)) {
225
- const controller = new AbortController();
226
- const entry = { controller };
227
- receivers.set(binding.assistant_id, entry);
228
- entry.done = track(receive(binding, controller.signal)).finally(() => {
229
- if (receivers.get(binding.assistant_id) === entry) receivers.delete(binding.assistant_id);
230
- }).catch(() => {});
231
- }
246
+ const bindings = store.list();
247
+ const ids = new Set(bindings.map((binding) => binding.assistant_id));
248
+ for (const id of receivers.keys()) if (!ids.has(id)) stopReceiver(id);
249
+ for (const binding of bindings) {
250
+ if (!recovered.has(binding.epoch)) {
251
+ store.recover(binding.epoch, feedback(binding.language, 'interrupted'));
252
+ if (store.hasUnknown(binding.epoch)) store.patch(binding.epoch, { error: 'delivery_unknown' });
253
+ recovered.add(binding.epoch);
232
254
  }
233
- // One slow Bot cannot prevent another account receiving or replying.
234
- await Promise.allSettled(bindings.map((binding) => {
235
- const work = processBinding(binding).catch((error) => setError(binding, error));
236
- bindingWork.set(binding.assistant_id, work);
237
- return work.finally(() => {
238
- if (bindingWork.get(binding.assistant_id) === work) bindingWork.delete(binding.assistant_id);
239
- });
240
- }));
241
- } finally { ticking = false; }
255
+ if (binding.status !== 'expired' && !retiring.has(binding.assistant_id) && !receivers.has(binding.assistant_id)) {
256
+ const controller = new AbortController();
257
+ const entry = { controller };
258
+ receivers.set(binding.assistant_id, entry);
259
+ entry.done = track(receive(binding, controller.signal)).finally(() => {
260
+ if (receivers.get(binding.assistant_id) === entry) receivers.delete(binding.assistant_id);
261
+ }).catch(() => {});
262
+ }
263
+ }
264
+ // One slow Bot cannot prevent another account receiving or replying.
265
+ await Promise.allSettled(bindings.map((binding) => {
266
+ if (bindingWork.has(binding.assistant_id) || retiring.has(binding.assistant_id)) return;
267
+ const work = processBinding(binding).catch((error) => setError(binding, error));
268
+ bindingWork.set(binding.assistant_id, work);
269
+ return work.finally(() => {
270
+ if (bindingWork.get(binding.assistant_id) === work) bindingWork.delete(binding.assistant_id);
271
+ });
272
+ }));
242
273
  };
243
274
 
244
275
  const status = (assistantID) => {
@@ -369,7 +400,7 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
369
400
  logins.get(assistantID)?.controller.abort();
370
401
  logins.delete(assistantID);
371
402
  try {
372
- await Promise.allSettled([stopReceiver(sourceAssistantID), bindingWork.get(sourceAssistantID), typing.forget(sourceAssistantID)]);
403
+ await Promise.allSettled([stopReceiver(sourceAssistantID), bindingWork.get(sourceAssistantID), inboundWork.get(sourceAssistantID), typing.forget(sourceAssistantID)]);
373
404
  assertOwner();
374
405
  // Revalidate after draining: deletion or a stale confirmation must not move credentials.
375
406
  service.channelPage(sourceAssistantID, { tipOnly: true });