@yuriai/web 0.2.19 → 0.2.20

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 (163) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/AgentAvatar-MK9jNcwx.js +1 -0
  3. package/dist/assets/AssistantView-CVf9ta92.js +3 -0
  4. package/dist/assets/{DiagramView-HNaj_sVG.js → DiagramView-ys2UVvx1.js} +1 -1
  5. package/dist/assets/{FadeInOnReveal-Dq1IuEQp.js → FadeInOnReveal-B1g8C4P7.js} +1 -1
  6. package/dist/assets/{GuiPluginSurface-N-iK-MeX.js → GuiPluginSurface-C1KQZUmj.js} +1 -1
  7. package/dist/assets/{GuiPluginWindow-ClutFX_h.js → GuiPluginWindow-D4TIvZDn.js} +1 -1
  8. package/dist/assets/{Icon-tnX3bel1.js → Icon-C93bLV0e.js} +1 -1
  9. package/dist/assets/{ImageLoadingPlaceholder-IE6JO3WM.js → ImageLoadingPlaceholder-DM2ifWd8.js} +1 -1
  10. package/dist/assets/{LoadingImage-DNZmZRZS.js → LoadingImage-BoaGSpZ_.js} +1 -1
  11. package/dist/assets/{MarkdownRenderer-DuA1vlFT.js → MarkdownRenderer-B8LWUc6A.js} +2 -2
  12. package/dist/assets/{MarkdownRendererImpl-BwZ91PA5.js → MarkdownRendererImpl-DL069I2q.js} +1 -1
  13. package/dist/assets/{MarkstreamRendererImpl-kgBwH_VF.js → MarkstreamRendererImpl-CwR_p-oQ.js} +1 -1
  14. package/dist/assets/{MobileDetailNavigation-sm5MbnK3.js → MobileDetailNavigation-C7Z7mVZV.js} +1 -1
  15. package/dist/assets/{MobileResizableSheet-Cw6rRBR2.js → MobileResizableSheet-ChrM2_er.js} +1 -1
  16. package/dist/assets/{MobileShareBridge-BjpB1cz1.js → MobileShareBridge-DtXwoQtk.js} +2 -2
  17. package/dist/assets/MobileTabPageHeader-BT7U61qi.js +2 -0
  18. package/dist/assets/{MultiRunWindow-pslncrAh.js → MultiRunWindow-CFWkmiwx.js} +1 -1
  19. package/dist/assets/{OnboardingScreen-o9e7j2Lk.js → OnboardingScreen-Bb3wmiKY.js} +1 -1
  20. package/dist/assets/{OverlayScrollbar-BA6KEyhj.js → OverlayScrollbar-DD6avzvO.js} +1 -1
  21. package/dist/assets/SettingsView-B4xkRLZ3.js +29 -0
  22. package/dist/assets/SettingsView-BRIvklfP.css +1 -0
  23. package/dist/assets/{SettingsWindow-D-Vjsme7.js → SettingsWindow-jF7nPmJG.js} +1 -1
  24. package/dist/assets/{TerminalView-B4bliT5i.js → TerminalView-Cms4rfIE.js} +1 -1
  25. package/dist/assets/{ToolOutputDialog-D1rZbaHo.js → ToolOutputDialog-CBSb39qy.js} +1 -1
  26. package/dist/assets/{YuriLogo-CDmH1ycw.js → YuriLogo-CeZsIqiE.js} +1 -1
  27. package/dist/assets/{appThemeRegistry-DyTPt9Uq.js → appThemeRegistry-Bps27som.js} +1 -1
  28. package/dist/assets/{assistant-attachment-cache-lEUFn3mr.js → assistant-attachment-cache-C2SmtQG7.js} +1 -1
  29. package/dist/assets/{button-BEOJB042.js → button--mt1oJ-H.js} +1 -1
  30. package/dist/assets/{capgoAdapter-BrU-ms8F.js → capgoAdapter-ZBPKiKyL.js} +1 -1
  31. package/dist/assets/{collapsible-DrQlDm15.js → collapsible-Dh2xZynB.js} +1 -1
  32. package/dist/assets/{desktop-dp2Z0toS.js → desktop-CiqEZVr5.js} +1 -1
  33. package/dist/assets/{desktopHosts-CYKaLp1V.js → desktopHosts-B4HMNmrx.js} +1 -1
  34. package/dist/assets/{desktopRelayRestore-5yuHB356.js → desktopRelayRestore-CRl62mqn.js} +1 -1
  35. package/dist/assets/{device-DzWRCXhq.js → device-Coc5tapU.js} +1 -1
  36. package/dist/assets/{diagram-DyQPPDKS.js → diagram-CrQbE7QP.js} +1 -1
  37. package/dist/assets/{dialog-CooVl0xA.js → dialog-BG9W4FO9.js} +1 -1
  38. package/dist/assets/{dropdown-menu.styles-Bj4YEb3T.js → dropdown-menu.styles-BOP49Dw2.js} +1 -1
  39. package/dist/assets/es-CuWYQYZ1.js +15 -0
  40. package/dist/assets/{fileMentionTouchSelection-8I9u8H6l.js → fileMentionTouchSelection-m4Xsn0cx.js} +1 -1
  41. package/dist/assets/{fileQueries-DbUx7NwP.js → fileQueries-Bd-OEFmO.js} +1 -1
  42. package/dist/assets/{fileReferenceActions-No7p4Kdo.js → fileReferenceActions-BnPPqYXw.js} +1 -1
  43. package/dist/assets/fr-yebDRPGw.js +13 -0
  44. package/dist/assets/{gitApi-BVMvxPtG.js → gitApi-C1pkEDXu.js} +1 -1
  45. package/dist/assets/{gitApiHttp-BtI23x-7.js → gitApiHttp-CoNokuDM.js} +1 -1
  46. package/dist/assets/{gui-BCPFcL_m.js → gui-D3wrcUs6.js} +1 -1
  47. package/dist/assets/{host-BoCxB_x4.js → host-BqNFap4A.js} +1 -1
  48. package/dist/assets/{image-loading-FUFYiO1j.js → image-loading-DVZlFuU5.js} +1 -1
  49. package/dist/assets/{input-B-4VixoV.js → input-BMUm4I0i.js} +1 -1
  50. package/dist/assets/{insertionBoundaries-YVc2e3H2.js → insertionBoundaries-WLpirs0A.js} +1 -1
  51. package/dist/assets/ja-f1wDEfxS.js +15 -0
  52. package/dist/assets/ko-n8CMb8k9.js +15 -0
  53. package/dist/assets/{main-Cs5VJerX.js → main-CNmq04w8.js} +21 -21
  54. package/dist/assets/{main-DZ5HVH-j.js → main-djohnOii.js} +2 -2
  55. package/dist/assets/{markdownHeightCache-SdaL8x58.js → markdownHeightCache-BWrnxGTO.js} +1 -1
  56. package/dist/assets/{mcpQueries-B1ZULr7c.js → mcpQueries-BfSiXImW.js} +1 -1
  57. package/dist/assets/miniChat-DXN8mcdi.js +2 -0
  58. package/dist/assets/mobile--08sYbKy.js +2 -0
  59. package/dist/assets/{mobileBackNavigation-D-cRdrKd.js → mobileBackNavigation-EIV61ZvG.js} +1 -1
  60. package/dist/assets/{multirun-D6bNScic.js → multirun-Dfuqt2Sd.js} +1 -1
  61. package/dist/assets/{native-config-obwt8WA1.js → native-config-Cswl9jqU.js} +1 -1
  62. package/dist/assets/{persistence-BfjCXjLZ.js → persistence-CNEHspb4.js} +1 -1
  63. package/dist/assets/pl-BpveZ1bR.js +15 -0
  64. package/dist/assets/{platform-syRnKuVU.js → platform-Q45KPuGv.js} +1 -1
  65. package/dist/assets/{projectMeta-LtQkG8fN.js → projectMeta-CuVxfoYb.js} +1 -1
  66. package/dist/assets/pt-BR-bq37AHb6.js +15 -0
  67. package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-DWgXfxGx.js} +1 -1
  68. package/dist/assets/{readiness-BWBtf7Am.js → readiness-DDF6yf-o.js} +1 -1
  69. package/dist/assets/{renderElectronMiniChatApp-EL2J2wQd.js → renderElectronMiniChatApp-Cfs2xjgL.js} +2 -2
  70. package/dist/assets/{renderMobileApp-DOCWKmuC.js → renderMobileApp-B66uW5zc.js} +7 -7
  71. package/dist/assets/runtime-auth-BaBM02zI.js +1 -0
  72. package/dist/assets/{runtime-fetch-BAN5Gnnp.js → runtime-fetch-DfALP7-b.js} +1 -1
  73. package/dist/assets/{runtime-file-download-BzblfnMx.js → runtime-file-download-xvItwYMc.js} +1 -1
  74. package/dist/assets/{runtime-file-resource-D3k0hKDj.js → runtime-file-resource-DtsKbFf3.js} +1 -1
  75. package/dist/assets/{runtime-switch-CAZiOV2G.js → runtime-switch-DhMY9eiB.js} +1 -1
  76. package/dist/assets/{runtimeConfig-D577Rc9x.js → runtimeConfig-DTkP4z43.js} +1 -1
  77. package/dist/assets/runtimeEndpointReset-BMAP5ZCY.js +149 -0
  78. package/dist/assets/{scheduledTaskNavigation-CJEzv5Zr.js → scheduledTaskNavigation-7slq1geN.js} +1 -1
  79. package/dist/assets/{sessionChangeSummary-DAV313F8.js → sessionChangeSummary-BYv_KUyn.js} +1 -1
  80. package/dist/assets/{sessionLookup-CN_iYfk5.js → sessionLookup-Cx0pE6yS.js} +1 -1
  81. package/dist/assets/{sortable-tabs-strip-9okrTn1K.js → sortable-tabs-strip-D_efLXen.js} +1 -1
  82. package/dist/assets/{speechSettingsQueries-BvJCYdR_.js → speechSettingsQueries-BxHtdoOT.js} +2 -2
  83. package/dist/assets/src-DHHaXffU.css +2 -0
  84. package/dist/assets/store-CKBj6kYd.js +15 -0
  85. package/dist/assets/{terminalApi-Dw1h9m3h.js → terminalApi-DFhCeMya.js} +1 -1
  86. package/dist/assets/{textarea-9sBs8Uld.js → textarea-CNvFHvhC.js} +1 -1
  87. package/dist/assets/{tooltip-BkcQKx-p.js → tooltip-C-gdI2Am.js} +1 -1
  88. package/dist/assets/{types-BcumvHrl.js → types-BHKyslK4.js} +1 -1
  89. package/dist/assets/uk-Ds3imyqV.js +15 -0
  90. package/dist/assets/{useAppFontEffects-D9c0mG1P.js → useAppFontEffects-Ucq0gPN8.js} +9 -9
  91. package/dist/assets/{useAssistantUIStore-rdsbsVts.js → useAssistantUIStore-BZt-lLlW.js} +1 -1
  92. package/dist/assets/{useDesktopWindowControlsLayout-Dx-zWLPl.js → useDesktopWindowControlsLayout-BEscodj1.js} +1 -1
  93. package/dist/assets/{useEffectiveDirectory-DPvKdopQ.js → useEffectiveDirectory-BWRQNoDF.js} +1 -1
  94. package/dist/assets/{useFontPreferences-B4LGrKaG.js → useFontPreferences-DmeLn0t9.js} +1 -1
  95. package/dist/assets/{useMobileNavigationStore-9pGm6Lkc.js → useMobileNavigationStore-DzkVc9H_.js} +12 -11
  96. package/dist/assets/{useUIStore-NMQx_cnG.js → useUIStore-CEingF2z.js} +1 -1
  97. package/dist/assets/{useWorkerHighlightedLines-DSzghYUI.js → useWorkerHighlightedLines-Dz6lLZ-1.js} +1 -1
  98. package/dist/assets/zh-CN-BNJ3ElZ9.js +15 -0
  99. package/dist/assets/{zh-TW-CtLsIcFb.js → zh-TW-C0jQloeH.js} +2 -2
  100. package/dist/index.html +21 -21
  101. package/dist/mini-chat.html +21 -21
  102. package/dist/mobile.html +21 -21
  103. package/package.json +1 -1
  104. package/server/lib/assistants/DOCUMENTATION.md +192 -20
  105. package/server/lib/assistants/assign.js +2 -1
  106. package/server/lib/assistants/contact-store.js +151 -17
  107. package/server/lib/assistants/contact-store.test.js +44 -2
  108. package/server/lib/assistants/contact-tools.js +54 -12
  109. package/server/lib/assistants/contact-tools.test.js +21 -0
  110. package/server/lib/assistants/harness.js +39 -16
  111. package/server/lib/assistants/harness.test.js +58 -18
  112. package/server/lib/assistants/opencode-tools.js +167 -0
  113. package/server/lib/assistants/opencode-tools.test.js +295 -0
  114. package/server/lib/assistants/progressive-tools.js +33 -0
  115. package/server/lib/assistants/progressive-tools.test.js +66 -0
  116. package/server/lib/assistants/routes.js +1 -0
  117. package/server/lib/assistants/service.js +87 -40
  118. package/server/lib/assistants/service.test.js +270 -40
  119. package/server/lib/assistants/summary.js +90 -0
  120. package/server/lib/assistants/summary.test.js +86 -0
  121. package/server/lib/assistants/yuri-project.http.test.js +126 -0
  122. package/server/lib/assistants/yuri-tools.js +42 -0
  123. package/server/lib/assistants/yuri-tools.test.js +151 -0
  124. package/server/lib/llm/DOCUMENTATION.md +12 -2
  125. package/server/lib/llm/bridge-client.js +65 -16
  126. package/server/lib/llm/bridge-client.test.js +63 -2
  127. package/server/lib/opencode/DOCUMENTATION.md +2 -0
  128. package/server/lib/opencode/feature-routes-runtime.js +9 -0
  129. package/server/lib/opencode/feature-routes-runtime.test.js +12 -0
  130. package/server/lib/opencode/npm-registry.js +106 -11
  131. package/server/lib/opencode/npm-registry.test.js +64 -0
  132. package/server/lib/opencode/plugin-routes.js +3 -1
  133. package/server/lib/opencode/plugin-routes.test.js +3 -3
  134. package/server/lib/opencode/routes.js +4 -32
  135. package/server/lib/opencode/settings-runtime.js +7 -2
  136. package/server/lib/projects/DOCUMENTATION.md +29 -0
  137. package/server/lib/projects/registry.js +36 -0
  138. package/server/lib/projects/registry.test.js +107 -0
  139. package/server/lib/quota/providers/index.js +6 -2
  140. package/server/lib/quota/providers/index.test.js +6 -1
  141. package/server/lib/relay/DOCUMENTATION.md +3 -3
  142. package/server/lib/relay/host-client.js +4 -6
  143. package/server/lib/relay/host-client.reconnect.test.js +3 -2
  144. package/server/lib/relay/relay-server.e2e.test.ts +144 -1
  145. package/server/lib/small-model/DOCUMENTATION.md +2 -1
  146. package/dist/assets/AgentAvatar-CVIpaYPU.js +0 -1
  147. package/dist/assets/AssistantView-D5vJW3gp.js +0 -3
  148. package/dist/assets/MobileTabPageHeader-CEsc9PYV.js +0 -2
  149. package/dist/assets/SettingsView-20rmUHhk.js +0 -26
  150. package/dist/assets/es-DklBd0ox.js +0 -15
  151. package/dist/assets/fr-CVUs46wM.js +0 -13
  152. package/dist/assets/ja-5reg09JK.js +0 -15
  153. package/dist/assets/ko-DZdC6ooz.js +0 -15
  154. package/dist/assets/miniChat-DUSGfEUO.js +0 -2
  155. package/dist/assets/mobile-CMXtTX1x.js +0 -2
  156. package/dist/assets/pl-BerZSK-a.js +0 -15
  157. package/dist/assets/pt-BR-ydmV6U49.js +0 -15
  158. package/dist/assets/runtime-auth-ef9W7A43.js +0 -1
  159. package/dist/assets/runtimeEndpointReset-C5EiiaQf.js +0 -149
  160. package/dist/assets/src-nJdn6EvY.css +0 -2
  161. package/dist/assets/store-ClIuNNU7.js +0 -15
  162. package/dist/assets/uk-BnTevguX.js +0 -15
  163. package/dist/assets/zh-CN-DT6qIAPJ.js +0 -15
@@ -0,0 +1,126 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import http from 'node:http';
6
+ import express from 'express';
7
+ import { describe, expect, it, vi } from 'vitest';
8
+
9
+ const external = vi.hoisted(() => ({ complete: null, client: null }));
10
+ vi.mock('../llm/completions.js', () => ({ createChatCompletion: (input) => external.complete(input) }));
11
+ vi.mock('../opencode/v2-client.js', () => ({ makeOpenCodeV2Client: () => external.client }));
12
+ vi.mock('@opencode/client', () => ({ OpenCode: { make: () => external.client } }));
13
+ import { registerAssistantRoutes } from './routes.js';
14
+ import { registerConversationRoutes } from '../conversations/routes.js';
15
+ import { registerOpenCodeRoutes } from '../opencode/routes.js';
16
+ import { createSettingsRuntime } from '../opencode/settings-runtime.js';
17
+ import { createSettingsNormalizationRuntime } from '../opencode/settings-normalization-runtime.js';
18
+ import { createProjectDirectoryRuntime } from '../opencode/project-directory-runtime.js';
19
+ import { createProjectRegistry } from '../projects/registry.js';
20
+
21
+ const call = (name, args) => ({ completion: { choices: [{ message: { content: '', tool_calls: [{ id: `call_${name}`, type: 'function', function: { name, arguments: JSON.stringify(args) } }] } }] } });
22
+
23
+ describe('HTTP → real contact Agent → project registry → worker admission', () => {
24
+ it('registers a cloned directory, sends hello and persists a real session card without manual Settings', async () => {
25
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-project-http-'));
26
+ const workspace = path.join(directory, 'cloned-app');
27
+ await fs.mkdir(workspace);
28
+ const canonical = await fs.realpath(workspace);
29
+ const normalization = createSettingsNormalizationRuntime({ os, path, processLike: process });
30
+ const settings = createSettingsRuntime({ fsPromises: fs, path, crypto, SETTINGS_FILE_PATH: path.join(directory, 'settings.json'), ...normalization,
31
+ sanitizeSettingsUpdate: (patch) => patch, mergePersistedSettings: (current, patch) => ({ ...current, ...patch }),
32
+ formatSettingsResponse: (value) => value, resolveDirectoryCandidate: (value) => value,
33
+ });
34
+ const { validateDirectoryPath } = createProjectDirectoryRuntime({ fsPromises: fs, path, normalizeDirectoryPath: normalization.normalizeDirectoryPath });
35
+ const registry = createProjectRegistry({ persistSettings: settings.persistSettings, validateDirectoryPath });
36
+ const creates = vi.fn(async () => ({ id: 'ses_hello' }));
37
+ const prompts = vi.fn(async () => ({ id: 'inbox_hello', type: 'user' }));
38
+ external.client = {
39
+ provider: { list: async () => ({ data: [{ id: 'p' }] }) },
40
+ model: { list: async () => ({ data: [{ id: 'm', providerID: 'p' }] }) },
41
+ skill: { list: async () => ({ data: [] }) },
42
+ session: { create: creates, prompt: prompts, active: async () => ({}) },
43
+ };
44
+ const roots = [];
45
+ const refresh = async () => {
46
+ const current = await settings.readSettingsFromDiskStrict();
47
+ roots.splice(0, roots.length, ...(current.projects || []).map((project) => project.path));
48
+ };
49
+ let round = 0;
50
+ external.complete = async ({ body }) => {
51
+ round++;
52
+ if (round === 1) {
53
+ expect(body.tools.some((tool) => tool.function.name === 'register_project')).toBe(false);
54
+ expect(body.tools.some((tool) => tool.function.name === 'websearch')).toBe(false);
55
+ return call('load_tools', { domain: 'opencode.web' });
56
+ }
57
+ if (round === 2) {
58
+ expect(body.tools.some((tool) => tool.function.name === 'websearch')).toBe(true);
59
+ return call('load_tools', { domain: 'yuri.projects' });
60
+ }
61
+ if (round === 3) {
62
+ expect(body.tools.some((tool) => tool.function.name === 'register_project')).toBe(true);
63
+ return call('register_project', { path: workspace, label: 'Cloned App' });
64
+ }
65
+ if (round === 4) {
66
+ expect(body.messages.find((message) => message.name === 'register_project')?.content).toContain(canonical);
67
+ return call('assign_session', { projectPath: canonical, prompt: 'hello' });
68
+ }
69
+ return { text: '已在这个项目里创建会话并发送 hello。' };
70
+ };
71
+ const app = express(); app.use(express.json());
72
+ const runtime = registerAssistantRoutes(app, {
73
+ dbPath: path.join(directory, 'assistants.sqlite'), yuriDataDir: directory,
74
+ getAllowedRoots: () => roots, refreshAllowedRoots: refresh,
75
+ listProjects: async () => (await settings.readSettingsFromDiskStrict()).projects || [],
76
+ registerProject: async (input) => { const result = await registry.register(input); await refresh(); return result; },
77
+ buildOpenCodeUrl: (pathname) => `http://upstream.invalid${pathname}`, getOpenCodeAuthHeaders: () => ({}),
78
+ });
79
+ registerOpenCodeRoutes(app, { ...settings, validateDirectoryPath, formatSettingsResponse: (value) => value });
80
+ registerConversationRoutes(app, { buildOpenCodeUrl: (pathname) => `http://upstream.invalid${pathname}`, getOpenCodeAuthHeaders: () => ({}) });
81
+ const server = http.createServer(app);
82
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
83
+ const base = `http://127.0.0.1:${server.address().port}`;
84
+ const request = async (route, body) => {
85
+ const response = await fetch(`${base}${route}`, { method: body ? 'POST' : 'GET', headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
86
+ expect(response.ok).toBe(true);
87
+ return response.json();
88
+ };
89
+ try {
90
+ const assistant = await request('/api/yuri/assistants', { name: 'Test Bot', providerID: 'p', modelID: 'm' });
91
+ const admitted = await request(`/api/yuri/assistants/${assistant.id}/messages`, { messageID: 'create-project-chat', text: `Add ${workspace} and open a session saying hello` });
92
+ expect(admitted.admitted).toBe(true);
93
+ expect((await runtime.service.whenContactTurnSettled(admitted.messageID)).status).toBe('complete');
94
+ expect(creates).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ location: { directory: canonical } }));
95
+ expect(prompts).toHaveBeenCalledWith(expect.objectContaining({ sessionID: 'ses_hello', text: 'hello' }));
96
+ expect(prompts.mock.calls[0][0]).not.toHaveProperty('skills');
97
+ expect(prompts.mock.calls[0][0]).not.toHaveProperty('tools');
98
+ expect(JSON.stringify(creates.mock.calls[0][0])).not.toContain('load_tools');
99
+ expect(JSON.stringify(creates.mock.calls[0][0])).not.toContain('opencode.web');
100
+ const page = await request(`/api/yuri/assistants/${assistant.id}/contact/messages`);
101
+ expect(page.messages.flatMap((message) => message.parts)).toContainEqual(expect.objectContaining({ type: 'card', cardType: 'session', sessionID: 'ses_hello', directory: canonical }));
102
+ const persisted = await settings.readSettingsFromDiskStrict();
103
+ expect(persisted.projects).toHaveLength(1);
104
+ expect(persisted.projects[0]).toMatchObject({ path: canonical, label: 'Cloned App' });
105
+ // The pre-existing UI API uses the same registration owner and identity.
106
+ const ui = await request('/api/opencode/directory', { path: workspace });
107
+ expect(ui.settings.projects).toHaveLength(1);
108
+ expect(ui.path).toBe(canonical);
109
+ expect(ui.settings.activeProjectId).toBe(persisted.projects[0].id);
110
+ // Ordinary Session admission after a contact load still receives only its own prompt.
111
+ const modelRounds = round;
112
+ const session = await request('/api/yuri/conversations', {
113
+ input: { type: 'prompt' }, directory: canonical, messageID: 'ordinary-session',
114
+ model: { providerID: 'p', modelID: 'm' }, parts: [{ type: 'text', text: 'ordinary hello' }],
115
+ });
116
+ expect(session.ok).toBe(true);
117
+ expect(prompts.mock.calls.at(-1)[0]).toEqual({ sessionID: 'ses_hello', id: 'ordinary-session', text: 'ordinary hello', delivery: 'steer' });
118
+ expect(round).toBe(modelRounds);
119
+ } finally {
120
+ runtime.close(); server.closeAllConnections();
121
+ await new Promise((resolve) => server.close(resolve));
122
+ external.complete = null; external.client = null;
123
+ await fs.rm(directory, { recursive: true, force: true });
124
+ }
125
+ });
126
+ });
@@ -0,0 +1,42 @@
1
+ export function createYuriContactToolGroups(tools) {
2
+ return [
3
+ { id: 'yuri.projects', description: 'Register an existing workspace before opening a coding session.', names: ['register_project'] },
4
+ { id: 'yuri.assistants', description: 'Create a Bot or change its avatar.', names: ['create_assistant', 'update_avatar'] },
5
+ { id: 'yuri.tasks', description: 'Create or update scheduled tasks (including pause/resume).', names: ['schedule_task', 'update_scheduled_task'] },
6
+ ].map(({ id, description, names }) => ({ id, description, tools: tools.filter((tool) => names.includes(tool.name)) }))
7
+ .filter((group) => group.tools.length > 0);
8
+ }
9
+
10
+ const result = (details, isError = false) => ({
11
+ content: [{ type: 'text', text: JSON.stringify(details) }], details, isError, terminate: false,
12
+ });
13
+
14
+ /** Assistant-local business capability; never registered with OpenCode or its skills catalog. */
15
+ export function createYuriContactTools({ registerProject } = {}) {
16
+ if (typeof registerProject !== 'function') return [];
17
+ return [{
18
+ name: 'register_project', label: 'Register project',
19
+ description: 'Register an existing user-requested absolute Host directory as a Yuri project, then call assign_session with the returned project.path in the same turn. Does not clone/create files or switch an existing active project. Never register a guessed directory or assistant-workspaces.',
20
+ parameters: { type: 'object', additionalProperties: false, required: ['path'], properties: {
21
+ path: { type: 'string', minLength: 1, maxLength: 4096, description: 'Existing absolute Host directory resolved from the user request or filesystem discovery.' },
22
+ label: { type: 'string', minLength: 1, maxLength: 80, description: 'Optional project display name.' },
23
+ } },
24
+ execute: async (_id, params, signal) => {
25
+ signal?.throwIfAborted();
26
+ if (!params || Array.isArray(params) || typeof params !== 'object'
27
+ || Object.keys(params).some((key) => !['path', 'label'].includes(key))
28
+ || typeof params.path !== 'string' || !params.path.trim() || params.path.length > 4096
29
+ || (params.label !== undefined && (typeof params.label !== 'string' || !params.label.trim() || params.label.length > 80))) {
30
+ return result({ error: 'validation_error' }, true);
31
+ }
32
+ try {
33
+ const { project, created } = await registerProject(params, signal);
34
+ return result({ project: { id: project.id, path: project.path, ...(project.label ? { label: project.label } : {}) }, created });
35
+ } catch (error) {
36
+ signal?.throwIfAborted();
37
+ const code = ['validation_error', 'workspace_forbidden', 'project_unavailable'].includes(error?.code) ? error.code : 'yuri_operation_failed';
38
+ return result({ error: code, message: 'Registration failed. Check the project catalog before retrying; do not claim success.' }, true);
39
+ }
40
+ },
41
+ }];
42
+ }
@@ -0,0 +1,151 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createContactTools } from './contact-tools.js';
3
+ import { runContactTurn } from './harness.js';
4
+ import { createYuriContactToolGroups, createYuriContactTools } from './yuri-tools.js';
5
+ import { createProgressiveTools } from './progressive-tools.js';
6
+
7
+ const call = (name, args) => ({ completion: { choices: [{ message: { content: '', tool_calls: [{
8
+ id: `call_${name}`, type: 'function', function: { name, arguments: JSON.stringify(args) },
9
+ }] } }] } });
10
+ const names = (body) => body.tools.map((tool) => tool.function.name);
11
+ const turn = (tools, createChatCompletion, extra = {}) => runContactTurn({
12
+ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: 'Perform the requested operation.', tools, createChatCompletion, ...extra,
13
+ });
14
+
15
+ describe('assistant-only progressive business tools', () => {
16
+ it('keeps only registration from the eleven-tool expansion, with safe projections', async () => {
17
+ expect(createYuriContactTools()).toEqual([]);
18
+ const registerProject = vi.fn(async () => ({ project: { id: 'p', path: '/workspace', label: 'App', secret: 'private' }, created: true, settings: { token: 'private' } }));
19
+ const tools = createYuriContactTools({ registerProject });
20
+ expect(tools.map((tool) => tool.name)).toEqual(['register_project']);
21
+ const result = await tools[0].execute('register', { path: '/workspace' });
22
+ expect(result.details).toEqual({ project: { id: 'p', path: '/workspace', label: 'App' }, created: true });
23
+ expect(result.terminate).toBe(false);
24
+ expect(JSON.stringify(result)).not.toContain('private');
25
+ });
26
+
27
+ it.each([null, [], { path: '' }, { path: 123 }, { path: '/workspace', url: 'https://example.test' }, { path: '/workspace', label: null }])('rejects malformed registration before invoking the owner: %j', async (params) => {
28
+ const registerProject = vi.fn();
29
+ const result = await createYuriContactTools({ registerProject })[0].execute('bad', params);
30
+ expect(result).toMatchObject({ isError: true, details: { error: 'validation_error' } });
31
+ expect(registerProject).not.toHaveBeenCalled();
32
+ });
33
+
34
+ it('propagates cancellation and never exposes upstream errors', async () => {
35
+ const registerProject = vi.fn(async () => { throw new Error('Bearer private'); });
36
+ const tool = createYuriContactTools({ registerProject })[0];
37
+ const failure = await tool.execute('failed', { path: '/workspace' });
38
+ expect(failure.isError).toBe(true);
39
+ expect(JSON.stringify(failure)).not.toContain('private');
40
+ const controller = new AbortController(); controller.abort();
41
+ await expect(tool.execute('cancelled', { path: '/workspace' }, controller.signal)).rejects.toThrow();
42
+ expect(registerProject).toHaveBeenCalledTimes(1);
43
+ });
44
+
45
+ it('omits unavailable groups, rejects unknown/extra arguments and makes repeat loads idempotent', async () => {
46
+ const source = createYuriContactTools({ registerProject: vi.fn() });
47
+ const progressive = createProgressiveTools({ tools: source, groups: createYuriContactToolGroups(source) });
48
+ const loader = progressive.getTools()[0];
49
+ expect(loader.parameters.properties.domain.enum).toEqual(['yuri.projects']);
50
+ for (const params of [{ domain: 'yuri.tasks' }, { domain: 'yuri.projects', url: '/' }, {}, null]) {
51
+ expect((await loader.execute('bad', params)).isError).toBe(true);
52
+ expect(progressive.getTools().map((tool) => tool.name)).toEqual(['load_tools']);
53
+ }
54
+ expect((await loader.execute('load', { domain: 'yuri.projects' })).addedToolNames).toEqual(['register_project']);
55
+ expect((await loader.execute('again', { domain: 'yuri.projects' })).details.alreadyLoaded).toBe(true);
56
+ expect(progressive.getTools().map((tool) => tool.name)).toEqual(['load_tools', 'register_project']);
57
+ expect(source.map((tool) => tool.name)).toEqual(['register_project']);
58
+ expect(createProgressiveTools({ tools: source, groups: createYuriContactToolGroups(source) }).getTools().map((tool) => tool.name)).toEqual(['load_tools']);
59
+ });
60
+
61
+ it('really mounts schemas and executors on the next model round, then resets on the next contact turn', async () => {
62
+ const registerProject = vi.fn(async () => ({ project: { id: 'p', path: '/workspace' }, created: true }));
63
+ const tools = [...createContactTools({}), ...createYuriContactTools({ registerProject })];
64
+ let round = 0;
65
+ const result = await turn(tools, async ({ body }) => {
66
+ round++;
67
+ if (round === 1) {
68
+ expect(names(body)).toContain('assign_session');
69
+ expect(names(body)).toContain('load_tools');
70
+ for (const name of ['register_project', 'create_assistant', 'update_avatar', 'schedule_task', 'update_scheduled_task']) expect(names(body)).not.toContain(name);
71
+ expect(JSON.stringify(body)).not.toContain('register_project');
72
+ return call('load_tools', { domain: 'yuri.projects' });
73
+ }
74
+ expect(names(body)).toContain('register_project');
75
+ expect(names(body)).not.toContain('schedule_task');
76
+ const registration = body.tools.find((tool) => tool.function.name === 'register_project');
77
+ expect(registration.function.parameters.required).toEqual(['path']);
78
+ if (round === 2) return call('register_project', { path: '/workspace' });
79
+ expect(body.messages.findLast((message) => message.name === 'register_project')?.content).toContain('/workspace');
80
+ return { text: 'Registered.' };
81
+ });
82
+ expect(result.tools.map((tool) => tool.name)).toContain('register_project');
83
+ expect(registerProject).toHaveBeenCalledTimes(1);
84
+ await turn(tools, async ({ body }) => {
85
+ expect(names(body)).not.toContain('register_project');
86
+ return { text: 'New turn.' };
87
+ });
88
+ });
89
+
90
+ it('rejects guessed hidden calls before execution and corrects to the visible loader', async () => {
91
+ const registerProject = vi.fn(async () => ({ project: { id: 'p', path: '/workspace' }, created: true }));
92
+ let round = 0;
93
+ await turn(createYuriContactTools({ registerProject }), async ({ body }) => {
94
+ round++;
95
+ if (round === 1) return call('register_project', { path: '/workspace' });
96
+ expect(registerProject).not.toHaveBeenCalled();
97
+ if (round === 2) {
98
+ expect(names(body)).not.toContain('register_project');
99
+ expect(JSON.stringify(body.messages)).toContain('load_tools');
100
+ return call('load_tools', { domain: 'yuri.projects' });
101
+ }
102
+ return { text: 'Loaded, no mutation requested.' };
103
+ });
104
+ expect(registerProject).not.toHaveBeenCalled();
105
+ });
106
+
107
+ it('cannot load and execute a hidden operation in the same response', async () => {
108
+ const registerProject = vi.fn();
109
+ let round = 0;
110
+ await turn(createYuriContactTools({ registerProject }), async ({ body }) => {
111
+ round++;
112
+ expect(names(body)).not.toContain('register_project');
113
+ if (round === 1) {
114
+ const response = call('load_tools', { domain: 'yuri.projects' });
115
+ response.completion.choices[0].message.tool_calls.push(call('register_project', { path: '/workspace' }).completion.choices[0].message.tool_calls[0]);
116
+ return response;
117
+ }
118
+ return { text: 'No operation executed.' };
119
+ });
120
+ expect(registerProject).not.toHaveBeenCalled();
121
+ });
122
+
123
+ it.each(['assistants', 'tasks'])('loads existing %s operations without altering their owners', async (domain) => {
124
+ const createAssistant = vi.fn(async () => ({ id: 'bot', name: 'Peer', providerID: 'p', modelID: 'm' }));
125
+ const updateScheduledTask = vi.fn(async () => ({ task: { id: 'task', name: 'Task', enabled: false } }));
126
+ const name = domain === 'assistants' ? 'create_assistant' : 'update_scheduled_task';
127
+ const params = domain === 'assistants' ? { name: 'Peer', providerID: 'p', modelID: 'm' } : { projectID: 'p', taskID: 'task', enabled: false };
128
+ let round = 0;
129
+ await turn(createContactTools({ createAssistant, updateScheduledTask }), async ({ body }) => {
130
+ round++;
131
+ if (round === 1) {
132
+ expect(names(body)).not.toContain(name);
133
+ return call('load_tools', { domain: `yuri.${domain}` });
134
+ }
135
+ if (round === 2) return call(name, params);
136
+ return { text: 'Done.' };
137
+ });
138
+ expect(domain === 'assistants' ? createAssistant : updateScheduledTask).toHaveBeenCalledTimes(1);
139
+ });
140
+
141
+ it('never offers the loader or mutations in a background read-only review, even with all tools supplied', async () => {
142
+ const registerProject = vi.fn();
143
+ const tools = [...createContactTools({}), ...createYuriContactTools({ registerProject })];
144
+ await turn(tools, async ({ body }) => {
145
+ expect(names(body)).toContain('list_scheduled_tasks');
146
+ for (const name of ['load_tools', 'register_project', 'create_assistant', 'schedule_task', 'update_avatar']) expect(names(body)).not.toContain(name);
147
+ return { text: 'Reviewed.' };
148
+ }, { readOnly: true });
149
+ expect(registerProject).not.toHaveBeenCalled();
150
+ });
151
+ });
@@ -7,8 +7,18 @@ start or replace OpenCode to provide inference.
7
7
  ## Ownership and security
8
8
 
9
9
  - `bridge-client.js` writes one self-contained built-in plugin to a Yuri-owned
10
- temporary `.opencode/plugins` directory. Official client `plugin.list` activates
11
- that isolated Location. No global/project OpenCode configuration is changed.
10
+ `.opencode/plugins` directory under the OS temporary directory. Official client
11
+ `plugin.list` activates that isolated Location. No global/project OpenCode
12
+ configuration is changed.
13
+ - The directory name is `yuri-inference-<sha256 prefix of the plugin bundle>`.
14
+ Every Location stays loaded in the shared service until its idle sweep, so
15
+ restarts and concurrent hosts running the same bundle reuse one directory and
16
+ one Location instead of adding one per process. The plugin file is replaced
17
+ atomically only when its content differs. Shutdown never deletes this shared
18
+ directory. On first use per process, cleanup removes other `yuri-inference-*`
19
+ directories (older bundles and the former per-process layout) unless upstream
20
+ `debug.location.list` reports them loaded; an unreadable inventory skips the
21
+ pass. Cleanup is best effort and never delays inference.
12
22
  - Calls use the official authenticated `client.rpc(LlmBridge)` transport, scoped
13
23
  to that directory. `ready` verifies protocol version 2 and runtime service availability; only RPC-not-ready
14
24
  startup errors receive a bounded readiness retry. Generation is not rerun for
@@ -1,30 +1,79 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
- import { randomUUID } from 'node:crypto';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { OpenCode } from '@opencode/client';
7
7
  import { LlmBridge, LLM_BRIDGE_VERSION } from './bridge-contract.js';
8
8
 
9
+ const BRIDGE_PLUGIN_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bridge-plugin.bundle.js');
10
+
11
+ // Every directory activates one upstream Location that the shared service keeps
12
+ // alive. The directory is keyed by plugin content, so restarts and concurrent
13
+ // hosts running the same bundle reuse one Location instead of adding one each.
14
+ export async function prepareLlmBridgeDirectory({ pluginPath = BRIDGE_PLUGIN_PATH, root = os.tmpdir(), fsLike = fs } = {}) {
15
+ const code = await fsLike.readFile(pluginPath);
16
+ const digest = createHash('sha256').update(code).digest('hex').slice(0, 16);
17
+ const directory = path.join(root, `yuri-inference-${digest}`);
18
+ const plugins = path.join(directory, '.opencode', 'plugins');
19
+ const target = path.join(plugins, 'yuri-llm.js');
20
+ const current = await fsLike.readFile(target).catch(() => null);
21
+ if (current && current.equals(code)) return directory;
22
+ await fsLike.mkdir(plugins, { recursive: true });
23
+ // Another host may be loading the same file; replace it atomically.
24
+ const staging = `${target}.${process.pid}.${randomUUID()}.tmp`;
25
+ try {
26
+ await fsLike.writeFile(staging, code);
27
+ await fsLike.rename(staging, target);
28
+ } catch (error) {
29
+ await fsLike.rm(staging, { force: true });
30
+ throw error;
31
+ }
32
+ return directory;
33
+ }
34
+
35
+ /**
36
+ * Removes bridge directories left by earlier builds or by the former per-process
37
+ * temporary layout. A directory whose Location is still loaded upstream may be
38
+ * in use by another host, so it stays until the upstream idle sweep unloads it.
39
+ * Only failure to read the live inventory skips the whole pass.
40
+ */
41
+ export async function pruneStaleLlmBridgeDirectories({ client, keep, root = os.tmpdir(), fsLike = fs, signal }) {
42
+ const entries = await Promise.resolve().then(() => client.debug.location.list(signal ? { signal } : undefined)).catch(() => null);
43
+ if (!Array.isArray(entries)) return [];
44
+ const live = new Set(entries.map((entry) => entry?.directory && path.resolve(entry.directory)).filter(Boolean));
45
+ const names = await fsLike.readdir(root).catch(() => []);
46
+ const removed = [];
47
+ for (const name of names) {
48
+ if (!name.startsWith('yuri-inference-')) continue;
49
+ const directory = path.join(root, name);
50
+ if (directory === keep || live.has(directory)) continue;
51
+ const resolved = await fsLike.realpath(directory).catch(() => directory);
52
+ if (live.has(resolved)) continue;
53
+ await fsLike.rm(directory, { recursive: true, force: true }).then(() => removed.push(directory), () => undefined);
54
+ }
55
+ return removed;
56
+ }
57
+
9
58
  let directoryPromise;
10
- export async function ensureLlmBridgeDirectory() {
11
- if (!directoryPromise) directoryPromise = (async () => {
12
- const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-inference-'));
13
- try {
14
- const plugins = path.join(directory, '.opencode', 'plugins');
15
- await fs.mkdir(plugins, { recursive: true });
16
- const plugin = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bridge-plugin.bundle.js');
17
- await fs.copyFile(plugin, path.join(plugins, 'yuri-llm.js'));
18
- return directory;
19
- } catch (error) { await fs.rm(directory, { recursive: true, force: true }); throw error; }
20
- })().catch(error => { directoryPromise = undefined; throw error; });
21
- return directoryPromise;
59
+ let pruneStarted = false;
60
+ export async function ensureLlmBridgeDirectory({ client } = {}) {
61
+ if (!directoryPromise) directoryPromise = prepareLlmBridgeDirectory()
62
+ .catch(error => { directoryPromise = undefined; throw error; });
63
+ const directory = await directoryPromise;
64
+ if (client && !pruneStarted) {
65
+ pruneStarted = true;
66
+ // Cleanup is best effort and never delays inference.
67
+ void pruneStaleLlmBridgeDirectories({ client, keep: directory }).catch(() => undefined);
68
+ }
69
+ return directory;
22
70
  }
23
71
 
72
+ // The content-addressed directory may be shared with other hosts, so shutdown
73
+ // only forgets it and never deletes it.
24
74
  export async function stopLlmBridgeDirectory() {
25
- const pending = directoryPromise;
26
75
  directoryPromise = undefined;
27
- if (pending) await fs.rm(await pending, { recursive: true, force: true });
76
+ pruneStarted = false;
28
77
  }
29
78
 
30
79
  export async function generateCleanCompletion({ buildOpenCodeUrl, getOpenCodeAuthHeaders, clientFactory,
@@ -33,7 +82,7 @@ export async function generateCleanCompletion({ buildOpenCodeUrl, getOpenCodeAut
33
82
  }) {
34
83
  signal?.throwIfAborted();
35
84
  const client = clientFactory?.() ?? OpenCode.make({ baseUrl: buildOpenCodeUrl('/', '').replace(/\/$/, ''), headers: getOpenCodeAuthHeaders() });
36
- const directory = await ensureBridgeDirectory();
85
+ const directory = await ensureBridgeDirectory({ client });
37
86
  const options = { location: { directory }, signal };
38
87
  const rpc = client.rpc(LlmBridge);
39
88
  // Loading this isolated Location activates only its own plugin file, without global config writes.
@@ -1,5 +1,8 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import { generateCleanCompletion } from './bridge-client.js';
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { generateCleanCompletion, prepareLlmBridgeDirectory, pruneStaleLlmBridgeDirectories } from './bridge-client.js';
3
6
  import { LLM_BRIDGE_VERSION } from './bridge-contract.js';
4
7
 
5
8
  describe('external OpenCode inference bridge', () => {
@@ -32,4 +35,62 @@ describe('external OpenCode inference bridge', () => {
32
35
  expect(vi.getTimerCount()).toBe(0);
33
36
  } finally { vi.useRealTimers(); }
34
37
  });
38
+
39
+ it('passes the client to directory preparation so stale bridge cleanup can consult upstream', async () => {
40
+ const client = { plugin: { list: async () => [] }, rpc: () => ({ ready: async () => ({ version: LLM_BRIDGE_VERSION }), generate: async () => ({ text: '', toolCalls: [] }) }) };
41
+ const ensureBridgeDirectory = vi.fn(async () => '/isolated');
42
+ await generateCleanCompletion({ clientFactory: () => client, ensureBridgeDirectory });
43
+ expect(ensureBridgeDirectory).toHaveBeenCalledWith({ client });
44
+ });
45
+ });
46
+
47
+ describe('bridge directory lifecycle', () => {
48
+ const roots = [];
49
+ const makeRoot = async () => {
50
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'bridge-root-'));
51
+ roots.push(root);
52
+ return root;
53
+ };
54
+ afterEach(async () => {
55
+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
56
+ });
57
+
58
+ it('reuses one content-addressed directory across restarts and rewrites only changed plugins', async () => {
59
+ const root = await makeRoot();
60
+ const pluginPath = path.join(root, 'bundle.js');
61
+ await fs.writeFile(pluginPath, 'v1');
62
+ const first = await prepareLlmBridgeDirectory({ pluginPath, root });
63
+ const target = path.join(first, '.opencode', 'plugins', 'yuri-llm.js');
64
+ const { mtimeMs } = await fs.stat(target);
65
+ expect(await prepareLlmBridgeDirectory({ pluginPath, root })).toBe(first);
66
+ expect((await fs.stat(target)).mtimeMs).toBe(mtimeMs);
67
+ expect(await fs.readFile(target, 'utf8')).toBe('v1');
68
+
69
+ await fs.writeFile(pluginPath, 'v2');
70
+ const second = await prepareLlmBridgeDirectory({ pluginPath, root });
71
+ expect(second).not.toBe(first);
72
+ expect(path.basename(second)).toMatch(/^yuri-inference-[0-9a-f]{16}$/);
73
+ expect(await fs.readFile(path.join(second, '.opencode', 'plugins', 'yuri-llm.js'), 'utf8')).toBe('v2');
74
+ expect((await fs.readdir(path.join(second, '.opencode', 'plugins')))).toEqual(['yuri-llm.js']);
75
+ });
76
+
77
+ it('prunes stale bridge directories except the current and upstream-loaded ones', async () => {
78
+ const root = await makeRoot();
79
+ const make = async (name) => { const dir = path.join(root, name); await fs.mkdir(dir); return dir; };
80
+ const keep = await make('yuri-inference-current');
81
+ const loaded = await make('yuri-inference-loaded');
82
+ const stale = await make('yuri-inference-AbC123');
83
+ const unrelated = await make('other-dir');
84
+ const client = { debug: { location: { list: vi.fn(async () => [{ directory: loaded }]) } } };
85
+ expect(await pruneStaleLlmBridgeDirectories({ client, keep, root })).toEqual([stale]);
86
+ expect((await fs.readdir(root)).sort()).toEqual([path.basename(unrelated), path.basename(keep), path.basename(loaded)].sort());
87
+ });
88
+
89
+ it('skips pruning when the upstream inventory cannot be read', async () => {
90
+ const root = await makeRoot();
91
+ await fs.mkdir(path.join(root, 'yuri-inference-stale'));
92
+ const client = { debug: { location: { list: vi.fn(async () => { throw new Error('503'); }) } } };
93
+ expect(await pruneStaleLlmBridgeDirectories({ client, keep: '/none', root })).toEqual([]);
94
+ expect(await fs.readdir(root)).toEqual(['yuri-inference-stale']);
95
+ });
35
96
  });
@@ -63,12 +63,14 @@ This module provides OpenCode server integration utilities for the web server ru
63
63
  - `packages/web/server/lib/opencode/project-icon-routes.js`: project icon upload/read/discovery route registration and icon storage orchestration.
64
64
  - `packages/web/server/lib/opencode/skill-routes.js`: route registration for skill config CRUD, supporting files, and skills catalog scan/install flows.
65
65
  - `packages/web/server/lib/opencode/settings-runtime.js`: Settings persistence runtime (disk IO, migrations, normalization, project validation, and persisted update serialization).
66
+ - Trusted resource owners can pass a functional update to `persistSettings`; it strictly reads and derives the patch inside the same Host/Electron lock, preserving concurrent writes. These callers validate their affected resource instead of sweeping unrelated offline projects. `projects/registry.js` shares project registration between the existing directory HTTP API and assistant tools; ordinary object-based settings updates retain their existing full-list validation behavior.
66
67
  - Missing theme preferences use `carbonfox-light` / `cursor-dark`, matching the shared UI defaults. Existing per-variant IDs and legacy explicitly selected theme IDs remain authoritative; changing the default does not rewrite a user's saved theme.
67
68
  - Project registry order and `projectSortOrder` are shared Host authority. After a successful changed write, `onProjectOrderChanged` emits `yuri:project-order-changed` on the existing Yuri SSE channel. Clients GET settings on initial mount, tip, and reconnect. Unchanged and failed writes emit no tip; older settings without a sort mode use `manual`.
68
69
  - `packages/web/server/lib/opencode/settings-helpers.js`: Settings payload sanitization/format helpers runtime for response shaping and persisted merge prep.
69
70
  - `packages/web/server/lib/opencode/settings-normalization-runtime.js`: path/settings normalization and sanitization helpers runtime used by settings/routes/config wiring.
70
71
  - `packages/web/server/lib/opencode/theme-runtime.js`: custom theme JSON validation and theme directory loading runtime for settings utility routes.
71
72
  - `packages/web/server/lib/opencode/proxy.js`: OpenCode API/SSE forwarding and readiness-gate route registration.
73
+ - `npm-registry.js`: plugin package lookup used by `GET /api/config/plugins/registry`. It asks the user's own `npm view` first (run in the project directory, so scope registries, auth tokens and mirrors from `.npmrc` apply as they do for `npm install`) and falls back to a direct request to the public registry only when the CLI is unavailable; a CLI 404 is final. Results are cached per name and directory. The latest release's `magpie.icon` is returned as `icon` only when it is an `https://` URL or `data:image/` URI of at most ~1.5 MB (`sanitizePluginIcon`); nothing is fetched server-side and clients render it as an image.
72
74
  - `plugin-gui-response.js`: shared Web/Electron/VS Code code-only revision response owner for exact `GET /api/plugin/gui?id=…` (one nonempty id). The installed GUI client alias is official `@opencode/client@2.2.0`: HTTP returns `{ location, data: { code, revision, options } }`. Every call still reads the complete current upstream response through the existing auth/readiness/abort boundary; there is no Host bundle cache.
73
75
  - Request `X-Yuri-Gui-Revision: <lowercase SHA-256 hex of UTF-8 revision>` opts into code reuse. This header and HTTP condition/range headers are stripped before upstream so Yuri always requests a complete representation. Other query and request headers retain proxy semantics.
74
76
  - A valid upstream 200 JSON bundle (`code` string, nonempty `revision` string, `options` object) receives `X-Yuri-Gui-Revision` and `Cache-Control: private, no-store`. Matching tokens additionally receive `X-Yuri-Gui-Code: cached` and only `data.code` becomes `''`; current `options`, `revision`, location and other fields remain. Unmatched/ordinary calls preserve original body bytes. No 304 or Yuri ETag is generated. Upstream failure statuses/bodies remain failures; malformed successful bodies remain unchanged without a revision receipt.
@@ -20,6 +20,7 @@ import { registerScheduledTaskSessionSkill } from '../scheduled-tasks/session-sk
20
20
  import { registerConversationRoutes } from '../conversations/routes.js';
21
21
  import { registerSessionTurnPageRoutes } from '../session-turn-pages/routes.js';
22
22
  import { registerAssistantRoutes } from '../assistants/routes.js';
23
+ import { createProjectRegistry } from '../projects/registry.js';
23
24
  import { registerLlmRoutes } from '../llm/routes.js';
24
25
  import { registerMessageQueueRoutes } from '../message-queue/routes.js';
25
26
  import { getBrowserProviderHost } from '../browser-provider/host.js';
@@ -283,6 +284,13 @@ export const createFeatureRoutesRuntime = (dependencies) => {
283
284
  .filter((value) => typeof value === 'string'));
284
285
  };
285
286
  await refreshAssistantAllowedRoots();
287
+ const projectRegistry = createProjectRegistry({ persistSettings, validateDirectoryPath });
288
+ const registerAssistantProject = async (input) => {
289
+ const result = await projectRegistry.register(input);
290
+ await refreshAssistantAllowedRoots();
291
+ // Full settings may contain credentials; only return the affected resource.
292
+ return { project: result.project, created: result.created };
293
+ };
286
294
  const broadcastAssistantRevisionTip = createYuriEventBroadcaster({
287
295
  getYuriEventClients,
288
296
  writeSseEvent,
@@ -305,6 +313,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
305
313
  getOpenCodeAuthHeaders,
306
314
  getServerId,
307
315
  getAllowedRoots: () => assistantAllowedRoots,
316
+ registerProject: registerAssistantProject,
308
317
  listProjects: async () => {
309
318
  const settings = await readSettingsFromDiskMigrated();
310
319
  return sanitizeProjects(settings?.projects ?? [])
@@ -31,6 +31,18 @@ describe('feature routes runtime composition', () => {
31
31
  expect(source).toMatch(/label: project\.label\.trim\(\)/);
32
32
  });
33
33
 
34
+ it('wires only project registration and live roots into the assistant extension tools', async () => {
35
+ const source = await fs.readFile(new URL('./feature-routes-runtime.js', import.meta.url), 'utf8');
36
+ const routes = await fs.readFile(new URL('../assistants/routes.js', import.meta.url), 'utf8');
37
+ expect(source).toContain('createProjectRegistry({ persistSettings, validateDirectoryPath })');
38
+ expect(source).toMatch(/projectRegistry.register\(input\);\s*await refreshAssistantAllowedRoots\(\)/);
39
+ expect(source).toContain('registerProject: registerAssistantProject');
40
+ expect(routes).toContain('registerProject: dependencies.registerProject');
41
+ for (const name of ['updateProject', 'removeProject', 'runScheduledTask', 'deleteScheduledTask']) {
42
+ expect(routes).not.toContain(`${name}: dependencies.${name}`);
43
+ }
44
+ });
45
+
34
46
  it('fans contact turn events out on the Yuri SSE bus separately from revision tips', async () => {
35
47
  const source = await fs.readFile(new URL('./feature-routes-runtime.js', import.meta.url), 'utf8');
36
48
  expect(source).toMatch(/const broadcastContactTurnEvent = createYuriEventBroadcaster\(/);