@yuriai/web 0.2.27-beta.8 → 0.2.28

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 (198) hide show
  1. package/dist/assets/{AgentAvatar-BJ42lGZD.js → AgentAvatar-BybF1ayP.js} +1 -1
  2. package/dist/assets/AssistantContactStatus-BwpxTn0d.js +3 -0
  3. package/dist/assets/{AssistantUnreadBadge-QwhBfXpC.js → AssistantUnreadBadge-DqThZdCe.js} +1 -1
  4. package/dist/assets/{AssistantView-D7ryIKL0.js → AssistantView-DPUDCXoY.js} +1 -1
  5. package/dist/assets/{DiagramView-ERrGEBDp.js → DiagramView-CHVLoYrV.js} +1 -1
  6. package/dist/assets/{FadeInOnReveal-Bu2GvaM9.js → FadeInOnReveal-Cj3JXYvE.js} +1 -1
  7. package/dist/assets/{GuiPluginSurface-MzQgEZNr.js → GuiPluginSurface-CBZYeKHb.js} +1 -1
  8. package/dist/assets/{GuiPluginWindow-DZMmlQzx.js → GuiPluginWindow-_Z5wycnH.js} +1 -1
  9. package/dist/assets/{Icon-Dj4CCqCP.js → Icon-CeRMtJa8.js} +1 -1
  10. package/dist/assets/{ImageLoadingPlaceholder-BnFXgUuO.js → ImageLoadingPlaceholder-DjLaKB4o.js} +1 -1
  11. package/dist/assets/{LoadingImage-PBnivDKv.js → LoadingImage-DG3otL5V.js} +1 -1
  12. package/dist/assets/MarkdownRenderer-C8rv6z7p.js +2 -0
  13. package/dist/assets/{MarkdownRendererImpl-CfyXL4rg.js → MarkdownRendererImpl-_plqOlsV.js} +1 -1
  14. package/dist/assets/{MarkstreamRendererImpl-BGadklK1.js → MarkstreamRendererImpl-bs8HZ4Ra.js} +1 -1
  15. package/dist/assets/{MobileDetailNavigation-DqajQdB4.js → MobileDetailNavigation-SeT764Ps.js} +1 -1
  16. package/dist/assets/{MobileResizableSheet-BvdUgwA3.js → MobileResizableSheet-BY1-oo_E.js} +1 -1
  17. package/dist/assets/{MobileShareBridge-3oPoYnry.js → MobileShareBridge-Dw8gLtJD.js} +2 -2
  18. package/dist/assets/MobileTabPageHeader-EsrOCLyg.js +2 -0
  19. package/dist/assets/{MultiRunWindow-yhs0Ih5_.js → MultiRunWindow-C-Qw_g7N.js} +1 -1
  20. package/dist/assets/{OnboardingScreen-Bi1VWFQC.js → OnboardingScreen-CGqabMbp.js} +1 -1
  21. package/dist/assets/{OverlayScrollbar-BBDwGvGO.js → OverlayScrollbar-AGSWQKg-.js} +1 -1
  22. package/dist/assets/{SettingsView-BSf-SJUA.js → SettingsView-BLfFnnnX.js} +14 -14
  23. package/dist/assets/{SettingsWindow-BvSXVMTm.js → SettingsWindow-lyYO8Byy.js} +1 -1
  24. package/dist/assets/{TerminalView-DhL01N7e.js → TerminalView-OHqpkHzz.js} +1 -1
  25. package/dist/assets/{ToolOutputDialog-C8lnH4Ky.js → ToolOutputDialog-DU4Pb1s0.js} +1 -1
  26. package/dist/assets/{YuriLogo-D8asj1CS.js → YuriLogo-Bb6yHagP.js} +1 -1
  27. package/dist/assets/{appThemeRegistry-C-maYSdv.js → appThemeRegistry-9j-rCSlE.js} +1 -1
  28. package/dist/assets/{button-vXOdzd8x.js → button-Bjh2BSXh.js} +1 -1
  29. package/dist/assets/{capgoAdapter-DJ_h2x5D.js → capgoAdapter-DERfot6h.js} +1 -1
  30. package/dist/assets/{collapsible-DwDQs3Wa.js → collapsible-BEAHoxNi.js} +1 -1
  31. package/dist/assets/{context-menu-BabBujQ-.js → context-menu-BxLcot-3.js} +1 -1
  32. package/dist/assets/device-BcRP6Tjd.js +2 -0
  33. package/dist/assets/{diagram-HwgrQxY5.js → diagram-CXVm2vzI.js} +1 -1
  34. package/dist/assets/{dialog-Dnf626tb.js → dialog-nshKUSE5.js} +1 -1
  35. package/dist/assets/{dropdown-menu.styles-CBc_a-Nv.js → dropdown-menu.styles-M78xpvb2.js} +1 -1
  36. package/dist/assets/{es-BQkO-Odr.js → es-N9ZkQwG9.js} +2 -2
  37. package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
  38. package/dist/assets/{fileMentionTouchSelection-CKPnEetl.js → fileMentionTouchSelection-B9NbPN9D.js} +2 -2
  39. package/dist/assets/{fileReferenceActions-g7KZLi_G.js → fileReferenceActions-CrIAce3K.js} +1 -1
  40. package/dist/assets/{fr-C852roK5.js → fr-CIGqV46N.js} +2 -2
  41. package/dist/assets/{gitApi-CVq5oKCd.js → gitApi-CY3D5CF0.js} +1 -1
  42. package/dist/assets/{gitApiHttp-BYOIbYIh.js → gitApiHttp-B7vYwgBh.js} +4 -4
  43. package/dist/assets/{gui-M_Rbwkyu.js → gui-CJjEj3l4.js} +1 -1
  44. package/dist/assets/host-CnVx34Dh.js +1 -0
  45. package/dist/assets/{image-loading-D5UhMj7Z.js → image-loading-D6kOgU4w.js} +1 -1
  46. package/dist/assets/{input-BtM712b1.js → input-3Re4pmHm.js} +1 -1
  47. package/dist/assets/insertionBoundaries-DK7XYF8d.js +1 -0
  48. package/dist/assets/{ja-BqC39qK6.js → ja-DAhnTq6V.js} +2 -2
  49. package/dist/assets/{ko-BMaChAWh.js → ko-FbMgNKcI.js} +2 -2
  50. package/dist/assets/main-B_THXYMs.js +2 -0
  51. package/dist/assets/main-CpcudEZb.js +169 -0
  52. package/dist/assets/{markdownHeightCache-Bf8iisO4.js → markdownHeightCache-DVWGXtAX.js} +1 -1
  53. package/dist/assets/{mcpQueries-DpXqegX5.js → mcpQueries-CdOYmUdO.js} +1 -1
  54. package/dist/assets/miniChat-DxZiTnAZ.js +2 -0
  55. package/dist/assets/mobile-BJuATiaC.js +2 -0
  56. package/dist/assets/{mobileBackNavigation-DZcI7aZg.js → mobileBackNavigation-CgZndzFA.js} +1 -1
  57. package/dist/assets/{multirun-hzspPepd.js → multirun-BlaYsQi2.js} +1 -1
  58. package/dist/assets/{native-H7K64Ulc.js → native-BYMhr-xH.js} +1 -1
  59. package/dist/assets/{native-config-CddZtLQ1.js → native-config-BpsFKLGl.js} +1 -1
  60. package/dist/assets/{persistence-BT8045Ue.js → persistence-CWuLIq1J.js} +2 -2
  61. package/dist/assets/{pl-Ubs8p28T.js → pl-DzX0cbiQ.js} +2 -2
  62. package/dist/assets/{projectMeta-CEf0QPmD.js → projectMeta-CnXHTolN.js} +1 -1
  63. package/dist/assets/{pt-BR-8rAOjJrs.js → pt-BR-C5yvwyDK.js} +2 -2
  64. package/dist/assets/queue-abort-optimistic-DCLBpirg.js +1 -0
  65. package/dist/assets/{readiness-Dyr7314z.js → readiness-U16Qor79.js} +1 -1
  66. package/dist/assets/renderElectronMiniChatApp-n-nhgy1V.js +2 -0
  67. package/dist/assets/renderMobileApp-DBj_7RlD.js +28 -0
  68. package/dist/assets/{runtimeConfig-B8VHHNxj.js → runtimeConfig-BBgkLVr_.js} +1 -1
  69. package/dist/assets/runtimeEndpointReset-BvSQVFfx.js +149 -0
  70. package/dist/assets/{scheduledTaskNavigation-Zm87Nydi.js → scheduledTaskNavigation-EomDNVu2.js} +1 -1
  71. package/dist/assets/sessionLookup-C_CCp7MJ.js +1 -0
  72. package/dist/assets/{sortable-tabs-strip-D4pVoodN.js → sortable-tabs-strip-p16Pn6Zz.js} +1 -1
  73. package/dist/assets/{speechSettingsQueries-RlCLMBtr.js → speechSettingsQueries-CBSEAKyj.js} +2 -2
  74. package/dist/assets/src-u-YDfCVw.css +2 -0
  75. package/dist/assets/{store-ME7oHni1.js → store-DVfZQktm.js} +4 -3
  76. package/dist/assets/{terminalApi-BSaclMDJ.js → terminalApi-rl9mZAlB.js} +1 -1
  77. package/dist/assets/{textarea-B98rsLs7.js → textarea-C6VQ7dHH.js} +1 -1
  78. package/dist/assets/{tooltip-B9810jbK.js → tooltip-Dnc6GA-X.js} +1 -1
  79. package/dist/assets/types-DnZw0gLD.js +2 -0
  80. package/dist/assets/{uk-LzwzUApL.js → uk-zbDcUpBy.js} +2 -2
  81. package/dist/assets/{useAppFontEffects-D2C1sBYM.js → useAppFontEffects-CEgDiZHu.js} +49 -49
  82. package/dist/assets/{useAssistantUIStore-TUN_ycy5.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
  83. package/dist/assets/useDesktopWindowControlsLayout-B2o4IFmd.js +1 -0
  84. package/dist/assets/useEffectiveDirectory-BOYMJ6k7.js +1 -0
  85. package/dist/assets/{useFontPreferences-BlhlCJCX.js → useFontPreferences-DeqW9nRx.js} +1 -1
  86. package/dist/assets/useMobileNavigationStore-DlvrZQ49.js +17 -0
  87. package/dist/assets/{useUIStore-DRx6OgCp.js → useUIStore-C6CE42oh.js} +1 -1
  88. package/dist/assets/{useWorkerHighlightedLines-D093jNsH.js → useWorkerHighlightedLines-EcJThS4x.js} +1 -1
  89. package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
  90. package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
  91. package/dist/assets/{vendor-opencode-plugin-BBOP6WNx.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
  92. package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
  93. package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
  94. package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
  95. package/dist/assets/{zh-CN-D-FVCeks.js → zh-CN-BHRJ7CF3.js} +2 -2
  96. package/dist/assets/{zh-TW-B9iH_NXL.js → zh-TW-BFI_YFd-.js} +2 -2
  97. package/dist/index.html +12 -12
  98. package/dist/mini-chat.html +12 -12
  99. package/dist/mobile.html +12 -12
  100. package/package.json +1 -1
  101. package/server/index.js +2 -145
  102. package/server/lib/assistants/DOCUMENTATION.md +63 -10
  103. package/server/lib/assistants/cards.js +1 -1
  104. package/server/lib/assistants/channel-image.js +92 -0
  105. package/server/lib/assistants/channel-image.test.js +76 -0
  106. package/server/lib/assistants/channel-output-store.test.js +41 -0
  107. package/server/lib/assistants/channel-output.integration.test.js +128 -0
  108. package/server/lib/assistants/channel-output.js +90 -0
  109. package/server/lib/assistants/channel-output.test.js +79 -0
  110. package/server/lib/assistants/channels/DOCUMENTATION.md +52 -14
  111. package/server/lib/assistants/channels/PROTOCOLS.md +23 -1
  112. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +19 -7
  113. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +8 -0
  114. package/server/lib/assistants/channels/routes.js +12 -0
  115. package/server/lib/assistants/channels/routes.test.js +34 -0
  116. package/server/lib/assistants/channels/runtime.js +117 -26
  117. package/server/lib/assistants/channels/runtime.test.js +179 -5
  118. package/server/lib/assistants/channels/sdk-adapters.js +15 -3
  119. package/server/lib/assistants/channels/sdk-adapters.test.js +17 -0
  120. package/server/lib/assistants/channels/store.js +9 -6
  121. package/server/lib/assistants/channels/store.test.js +21 -11
  122. package/server/lib/assistants/channels/transport.js +2 -1
  123. package/server/lib/assistants/channels/wecom-chat-adapter.js +16 -2
  124. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +21 -0
  125. package/server/lib/assistants/contact-store.js +9 -3
  126. package/server/lib/assistants/contact-store.test.js +27 -0
  127. package/server/lib/assistants/contact-tools.js +65 -75
  128. package/server/lib/assistants/contact-tools.test.js +114 -22
  129. package/server/lib/assistants/harness.js +80 -34
  130. package/server/lib/assistants/harness.test.js +68 -20
  131. package/server/lib/assistants/resource-reference.integration.test.js +284 -0
  132. package/server/lib/assistants/routes.js +0 -3
  133. package/server/lib/assistants/service.js +116 -69
  134. package/server/lib/assistants/service.test.js +31 -17
  135. package/server/lib/assistants/weixin/DOCUMENTATION.md +34 -9
  136. package/server/lib/assistants/weixin/api.js +43 -1
  137. package/server/lib/assistants/weixin/api.test.js +28 -0
  138. package/server/lib/assistants/weixin/chat-adapter.js +8 -2
  139. package/server/lib/assistants/weixin/inbound.js +5 -3
  140. package/server/lib/assistants/weixin/inbound.test.js +20 -0
  141. package/server/lib/assistants/weixin/runtime.js +27 -18
  142. package/server/lib/assistants/weixin/runtime.test.js +36 -0
  143. package/server/lib/assistants/weixin/store.js +8 -4
  144. package/server/lib/assistants/weixin/store.test.js +21 -0
  145. package/server/lib/assistants/yuri-project.http.test.js +9 -3
  146. package/server/lib/notifications/DOCUMENTATION.md +6 -0
  147. package/server/lib/notifications/runtime.js +26 -15
  148. package/server/lib/notifications/runtime.test.js +14 -13
  149. package/server/lib/opencode/DOCUMENTATION.md +9 -0
  150. package/server/lib/opencode/auth.d.ts +6 -2
  151. package/server/lib/opencode/core-routes.js +0 -1
  152. package/server/lib/opencode/feature-routes-runtime.js +0 -24
  153. package/server/lib/opencode/location-release.d.ts +5 -1
  154. package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
  155. package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
  156. package/server/lib/opencode/native-goal.js +15 -0
  157. package/server/lib/opencode/native-goal.test.js +17 -0
  158. package/server/lib/opencode/settings-helpers.js +0 -6
  159. package/server/lib/opencode/shutdown-runtime.js +0 -2
  160. package/server/lib/projects/project-config.js +3 -6
  161. package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
  162. package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
  163. package/server/lib/scheduled-tasks/routes.js +0 -26
  164. package/server/lib/scheduled-tasks/runtime.js +33 -257
  165. package/server/lib/scheduled-tasks/runtime.test.js +24 -65
  166. package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
  167. package/server/lib/session-metadata/routes.js +4 -38
  168. package/server/lib/session-metadata/routes.test.js +2 -2
  169. package/dist/assets/AssistantContactStatus-dtkObamV.js +0 -3
  170. package/dist/assets/MarkdownRenderer-BajF4gUU.js +0 -2
  171. package/dist/assets/MobileTabPageHeader-B6cRyIRH.js +0 -2
  172. package/dist/assets/device-BjRYYXNT.js +0 -2
  173. package/dist/assets/host-BW3FEJdU.js +0 -1
  174. package/dist/assets/insertionBoundaries-Dx3WAY6i.js +0 -1
  175. package/dist/assets/main-9uP2z1qT.js +0 -2
  176. package/dist/assets/main-Mey7bCWf.js +0 -169
  177. package/dist/assets/miniChat-DqZvVkme.js +0 -2
  178. package/dist/assets/mobile-DXAWjYcN.js +0 -2
  179. package/dist/assets/renderElectronMiniChatApp-DoOq8Cuo.js +0 -2
  180. package/dist/assets/renderMobileApp-TTxtOb8b.js +0 -28
  181. package/dist/assets/runtimeEndpointReset-BC6XWntz.js +0 -149
  182. package/dist/assets/sessionLookup-De53jDwM.js +0 -1
  183. package/dist/assets/src-lE4uqaHS.css +0 -2
  184. package/dist/assets/types-DFf9vd1b.js +0 -2
  185. package/dist/assets/useDesktopWindowControlsLayout-BjKaHN0x.js +0 -1
  186. package/dist/assets/useEffectiveDirectory-TEvyiQSC.js +0 -1
  187. package/dist/assets/useMobileNavigationStore-DTvJV9s-.js +0 -23
  188. package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +0 -23
  189. package/dist/assets/vendor-solid-js-9wmPZH9g.js +0 -1
  190. package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
  191. package/server/lib/session-goal/DOCUMENTATION.md +0 -371
  192. package/server/lib/session-goal/capability.js +0 -57
  193. package/server/lib/session-goal/capability.test.js +0 -33
  194. package/server/lib/session-goal/objectives.js +0 -61
  195. package/server/lib/session-goal/routes.js +0 -274
  196. package/server/lib/session-goal/routes.test.js +0 -211
  197. package/server/lib/session-goal/runtime.js +0 -2452
  198. package/server/lib/session-goal/runtime.test.js +0 -2125
@@ -0,0 +1,284 @@
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, vi } from 'vitest';
6
+ import { createAssistantsService } from './service.js';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const call = (name, args) => ({ completion: { choices: [{ message: { content: '', tool_calls: [
10
+ { id: `call_${name}`, type: 'function', function: { name, arguments: JSON.stringify(args) } },
11
+ ] } }] } });
12
+ const task = (schedule) => ({ id: 'task', name: 'Review', enabled: true, schedule, execution: { prompt: 'Review notes', providerID: 'p', modelID: 'm' } });
13
+ const cards = (service, id) => service.contactMessages(id, { limit: 50 }).messages.flatMap((message) => message.cards);
14
+ const fixture = (options = {}) => {
15
+ const directory = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'resource-reference-')));
16
+ const client = {
17
+ session: {
18
+ get: vi.fn(async ({ sessionID }) => ({ id: sessionID, directory, title: 'Actual conversation', status: { type: 'busy' } })),
19
+ create: vi.fn(async () => ({ id: 'ses_created' })),
20
+ prompt: vi.fn(async () => ({ id: 'inbox_created', type: 'user' })),
21
+ active: async () => ({}),
22
+ },
23
+ message: { list: vi.fn(async () => ({ data: [{ info: { id: 'msg', role: 'user', sessionID: 'ses_found' }, parts: [{ type: 'text', text: 'Discuss the release plan.' }] }], cursor: {} })) },
24
+ provider: { list: async () => ({ data: [] }) }, model: { list: async () => ({ data: [] }) },
25
+ };
26
+ let service;
27
+ const open = (extra = {}) => {
28
+ service = createAssistantsService({
29
+ dbPath: path.join(directory, 'assistants.sqlite'), dataDir: directory,
30
+ getAllowedRoots: () => [directory], listProjects: async () => [{ id: 'project', path: directory }],
31
+ buildOpenCodeUrl: () => 'http://upstream.invalid', getOpenCodeAuthHeaders: () => ({}),
32
+ clientFactory: () => client, ...options, ...extra,
33
+ });
34
+ return service;
35
+ };
36
+ open();
37
+ const host = service.createAssistant({ name: 'Host', providerID: 'p', modelID: 'm' });
38
+ return { directory, client, host, get service() { return service; }, open,
39
+ async send(text = 'Show the matching resources') {
40
+ const admitted = await service.send(host.id, { messageID: `turn_${Date.now()}`, text });
41
+ return service.whenContactTurnSettled(admitted.messageID);
42
+ },
43
+ close() { service.close(); fs.rmSync(directory, { recursive: true, force: true }); },
44
+ };
45
+ };
46
+
47
+ describe('explicit resource references through the real contact Agent and SQLite', () => {
48
+ it('looks up a conversation and tasks, references both, acknowledges persistence and survives restart without watches', async () => {
49
+ let round = 0;
50
+ let f;
51
+ const complete = vi.fn(async ({ body }) => {
52
+ round++;
53
+ if (round === 1) return call('list_sessions', { query: 'release' });
54
+ if (round === 2) {
55
+ expect(body.messages.find((message) => message.name === 'list_sessions')?.content).toContain('ses_found');
56
+ return call('read_session', { sessionID: 'ses_found' });
57
+ }
58
+ if (round === 3) {
59
+ expect(body.messages.find((message) => message.name === 'read_session')?.content).toContain('release plan');
60
+ return call('reference_resource', { cardType: 'session', sessionID: 'ses_found', projectID: 'project' });
61
+ }
62
+ if (round === 4) {
63
+ expect(cards(f.service, f.host.id)).toHaveLength(1);
64
+ expect(body.messages.find((message) => message.name === 'reference_resource')?.content).toContain('sent');
65
+ return call('list_scheduled_tasks', {});
66
+ }
67
+ if (round === 5) return call('reference_resource', { cardType: 'schedule', projectID: 'project', taskID: 'task' });
68
+ expect(cards(f.service, f.host.id)).toHaveLength(2);
69
+ return { text: '这个会话在讨论发布计划;定时任务会检查笔记。' };
70
+ });
71
+ f = fixture({ createChatCompletion: complete,
72
+ sessionIndexService: { snapshot: () => ({ directories: [{ directory: f.directory, sessions: [{ id: 'ses_found', title: 'Release', time: { updated: 1 } }] }] }) },
73
+ listScheduledTasks: async () => [task({ kind: 'cron', cron: '0 9 * * 1', timezone: 'UTC' })],
74
+ });
75
+ try {
76
+ expect(await f.send('帮我看一下定时任务并列出来,也看看发布会话是做什么的')).toMatchObject({ status: 'complete' });
77
+ expect(complete).toHaveBeenCalledTimes(6);
78
+ const published = cards(f.service, f.host.id);
79
+ expect(published).toEqual([
80
+ expect.objectContaining({ cardType: 'session', sessionID: 'ses_found', title: 'Actual conversation' }),
81
+ expect.objectContaining({ cardType: 'schedule', taskID: 'task', projectID: 'project', cron: '0 9 * * 1' }),
82
+ ]);
83
+ expect(f.service.snapshot().assistants[0].assignedSessionIDs).toEqual([]);
84
+ expect(f.client.session.create).not.toHaveBeenCalled();
85
+ expect(f.client.session.prompt).not.toHaveBeenCalled();
86
+ f.service.close(); f.open();
87
+ expect(cards(f.service, f.host.id)).toEqual(published);
88
+ expect(f.service.snapshot().assistants[0].assignedSessionIDs).toEqual([]);
89
+ } finally { f.close(); }
90
+ });
91
+
92
+ it.each([
93
+ { kind: 'cron', cron: '0 9 1 * *', timezone: 'UTC' },
94
+ { kind: 'once', date: '2026-12-01', time: '09:00', timezone: 'UTC' },
95
+ { kind: 'weekly', times: ['09:00', '18:00'], weekdays: [1, 3], timezone: 'UTC' },
96
+ ])('creates then explicitly references a task with its complete $kind schedule', async (schedule) => {
97
+ let saved;
98
+ let round = 0;
99
+ let f;
100
+ f = fixture({
101
+ upsertScheduledTask: async (_projectID, input) => { saved = { ...input, id: 'task', schedule }; return { task: saved }; },
102
+ listScheduledTasks: async () => saved ? [saved] : [],
103
+ createChatCompletion: async ({ body }) => {
104
+ round++;
105
+ if (round === 1) return call('load_tools', { domain: 'yuri.tasks' });
106
+ if (round === 2) return call('schedule_task', { name: 'Review', prompt: 'Review notes', time: '09:00', timezone: 'UTC' });
107
+ if (round === 3) {
108
+ expect(cards(f.service, f.host.id)).toEqual([]);
109
+ expect(body.messages.find((message) => message.name === 'schedule_task')?.content).toContain('reference_resource');
110
+ return call('reference_resource', { cardType: 'schedule', projectID: 'project', taskID: 'task' });
111
+ }
112
+ expect(cards(f.service, f.host.id)).toHaveLength(1);
113
+ return { text: '定时任务已创建,卡片发给你了。' };
114
+ },
115
+ });
116
+ try {
117
+ expect(await f.send('Create the requested task')).toMatchObject({ status: 'complete' });
118
+ expect(cards(f.service, f.host.id)[0]).toMatchObject(schedule);
119
+ expect(f.service.snapshot().assistants[0].assignedSessionIDs).toEqual([]);
120
+ } finally { f.close(); }
121
+ });
122
+
123
+ it('keeps assignment watches independent and limits the result phase to explicit reference calls', async () => {
124
+ let round = 0;
125
+ let f;
126
+ f = fixture({ createChatCompletion: async ({ body }) => {
127
+ round++;
128
+ if (round === 1) return call('assign_session', { prompt: 'Review release plan', projectPath: f.directory });
129
+ expect(body.tools.map((tool) => tool.function.name)).toEqual(['reference_resource']);
130
+ if (round === 2) {
131
+ expect(cards(f.service, f.host.id)).toEqual([]);
132
+ expect(f.service.snapshot().assistants[0].assignedSessionIDs).toEqual(['ses_created']);
133
+ return call('assign_session', { prompt: 'Accidental duplicate', projectPath: f.directory });
134
+ }
135
+ if (round === 3) {
136
+ expect(body.messages.at(-1).content).toContain('not an available tool');
137
+ return call('reference_resource', { cardType: 'session', sessionID: 'ses_created' });
138
+ }
139
+ expect(body.messages.find((message) => message.name === 'reference_resource')?.content).toContain('sent');
140
+ return { text: '已交给工作会话,卡片在这里。' };
141
+ } });
142
+ try {
143
+ expect(await f.send('Open a session to review release plan')).toMatchObject({ status: 'complete' });
144
+ expect(f.client.session.create).toHaveBeenCalledTimes(1);
145
+ expect(f.client.session.prompt).toHaveBeenCalledTimes(1);
146
+ expect(cards(f.service, f.host.id)).toHaveLength(1);
147
+ expect(f.service.snapshot().assistants[0].assignedSessionIDs).toEqual(['ses_created']);
148
+ } finally { f.close(); }
149
+ });
150
+
151
+ it('creates a Bot without auto-publishing, then explicitly references its stored identity', async () => {
152
+ let round = 0;
153
+ let f;
154
+ f = fixture({ createChatCompletion: async ({ body }) => {
155
+ round++;
156
+ if (round === 1) return call('load_tools', { domain: 'yuri.assistants' });
157
+ if (round === 2) return call('create_assistant', { name: 'Peer' });
158
+ if (round === 3) {
159
+ expect(cards(f.service, f.host.id)).toEqual([]);
160
+ const result = JSON.parse(JSON.parse(body.messages.find((message) => message.name === 'create_assistant').content).content);
161
+ return call('reference_resource', result.reference);
162
+ }
163
+ return { text: '新助理已创建。' };
164
+ } });
165
+ try {
166
+ expect(await f.send('Create a Bot named Peer')).toMatchObject({ status: 'complete' });
167
+ const peer = f.service.snapshot().assistants.find((assistant) => assistant.name === 'Peer');
168
+ expect(cards(f.service, f.host.id)).toEqual([expect.objectContaining({ cardType: 'assistant', assistantID: peer.id, name: 'Peer' })]);
169
+ } finally { f.close(); }
170
+ });
171
+
172
+ it('updates an existing task without an implicit card, then references the new authoritative values', async () => {
173
+ let saved = task({ kind: 'daily', time: '09:00', timezone: 'UTC' });
174
+ let round = 0;
175
+ let f;
176
+ const patch = vi.fn(async (_project, _task, changes) => { saved = { ...saved, ...changes }; return { task: saved }; });
177
+ f = fixture({ listScheduledTasks: async () => [saved], patchScheduledTask: patch,
178
+ createChatCompletion: async ({ body }) => {
179
+ round++;
180
+ if (round === 1) return call('load_tools', { domain: 'yuri.tasks' });
181
+ if (round === 2) return call('update_scheduled_task', { projectID: 'project', taskID: 'task', name: 'Updated review' });
182
+ if (round === 3) {
183
+ expect(cards(f.service, f.host.id)).toEqual([]);
184
+ const result = JSON.parse(JSON.parse(body.messages.find((message) => message.name === 'update_scheduled_task').content).content);
185
+ return call('reference_resource', result.reference);
186
+ }
187
+ return { text: '任务已修改。' };
188
+ },
189
+ });
190
+ try {
191
+ expect(await f.send('Rename the existing task')).toMatchObject({ status: 'complete' });
192
+ expect(patch).toHaveBeenCalledTimes(1);
193
+ expect(cards(f.service, f.host.id)).toEqual([expect.objectContaining({ cardType: 'schedule', name: 'Updated review' })]);
194
+ } finally { f.close(); }
195
+ });
196
+
197
+ it('keeps admitted work successful with an explicit watch-storage warning and never duplicates it', async () => {
198
+ let db;
199
+ let round = 0;
200
+ let f;
201
+ f = fixture({ createChatCompletion: async ({ body }) => {
202
+ round++;
203
+ if (round === 1) return call('assign_session', { projectPath: f.directory, prompt: 'Review notes' });
204
+ expect(body.tools.map((tool) => tool.function.name)).toEqual(['reference_resource']);
205
+ expect(body.messages.find((message) => message.name === 'assign_session')?.content).toContain('watch_registration_failed');
206
+ return { text: '会话已启动,但自动跟进没有注册成功。' };
207
+ } });
208
+ db = new (require('better-sqlite3'))(path.join(f.directory, 'assistants.sqlite'));
209
+ try {
210
+ db.exec("CREATE TRIGGER reject_watch BEFORE INSERT ON assistant_contact_watch BEGIN SELECT RAISE(ABORT, 'watch write failed'); END");
211
+ expect(await f.send('Open a session')).toMatchObject({ status: 'complete' });
212
+ expect(f.client.session.create).toHaveBeenCalledTimes(1);
213
+ expect(f.client.session.prompt).toHaveBeenCalledTimes(1);
214
+ expect(cards(f.service, f.host.id)).toEqual([]);
215
+ expect(f.service.snapshot().assistants[0].assignedSessionIDs).toEqual([]);
216
+ } finally { db.close(); f.close(); }
217
+ });
218
+
219
+ it('rejects a late reference after its user turn was wiped', async () => {
220
+ let f;
221
+ let result;
222
+ f = fixture({ runContactTurn: async ({ tools }) => {
223
+ f.service.resetContact(f.host.id, {});
224
+ result = await tools.find((tool) => tool.name === 'reference_resource').execute('late', { cardType: 'session', sessionID: 'ses_found' });
225
+ return { text: '引用已失效。', bubbles: ['引用已失效。'] };
226
+ } });
227
+ try {
228
+ expect(await f.send()).toMatchObject({ status: 'complete' });
229
+ expect(result).toMatchObject({ isError: true, details: { error: 'validation_error' } });
230
+ expect(cards(f.service, f.host.id)).toEqual([]);
231
+ } finally { f.close(); }
232
+ });
233
+
234
+ it('reports publication failure, retries safely, deduplicates references, and never rearms a cancelled watch', async () => {
235
+ const results = [];
236
+ let db;
237
+ const f = fixture({ runContactTurn: async ({ tools }) => {
238
+ const reference = tools.find((tool) => tool.name === 'reference_resource');
239
+ const input = { cardType: 'session', sessionID: 'ses_found' };
240
+ db.exec("CREATE TRIGGER reject_reference BEFORE INSERT ON assistant_contact_part WHEN json_extract(NEW.part_json, '$.type')='card' BEGIN SELECT RAISE(ABORT, 'card write failed'); END");
241
+ results.push(await reference.execute('failed', input));
242
+ db.exec('DROP TRIGGER reject_reference');
243
+ results.push(await reference.execute('retry', input));
244
+ results.push(await reference.execute('duplicate', input));
245
+ return { text: '卡片已发送。', bubbles: ['卡片已发送。'] };
246
+ } });
247
+ db = new (require('better-sqlite3'))(path.join(f.directory, 'assistants.sqlite'));
248
+ try {
249
+ f.service.appendContactCard(f.host.id, { cardType: 'session', sessionID: 'ses_found', directory: f.directory, status: 'busy' });
250
+ f.service.reportAssignedSessionSettle('ses_found', 'cancelled', false);
251
+ expect(await f.send()).toMatchObject({ status: 'complete' });
252
+ expect(results[0]).toMatchObject({ isError: true, details: { error: 'reference_failed' } });
253
+ expect(results[0].details.card).toBeUndefined();
254
+ expect(results.slice(1).every((result) => result.details.sent === true)).toBe(true);
255
+ expect(cards(f.service, f.host.id)).toHaveLength(2);
256
+ expect(db.prepare('SELECT active, status FROM assistant_contact_watch').get()).toMatchObject({ active: 0, status: 'cancelled' });
257
+ } finally { db.close(); f.close(); }
258
+ });
259
+
260
+ it('fails closed on deleted, forbidden and unavailable resources without fabricating cards', async () => {
261
+ const results = [];
262
+ const f = fixture({ listScheduledTasks: async () => { throw new Error('unavailable'); },
263
+ runContactTurn: async ({ tools }) => {
264
+ const reference = tools.find((tool) => tool.name === 'reference_resource');
265
+ for (const input of [
266
+ { cardType: 'assistant', assistantID: 'deleted' },
267
+ { cardType: 'session', sessionID: 'ses_forbidden' },
268
+ { cardType: 'session', sessionID: 'ses_forbidden', projectID: 'project' },
269
+ { cardType: 'schedule', projectID: 'project', taskID: 'task' },
270
+ { cardType: 'schedule', projectID: 'unregistered', taskID: 'task' },
271
+ { cardType: 'session', sessionID: 'ses_found', directory: '/forged' },
272
+ ]) results.push(await reference.execute('invalid', input));
273
+ return { text: '这些卡片暂时无法发送。', bubbles: ['这些卡片暂时无法发送。'] };
274
+ },
275
+ });
276
+ f.client.session.get.mockImplementation(async ({ sessionID }) => ({ id: sessionID, directory: path.dirname(f.directory) }));
277
+ try {
278
+ expect(await f.send()).toMatchObject({ status: 'complete' });
279
+ expect(results.every((result) => result.isError && !result.details.sent && !result.details.card)).toBe(true);
280
+ expect(cards(f.service, f.host.id)).toEqual([]);
281
+ expect(f.client.session.prompt).not.toHaveBeenCalled();
282
+ } finally { f.close(); }
283
+ });
284
+ });
@@ -1,7 +1,6 @@
1
1
  import { AssistantError, createAssistantsService } from './service.js';
2
2
  import { isSafeInlineImageMime } from './contact-attachments.js';
3
3
  import { createChatCompletion } from '../llm/completions.js';
4
- import { setAssignedSessionSettleHandler } from '../session-goal/runtime.js';
5
4
  import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
6
5
  import path from 'node:path';
7
6
  import { createWeixinRuntime } from './weixin/runtime.js';
@@ -58,7 +57,6 @@ export const registerAssistantRoutes = (app, dependencies) => {
58
57
  onSystemSessionPersisted: dependencies.onSystemSessionPersisted,
59
58
  createChatCompletion: boundCompletion,
60
59
  });
61
- setAssignedSessionSettleHandler(({ sessionId, status }) => service.reportAssignedSessionSettle(sessionId, status));
62
60
  const unsubscribeTaskResults = dependencies.setTaskResultHandler?.((run) => service.reportScheduledTaskResult(run));
63
61
  app.use('/api/yuri/assistants', (req, res, next) => Promise.resolve(dependencies.refreshAllowedRoots?.()).then(next).catch((error) => respond(res, () => { throw error; })));
64
62
  app.get('/api/yuri/assistants/capability', (_req, res) => respond(res, () => service.capability()));
@@ -141,7 +139,6 @@ export const registerAssistantRoutes = (app, dependencies) => {
141
139
  registerAssistantChannelRoutes(app, channels);
142
140
  return { service, close: async () => {
143
141
  unsubscribeTaskResults?.();
144
- setAssignedSessionSettleHandler(null);
145
142
  await Promise.all([weixin.close(), channels.close()]);
146
143
  service.close();
147
144
  } };
@@ -3,11 +3,13 @@ import fs from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import path from 'node:path';
5
5
  import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
6
+ import { getNativeSessionGoal } from '../opencode/native-goal.js';
6
7
  import { validAssistantDeliveryParts } from '../assistant-delivery-parts.js';
7
8
  import { createContactMemoryReader } from './memory.js';
8
9
  import { getContactGreeting } from './contact-greeting.js';
10
+ import { loadChannelImage } from './channel-image.js';
9
11
  import { getWorktrees as defaultListWorktrees } from '../git/service.js';
10
- import { contactCardIdentity, parseContactCard, parseContactPart } from './cards.js';
12
+ import { contactCardIdentity, createAssistantCardPart, createScheduleCardPart, createSessionCardPart, parseContactCard, parseContactPart } from './cards.js';
11
13
  import { ensureContactSummary } from './summary.js';
12
14
  import {
13
15
  CONTACT_PAGE_DEFAULT_LIMIT,
@@ -47,6 +49,7 @@ import {
47
49
  canonicalDescriptorFromRow,
48
50
  ensureContactAttachmentSchema,
49
51
  getContactAttachmentRow,
52
+ getContactAttachmentByUploadID,
50
53
  ingestDataUrlFilePart,
51
54
  isSafeInlineImageMime,
52
55
  materializeContactHistory,
@@ -152,8 +155,8 @@ const isMissingError = (error) => {
152
155
  };
153
156
  const ASSISTANT_SUCCESS_FINISH = new Set(['stop']);
154
157
  const ASSISTANT_ERROR_FINISH = new Set(['error', 'length', 'content-filter']);
155
- const GOAL_ACTIVE_STATUSES = new Set(['active', 'paused']);
156
- const GOAL_ERROR_STATUSES = new Set(['blocked', 'budgetLimited']);
158
+ const GOAL_ACTIVE_STATUSES = new Set(['active']);
159
+ const GOAL_ERROR_STATUSES = new Set(['paused']);
157
160
  const isTransientMessagesFailure = (result, error) => {
158
161
  if (error) {
159
162
  if (error instanceof AssistantError) return false;
@@ -626,7 +629,6 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
626
629
  return null;
627
630
  };
628
631
  // Stash assign delivery message IDs until the session card watch is written.
629
- const pendingAssignMessageIDs = new Map();
630
632
  // Assigned-session complete/error/cancelled resumes the contact LLM (no canned settle bubble).
631
633
  // Assigned after inContactTurnLane exists; reportAssignedSession only schedules via this ref.
632
634
  const assignedSessionResumeRef = { schedule: null };
@@ -795,12 +797,6 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
795
797
  void assignedCompletion.observe({ kind: 'complete', sessionId: sessionID }, { sessionID, options });
796
798
  return true;
797
799
  };
798
- const goalOfSession = (session) => {
799
- const goal = session?.metadata?.yuri?.goal;
800
- if (!goal || typeof goal !== 'object') return null;
801
- const status = typeof goal.status === 'string' ? goal.status.trim() : '';
802
- return status ? { status } : null;
803
- };
804
800
  /** Messages that belong to this delivery watermark (assign prompt messageID). */
805
801
  const messagesOwnedByDelivery = (messages, deliveryMessageID) => {
806
802
  if (!Array.isArray(messages)) return [];
@@ -865,7 +861,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
865
861
  if (!finish && !assistantInfo.time?.completed) return null;
866
862
  return null;
867
863
  };
868
- const inferAssignedSessionSettleStatus = (getResult, messagesResult, { deliveryMessageID = null, activeBusy = null } = {}) => {
864
+ const inferAssignedSessionSettleStatus = (getResult, messagesResult, { deliveryMessageID = null, activeBusy = null, goal = null } = {}) => {
869
865
  // Another Host may share this watch store but use a different OpenCode database.
870
866
  // Absence there is not an authoritative terminal result for the owning worker.
871
867
  if (isMissing(getResult)) return null;
@@ -874,8 +870,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
874
870
  if (activeBusy === true) return null;
875
871
  const session = sessionRecord(getResult);
876
872
  if (session?.error) return isUserAbort(session.error) ? 'cancelled' : 'error';
877
- const goal = goalOfSession(session);
878
- // Goal settle is owned by the session-goal reporter — never invent success.
873
+ // Goal completion comes only from OpenCode's native plugin state.
879
874
  if (goal && GOAL_ACTIVE_STATUSES.has(goal.status)) return null;
880
875
  if (goal && GOAL_ERROR_STATUSES.has(goal.status)) return 'error';
881
876
  if (goal && goal.status === 'complete') return 'complete';
@@ -952,9 +947,11 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
952
947
  else messagesResult = null;
953
948
  }
954
949
  if (closed) return;
950
+ const goal = await getNativeSessionGoal(client(), watch.sessionID, directory);
955
951
  const status = inferAssignedSessionSettleStatus(getResult, messagesResult, {
956
952
  deliveryMessageID: watch.messageID,
957
953
  activeBusy,
954
+ goal,
958
955
  });
959
956
  if (status) reportAssignedSession(watch.sessionID, status);
960
957
  } catch {
@@ -972,6 +969,11 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
972
969
  payload,
973
970
  );
974
971
  const body = eventBody(payload);
972
+ if (payload.type === 'rpc.opencode.goal.changed' && nonEmptyString(body?.sessionID)) {
973
+ if (body.goal?.status === 'complete') return reportAssignedSession(body.sessionID, 'complete');
974
+ if (body.goal?.status === 'paused') return reportAssignedSession(body.sessionID, 'error');
975
+ return false;
976
+ }
975
977
  // Message lifecycle still requires a body; execution/status may carry sessionID on body only.
976
978
  if (payload.type === 'message.updated') {
977
979
  if (!plainObject(body)) return false;
@@ -1705,14 +1707,18 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
1705
1707
 
1706
1708
  const persistPublishedContactCard = (assistantID, { userMessageID, turnID, index, card: cardInput }) => {
1707
1709
  const card = parseContactCard({ type: 'card', cardType: cardInput?.cardType || 'session', ...cardInput });
1708
- if (!card) return false;
1710
+ if (!card) throw new AssignError(ASSIGN_CODES.VALIDATION, 'Invalid resource reference.');
1709
1711
  const cardID = contactCardMessageID(userMessageID, index);
1710
- if (getContactMessage(db, cardID)) return false;
1711
1712
  db.exec('BEGIN IMMEDIATE');
1712
1713
  try {
1713
- if (getContactMessage(db, cardID)) {
1714
+ editable(assistantID);
1715
+ if (!getContactMessage(db, userMessageID)) throw new AssignError(ASSIGN_CODES.VALIDATION, 'This turn no longer belongs to the transcript.');
1716
+ const existing = getContactMessage(db, cardID);
1717
+ if (existing) {
1718
+ const published = existing.parts.find((part) => part.type === 'card');
1719
+ if (!published || contactCardIdentity(published) !== contactCardIdentity(card)) throw new AssignError(ASSIGN_CODES.VALIDATION, 'Reference slot already belongs to another resource.');
1714
1720
  db.exec('COMMIT');
1715
- return false;
1721
+ return published;
1716
1722
  }
1717
1723
  insertContactMessage(db, {
1718
1724
  messageID: cardID,
@@ -1725,23 +1731,9 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
1725
1731
  status: 'complete',
1726
1732
  parts: [card],
1727
1733
  });
1728
- if (card.cardType === 'session' && card.sessionID) {
1729
- const deliveryMessageID = pendingAssignMessageIDs.get(card.sessionID)
1730
- || (nonEmptyString(card.messageID) ? card.messageID : null);
1731
- if (pendingAssignMessageIDs.has(card.sessionID)) pendingAssignMessageIDs.delete(card.sessionID);
1732
- upsertContactWatch(db, {
1733
- assistantID,
1734
- sessionID: card.sessionID,
1735
- directory: card.directory,
1736
- status: card.status === 'error' || card.status === 'question' || card.status === 'complete' ? card.status : 'busy',
1737
- updatedAt: now(),
1738
- messageID: deliveryMessageID || null,
1739
- });
1740
- if (deliveryMessageID) void assignedCompletion.observe({ kind: 'running', sessionId: card.sessionID });
1741
- }
1742
1734
  bump();
1743
1735
  db.exec('COMMIT');
1744
- return true;
1736
+ return card;
1745
1737
  } catch (error) {
1746
1738
  db.exec('ROLLBACK');
1747
1739
  throw error;
@@ -1775,17 +1767,12 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
1775
1767
  };
1776
1768
 
1777
1769
  const rememberPublishedContactCard = (assistantID, { userMessageID, turnID, assignedCards, card }) => {
1778
- assignedCards.push(card);
1779
- try {
1780
- persistPublishedContactCard(assistantID, {
1781
- userMessageID,
1782
- turnID,
1783
- index: assignedCards.length - 1,
1784
- card,
1785
- });
1786
- } catch {
1787
- // Publishing a card must not abort the live turn.
1788
- }
1770
+ const index = assignedCards.findIndex((item) => contactCardIdentity(item) === contactCardIdentity(card));
1771
+ const published = persistPublishedContactCard(assistantID, {
1772
+ userMessageID, turnID, index: index < 0 ? assignedCards.length : index, card,
1773
+ });
1774
+ if (index < 0) assignedCards.push(published);
1775
+ return published;
1789
1776
  };
1790
1777
 
1791
1778
  /** Persist remaining assistant bubbles/cards for an already-admitted user turn (no user row). */
@@ -1833,20 +1820,6 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
1833
1820
  parts: [card],
1834
1821
  });
1835
1822
  ordinal += 1;
1836
- if (card.cardType === 'session' && card.sessionID) {
1837
- const deliveryMessageID = pendingAssignMessageIDs.get(card.sessionID)
1838
- || (nonEmptyString(card.messageID) ? card.messageID : null);
1839
- if (pendingAssignMessageIDs.has(card.sessionID)) pendingAssignMessageIDs.delete(card.sessionID);
1840
- upsertContactWatch(db, {
1841
- assistantID,
1842
- sessionID: card.sessionID,
1843
- directory: card.directory,
1844
- status: card.status === 'error' || card.status === 'question' || card.status === 'complete' ? card.status : 'busy',
1845
- updatedAt: now(),
1846
- messageID: deliveryMessageID || null,
1847
- });
1848
- if (deliveryMessageID) void assignedCompletion.observe({ kind: 'running', sessionId: card.sessionID });
1849
- }
1850
1823
  });
1851
1824
  bump();
1852
1825
  db.exec('COMMIT');
@@ -2459,14 +2432,26 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
2459
2432
  lookupMessage: (lookup) => lookupAssignMessage({ ...lookup, signal }),
2460
2433
  messageID: params?.messageID || `msg_assign_${id()}`,
2461
2434
  });
2462
- // Stash until the session card watch is written so reuse cannot settle on an old tail.
2435
+ // Watch admission belongs to assignment, independently of whether a card is sent.
2463
2436
  if (nonEmptyString(assigned?.sessionID) && nonEmptyString(assigned?.messageID)) {
2464
- pendingAssignMessageIDs.set(assigned.sessionID, assigned.messageID);
2437
+ try {
2438
+ db.transaction(() => {
2439
+ upsertContactWatch(db, {
2440
+ assistantID: row.assistant_id, sessionID: assigned.sessionID,
2441
+ directory: assigned.directory, status: assigned.status || 'busy',
2442
+ updatedAt: now(), messageID: assigned.messageID,
2443
+ });
2444
+ bump();
2445
+ }).immediate();
2446
+ } catch {
2447
+ return { ...assigned, watchError: 'watch_registration_failed' };
2448
+ }
2449
+ void assignedCompletion.observe({ kind: 'running', sessionId: assigned.sessionID });
2465
2450
  }
2466
2451
  return assigned;
2467
2452
  };
2468
2453
  /** Watch an existing session only — no prompt. Baseline status avoids false settle resume. */
2469
- const watchSessionWork = async (_row, params = {}) => {
2454
+ const watchSessionWork = async (row, params = {}) => {
2470
2455
  const sessionID = typeof params.sessionID === 'string' ? params.sessionID.trim() : '';
2471
2456
  if (!sessionID) {
2472
2457
  throw new AssignError(ASSIGN_CODES.VALIDATION, 'watch_session requires sessionID.');
@@ -2488,6 +2473,14 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
2488
2473
  status = 'busy';
2489
2474
  }
2490
2475
  }
2476
+ params.signal?.throwIfAborted();
2477
+ db.transaction(() => {
2478
+ upsertContactWatch(db, {
2479
+ assistantID: row.assistant_id, sessionID: resolved.sessionID,
2480
+ directory: resolved.directory, status, updatedAt: now(), messageID: null,
2481
+ });
2482
+ bump();
2483
+ }).immediate();
2491
2484
  return {
2492
2485
  sessionID: resolved.sessionID,
2493
2486
  directory: resolved.directory,
@@ -2779,6 +2772,33 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
2779
2772
  }
2780
2773
  return { tasks, ...(failed.length > 0 ? { partial: true, failed } : {}) };
2781
2774
  };
2775
+ const resolveContactResource = async (input, signal) => {
2776
+ signal?.throwIfAborted();
2777
+ if (input.cardType === 'session') {
2778
+ const resolved = await resolveReferencedSession({ sessionID: input.sessionID, signal, includeMessages: false });
2779
+ return createSessionCardPart(resolved);
2780
+ }
2781
+ if (input.cardType === 'assistant') {
2782
+ const target = output(editable(input.assistantID));
2783
+ return createAssistantCardPart({ ...target, assistantID: target.id });
2784
+ }
2785
+ const projects = await listProjects();
2786
+ if (!Array.isArray(projects)) throw new AssignError(ASSIGN_CODES.UPSTREAM, 'Project lookup failed.');
2787
+ if (!normalizeRegisteredProjects(projects).some((project) => project.id === input.projectID)) throw new AssignError(ASSIGN_CODES.PROJECT_REQUIRED, 'The task project is not registered.');
2788
+ if (typeof listScheduledTasks !== 'function') throw new AssignError(ASSIGN_CODES.UPSTREAM, 'Task lookup is unavailable.');
2789
+ const tasks = await listScheduledTasks(input.projectID);
2790
+ signal?.throwIfAborted();
2791
+ if (!Array.isArray(tasks)) throw new AssignError(ASSIGN_CODES.UPSTREAM, 'Task lookup failed.');
2792
+ const task = tasks.find((task) => task?.id === input.taskID);
2793
+ if (!task) throw new AssignError(ASSIGN_CODES.NOT_FOUND, 'The scheduled task no longer exists.');
2794
+ return createScheduleCardPart({
2795
+ taskID: task.id, projectID: input.projectID, name: task.name,
2796
+ kind: task.schedule?.kind, time: task.schedule?.time || task.schedule?.times?.[0],
2797
+ timezone: task.schedule?.timezone, prompt: task.execution?.prompt,
2798
+ cron: task.schedule?.cron ?? null, date: task.schedule?.date ?? null,
2799
+ times: task.schedule?.times ?? null, weekdays: task.schedule?.weekdays ?? null,
2800
+ });
2801
+ };
2782
2802
  const updateScheduledTaskWork = async (row, params, signal) => {
2783
2803
  signal?.throwIfAborted();
2784
2804
  if (typeof patchScheduledTask !== 'function') throw new AssignError(ASSIGN_CODES.UPSTREAM, 'Updating a scheduled task is unavailable.');
@@ -3224,9 +3244,12 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
3224
3244
  return output(editable(targetID));
3225
3245
  },
3226
3246
  currentAssistant: assistantSnapshot,
3247
+ resolveResource: resolveContactResource,
3227
3248
  onCard: (card) => {
3228
- if (contactResetThisTurn) return;
3229
- rememberPublishedContactCard(assistantID, {
3249
+ controller.signal.throwIfAborted();
3250
+ if (contactResetThisTurn) throw new AssignError(ASSIGN_CODES.VALIDATION, 'This turn reset its context.');
3251
+ editable(assistantID);
3252
+ return rememberPublishedContactCard(assistantID, {
3230
3253
  userMessageID: messageID, turnID, assignedCards, card,
3231
3254
  });
3232
3255
  },
@@ -3568,9 +3591,13 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
3568
3591
  },
3569
3592
  updateAssistantSettings: (patch) => updateContactSettings(row.assistant_id, patch),
3570
3593
  currentAssistant: assistantSnapshot,
3594
+ resolveResource: resolveContactResource,
3571
3595
  onCard: (card) => {
3572
- if (contactResetThisTurn) return;
3573
- rememberPublishedContactCard(row.assistant_id, {
3596
+ controller.signal.throwIfAborted();
3597
+ if (contactResetThisTurn) throw new AssignError(ASSIGN_CODES.VALIDATION, 'This turn reset its context.');
3598
+ editable(row.assistant_id);
3599
+ if (!getContactMessage(db, messageID)) throw new AssignError(ASSIGN_CODES.VALIDATION, 'This turn no longer belongs to the transcript.');
3600
+ return rememberPublishedContactCard(row.assistant_id, {
3574
3601
  userMessageID: messageID, turnID, assignedCards, card,
3575
3602
  });
3576
3603
  },
@@ -3862,9 +3889,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
3862
3889
  parts: [card],
3863
3890
  });
3864
3891
  if (card.cardType === 'session' && card.sessionID) {
3865
- const deliveryMessageID = pendingAssignMessageIDs.get(card.sessionID)
3866
- || (nonEmptyString(card.messageID) ? card.messageID : null);
3867
- if (pendingAssignMessageIDs.has(card.sessionID)) pendingAssignMessageIDs.delete(card.sessionID);
3892
+ const deliveryMessageID = nonEmptyString(card.messageID) ? card.messageID : null;
3868
3893
  upsertContactWatch(db, {
3869
3894
  assistantID: row.assistant_id,
3870
3895
  sessionID: card.sessionID,
@@ -4108,11 +4133,33 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
4108
4133
  active(assistantID);
4109
4134
  return readContactChannelPage(db, assistantID, options);
4110
4135
  };
4111
- return { capability: async () => ({ supported: true, enabled: enabled(), revision: revision(), serverInstanceID: await getServerId(), sharingAvailable: false, archiveMetadataAvailable: typeof archiveSessionHost === 'function', sessionMetadataAvailable: false }), snapshot, channelPage, ensureDefaultAssistant, createAssistant, updateAssistant, setEnabled: (input) => { if (!plainObject(input) || typeof input.enabled !== 'boolean' || input.expectedRevision !== revision()) fail('revision_conflict'); return { enabled: true, revision: revision() }; }, removeAssistant, ensure, createNew, compact, send, whenContactTurnSettled, abort, captureQueueDeliveryTarget, sendWithCapturedConfig, share, shareOperation, historicalMessages, contactMessages, clearContactMemory, resetContact, markContactRead, appendContactCard, deliverPeerMessage, listAssistantScheduledTasks, reportScheduledTaskResult, putAssistantContactAttachment, getAssistantContactAttachment, migrateContactAttachments, processEvent, reportAssignedSessionSettle: reportAssignedSession, reconcile, close: () => {
4136
+ const prepareChannelImage = async (assistantID, source, { generation, uploadID, signal }) => {
4137
+ const row = active(assistantID);
4138
+ const assertGeneration = () => {
4139
+ signal?.throwIfAborted();
4140
+ if (channelPage(assistantID, { tipOnly: true }).generation !== generation) fail('cancelled');
4141
+ };
4142
+ assertGeneration();
4143
+ const existing = getContactAttachmentByUploadID(db, assistantID, uploadID);
4144
+ if (existing && existing.generation === generation) return canonicalDescriptorFromRow(existing);
4145
+ const { buffer, mime, filename } = await loadChannelImage(source, {
4146
+ cwd: resolveAssistantCwd({ workspacePath: row.workspace_path, effectiveWorkspacePath: effectiveWorkspace(row) }),
4147
+ allowedRoots: getAllowedRoots(), signal,
4148
+ readAttachment: (attachmentID) => getAssistantContactAttachment(assistantID, attachmentID),
4149
+ });
4150
+ assertGeneration();
4151
+ const image = await putAssistantContactAttachment(assistantID, uploadID, {
4152
+ stream: { body: buffer }, signal,
4153
+ headers: { 'content-type': mime, 'x-attachment-filename': filename,
4154
+ 'x-content-size': String(buffer.length), 'x-content-sha256': crypto.createHash('sha256').update(buffer).digest('hex') },
4155
+ });
4156
+ assertGeneration();
4157
+ return image;
4158
+ };
4159
+ return { capability: async () => ({ supported: true, enabled: enabled(), revision: revision(), serverInstanceID: await getServerId(), sharingAvailable: false, archiveMetadataAvailable: typeof archiveSessionHost === 'function', sessionMetadataAvailable: false }), snapshot, channelPage, prepareChannelImage, ensureDefaultAssistant, createAssistant, updateAssistant, setEnabled: (input) => { if (!plainObject(input) || typeof input.enabled !== 'boolean' || input.expectedRevision !== revision()) fail('revision_conflict'); return { enabled: true, revision: revision() }; }, removeAssistant, ensure, createNew, compact, send, whenContactTurnSettled, abort, captureQueueDeliveryTarget, sendWithCapturedConfig, share, shareOperation, historicalMessages, contactMessages, clearContactMemory, resetContact, markContactRead, appendContactCard, deliverPeerMessage, listAssistantScheduledTasks, reportScheduledTaskResult, putAssistantContactAttachment, getAssistantContactAttachment, migrateContactAttachments, processEvent, reportAssignedSessionSettle: reportAssignedSession, reconcile, close: () => {
4112
4160
  assignedCompletion.dispose();
4113
4161
  cancelAssignedResumes({});
4114
4162
  sessionAbortInflight.clear();
4115
- pendingAssignMessageIDs.clear();
4116
4163
  for (const turn of contactControllers.values()) turn.controller.abort();
4117
4164
  if (!closed) {
4118
4165
  closed = true;