@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
@@ -18,11 +18,57 @@ the pinned list. Existing snapshot events distribute confirmed changes to client
18
18
 
19
19
  ## WeChat message channel
20
20
 
21
- Each saved Bot has a Host-owned, QR-authorized text channel configured in the final
21
+ Message channel configuration is shared: WeChat, WeCom, Feishu and DingTalk use
22
+ four colored entries in a 2×2 grid at the bottom of each saved Bot's settings,
23
+ with configuration mounted only inside its dialog. Platform messaging follows
24
+ Chat SDK's Adapter interface: vendor/community adapters are reused where suitable;
25
+ personal-WeChat and DingTalk implement extensions. Yuri remains authoritative for
26
+ Bot permissions, durable receipts, output and lifecycle, not a second Chat bot engine.
27
+ See `channels/DOCUMENTATION.md` for enterprise configuration and SDK integration.
28
+
29
+ Published image output is shared by all four channels through `channel-output.js`.
30
+ It extracts actual Markdown images (including reference images) and image file
31
+ parts, not ordinary links, code examples or tool traces, preserving prose/image
32
+ order. `service.prepareChannelImage()` snapshots bytes into the existing private
33
+ contact-attachment store before the channel advances its feed. Stable upload IDs
34
+ are scoped to Bot, transcript generation, message and output position; replay
35
+ reuses the snapshot without rereading the original. The internal `channel-image.js`
36
+ loader accepts owned attachments, raster data URLs, canonical paths in the Bot cwd,
37
+ registered roots or OS temp directory, and public HTTPS images. Remote reads pin
38
+ validated DNS addresses, reject private/reserved addresses and redirects, never
39
+ forward Host credentials, and have a 20-second/20-MiB bound. SVG/HTML are rejected.
40
+ There are at most eight images and 50 MiB of image delivery per published message.
41
+ Outboxes persist opaque attachment descriptors, never image bytes or source paths;
42
+ sent rows clear them. Each image is a separate delivery with its own stable ID,
43
+ retry/uncertainty state and original recipient. Failed preparation produces a safe
44
+ text notice without dropping adjacent output. Reset, disconnect, transfer and
45
+ shutdown fence late preparation; adapters recheck authority after uploading and
46
+ before submitting the message. This does not recall already submitted messages.
47
+ All Host surfaces (web, Electron, hosted/native mobile) reuse this backend path;
48
+ standalone VS Code still has no Host-owned channel service.
49
+ Yuri's built-in IM is itself a source channel. `channelPage()` excludes replies
50
+ whose persisted `turnID` identifies this Bot's admitted user message without an
51
+ external channel receipt prefix. This covers streamed, final and error replies,
52
+ while keeping them in the Yuri transcript. The feed cursor still advances over
53
+ excluded rows. Routing uses the original admission, never the latest user message;
54
+ existing stored transcripts need no migration. External-channel turns retain their
55
+ receipt-owned routing, and source-less proactive turns such as scheduled-task
56
+ result reviews remain eligible for delivery to all bound channels.
57
+ Internal card parts (`session`, `assistant`, `schedule` and future card types) are
58
+ unsupported channel output and silently skipped by the shared projector. They are
59
+ not downgraded to titles, anchors or deeplinks, do not enter the outbox and do not
60
+ produce an unsupported/error notice or retry. The feed watermark still advances;
61
+ adjacent text/images continue normally. Cards remain in the Yuri transcript/UI.
62
+
63
+ Each saved Bot has a Host-owned, QR-authorized message channel configured in the final
22
64
  **Message channels** settings group. It admits only the QR-confirmed owner through
23
65
  the existing `send()` pipeline and reads committed public replies through the internal
24
66
  `channelPage()` feed. Bindings, private credentials, durable receipts/outbox and
25
67
  process leases are owned by `weixin/`, not ordinary Session delivery or UI state.
68
+ Rich input reuses contact attachments for images/files and untranscribed audio/video;
69
+ platform voice transcripts and bounded unknown share fields reach the model as
70
+ user content, with structured metadata encoded as TOON. Receiving an article link
71
+ does not imply that its body was fetched. See the channel documentation for limits.
26
72
  See `weixin/DOCUMENTATION.md` for authorization, shared-context/output semantics,
27
73
  restart ambiguity, local disconnect and the explicit platform-verification limits.
28
74
  An existing local WeChat connection can be moved to an unbound Bot only through
@@ -84,6 +130,11 @@ not become list previews, unread counts, or LLM memory. If error persistence its
84
130
  fails, the service emits a body-free warning and still settles activity and sends
85
131
  live failure feedback; that failure cannot be recovered after reconnect.
86
132
  Worker-card execution status remains part of the card's authoritative state.
133
+ Descriptive channel text such as TOON's "WeChat message data" or "Channel message
134
+ metadata" is not an imperative peer-message request. The missed-tool hint only
135
+ matches explicit English message/tell clauses, so a completed session assignment
136
+ is not retried or marked failed because of those labels. Channel delivery failures
137
+ remain in each channel's outbox and never rewrite a worker's execution status.
87
138
 
88
139
  ## Contact attachment chronology
89
140
 
@@ -454,7 +505,8 @@ and keep their existing error result handling.
454
505
  - Public progress uses the harness-owned `notify_user` tool `{ text }` (max 2,000 characters), usually batched with the next call. Its text emits `done:true` bubbles when the response arrives, before the batch executes. Batched notes are dropped from execution and stored as the assistant message's public text (`contactPublicText`); a notes-only response executes and the loop continues. Text beside tool calls is model narration and stays private. Later rounds replay delivered notes to the model as `notify_user` calls.
455
506
  - The model is prompted to send a progress message only when it adds information the user does not already have (a direction worth correcting, a meaningful finding, a blocker, or expected long work), then give a short final outcome. A message is not required before each tool call, and successful lookups need no separate confirmation. Public messages share the existing SSE, durable contact rows, and turn-global indices across web, desktop, VS Code, hosted mobile, and Capacitor. No timer narration, tool logs, progress widgets, or synthetic chat messages are added. Timing of model-authored milestones remains model policy; the transport guarantees immediate delivery once an explicit public record arrives.
456
507
  - Completion notifications use the latest spoken message, keeping earlier progress out of the final notification body. Transcript persistence reconciles by stable bubble IDs and adds only remaining messages.
457
- - Tool results remain model context for every tool. The outcome projector uses assistant-authored text only. Terminal operations retain the mutation stop gate, followed by a tools-disabled completion on the same provider/model to communicate the actual result. A failed/empty summary surfaces a turn error; a completed side effect stays committed and is never replayed by that summary pass.
508
+ - Tool results remain model context for every tool. The outcome projector uses assistant-authored text only. Terminal operations retain the mutation stop gate. Successful interactive assign/watch gets a result-only Agent on the same provider/model with **only** `reference_resource`, followed by a final reply; no coding, loader or business mutation tool is available. Other terminal operations, failures and resets retain their tools-disabled summary. A failed/empty summary surfaces a turn error; a completed side effect stays committed and is never replayed by the result phase.
509
+ - Tools-disabled summaries project actual completed tool results into labeled, quoted user-role evidence (tool name, error flag and public text only), removing native call/result framing. Some providers reject historical native calls when their tool definitions are absent. The reference-only phase and ordinary Agent rounds retain native call/result association; no execution or permission fallback is introduced. Reset summaries still receive only the current user request and the successful reset result.
458
510
  - Reset summaries receive only the successful reset tool result, excluding prior messages and attachments. The service retains one model-generated confirmation and discards pre-reset output for that turn. Failures emit recoverable error feedback outside assistant speech bubbles, retained until the next contact message update.
459
511
 
460
512
  - Protocol correction never replays rejected assistant prose into model history: simulated User/Assistant turns and tool-result records are rejected as fabricated evidence. Corrections remain bounded and exhaustion is an error, not a completion.
@@ -470,23 +522,29 @@ and keep their existing error result handling.
470
522
 
471
523
  - First-class contact parts reuse one slot: `cardType` `session` | `assistant` | `schedule`.
472
524
  - Persist in `assistant_contact_message` / `assistant_contact_part`. Survive reload.
473
- - Schedule create/update auto-cards persist the authoritative schedule's optional `cron`, `date`, `times`, and `weekdays`, not just a `time`/first-time projection. The card parser and UI DTO retain these fields through JSON persistence and transport. Omitted legacy fields stay omitted; explicit null marks an inapplicable field on new cards. This is additive contact-part JSON, with no SQLite migration or task rewrite. Clients may recover legacy display details through the existing Assistant-scoped task mapping, matching `(projectID, taskID)`; failed/deleted task lookups do not erase stored card information.
474
- - Cards are **assistant-emitted UI**, not user slash commands. The user never types `/card`. Insert: tool auto-cards (`assign_session`, `watch_session`, `create_assistant`, `schedule_task`), and API `POST /:id/contact/cards` for harness/tests. Later project/worktree/PR, inbound pushes, and summon **must** reuse this card slot.
525
+ - `reference_resource` is an always-mounted **interactive assistant-only** tool. It takes `cardType: session` + `sessionID`, `assistant` + `assistantID`, or `schedule` + `projectID`/`taskID`. Exact IDs come from lookups, current creation/update results or existing references; the model cannot supply titles, directories, card payloads or URLs. Session references reuse authoritative resolution and registered-root checks, Bot references read live contacts, and task references load the exact registered project's current task configuration. Missing/deleted/forbidden/unavailable resources fail without fabricating a card.
526
+ - Session references also tolerate a redundant, well-formed `projectID` from lookup context. It is discarded before resolution and is never lookup authority or part of the session card identity; the real session directory and registered-project boundary still come only from the Host. Other resource IDs and card-content fields remain rejected for session references.
527
+ - Querying and resource mutation do **not** publish cards. `assign_session`, `watch_session`, `create_assistant`, `schedule_task` and `update_scheduled_task` return model-visible resource IDs and guidance to call `reference_resource`. Prompt policy encourages relevant cards after lookup/explanation and successful creation/update, unless unwanted; there is no forced auto-card fallback. Only successful explicit reference results contribute cards to the harness outcome.
528
+ - `reference_resource` awaits SQLite publication before returning public tool text `{ sent: true, card }` to the model. Persistence failure is an actual tool error with `sent:false`; a created resource stays valid and must not be recreated. The connected Host's ordinary contact snapshot/revision transport delivers the same persisted part to web, Electron, hosted mobile and Capacitor. This acknowledges publication in Yuri, not delivery to an external messaging channel; internal card parts retain the channel-output exclusion above. Standalone VS Code does not gain an assistant Host. No client DTO, HTTP route, tool registration in ordinary Sessions, or schema migration is added.
529
+ - Same-turn references to the same identity reuse the first successfully published card and return that snapshot. Failed publication does not claim a slot and can be retried. Cancellation and a removed turn/transcript fence late publication. Session references never create/rearm watches, prompt workers or change notification policy. Existing card history and completion receipts remain readable.
530
+ - Schedule references persist the authoritative schedule's optional `cron`, `date`, `times`, and `weekdays`, not just a `time`/first-time projection. The card parser and UI DTO retain these fields through JSON persistence and transport. Omitted legacy fields stay omitted; explicit null marks an inapplicable field on new cards. This is additive contact-part JSON, with no SQLite migration or task rewrite. Clients may recover legacy display details through the existing Assistant-scoped task mapping, matching `(projectID, taskID)`; failed/deleted task lookups do not erase stored card information.
531
+ - Cards are **assistant-emitted UI**, not user slash commands. The user never types `/card`. Interactive insertion uses `reference_resource`; the existing API `POST /:id/contact/cards` remains for harness/tests with its legacy session-watch admission behavior. Later project/worktree/PR, inbound pushes, and summon **must** reuse this card slot.
532
+ - `resource-reference.integration.test.js` runs the real Agent, service and SQLite with only model/upstream results replaced: lookup → read → explicit reference, create → reference, reference-only handoff result phase, complete schedule fields, persisted acknowledgements/restart, publication rollback/retry/deduplication, scope failures and no watch rearm. The project HTTP test additionally covers route admission → handoff → explicit reference. These are deterministic contract checks, not live-model decision quality or device UI/channel-delivery evidence.
475
533
 
476
534
  **Assign work (this PR)**
477
535
 
478
536
  - `assign_session` is an Yuri AgentTool on the contact harness. It creates or reuses a visible OpenCode/Yuri session on a **registered project path** (Settings projects / `getAllowedRoots()`), optionally an **existing** Chat worktree/branch via `getWorktrees`, then kicks the coding prompt into that session with `session.create` + `session.prompt` (same worker path as `POST /api/yuri/conversations`).
479
537
  - That worker session owns substantive implementation. The contact owns communication and coordination, with direct pi tools for small, bounded tasks. Assign sessions are **not** archived Assistant bindings and must not use `assistant-workspaces`.
480
538
  - **Reuse / continue existing session:** `assign_session` with `sessionID` + coding prompt continues that worker. Before prompt, the service resolves directory/project from **authoritative** session metadata (session index directory → `session.get` payload → registered project match). User-supplied `projectPath`/`directory` are lookup **hints only** and never override scope. Missing/unregistered/failed session lookup **fails closed** (not empty success). Prior worker model/config semantics stay: omit model args to follow the session model when still connected.
481
- - **`watch_session`:** listen-only attach for an existing session (`sessionID` required). No `session.prompt`. Emits the same session card slot and reuses `assistant_contact_watch` + `reportAssignedSession` / reconcile / resume. Baseline card/watch status comes from live `session.get` (+ messages when needed) via `mapSessionToWatchStatus` so an already-terminal idle is **not** treated as a fresh complete transition (no false resume). In-flight baseline (`busy`/`question`) keeps the watch until real settle. A plain user `@session:id` (or JSON title/sessionID/directory) reference is **context only** — it does not auto-call `watch_session`; the model must hear an explicit listen/watch/monitor intent.
539
+ - **`watch_session`:** listen-only attach for an existing session (`sessionID` required). No `session.prompt`. Registers `assistant_contact_watch` directly and reuses `reportAssignedSession` / reconcile / resume, independently of whether a reference card is sent. Baseline watch status comes from live `session.get` (+ messages when needed) via `mapSessionToWatchStatus` so an already-terminal idle is **not** treated as a fresh complete transition (no false resume). In-flight baseline (`busy`/`question`) keeps the watch until real settle. A plain user `@session:id` (or JSON title/sessionID/directory) reference is **context only** — it does not auto-call `watch_session`; the model must hear an explicit listen/watch/monitor intent.
482
540
  - **`stop_session`:** calls real OpenCode `session.interrupt` for `sessionID` after the same authoritative directory resolve. Returns the true abort result — transport/`not_found`/upstream errors stay errors (never claim stopped on failure). Abort is registered in a private per-session inflight map before `await abort` so concurrent SSE `complete`/`error` cannot schedule a `resume=true` continuation ahead of `resume=false`. On successful abort the service marks the watch/card `cancelled` even when upstream emits no idle/error event. Idle/error events still flow through the existing watch reporter when a watch exists.
483
541
  - **Worker model selection:** optional tool args `providerID` / `modelID` / `model` resolve against the live connected OpenCode catalog (`loadConnectedCatalog` / `GET /provider` + `GET /config/providers`). Explicit selection must match uniquely — missing or ambiguous names fail closed (`model_not_found` / `model_ambiguous`) with **no silent fallback**. Omitting model args on a **new** worker keeps the contact assistant's default provider/model. **Reusing `sessionID` without an explicit model** follows that session's last model (`session.get` → `session.model` `{ providerID, id|modelID }`, else newest user/assistant `info.model`) when it is still an exact providerID+modelID match in the connected catalog (`source: 'session'`); missing session model, catalog miss, or lookup failure **degrades** to the assistant default (`source: 'assistant'`) and never fails assign once the session itself resolved. Selecting a worker model **never** mutates the contact assistant row.
484
542
  - The connected model catalog is **not** injected into turns. The base tool `list_models({ query? })` (absent from read-only background reviews) loads it on demand; each call reloads the current instance's **Connected OpenCode models** block (exact providerID, modelID, providerName, name, acceptsImages), plus settings-backed favorite models in saved order and recent models newest first. Only connected catalog entries qualify as preference candidates; variants remain separate from model IDs. Catalog and preference read failures remain explicit unknown states, distinct from successful empty lists; either read can succeed independently. The tool projects only favoriteModels/recentModels from the strict settings reader; defaultModel/defaultVariant are used separately for initial contact creation, never arbitrary settings or credentials. No catalog is cached across turns or runtime switches. Informal `model` aliases normalize punctuation/spacing and require a unique catalog match; explicit `modelID` stays exact. Ambiguous aliases never silently prefer a favorite/provider. This server-owned context is shared by web, desktop, and mobile clients of that instance.
485
543
  - **Current-turn attachments:** server-authoritative `userParts` file parts from this contact turn are forwarded into worker `session.prompt` parts by default (including “just open a session” intents). The model must not base64-encode or invent local paths. History images are **not** unbounded-forwarded. Image parts require a vision-capable catalog entry (`acceptsImages`); otherwise assign fails with `image_not_supported` before create. Sensitive file bodies are never logged.
486
544
  - **Create-then-prompt failure:** if `session.create` succeeds and `session.prompt` fails, assign best-effort `session.delete`s the new worker so empty sessions are not left behind. Reused `sessionID` paths never delete on prompt failure.
487
- - Successful `assign_session` and `watch_session` return `terminate: true` to stop the mutation loop. The harness then requests a tools-disabled model summary. Prerequisite tools (`list_projects` / `list_sessions`) may still run before assign/watch/stop in the same turn; multi-operation user intents remain ordered **across turns** after a successful assign/watch.
545
+ - Successful `assign_session` and `watch_session` return `terminate: true` to stop the mutation loop. The harness then runs the reference-only result phase described above (tools-disabled for background turns). Prerequisite tools (`list_projects` / `list_sessions`) may still run before assign/watch/stop in the same turn; multi-operation user intents remain ordered **across turns** after a successful assign/watch.
488
546
  - Same contact-turn assign gate (tools instance lifetime only, not cross-turn): identical args after success replay the cached success result (no second worker); different args after success, or parallel mismatched args, fail closed with a validation error. The idempotent key includes worker model selection and current-turn attachment scope. Failure clears the gate so a corrected retry may run. Parallel identical args share one in-flight promise.
489
- - After a successful assign or watch, the service persists the existing session card into the contact transcript (user bubbles first, then the card) and watches that worker session in `assistant_contact_watch` (watch baselines the live status). The user-facing outcome is the session card plus any `notify_user` progress note; English tool-result confirms (`Opened a coding session.`, `Watching that coding session.`, `Created assistant…`, `Sent to…`) for card/side-effect tools are **not** written into the transcript.
547
+ - Successful assign/watch registers that worker in `assistant_contact_watch` before returning, not during card insertion. Assignment keeps its admitted message watermark even if no card is sent or publication fails. If post-admission watch storage fails, assignment remains successful with `watchError: watch_registration_failed`; the model must report unavailable automatic follow-up without recreating the worker. Watch registration and revision commit together. Cards are separately sent by `reference_resource`, and tool evidence is never written as assistant speech.
490
548
  - Existing OpenCode SSE on the same `globalEventHub` as notifications (`session.idle`, `session.error`, `session.status`, `session.execution.*`, `question.asked`, `permission.asked`) updates **the same card** (`busy` → `complete` / `error` / `question` / `cancelled`). **No canned settle transcript bubbles** (`oc.settle.complete` / `error` / `question` are not written). On **complete, error, or cancelled (user interrupt)** when the watch status actually changed, the service schedules an async contact-lane **continuation** (`inContactTurnLane` + `runContactTurn`) per related assistant: no admitted user row (internal `userText` only), active contact turn (green dot / 3-dot), stable resume id `resume_${assistantID}_${sessionID}_${status}_${updatedAt}`, bounded last worker assistant text (~2000 chars; fetch failure still resumes with status only). Cancelled continuations include `reason: user_interrupted` so the contact can acknowledge the user's abort. The contact Agent can perform read-only lookups and summarize in the user's language, but cannot reassign or mutate a session during this notification — the user sees that Agent summary, not 「会话已完成/会话失败」. `question` updates the card only (worker waiting on the user). `stop_session` cancellation does not schedule this continuation. Session-goal settle (`emitGoalNotification`) uses the same reporter — not a second scheduler. Idle after `session.error` must not rewrite 失败 as 完成 (`changed=false` → no second resume). Same complete status re-reported is idempotent. The watch rows are read inside the `BEGIN IMMEDIATE` transition, so multiple Host processes sharing `assistants.sqlite` schedule at most one continuation per transition. The lock is SQLite's OS file lock, held only for that synchronous transaction (no awaits); a Host that exits mid-transaction releases it and its uncommitted write is discarded. Turn lanes and active-turn markers are process-local memory, so a dead Host never leaves a durable lock: whichever Host receives the next user send admits and runs it.
491
549
  - **Shutdown interrupt (ticket 07):** official `session.execution.interrupted` reason is `user | shutdown | superseded | inactivity`. **`reason: shutdown` does not settle** the watch and does **not** schedule contact resume — upstream keeps the execution claim for restart recovery. The card stays `busy` until an authoritative terminal (`session.execution.succeeded` / `failed` / user interrupt / reconcile). `reason: user` settles `cancelled` + resume. Other non-shutdown interrupts settle `error` unless `MessageAbortedError`. No parallel recovery store — the existing watch row remains the owner.
492
550
  - Restart or a missed `session.idle` cannot leave the watch stuck: boot and the existing 60s reconcile timer `listInFlightWatches` and poll OpenCode `session.get` / `message.list`. Idle or `time.completed` settles the same card (`busy` → 完成) and triggers the same contact continuation (no `oc.settle.complete` bubble). A missing session or message page remains unknown and keeps the watch in flight: another Host sharing the store may use a different OpenCode database, so 404 is not proof that the owning worker ended. Isolated HMR therefore also isolates Yuri state. `session.error` or last-assistant `info.error` settles 失败 + resume once; last-assistant `MessageAbortedError` settles `cancelled` + the interrupt notify once. Transport / get errors leave the watch in flight (failure is not empty success). One failed watch does not block unrelated watches. Reconcile reuses `reportAssignedSession`, so an error watch is never rewritten as complete. Tombstoned assistants skip resume.
@@ -496,7 +554,7 @@ and keep their existing error result handling.
496
554
  - **Completion receipt:** consuming a successful notification-enabled watch inserts one additional ordinary session-reference card in the same transaction as the old card update and release. Its stable resume-derived receipt ID is claimed once across Hosts. It does not create/rearm a watch or fabricate a text bubble, and remains available even if the model review is silent or fails. Existing UI session-summary diff presentation is reused (real non-zero changes only); parent idle alone cannot override the server's busy/retry family status. Error/cancel paths do not issue success receipts.
497
555
  - **Result context order:** `message.list(order: 'desc')` is normalized through the existing V2 projection adapter and read newest-first for bounded worker text. The callback must not take the oldest assistant progress message from the page or omit native V2 `content` text. Fetch failure remains unavailable context and the review may use `read_session`.
498
556
  - **Model watch-state synchronization:** the internal result-review input explicitly carries `watchState: released`, `watchMode: one_shot`, and `rewatchAllowed` (`false` for interruption). It tells the model that the server released the watch before this invocation, no cleanup call is needed, future rounds will not auto-notify, and earlier watching confirmations are historical. The model must not promise continued monitoring without a successful new `watch_session` call; sufficient results leave the watch released. These fields are internal context, not a new transcript bubble or client DTO.
499
- - **Explicit rewatch:** successful `watch_session` / `assign_session` card admission rearms only its `(assistantID, sessionID)` row. Listen-only watch clears an old assignment delivery watermark. A new terminal-baseline watch stays armed for the next observed running → terminal transition, without replaying the old result. Non-interrupted worker-result reviews expose one narrowly scoped exception to read-only tools: `watch_session` for that exact worker, enforced in the service callback. The contact may explicitly rewatch only when the original user request still needs monitoring; worker output is evidence, never authorization. Cancellation reviews, scheduled-task reviews, and peer-message turns retain lookup-only tools. No background review gains assignment, prompting, stop, file, shell, or settings mutation tools.
557
+ - **Explicit rewatch:** successful `watch_session` / `assign_session` admission rearms only its `(assistantID, sessionID)` row; `reference_resource` never rearms it. Listen-only watch clears an old assignment delivery watermark. A new terminal-baseline watch stays armed for the next observed running → terminal transition, without replaying the old result. Non-interrupted worker-result reviews expose one narrowly scoped exception to read-only tools: `watch_session` for that exact worker, enforced in the service callback. The contact may explicitly rewatch only when the original user request still needs monitoring; worker output is evidence, never authorization. Cancellation reviews, scheduled-task reviews, and peer-message turns retain lookup-only tools. No background review gains resource publication, assignment, prompting, stop, file, shell, or settings mutation tools.
500
558
  - `AssistantDTO.assignedSessionIDs` lists in-flight (`busy`/`question`) watches for assigned worker sessions. Session-card busy stays on the card; it does **not** drive the list green dot.
501
559
  - **Contact active turn (server authoritative):** process-local metadata tracks admission → `queued` → `running` → settled (removed). `AssistantDTO.working` is true only while that assistant has an unsettled contact turn. `AssistantDTO.activeContactTurn` is `{ turnID, messageID, status: 'queued'|'running', admittedAt }` or `null` so APP restart / reconnect can rehydrate list green dots and the contact 3-dot row from the snapshot HTTP GET. Spoken bubbles and cards persist to SQLite as soon as they publish (`done:true` / `onCard`) so another device or APP restart can GET them while the turn is still running. Token-level SSE deltas remain live paint only. A server process restart clears in-memory activity (no permanent green; tools are not auto-rerun) but already-published bubbles/cards stay in the transcript. Per-assistant lanes isolate turns across assistants/runtimes. Stale `contact-turn-end` for an older `turnID` must not clear a newer active turn.
502
560
  - **List latest-message preview (server authoritative):** every `AssistantDTO` path (`snapshot` / `create` / `update` / other `output` rows) carries `latestMessagePreview: { messageID, ordinal, createdAt, role: 'user'|'assistant', text, fallbackKind: 'image'|'file'|'session'|'assistant'|'schedule'|null } | null`. Source is the contact transcript only (not `defaultPrompt` / `updatedAt`). Order is the same keyset as contact pages: newest `(ordinal DESC, message_id DESC)`. Visible roles are `user`, `assistant`, and `peer` (peer maps to `role: 'user'` because inbound DMs are user-visible). Internal assigned-session settle markers (`oc.settle.*`) are excluded in the SQL candidate probe (and again in `buildContactMessagePreview`). Recoverable errors are excluded in SQL and the preview projector and cannot replace the preview. Plain text is sanitized and capped at `CONTACT_PREVIEW_MAX_CHARS` (500) with no data-URL/base64 bodies. File-only rows set `fallbackKind` `image`/`file`; pure cards set `session`/`assistant`/`schedule`. Empty transcript → `null`. **Snapshot cost:** one prepared statement reused per assistant (`assistant_id` + indexed `ORDER BY ordinal DESC, message_id DESC LIMIT candidateLimit`, catalog ≤100) collecting only those bounded candidates, then **one** parts `IN` query — not a window/`ROW_NUMBER` over full multi-assistant history and not HTTP N+1. SQL already drops pure settle tails so they cannot exhaust the LIMIT and hide an older real bubble; remaining non-preview empty rows may still consume a candidate slot within that same LIMIT. Admission, assistant completion, peer DM, card insert, wipe, and clear-memory already bump domain revision / `yuri:assistants-changed`; clients re-GET snapshot for the new preview. Clear-memory keeps transcript rows so the preview still reflects the last bubble; clear-history / reset remove rows so the preview becomes the wipe confirm (or `null` after a full unbounded wipe with no remaining user).
@@ -528,10 +586,10 @@ and keep their existing error result handling.
528
586
 
529
587
  Reply language follows the user's latest substantive message and conversation context, with explicit language requests taking precedence. Ambiguous messages and background follow-ups retain the conversation language. The built-in prompt and terminal-tool summary never select a response language from UI locale. Reset summaries receive the current user request as language context alongside the reset result, without restoring earlier history. Explicit `{{LANGUAGE}}` placeholders in user-authored `defaultPrompt` retain their locale substitution contract; the built-in prompt no longer uses that token.
530
588
 
531
- - `create_assistant` calls the same in-process `createAssistant` (`name`, connected OpenCode `providerID`/`modelID`, `mode: 'continuous'`). It emits an `assistant` card that opens that contact.
532
- - `schedule_task` calls in-process `projectConfigRuntime.upsertScheduledTask` with the same payload as `PUT /api/projects/:id/scheduled-tasks` (`name`, `schedule.kind/time/timezone`, `execution.prompt` + provider/model) on a registered project, then best-effort `scheduledTasksRuntime.syncProject`. It emits a `schedule` card.
589
+ - `create_assistant` calls the same in-process `createAssistant` (`name`, connected OpenCode `providerID`/`modelID`, `mode: 'continuous'`). It returns the new identity; `reference_resource` separately sends the `assistant` card that opens that contact.
590
+ - `schedule_task` calls in-process `projectConfigRuntime.upsertScheduledTask` with the same payload as `PUT /api/projects/:id/scheduled-tasks` (`name`, `schedule.kind/time/timezone`, `execution.prompt` + provider/model) on a registered project, then best-effort `scheduledTasksRuntime.syncProject`. It returns exact task/project IDs for a separate `reference_resource` call.
533
591
  - `list_scheduled_tasks` lists registered projects' tasks with exact task/project IDs, schedule, model and a bounded prompt preview. Failed project reads remain explicit partial failures. Read-only background turns may list but cannot modify tasks.
534
- - `update_scheduled_task` uses the existing project-config patch operation and scheduler sync, changing only supplied fields and validating explicit models against the connected catalog. It emits the existing schedule card; it can edit tasks created outside the Assistant.
592
+ - `update_scheduled_task` uses the existing project-config patch operation and scheduler sync, changing only supplied fields and validating explicit models against the connected catalog. It returns the task/project reference for a separate card call; it can edit tasks created outside the Assistant.
535
593
  - Native calls use tool-name validation and shell-alias normalization. `shell`, `powershell`, `grep`, `glob`, `find` and `ls` may resolve to the existing `bash` tool only when it is available. Native call IDs survive normalization. Unknown tool corrections identify the rejected name and available tools, without executing a rejected prefix. The contact harness owns bounded correction; generic completion callers retain strict tool-name validation.
536
594
  - Successful `schedule_task` also writes an assistants-owned mapping row in `assistants.sqlite` (`assistant_scheduled_task`: assistantID + projectID + taskID). Project-config execution strips unknown fields, so ownership stays out of the task payload. `GET /api/yuri/assistants/:id/scheduled-tasks` returns those mappings joined with live `listScheduledTasks` records when possible; failed project lookups keep the mapping with `task: null`.
537
595
  - `CONTACT_SYSTEM_PROMPT` + `formatContactToolsPrompt` + `formatPiCodingPrompt` tell the model to call these from natural language (开新对话 / 找项目 / 现有对话 / 查看助手设定·默认提示词 / 改默认提示词·设置人设 / 建助理 / 建会话·继续会话 / 监听会话 / 停止会话 / 排定时任务 / 给 X 说一声). Argument schemas travel only in the native tool definitions. A reply without the tool call does nothing; never say 已创建 / 已发送 / 已停止 unless the tool returned. Tool results are sent as native tool-role messages with JSON `{ isError, content }`; assistant calls keep their arguments/IDs so multi-step turns keep call/result association. The harness replaces every `{{LANGUAGE}}` token — in the built-in prompt and in `defaultPrompt` — with the UI locale sent on the composer payload (`language` field, whitelisted locale code → display name). Background/settle turns recall the last locale seen for that assistant; unknown or missing locales resolve to `the user's interface language`, so the token never leaks into the prompt.
@@ -1,6 +1,6 @@
1
1
  export const CONTACT_CARD_TYPES = Object.freeze(['session', 'assistant', 'schedule']);
2
2
  const CARD_TYPES = new Set(CONTACT_CARD_TYPES);
3
- // Assign / create_assistant / schedule_task auto-insert these cards.
3
+ // Assistant tools explicitly publish these cards through reference_resource.
4
4
  // project | worktree | watch MUST reuse this slot. Do not invent a second card system.
5
5
 
6
6
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { lookup } from 'node:dns/promises';
6
+ import { request } from 'node:https';
7
+ import { BlockList, isIP } from 'node:net';
8
+ import { collectRequestBytes, decodeDataUrlStrict, assertImageContentMatchesMime } from '../fs/prompt-attachment-store.js';
9
+
10
+ const MAX_BYTES = 20 * 1024 * 1024;
11
+ const blocked = new BlockList();
12
+ for (const [ip, prefix] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 3]]) blocked.addSubnet(ip, prefix, 'ipv4');
13
+ const globalV6 = new BlockList();
14
+ globalV6.addSubnet('2000::', 3, 'ipv6');
15
+ blocked.addSubnet('2001::', 23, 'ipv6');
16
+ blocked.addSubnet('2001:db8::', 32, 'ipv6');
17
+ blocked.addSubnet('2002::', 16, 'ipv6');
18
+
19
+ const fail = () => { throw Object.assign(new Error('image_unavailable'), { code: 'image_unavailable' }); };
20
+ const within = (root, value) => value === root || value.startsWith(`${root}${path.sep}`);
21
+
22
+ /** HTTPS only, pinned public DNS, no redirects, cookies, auth forwarding or proxy. */
23
+ async function download(url, signal) {
24
+ const target = new URL(url);
25
+ if (target.protocol !== 'https:' || target.port || target.username || target.password || target.hash) fail();
26
+ const host = target.hostname.replace(/^\[|\]$/g, '');
27
+ const addresses = isIP(host) ? [{ address: host, family: isIP(host) }] : await lookup(host, { all: true });
28
+ if (!addresses.length || addresses.some(({ address, family }) => family === 6
29
+ ? !globalV6.check(address, 'ipv6') || blocked.check(address, 'ipv6')
30
+ : blocked.check(address, 'ipv4'))) fail();
31
+ signal.throwIfAborted();
32
+ const pinned = addresses[0];
33
+ return new Promise((resolve, reject) => {
34
+ const req = request(target, { signal, lookup: (_host, options, callback) => options?.all
35
+ ? callback(null, [pinned]) : callback(null, pinned.address, pinned.family) }, async (response) => {
36
+ try {
37
+ if (response.statusCode !== 200 || Number(response.headers['content-length']) > MAX_BYTES) {
38
+ response.destroy();
39
+ fail();
40
+ }
41
+ const { buffer } = await collectRequestBytes(response, { maxBytes: MAX_BYTES, signal });
42
+ resolve(buffer);
43
+ } catch (error) { response.destroy(); reject(error); }
44
+ });
45
+ req.on('error', reject);
46
+ req.end();
47
+ });
48
+ }
49
+
50
+ function imageMime(buffer) {
51
+ if (buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png';
52
+ if (buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return 'image/jpeg';
53
+ if (/^GIF8[79]a$/.test(buffer.subarray(0, 6).toString())) return 'image/gif';
54
+ if (buffer.subarray(0, 4).toString() === 'RIFF' && buffer.subarray(8, 12).toString() === 'WEBP') return 'image/webp';
55
+ if (buffer.subarray(0, 2).toString() === 'BM') return 'image/bmp';
56
+ fail();
57
+ }
58
+
59
+ /** Local authority is the Bot cwd, registered projects and generator temp files. */
60
+ export async function loadChannelImage(source, { cwd, allowedRoots, signal, readAttachment }) {
61
+ const deadline = AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(20_000)]);
62
+ deadline.throwIfAborted();
63
+ let buffer;
64
+ if (source.attachmentID) {
65
+ ({ buffer } = await readAttachment(source.attachmentID));
66
+ } else if (typeof source.url !== 'string' || source.url.length > MAX_BYTES * 1.4) {
67
+ fail();
68
+ } else if (source.url.startsWith('data:')) {
69
+ ({ buffer } = decodeDataUrlStrict(source.url, { maxBytes: MAX_BYTES }));
70
+ } else if (/^https?:/i.test(source.url)) {
71
+ buffer = await download(source.url, deadline);
72
+ } else {
73
+ let candidate = source.url;
74
+ if (candidate.startsWith('file:')) candidate = fileURLToPath(candidate);
75
+ else if ((!path.isAbsolute(candidate) && /^[a-z][a-z0-9+.-]*:/i.test(candidate)) || candidate.startsWith('//') || candidate.startsWith('\\\\')) fail();
76
+ if (candidate.startsWith('~/')) candidate = path.join(os.homedir(), candidate.slice(2));
77
+ const resolved = await fs.realpath(path.resolve(cwd, candidate));
78
+ const roots = await Promise.all([cwd, ...allowedRoots, os.tmpdir()].map((root) => fs.realpath(root).catch(() => null)));
79
+ if (!roots.some((root) => root && within(root, resolved))) fail();
80
+ const handle = await fs.open(resolved, 'r');
81
+ try {
82
+ const stat = await handle.stat();
83
+ if (!stat.isFile() || stat.size > MAX_BYTES) fail();
84
+ ({ buffer } = await collectRequestBytes(handle.createReadStream({ autoClose: false }), { maxBytes: MAX_BYTES, signal: deadline }));
85
+ } finally { await handle.close(); }
86
+ }
87
+ deadline.throwIfAborted();
88
+ if (!buffer?.length || buffer.length > MAX_BYTES) fail();
89
+ const mime = imageMime(buffer);
90
+ assertImageContentMatchesMime(buffer, mime);
91
+ return { buffer, mime, filename: `image.${mime === 'image/jpeg' ? 'jpg' : mime.slice(6)}` };
92
+ }
@@ -0,0 +1,76 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { Readable } from 'node:stream';
3
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ const io = vi.hoisted(() => ({ lookup: vi.fn(), request: vi.fn() }));
6
+ vi.mock('node:dns/promises', () => ({ lookup: io.lookup }));
7
+ vi.mock('node:https', () => ({ request: io.request }));
8
+ import { loadChannelImage } from './channel-image.js';
9
+
10
+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aKxkAAAAASUVORK5CYII=', 'base64');
11
+ const source = { url: 'https://images.example.com/generated.png?signature=image-capability' };
12
+ const input = { cwd: process.cwd(), allowedRoots: [] };
13
+ beforeEach(() => {
14
+ vi.resetAllMocks();
15
+ io.lookup.mockResolvedValue([{ address: '8.8.8.8', family: 4 }]);
16
+ io.request.mockImplementation((_url, _options, callback) => {
17
+ const request = new EventEmitter();
18
+ request.end = () => {
19
+ const response = Readable.from([png]);
20
+ response.statusCode = 200;
21
+ response.headers = {};
22
+ callback(response);
23
+ };
24
+ return request;
25
+ });
26
+ });
27
+
28
+ describe('public HTTPS image boundary', () => {
29
+ it('pins the validated DNS answer instead of looking it up again at connection time', async () => {
30
+ expect(await loadChannelImage(source, input)).toMatchObject({ buffer: png, mime: 'image/png' });
31
+ expect(io.lookup).toHaveBeenCalledOnce();
32
+ const [url, options] = io.request.mock.calls[0];
33
+ expect(url.hostname).toBe('images.example.com');
34
+ expect(options.headers).toBeUndefined();
35
+ expect(options.signal).toBeInstanceOf(AbortSignal);
36
+ const callback = vi.fn();
37
+ options.lookup('images.example.com', { all: true }, callback);
38
+ expect(callback).toHaveBeenCalledWith(null, [{ address: '8.8.8.8', family: 4 }]);
39
+ expect(io.lookup).toHaveBeenCalledOnce();
40
+ });
41
+
42
+ it('rejects any private DNS result before opening a connection', async () => {
43
+ io.lookup.mockResolvedValue([{ address: '8.8.8.8', family: 4 }, { address: '127.0.0.1', family: 4 }]);
44
+ await expect(loadChannelImage(source, input)).rejects.toMatchObject({ code: 'image_unavailable' });
45
+ expect(io.request).not.toHaveBeenCalled();
46
+ });
47
+
48
+ it.each([302, 401, 500])('rejects status %i without following redirects or accepting an empty image', async (status) => {
49
+ io.request.mockImplementation((_url, _options, callback) => {
50
+ const request = new EventEmitter();
51
+ request.end = () => {
52
+ const response = Readable.from([png]);
53
+ response.statusCode = status;
54
+ response.headers = { location: 'https://127.0.0.1/private' };
55
+ callback(response);
56
+ };
57
+ return request;
58
+ });
59
+ await expect(loadChannelImage(source, input)).rejects.toMatchObject({ code: 'image_unavailable' });
60
+ expect(io.request).toHaveBeenCalledOnce();
61
+ });
62
+
63
+ it('rejects oversized chunked bodies even without content-length', async () => {
64
+ io.request.mockImplementation((_url, _options, callback) => {
65
+ const request = new EventEmitter();
66
+ request.end = () => {
67
+ const response = Readable.from([Buffer.alloc(20 * 1024 * 1024 + 1)]);
68
+ response.statusCode = 200;
69
+ response.headers = {};
70
+ callback(response);
71
+ };
72
+ return request;
73
+ });
74
+ await expect(loadChannelImage(source, input)).rejects.toMatchObject({ code: 'PROMPT_ATTACHMENT_TOO_LARGE' });
75
+ });
76
+ });
@@ -0,0 +1,41 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { describe, expect, it } from 'vitest';
6
+ import { createAssistantChannelStore } from './channels/store.js';
7
+ import { createWeixinStore } from './weixin/store.js';
8
+
9
+ const Database = createRequire(import.meta.url)('better-sqlite3');
10
+ describe.each(['weixin', 'enterprise'])('%s durable image outbox', (kind) => {
11
+ it('migrates text-only queues and preserves image snapshots through restart/unknown recovery', () => {
12
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-image-outbox-'));
13
+ const filename = path.join(directory, 'channel.sqlite');
14
+ const legacy = new Database(filename);
15
+ legacy.exec(`CREATE TABLE outbox(id TEXT NOT NULL UNIQUE,epoch TEXT NOT NULL,text TEXT NOT NULL,state TEXT NOT NULL DEFAULT 'pending',sequence INTEGER PRIMARY KEY AUTOINCREMENT${kind === 'enterprise' ? ",target TEXT NOT NULL DEFAULT '',attempts INTEGER NOT NULL DEFAULT 0" : ''});`);
16
+ legacy.close();
17
+ const create = kind === 'weixin' ? createWeixinStore : createAssistantChannelStore;
18
+ let store = create(directory);
19
+ try {
20
+ const binding = store.bind(kind === 'weixin'
21
+ ? { assistant_id: 'bot', account_id: 'account', peer_id: 'owner', token: 'test', base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 1 }
22
+ : { assistant_id: 'bot', provider: 'feishu', client_id: 'client', client_secret: 'test', owner_id: 'owner', language: 'en', generation: 0, ordinal: 0, updated_at: 1 });
23
+ const image = { attachmentID: 'att_snapshot', mime: 'image/png', size: 68 };
24
+ store.collect(binding, { generation: 0, ordinal: 1 }, [{ id: 'image', text: '', image }, { id: 'later', text: 'later' }], 1);
25
+ expect(JSON.parse(store.nextDelivery(binding.epoch).image)).toEqual(image);
26
+ store.close();
27
+ store = create(directory);
28
+ expect(JSON.parse(store.nextDelivery(binding.epoch).image)).toEqual(image);
29
+ store.markDelivery('image', 'sending');
30
+ store.close();
31
+ store = create(directory);
32
+ store.recover(binding.epoch, 'interrupted');
33
+ expect(store.hasUnknown(binding.epoch)).toBe(true);
34
+ expect(store.nextDelivery(binding.epoch).id).toBe('later');
35
+ store.sent('later');
36
+ expect(store.nextDelivery(binding.epoch)).toBeUndefined();
37
+ store.collect(store.get('bot', 'feishu'), { generation: 1, ordinal: 0 }, [], 2);
38
+ expect(store.hasUnknown(binding.epoch)).toBe(false);
39
+ } finally { store.close(); fs.rmSync(directory, { recursive: true, force: true }); }
40
+ });
41
+ });
@@ -0,0 +1,114 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { describe, expect, it, vi } from 'vitest';
5
+ import { createAssistantsService } from './service.js';
6
+ import { createAssistantChannelsRuntime } from './channels/runtime.js';
7
+ import { createWeixinRuntime } from './weixin/runtime.js';
8
+ import { createWeixinStore } from './weixin/store.js';
9
+ import { createAssistantChannelStore } from './channels/store.js';
10
+
11
+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aKxkAAAAASUVORK5CYII=', 'base64');
12
+ describe('real contact output → all native image channels', () => {
13
+ it.each(['weixin', 'wecom', 'feishu', 'dingtalk'])('returns images only to %s, keeps app replies local and broadcasts scheduled results', async (source) => {
14
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-image-pipeline-'));
15
+ const imagePath = path.join(directory, 'generated.png');
16
+ await fs.writeFile(imagePath, png);
17
+ let enterprise;
18
+ let weixin;
19
+ const service = createAssistantsService({ dbPath: path.join(directory, 'assistants.sqlite'), dataDir: directory,
20
+ buildOpenCodeUrl: () => 'http://127.0.0.1:1', getOpenCodeAuthHeaders: () => ({}), getAllowedRoots: () => [directory],
21
+ clientFactory: () => ({ message: { list: async () => ({ data: [], cursor: {} }) } }),
22
+ listProjects: async () => [{ id: 'project', path: directory }],
23
+ upsertScheduledTask: async (_project, task) => ({ task: { ...task, id: 'task' } }),
24
+ syncScheduledTaskProject: async () => {},
25
+ createChatCompletion: async () => ({ choices: [] }),
26
+ runContactTurn: async ({ userText, tools, onBubbleDelta }) => {
27
+ if (userText === 'draw again') {
28
+ const scheduled = await tools.find((tool) => tool.name === 'schedule_task').execute('schedule', {
29
+ name: 'Draw daily', prompt: 'Draw an image', time: '18:00', timezone: 'UTC',
30
+ });
31
+ expect(scheduled.isError).not.toBe(true);
32
+ }
33
+ const image = `![generated](<${imagePath}>)`;
34
+ onBubbleDelta?.(0, image, true);
35
+ return { bubbles: [image] };
36
+ },
37
+ onContactTurnEvent: (event) => { enterprise?.onTurnEvent(event); weixin?.onTurnEvent(event); } });
38
+ const bot = service.createAssistant({ name: 'Image pipeline', providerID: 'p', modelID: 'm', workspacePath: directory });
39
+ const connections = new Map();
40
+ const sends = Object.fromEntries(['weixin', 'wecom', 'feishu', 'dingtalk'].map((provider) => [provider, vi.fn(async () => {})]));
41
+ const adapters = Object.fromEntries(['wecom', 'feishu', 'dingtalk'].map((provider) => [provider, {
42
+ connect: async (input) => { connections.set(provider, input); input.onReady();
43
+ await new Promise((resolve) => input.signal.aborted ? resolve() : input.signal.addEventListener('abort', resolve, { once: true })); },
44
+ send: sends[provider],
45
+ }]));
46
+ const incoming = [];
47
+ const api = { getQRCode: async () => ({ qrcode: 'qr', qrcode_img_content: 'qr-content' }),
48
+ getQRStatus: async () => ({ status: 'confirmed', bot_token: 'test', ilink_bot_id: 'account', ilink_user_id: 'owner', baseurl: 'https://ilinkai.weixin.qq.com' }),
49
+ getUpdates: async () => ({ msgs: incoming.splice(0), get_updates_buf: 'cursor' }),
50
+ sendImage: async (_binding, delivery) => sends.weixin(delivery), sendText: vi.fn(async () => {}),
51
+ getConfig: async () => ({ ret: 0 }), sendTyping: async () => {} };
52
+ try {
53
+ enterprise = createAssistantChannelsRuntime({ directory: path.join(directory, 'channels'), service, adapters, env: {}, intervalMs: 10 });
54
+ weixin = createWeixinRuntime({ directory: path.join(directory, 'weixin'), service, api, env: {}, intervalMs: 10 });
55
+ for (const provider of Object.keys(adapters)) {
56
+ await enterprise.save(bot.id, provider, { clientID: provider, clientSecret: 'test', ownerID: 'owner', language: 'zh-CN' });
57
+ }
58
+ await weixin.startLogin(bot.id, 'zh-CN');
59
+ await vi.waitFor(() => expect(weixin.status(bot.id).status).toBe('connected'));
60
+ const weixinStore = createWeixinStore(path.join(directory, 'weixin'));
61
+ weixinStore.patch(weixinStore.get(bot.id).epoch, { context_token: 'test-context' });
62
+ weixinStore.close();
63
+ await vi.waitFor(() => expect(connections.size).toBe(3));
64
+ const cards = [
65
+ { cardType: 'session', sessionID: 'ses_card', directory, title: 'Internal session', status: 'complete' },
66
+ { cardType: 'assistant', assistantID: bot.id, name: 'Internal Bot', providerID: 'p', modelID: 'm' },
67
+ { cardType: 'schedule', taskID: 'task_card', projectID: 'project_card', name: 'Internal schedule' },
68
+ ];
69
+ for (const card of cards) service.appendContactCard(bot.id, card);
70
+ const tip = service.channelPage(bot.id, { tipOnly: true }).tipOrdinal;
71
+ const channelStore = createAssistantChannelStore(path.join(directory, 'channels'));
72
+ const personalStore = createWeixinStore(path.join(directory, 'weixin'));
73
+ try {
74
+ await vi.waitFor(() => {
75
+ expect(personalStore.get(bot.id).ordinal).toBe(tip);
76
+ for (const provider of Object.keys(adapters)) expect(channelStore.get(bot.id, provider).ordinal).toBe(tip);
77
+ });
78
+ for (const send of Object.values(sends)) expect(send).not.toHaveBeenCalled();
79
+ expect(api.sendText).not.toHaveBeenCalled();
80
+ expect(weixin.status(bot.id).error).toBeNull();
81
+ for (const provider of Object.keys(adapters)) expect(enterprise.status(bot.id, provider).error).toBeNull();
82
+ expect(service.contactMessages(bot.id, { limit: 20 }).messages.flatMap((message) => message.cards)).toEqual(cards.map((card) => expect.objectContaining(card)));
83
+ } finally { channelStore.close(); personalStore.close(); }
84
+ if (source === 'weixin') incoming.push({ message_id: 'in', from_user_id: 'owner', message_type: 1,
85
+ context_token: 'test-context', item_list: [{ type: 1, text_item: { text: 'draw' } }] });
86
+ else await connections.get(source).onMessage({ id: 'in', senderID: 'owner', chatType: 'private', text: 'draw' });
87
+ await vi.waitFor(() => expect(sends[source]).toHaveBeenCalledOnce());
88
+ expect(sends[source].mock.calls[0][0].image.buffer).toEqual(png);
89
+ for (const [provider, send] of Object.entries(sends)) if (provider !== source) expect(send).not.toHaveBeenCalled();
90
+ await service.send(bot.id, { messageID: 'app-turn', parts: [{ type: 'text', text: 'draw again' }] });
91
+ await vi.waitFor(() => {
92
+ expect(service.contactMessages(bot.id, { limit: 20 }).messages.some((message) => message.messageID === 'app-turn:bubble:1')).toBe(true);
93
+ });
94
+ const appTip = service.channelPage(bot.id, { tipOnly: true }).tipOrdinal;
95
+ const appChannels = createAssistantChannelStore(path.join(directory, 'channels'));
96
+ const appWeixin = createWeixinStore(path.join(directory, 'weixin'));
97
+ try {
98
+ await vi.waitFor(() => {
99
+ expect(appWeixin.get(bot.id).ordinal).toBe(appTip);
100
+ for (const provider of Object.keys(adapters)) expect(appChannels.get(bot.id, provider).ordinal).toBe(appTip);
101
+ });
102
+ for (const [provider, send] of Object.entries(sends)) expect(send).toHaveBeenCalledTimes(provider === source ? 1 : 0);
103
+ } finally { appChannels.close(); appWeixin.close(); }
104
+ expect(await service.reportScheduledTaskResult({ id: 'run', projectId: 'project', taskId: 'task',
105
+ taskName: 'Draw daily', status: 'success', sessionId: 'worker', directory,
106
+ startedAt: Date.now(), finishedAt: Date.now(), prompt: 'Draw an image' })).toBe(true);
107
+ await vi.waitFor(() => {
108
+ for (const [provider, send] of Object.entries(sends)) expect(send).toHaveBeenCalledTimes(provider === source ? 2 : 1);
109
+ });
110
+ for (const send of Object.values(sends)) expect(send.mock.calls.at(-1)[0].image.buffer).toEqual(png);
111
+ expect(api.sendText).not.toHaveBeenCalled();
112
+ } finally { await enterprise?.close(); await weixin?.close(); service.close(); await fs.rm(directory, { recursive: true, force: true }); }
113
+ });
114
+ });
@@ -0,0 +1,90 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { parseMarkdown } from 'chat';
3
+
4
+ const digest = (value) => createHash('sha256').update(value).digest('hex');
5
+ export const channelImageFailure = (language) => String(language).startsWith('zh')
6
+ ? '图片未能发送,请在 Yuri 中查看原图。'
7
+ : 'The image could not be sent. View the original in Yuri.';
8
+
9
+ /** Project only published output; code examples and ordinary links are not media. */
10
+ function outputParts(message) {
11
+ const result = [];
12
+ const parts = message.parts?.length ? message.parts : [{ type: 'text', text: message.text ?? '' }];
13
+ for (const part of parts) {
14
+ if (part.type === 'file' && part.mime?.startsWith('image/')) {
15
+ result.push({ type: 'image', source: part });
16
+ continue;
17
+ }
18
+ if (part.type !== 'text' || !part.text?.trim() || part.text.trim().startsWith('oc.settle.')) continue;
19
+ if (!part.text.includes('![')) {
20
+ result.push({ type: 'text', text: part.text.trim() });
21
+ continue;
22
+ }
23
+ const tree = parseMarkdown(part.text);
24
+ const definitions = new Map(tree.children.filter((node) => node.type === 'definition').map((node) => [node.identifier, node.url]));
25
+ const spans = [];
26
+ const walk = (node) => {
27
+ const url = node.type === 'image' ? node.url : node.type === 'imageReference' ? definitions.get(node.identifier) : null;
28
+ if (url) spans.push({ start: node.position.start.offset, end: node.position.end.offset, url });
29
+ for (const child of node.children ?? []) walk(child);
30
+ };
31
+ walk(tree);
32
+ const used = new Set(spans.map((span) => span.url));
33
+ for (const node of tree.children) {
34
+ if (node.type === 'definition' && used.has(node.url)) spans.push({ start: node.position.start.offset, end: node.position.end.offset });
35
+ }
36
+ spans.sort((a, b) => a.start - b.start);
37
+ let offset = 0;
38
+ for (const span of spans) {
39
+ if (span.start < offset) continue;
40
+ const text = part.text.slice(offset, span.start).trim();
41
+ if (text) result.push({ type: 'text', text });
42
+ if (span.url) result.push({ type: 'image', source: { url: span.url } });
43
+ offset = span.end;
44
+ }
45
+ const text = part.text.slice(offset).trim();
46
+ if (text) result.push({ type: 'text', text });
47
+ }
48
+ return result;
49
+ }
50
+
51
+ /** Snapshot images into the existing attachment store before advancing the feed. */
52
+ export async function prepareChannelOutput(message, { service, assistantID, generation, language, failureText, signal, assertCurrent }) {
53
+ const deliveries = [];
54
+ const parts = message.status === 'error' ? [{ type: 'text', text: failureText }] : outputParts(message);
55
+ let images = 0;
56
+ let imageBytes = 0;
57
+ for (const part of parts) {
58
+ signal?.throwIfAborted();
59
+ assertCurrent();
60
+ if (part.type === 'image') {
61
+ images += 1;
62
+ try {
63
+ if (images > 8) throw new Error('image_limit');
64
+ const image = await service.prepareChannelImage(assistantID, part.source, {
65
+ generation, signal, uploadID: `channel-${digest(`${generation}:${message.messageID}:${deliveries.length}`)}`,
66
+ });
67
+ imageBytes += image.size ?? 0;
68
+ if (imageBytes > 50 * 1024 * 1024) throw new Error('image_budget');
69
+ assertCurrent();
70
+ deliveries.push({ text: '', image });
71
+ } catch {
72
+ assertCurrent();
73
+ signal?.throwIfAborted();
74
+ deliveries.push({ text: channelImageFailure(language) });
75
+ }
76
+ continue;
77
+ }
78
+ const chars = Array.from(part.text ?? '');
79
+ for (let index = 0; index < chars.length; index += 3500) deliveries.push({ text: chars.slice(index, index + 3500).join('') });
80
+ }
81
+ return deliveries;
82
+ }
83
+
84
+ export async function readChannelDeliveryImage(service, assistantID, image, signal) {
85
+ if (!image) return undefined;
86
+ signal?.throwIfAborted();
87
+ const { buffer, mime, filename } = await service.getAssistantContactAttachment(assistantID, image.attachmentID);
88
+ signal?.throwIfAborted();
89
+ return { buffer, mime, filename: filename || 'image.png' };
90
+ }