@yuriai/web 0.2.40-beta.5 → 0.2.40-beta.7

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 (176) hide show
  1. package/dist/assets/{AgentAvatar-B7KbxN8Y.js → AgentAvatar-BTLQDhXH.js} +1 -1
  2. package/dist/assets/AssistantConversationSurface-B59k-lXE.css +1 -0
  3. package/dist/assets/AssistantConversationSurface-CMMUXPIG.js +3 -0
  4. package/dist/assets/AssistantSessionCard-CZWiX3PR.js +2 -0
  5. package/dist/assets/{AssistantUnreadBadge-vu4ZhTft.js → AssistantUnreadBadge-B5I8avUG.js} +1 -1
  6. package/dist/assets/{AssistantView-CEfEWUIr.js → AssistantView-COHkH9qm.js} +1 -1
  7. package/dist/assets/{DiagramView-Dlzr08J_.js → DiagramView-DiwpnazQ.js} +1 -1
  8. package/dist/assets/{FadeInOnReveal-DMRmNsau.js → FadeInOnReveal-BxelcK76.js} +1 -1
  9. package/dist/assets/{GuiPluginPage-DVug4z_p.js → GuiPluginPage-CLD3qMom.js} +1 -1
  10. package/dist/assets/{GuiPluginSurface-L43o6Xv8.js → GuiPluginSurface-Cra2RdI2.js} +1 -1
  11. package/dist/assets/{GuiPluginWindow-tHXkS18H.js → GuiPluginWindow-CX4PYIEy.js} +1 -1
  12. package/dist/assets/{Icon-DizeYahT.js → Icon-BN1Zz-it.js} +1 -1
  13. package/dist/assets/{ImageLoadingPlaceholder-BZC5m_km.js → ImageLoadingPlaceholder-CZFYt1Xf.js} +1 -1
  14. package/dist/assets/{LoadingImage-Csw4L-Dr.js → LoadingImage-BCMztEsC.js} +1 -1
  15. package/dist/assets/{MarkdownRenderer-D_0iKhQN.js → MarkdownRenderer-194nc-0S.js} +2 -2
  16. package/dist/assets/{MarkdownRendererImpl-BZ0XgjS0.js → MarkdownRendererImpl-0-mJL1TL.js} +1 -1
  17. package/dist/assets/{MarkstreamRendererImpl-DBd6Glg9.js → MarkstreamRendererImpl-DaTyfTOH.js} +1 -1
  18. package/dist/assets/MobileDetailNavigation-CXAtNLak.js +1 -0
  19. package/dist/assets/{MobileResizableSheet-CQQ7O-2X.js → MobileResizableSheet-BvwMTE7L.js} +1 -1
  20. package/dist/assets/{MobileShareBridge-IO45gM2G.js → MobileShareBridge-BpO-ZEFG.js} +1 -1
  21. package/dist/assets/MobileSurface-DIhzZpb9.js +2 -0
  22. package/dist/assets/{MultiRunWindow-fJ3XfntS.js → MultiRunWindow-ErbLasVC.js} +1 -1
  23. package/dist/assets/{OnboardingScreen-MJS5T5rL.js → OnboardingScreen-C_rigW9c.js} +1 -1
  24. package/dist/assets/{OverlayScrollbar-jtMYTn1y.js → OverlayScrollbar-BopzmDhe.js} +1 -1
  25. package/dist/assets/RemoteAssistantSessionCard-6ktwRL7R.js +1 -0
  26. package/dist/assets/{SettingsView-ZWFLpPSI.js → SettingsView--qdcJENp.js} +10 -10
  27. package/dist/assets/{SettingsWindow-DGRmrIWz.js → SettingsWindow-BbJoqFSB.js} +1 -1
  28. package/dist/assets/{SetupTourDialog-BYbAubwA.js → SetupTourDialog-CT3NmpEw.js} +1 -1
  29. package/dist/assets/{TerminalView-CoJ6_9P1.js → TerminalView-Cw-p34fv.js} +1 -1
  30. package/dist/assets/{ToolOutputDialog-5xBwOJ6a.js → ToolOutputDialog-Bph7Tjg_.js} +1 -1
  31. package/dist/assets/{VoiceSettings-CN33koSc.js → VoiceSettings-B8jYVsYS.js} +2 -2
  32. package/dist/assets/{YuriLogo-CvyJy_R9.js → YuriLogo-VXtP1vhh.js} +1 -1
  33. package/dist/assets/{YuriWordmark-DnFAS-Ko.js → YuriWordmark-B7lmpLRB.js} +1 -1
  34. package/dist/assets/{capgoAdapter-CCLtBZL1.js → capgoAdapter-BQCbf31K.js} +1 -1
  35. package/dist/assets/{checkbox-rOV6DjeG.js → checkbox-q45nTdJl.js} +1 -1
  36. package/dist/assets/{client-uz8O6TPX.js → client-1Fk5IbQR.js} +3 -3
  37. package/dist/assets/{collapsible-CKswuqAw.js → collapsible-GtMRfwfw.js} +1 -1
  38. package/dist/assets/{context-menu-B4njwT_M.js → context-menu-efudajQ5.js} +1 -1
  39. package/dist/assets/{diagram-BppQ_USn.js → diagram-D39tZKkF.js} +1 -1
  40. package/dist/assets/{dialog-Bg8MJnOV.js → dialog-BtnUw5J1.js} +1 -1
  41. package/dist/assets/{es-Ba3NUCtE.js → es-DuTK1iYh.js} +1 -1
  42. package/dist/assets/{fileMentionTouchSelection-D-AdTJVr.js → fileMentionTouchSelection-CJ78x95X.js} +1 -1
  43. package/dist/assets/{fr-CRhp3hyT.js → fr-C_XToFWm.js} +1 -1
  44. package/dist/assets/{gitApi-DVx_V1x6.js → gitApi-CBnJOeVr.js} +1 -1
  45. package/dist/assets/gitApiHttp-B0FJaIhU.js +3 -0
  46. package/dist/assets/{gui-DN2sVP96.js → gui-BMN3-WPc.js} +1 -1
  47. package/dist/assets/{host-DrGjjO6K.js → host-D9EDWNmx.js} +1 -1
  48. package/dist/assets/{i18n-RH7UieOS.js → i18n-qHllte6P.js} +1 -1
  49. package/dist/assets/{input-DRjuZMeA.js → input-KETIwVja.js} +1 -1
  50. package/dist/assets/{input-store-CjUOfpyA.js → input-store-CsY-uaSj.js} +1 -1
  51. package/dist/assets/insertionBoundaries-CodoJFbE.js +1 -0
  52. package/dist/assets/{ja-D-UPjDY2.js → ja-D0pDybpB.js} +1 -1
  53. package/dist/assets/{ko-x-z9J5z7.js → ko-CAzlaaDJ.js} +1 -1
  54. package/dist/assets/main-Cgg4eDdr.js +2 -0
  55. package/dist/assets/{main-D2s9J_jN.js → main-D4t2Tw1D.js} +14 -14
  56. package/dist/assets/{markdownHeightCache-BL99DlhC.js → markdownHeightCache-BCzMmJds.js} +1 -1
  57. package/dist/assets/{mcpQueries-HzYMEVWd.js → mcpQueries-BIvH9V8j.js} +1 -1
  58. package/dist/assets/miniChat-CKw0itTX.js +2 -0
  59. package/dist/assets/mobile-w1JspRFK.js +2 -0
  60. package/dist/assets/{mobileBackNavigation--ZdrI-Yj.js → mobileBackNavigation-qI9CYpqm.js} +1 -1
  61. package/dist/assets/{mobileConnections-C3eGEOPy.js → mobileConnections-Cbt8y7gt.js} +2 -2
  62. package/dist/assets/{multirun-CDYNyLBH.js → multirun-DOmwPpvA.js} +1 -1
  63. package/dist/assets/{native-DsqzO52u.js → native-CDqNKjmz.js} +1 -1
  64. package/dist/assets/{native-config-DOawZfln.js → native-config-BIePc5av.js} +1 -1
  65. package/dist/assets/{navigation-Ibk_Pw-q.js → navigation-CxKtO3Tu.js} +2 -2
  66. package/dist/assets/openRemoteProjectSession-DbQYpcai.js +1 -0
  67. package/dist/assets/{pl-Cqo1FJwM.js → pl-BvjbUcJV.js} +1 -1
  68. package/dist/assets/{projectMeta-D1Ytss9U.js → projectMeta-AxnyOG6N.js} +1 -1
  69. package/dist/assets/prompt-attachment-upload-9fjmgafL.js +1 -0
  70. package/dist/assets/{pt-BR-C930XU1k.js → pt-BR-D71qrP91.js} +1 -1
  71. package/dist/assets/{pwa-CXupOTsD.js → pwa-BGo_AGpg.js} +1 -1
  72. package/dist/assets/{queue-abort-optimistic-CQXpIlq6.js → queue-abort-optimistic-CZ3DN-Qo.js} +1 -1
  73. package/dist/assets/{react-CgRToPwO.js → react-CTU-HLp4.js} +1 -1
  74. package/dist/assets/{readiness-BfuZm6Yw.js → readiness-Bu7mTG2d.js} +2 -2
  75. package/dist/assets/reference-history-n4Bw_yN2.js +1 -0
  76. package/dist/assets/{remote-input-store-BOdCWpQY.js → remote-input-store-84i8uDyM.js} +1 -1
  77. package/dist/assets/remoteProjectQueries-BZjiHj-6.js +1 -0
  78. package/dist/assets/remoteSessionReference-CQ0m6LgV.js +1 -0
  79. package/dist/assets/renderElectronMiniChatApp-B8nOPC1J.js +2 -0
  80. package/dist/assets/renderMobileApp-BvamjumJ.js +29 -0
  81. package/dist/assets/{runtimeConfig-tHm7o_0I.js → runtimeConfig-CbHzjd7l.js} +1 -1
  82. package/dist/assets/runtimeEndpointReset-CMyx_9Vr.js +151 -0
  83. package/dist/assets/scheduledTaskNavigation-y5g8D2ee.js +1 -0
  84. package/dist/assets/{select-B1On-Y4Z.js → select-Df_svQ9u.js} +1 -1
  85. package/dist/assets/sessionLookup-BN82Y0hu.js +1 -0
  86. package/dist/assets/{sortable-tabs-strip-nD1Me06z.js → sortable-tabs-strip-ByO3KYNT.js} +1 -1
  87. package/dist/assets/{speechSettingsQueries-BYhNpzDJ.js → speechSettingsQueries-DRAueMIJ.js} +1 -1
  88. package/dist/assets/src-INJJ62RE.css +2 -0
  89. package/dist/assets/{store-DunGyOfe.js → store-BOD3jjMl.js} +3 -3
  90. package/dist/assets/{terminalApi-madXrfqA.js → terminalApi-Cq0vjFe1.js} +1 -1
  91. package/dist/assets/{textarea-Qt06OhhX.js → textarea-BYUo-pZK.js} +1 -1
  92. package/dist/assets/{tooltip-D382RCy1.js → tooltip-CBCE3mxe.js} +1 -1
  93. package/dist/assets/tour-CMXP3Kif.js +1 -0
  94. package/dist/assets/{types-CHszLAS3.js → types-Bj4r_-Qe.js} +1 -1
  95. package/dist/assets/{uk-OXQSdzuT.js → uk-C7c1Zece.js} +1 -1
  96. package/dist/assets/{useAppFontEffects-CqXrCJVt.js → useAppFontEffects-DxY0a-0K.js} +61 -61
  97. package/dist/assets/useDesktopWindowControlsLayout-I02la7LE.js +1 -0
  98. package/dist/assets/{useDictation-Bs7TWO9r.js → useDictation-De8WB_Z7.js} +1 -1
  99. package/dist/assets/{useEffectiveDirectory-CCKRdyK9.js → useEffectiveDirectory-CYzFju6z.js} +1 -1
  100. package/dist/assets/{useFontPreferences-CPrl1_3z.js → useFontPreferences-CO-L-Gd7.js} +1 -1
  101. package/dist/assets/{useMobileNavigationStore-BNtVrnSw.js → useMobileNavigationStore-7nhBtrXS.js} +9 -9
  102. package/dist/assets/{usePluginsStore-bMuGciUE.js → usePluginsStore-1D6-GAgq.js} +1 -1
  103. package/dist/assets/{useProjectRuntimeAPIs-BFCXBu2J.js → useProjectRuntimeAPIs-CNOqSvoZ.js} +1 -1
  104. package/dist/assets/{useStreamingTextThrottle-C8xAqcgP.js → useStreamingTextThrottle-BsaiiBxk.js} +1 -1
  105. package/dist/assets/{vendor-opencode-client-cQ47ywrT.js → vendor-opencode-client-BM2r1f0o.js} +3 -3
  106. package/dist/assets/{vendor-opencode-plugin-BmdTE4Te.js → vendor-opencode-plugin-ZhpPgHCL.js} +1 -1
  107. package/dist/assets/{vendor-solid-js-D98iXT7C.js → vendor-solid-js-BBVUd3Hw.js} +1 -1
  108. package/dist/assets/{zh-CN-B5X8yCZV.js → zh-CN-D2ENuI1-.js} +1 -1
  109. package/dist/assets/{zh-TW-CF6zr1fk.js → zh-TW-C40BXFhK.js} +1 -1
  110. package/dist/index.html +11 -11
  111. package/dist/mini-chat.html +11 -11
  112. package/dist/mobile.html +2 -2
  113. package/package.json +1 -1
  114. package/server/index.js +1 -0
  115. package/server/lib/assistants/DOCUMENTATION.md +87 -0
  116. package/server/lib/assistants/assign.js +10 -7
  117. package/server/lib/assistants/builtin-skills.js +1 -0
  118. package/server/lib/assistants/builtin-skills.test.js +1 -1
  119. package/server/lib/assistants/cards.js +6 -1
  120. package/server/lib/assistants/contact-store.js +22 -5
  121. package/server/lib/assistants/contact-tools.js +46 -26
  122. package/server/lib/assistants/execution-target.js +136 -0
  123. package/server/lib/assistants/opencode-tools.js +22 -9
  124. package/server/lib/assistants/remote-execution.test.js +378 -0
  125. package/server/lib/assistants/remote-watch-reconciler.js +43 -0
  126. package/server/lib/assistants/remote-watch-reconciler.test.js +88 -0
  127. package/server/lib/assistants/routes.js +1 -0
  128. package/server/lib/assistants/service.js +302 -99
  129. package/server/lib/assistants/yuri-project.http.test.js +2 -2
  130. package/server/lib/gui-customization/DOCUMENTATION.md +8 -2
  131. package/server/lib/gui-customization/projects-client.mjs +10 -8
  132. package/server/lib/gui-customization/projects-remote.js +101 -0
  133. package/server/lib/gui-customization/projects-remote.test.js +125 -0
  134. package/server/lib/gui-customization/projects.js +30 -6
  135. package/server/lib/gui-customization/projects.test.js +66 -1
  136. package/server/lib/gui-customization/session-skill.js +2 -2
  137. package/server/lib/gui-customization/session-skill.test.js +4 -0
  138. package/server/lib/gui-customization/skill/SKILL.md +3 -1
  139. package/server/lib/gui-customization/skill/references/projects.md +30 -3
  140. package/server/lib/gui-customization/skill/references/remote-connections.md +2 -0
  141. package/server/lib/opencode/DOCUMENTATION.md +6 -0
  142. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  143. package/server/lib/opencode/v2-client.js +9 -4
  144. package/server/lib/remote-hosts/DOCUMENTATION.md +58 -0
  145. package/server/lib/remote-hosts/gateway.js +149 -40
  146. package/server/lib/remote-hosts/json-lifecycle.test.js +35 -0
  147. package/server/lib/remote-hosts/routes.js +10 -13
  148. package/server/lib/remote-hosts/routes.test.js +302 -1
  149. package/server/lib/remote-hosts/store.js +17 -3
  150. package/server/lib/remote-hosts/store.test.js +19 -0
  151. package/server/lib/remote-hosts/task-client.js +25 -0
  152. package/server/lib/remote-hosts/task-client.test.js +60 -0
  153. package/server/lib/remote-hosts/transport.js +7 -2
  154. package/server/lib/request-cors.js +1 -1
  155. package/server/lib/request-cors.test.js +1 -0
  156. package/server/lib/scheduled-tasks/session-skill.test.js +33 -2
  157. package/dist/assets/AssistantConversationSurface-BnK_KTBO.js +0 -3
  158. package/dist/assets/AssistantConversationSurface-n9w_Av0k.css +0 -1
  159. package/dist/assets/MobileDetailNavigation-xgwvsQuR.js +0 -1
  160. package/dist/assets/MobileSurface-DmYgZONB.js +0 -2
  161. package/dist/assets/gitApiHttp-DvTBxvX8.js +0 -3
  162. package/dist/assets/insertionBoundaries-DZtQt2Ah.js +0 -1
  163. package/dist/assets/main-BMFY9mtb.js +0 -2
  164. package/dist/assets/miniChat-BbJ0GKpk.js +0 -2
  165. package/dist/assets/mobile-_zUth69Z.js +0 -2
  166. package/dist/assets/prompt-attachment-upload-BNhDXymd.js +0 -1
  167. package/dist/assets/remoteProjectQueries-CkxdZNw4.js +0 -1
  168. package/dist/assets/renderElectronMiniChatApp-pJ59iC34.js +0 -2
  169. package/dist/assets/renderMobileApp-BQFC-gOA.js +0 -29
  170. package/dist/assets/runtimeEndpointReset-BhHWFNvo.js +0 -150
  171. package/dist/assets/scheduledTaskNavigation-BIDtQ4wN.js +0 -1
  172. package/dist/assets/sessionLookup-RcyTTDOy.js +0 -1
  173. package/dist/assets/src-BZCFf9_1.css +0 -2
  174. package/dist/assets/tour-CQMBn8gJ.js +0 -1
  175. package/dist/assets/useDesktopWindowControlsLayout-KH4UP7Gj.js +0 -1
  176. /package/dist/assets/{sessionLookup-8C8nv-EP.css → reference-history-8C8nv-EP.css} +0 -0
@@ -143,8 +143,8 @@ describe('HTTP → real contact Agent → project registry → worker admission'
143
143
  const admitted = await request(`/api/yuri/assistants/${assistant.id}/messages`, { messageID: 'create-project-chat', text: `Add ${workspace} and open a session saying hello` });
144
144
  expect(admitted.admitted).toBe(true);
145
145
  expect((await runtime.service.whenContactTurnSettled(admitted.messageID)).status).toBe('complete');
146
- expect(creates).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ location: { directory: canonical } }));
147
- expect(prompts).toHaveBeenCalledWith(expect.objectContaining({ sessionID: 'ses_hello', text: 'hello' }));
146
+ expect(creates).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ location: { directory: canonical } }), expect.objectContaining({ signal: expect.any(AbortSignal) }));
147
+ expect(prompts).toHaveBeenCalledWith(expect.objectContaining({ sessionID: 'ses_hello', text: 'hello' }), expect.objectContaining({ signal: expect.any(AbortSignal) }));
148
148
  expect(prompts.mock.calls[0][0]).not.toHaveProperty('skills');
149
149
  expect(prompts.mock.calls[0][0]).not.toHaveProperty('tools');
150
150
  expect(JSON.stringify(creates.mock.calls[0][0])).not.toContain('load_tools');
@@ -29,16 +29,22 @@ their immutable staged references until a new session is admitted. Contacts use
29
29
  their own granted `yuri.projects` tools, not this session binding.
30
30
 
31
31
  `projects.js` owns `POST /api/yuri/session-skills/projects` (`describe`, `list`,
32
- `add`). The global gate and route require the existing loopback service credential,
32
+ `add`, `remote-hosts`, `add-remote`, `remote-projects`, `sessions`, `read-session`, `create-session`, `prompt-session`). `projects-remote.js` uses the injected `remoteHostGateway` and its immutable task leases; discovery returns authenticated `{hubId,hostId,instanceId}` targets, and explicit targets never fall back to local. `remote-hosts` includes authorized machines with no associated project, reports per-machine failures and releases each probe. `add-remote` uses `gateway.registerProject`, shared with the UI: the target validates/canonicalizes and registers the directory before the Hub saves a deduplicated reference and broadcasts project-order invalidation. A Hub write failure leaves the remote project intact; retrying the same target/path completes association. Paths are never resolved on the Hub filesystem. Lease cleanup runs on every outcome. Remote SDK requests preserve generated request data through the lease; bounded message reads use the existing Host turn-page route. No remote bodies are persisted on Hub. Session creation/prompt require stable caller IDs for ambiguous-result inspection, not automatic replay. This capability neither uses nor grants the desktop SSH helper. The global gate and route require the existing loopback service credential,
33
33
  no browser Origin, shared-service ownership and the session's admitted Host origin.
34
34
  The bridge reuses `projects/registry.js`, just like the UI directory API and contact
35
35
  tools: strict reads, canonical path deduplication, serialized persistence and
36
36
  existing project-order SSE notifications remain with their owners. Registration
37
37
  preserves an existing active selection and returns only `{project, created}` after
38
38
  persistence, never settings/credentials. List errors remain errors. There is no
39
- cloning, directory creation, conversation creation or desktop window navigation.
39
+ cloning, directory creation or desktop window navigation. Remote conversation creation is explicit and separate from local registration.
40
40
  Web/Electron/connected-mobile shared-service sessions operate on their bound Host;
41
41
  private/external OpenCode and standalone VS Code have no session helper admission.
42
+ Remote SDK calls share `remote-hosts/task-client.js`, so the target proxy owns
43
+ execution admission even when the Hub's own OpenCode is unavailable. Reads use a
44
+ 25-second operation budget; explicit create/prompt use 300 seconds (the bound
45
+ client waits five seconds longer for the result). Caller disconnect cancels and
46
+ releases the task lease; uncertain writes are inspected by their stable IDs before
47
+ any retry.
42
48
 
43
49
  `references/plugin-styles.md` inventories existing host CSS variables for plugin-owned
44
50
  Solid/DOM content, including colors, typography, geometry, controls and optional
@@ -8,14 +8,15 @@ async function main() {
8
8
  try {
9
9
  const [encoded, operation] = process.argv.slice(2);
10
10
  const binding = JSON.parse(Buffer.from(encoded, 'base64url').toString());
11
- if (!['describe', 'list', 'add'].includes(operation)) throw new Error();
11
+ const operations = ['list', 'add', 'remote-hosts', 'add-remote', 'remote-projects', 'sessions', 'read-session', 'create-session', 'prompt-session'];
12
+ if (!['describe', ...operations].includes(operation)) throw new Error();
12
13
  const origin = new URL(binding.hostOrigin);
13
14
  if (origin.protocol !== 'http:' || !['127.0.0.1', '[::1]'].includes(origin.hostname) || origin.username || origin.password) throw new Error();
14
15
  const registration = JSON.parse(await readFile(binding.registrationFile, 'utf8'));
15
16
  if (new URL(registration.url).origin !== binding.upstreamOrigin || typeof registration.password !== 'string' || !registration.password) throw new Error();
16
17
  bound = true;
17
18
  let input = {};
18
- if (operation === 'add') {
19
+ if (!['describe', 'list', 'remote-hosts', 'remote-projects'].includes(operation)) {
19
20
  let text = '';
20
21
  for await (const chunk of process.stdin) {
21
22
  text += chunk;
@@ -24,7 +25,7 @@ async function main() {
24
25
  input = JSON.parse(text);
25
26
  }
26
27
  const response = await fetch(new URL('/api/yuri/session-skills/projects', origin), {
27
- method: 'POST', redirect: 'error', signal: AbortSignal.timeout(30_000),
28
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(['create-session', 'prompt-session'].includes(operation) ? 305_000 : 30_000),
28
29
  headers: { 'content-type': 'application/json', authorization: `Basic ${Buffer.from(`opencode:${registration.password}`).toString('base64')}` },
29
30
  body: JSON.stringify({ sessionID: binding.sessionID, operation, input }),
30
31
  });
@@ -32,23 +33,24 @@ async function main() {
32
33
  if (!response.ok) {
33
34
  const terminal = [401, 403, 501].includes(response.status);
34
35
  console.error(JSON.stringify({ error: 'Project API operation failed', status: response.status, terminal,
35
- ...(['invalid_input', 'validation_error', 'project_unavailable', 'project_operation_failed'].includes(result?.code) ? { code: result.code } : {}),
36
+ ...(['invalid_input', 'validation_error', 'project_unavailable', 'project_operation_failed', 'remote_unavailable', 'remote_target_mismatch', 'remote_response_invalid'].includes(result?.code) ? { code: result.code } : {}),
36
37
  recovery: terminal ? 'Stop this workflow; resume only with a new supported session and its bound project describe command.'
37
- : 'Result not confirmed. Check the path; use list or retry add with the same path after recovery. Never claim success from a failed request.',
38
+ : 'Result not confirmed. Inspect the same target before retrying; retain sessionID/messageID for interrupted writes. Never switch to local or claim success from a failed request.',
38
39
  }));
39
40
  process.exitCode = 1;
40
41
  return;
41
42
  }
42
- if (operation === 'add' && (typeof result.project?.id !== 'string' || typeof result.project?.path !== 'string' || typeof result.created !== 'boolean')) throw new Error();
43
+ if (['add', 'add-remote'].includes(operation) && (typeof result.project?.id !== 'string' || typeof result.project?.path !== 'string' || typeof result.created !== 'boolean')) throw new Error();
44
+ if (operation === 'remote-hosts' && (!Array.isArray(result.hosts) || !Array.isArray(result.failed) || typeof result.complete !== 'boolean')) throw new Error();
43
45
  if (operation === 'list' && !Array.isArray(result.projects)) throw new Error();
44
46
  if (operation === 'describe' && result.supported !== true) throw new Error();
45
47
  console.log(JSON.stringify(operation === 'describe' ? { ...result,
46
- commands: Object.fromEntries(['list', 'add'].map((op) => [op, sessionSkillCommand(process.execPath, process.argv[1], encoded, op)])),
48
+ commands: Object.fromEntries(operations.filter((op) => result.remoteSupported || ['list', 'add'].includes(op)).map((op) => [op, sessionSkillCommand(process.execPath, process.argv[1], encoded, op)])),
47
49
  } : result));
48
50
  } catch {
49
51
  console.error(JSON.stringify({ error: 'Bound project helper failed; the result is unconfirmed', terminal: !bound,
50
52
  recovery: !bound ? 'Stop this workflow; resume only with a new supported session and its bound project describe command.'
51
- : 'Check the input or connection. Resume with the bound describe command; retry add with the same path only after recovery.' }));
53
+ : 'Check the input or connection. Resume with the bound describe command; retry registration with the same target and path only after recovery.' }));
52
54
  process.exitCode = 1;
53
55
  }
54
56
  }
@@ -0,0 +1,101 @@
1
+ import { makeRemoteTaskOpenCodeClient } from '../remote-hosts/task-client.js';
2
+ import path from 'node:path';
3
+
4
+ const text = (value, limit = 4096) => typeof value === 'string' && value.trim() === value && value.length > 0 && value.length <= limit && !/[\x00-\x1f]/.test(value);
5
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value);
6
+ const targetValid = (value) => object(value) && Object.keys(value).length === 3
7
+ && ['hubId', 'hostId', 'instanceId'].every((key) => text(value[key], 512));
8
+ const fail = (code) => { throw Object.assign(new Error(code), { code }); };
9
+ const sessionRecord = (value) => value?.data && !value.id ? value.data : value;
10
+ const directoryOf = (value) => value?.location?.directory ?? value?.directory;
11
+ const sessionSummary = (value, target) => {
12
+ const session = sessionRecord(value);
13
+ if (!text(session?.id, 512) || !text(directoryOf(session))) fail('remote_response_invalid');
14
+ return { sessionID: session.id, directory: directoryOf(session), title: session.title ?? '', time: session.time, target };
15
+ };
16
+
17
+ export const remoteProjectOperations = ['remote-hosts', 'add-remote', 'remote-projects', 'sessions', 'read-session', 'create-session', 'prompt-session'];
18
+
19
+ export function validRemoteProjectInput(operation, input) {
20
+ if (!object(input)) return false;
21
+ if (operation === 'remote-projects' || operation === 'remote-hosts') return Object.keys(input).length === 0;
22
+ if (operation === 'add-remote') return Object.keys(input).every((key) => ['target', 'path', 'label'].includes(key))
23
+ && targetValid(input.target) && text(input.path) && (path.posix.isAbsolute(input.path) || path.win32.isAbsolute(input.path))
24
+ && (input.label === undefined || text(input.label, 80));
25
+ const extras = { sessions: ['cursor'], 'read-session': ['sessionID', 'cursor'], 'create-session': ['sessionID', 'title'], 'prompt-session': ['sessionID', 'messageID', 'text'] }[operation];
26
+ if (!extras || Object.keys(input).some((key) => !['target', 'directory', ...extras].includes(key))) return false;
27
+ if (!targetValid(input.target) || !text(input.directory)) return false;
28
+ if (operation !== 'sessions' && !text(input.sessionID, 512)) return false;
29
+ if (input.cursor !== undefined && !text(input.cursor, 4096)) return false;
30
+ if (input.title !== undefined && !text(input.title, 256)) return false;
31
+ return operation !== 'prompt-session' || (text(input.messageID, 512) && typeof input.text === 'string' && input.text.trim().length > 0 && input.text.length <= 12_000);
32
+ }
33
+
34
+ /** Only the admitted Hub's existing connections; no desktop configuration capability. */
35
+ export async function runRemoteProjectOperation(gateway, operation, input, signal) {
36
+ signal?.throwIfAborted();
37
+ if (!gateway?.acquireTask) fail('remote_unavailable');
38
+ const catalog = await gateway.list();
39
+ signal?.throwIfAborted();
40
+ if (!catalog.supported) fail('remote_unavailable');
41
+ if (operation === 'remote-hosts') {
42
+ const hosts = [], failed = [];
43
+ for (const host of catalog.hosts) {
44
+ let lease;
45
+ try {
46
+ if (host.available === false) fail('remote_unavailable');
47
+ lease = await gateway.acquireTask(host.id, { signal });
48
+ hosts.push({ name: host.name, source: host.source, target: lease.target });
49
+ } catch { signal?.throwIfAborted(); failed.push({ hostId: host.id, code: 'remote_unavailable' }); }
50
+ finally { lease?.release(); }
51
+ }
52
+ return { hosts, failed, complete: failed.length === 0 };
53
+ }
54
+ if (operation === 'remote-projects') {
55
+ const projects = [], failed = [];
56
+ for (const hostId of new Set(catalog.projects.map((project) => project.hostId))) {
57
+ let lease;
58
+ try {
59
+ lease = await gateway.acquireTask(hostId, { signal });
60
+ for (const project of catalog.projects.filter((project) => project.hostId === hostId)) {
61
+ projects.push({ id: project.id, path: project.path, ...(project.label ? { label: project.label } : {}), target: lease.target });
62
+ }
63
+ } catch { signal?.throwIfAborted(); failed.push({ hostId, code: 'remote_unavailable' }); }
64
+ finally { lease?.release(); }
65
+ }
66
+ return { projects, failed, complete: failed.length === 0 };
67
+ }
68
+ if (input.target.hubId !== catalog.hubId) fail('remote_target_mismatch');
69
+ if (operation === 'add-remote') {
70
+ const result = await gateway.registerProject(input.target.hostId, { path: input.path, ...(input.label ? { label: input.label } : {}) },
71
+ { instanceId: input.target.instanceId, signal });
72
+ return { ...result, target: input.target };
73
+ }
74
+ const lease = await gateway.acquireTask(input.target.hostId, { instanceId: input.target.instanceId, signal });
75
+ try {
76
+ if (['hubId', 'hostId', 'instanceId'].some((key) => lease.target[key] !== input.target[key])) fail('remote_target_mismatch');
77
+ gateway.assertProjectDirectory(input.target.hostId, input.directory);
78
+ const client = makeRemoteTaskOpenCodeClient(lease);
79
+ if (operation === 'sessions') {
80
+ const result = await client.session.list({ directory: input.directory, limit: 20, ...(input.cursor ? { cursor: input.cursor } : { order: 'desc' }) }, { signal });
81
+ const rows = result?.data;
82
+ if (!Array.isArray(rows)) fail('remote_response_invalid');
83
+ return { sessions: rows.map((row) => sessionSummary(row, lease.target)).filter((row) => row.directory === input.directory), nextCursor: result.cursor?.next ?? null };
84
+ }
85
+ if (operation === 'create-session') {
86
+ const created = await client.session.create({ id: input.sessionID, location: { directory: input.directory }, ...(input.title ? { title: input.title } : {}) }, { signal });
87
+ const session = sessionSummary(created, lease.target);
88
+ if (session.sessionID !== input.sessionID || session.directory !== input.directory) fail('remote_target_mismatch');
89
+ return { session, created: true };
90
+ }
91
+ const session = sessionRecord(await client.session.get({ sessionID: input.sessionID }, { signal }));
92
+ if (session?.id !== input.sessionID || directoryOf(session) !== input.directory) fail('remote_target_mismatch');
93
+ if (operation === 'read-session') {
94
+ const query = new URLSearchParams({ directory: input.directory, turns: '3', ...(input.cursor ? { cursor: input.cursor } : {}) });
95
+ const messages = await lease.json(`/api/yuri/sessions/${encodeURIComponent(input.sessionID)}/messages?${query}`, { signal });
96
+ return { session: sessionSummary(session, lease.target), messages };
97
+ }
98
+ await client.session.prompt({ sessionID: input.sessionID, id: input.messageID, text: input.text, delivery: 'steer' }, { signal });
99
+ return { session: sessionSummary(session, lease.target), messageID: input.messageID, admitted: true };
100
+ } finally { lease.release(); }
101
+ }
@@ -0,0 +1,125 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { configureServerOpenCodeFetchGate } from '../opencode/server-opencode-fetch.js';
3
+ import { runRemoteProjectOperation, validRemoteProjectInput } from './projects-remote.js';
4
+
5
+ const target = { hubId: 'hub', hostId: 'host', instanceId: 'instance' };
6
+ const input = { target, directory: '/repo', sessionID: 'ses_one' };
7
+ const session = { id: 'ses_one', location: { directory: '/repo' }, title: 'Remote', time: { created: 1, updated: 1 } };
8
+ const fixture = () => {
9
+ const request = vi.fn(async (route, init) => {
10
+ if (route === '/api/session/ses_one') return Response.json({ data: session });
11
+ const url = new URL(route, 'http://remote.invalid');
12
+ if (url.pathname === '/api/session' && init.method === 'GET') return Response.json({ data: [session], cursor: { next: 'next' } });
13
+ if (url.pathname === '/api/session' && init.method === 'POST') return Response.json({ data: session });
14
+ return Response.json({ data: {} });
15
+ });
16
+ const release = vi.fn(), json = vi.fn(async () => ({ messages: [], complete: true }));
17
+ const gateway = { supported: true, list: vi.fn(async () => ({ supported: true, hubId: 'hub', hosts: [{ id: 'host', name: 'Build machine', source: 'ssh' }], projects: [{ id: 'p', hostId: 'host', path: '/repo' }] })),
18
+ registerProject: vi.fn(async () => ({ project: { id: 'ref', path: '/repo', hostId: 'host' }, created: true })),
19
+ acquireTask: vi.fn(async () => ({ target, request, json, release })), assertProjectDirectory: vi.fn() };
20
+ return { gateway, request, json, release };
21
+ };
22
+
23
+ describe('bound remote project sessions', () => {
24
+ it('validates the complete target and operation allowlists', () => {
25
+ expect(validRemoteProjectInput('read-session', input)).toBe(true);
26
+ for (const value of [{ ...input, target: null }, { ...input, target: { ...target, instanceId: '' } }, { ...input, target: { hostId: 'host' } }, { ...input, hostOrigin: 'http://other' }]) {
27
+ expect(validRemoteProjectInput('read-session', value)).toBe(false);
28
+ }
29
+ expect(validRemoteProjectInput('prompt-session', { ...input, messageID: 'm', text: 'continue' })).toBe(true);
30
+ expect(validRemoteProjectInput('create-session', { target, directory: '/repo' })).toBe(false);
31
+ for (const path of ['/repo/new', 'C:\\Work\\项目 & 100%', '\\\\server\\share\\repo']) expect(validRemoteProjectInput('add-remote', { target, path, label: 'Project' })).toBe(true);
32
+ for (const value of [{ target, path: 'relative' }, { target, path: '/repo', label: '' }, { target, path: '/repo', label: 'x'.repeat(81) },
33
+ { target, path: '/repo\n' }, { target, path: '/repo', activate: true }, { target: { ...target, instanceId: '' }, path: '/repo' }]) expect(validRemoteProjectInput('add-remote', value)).toBe(false);
34
+ expect(validRemoteProjectInput('remote-hosts', {})).toBe(true);
35
+ expect(validRemoteProjectInput('remote-hosts', { target })).toBe(false);
36
+ });
37
+
38
+ it('discovers authorized machines even without projects and preserves per-machine failures without credentials', async () => {
39
+ const f = fixture();
40
+ f.gateway.list.mockResolvedValue({ supported: true, hubId: 'hub', hosts: [
41
+ { id: 'host', name: 'Build machine', source: 'ssh', apiUrl: 'private-url', clientToken: 'private-token' },
42
+ { id: 'offline', name: 'Offline', available: false }, { id: 'denied', name: 'Denied' },
43
+ ], projects: [] });
44
+ f.gateway.acquireTask.mockImplementation(async (id) => {
45
+ if (id === 'denied') throw new Error('private failure');
46
+ return { target, release: f.release };
47
+ });
48
+ const first = await runRemoteProjectOperation(f.gateway, 'remote-hosts', {});
49
+ expect(first).toMatchObject({ hosts: [{ name: 'Build machine', target }], failed: [{ hostId: 'offline' }, { hostId: 'denied' }], complete: false });
50
+ expect(JSON.stringify(first)).not.toMatch(/private/);
51
+ expect(f.release).toHaveBeenCalledOnce();
52
+ f.gateway.acquireTask.mockClear(); f.release.mockClear();
53
+ f.gateway.list.mockResolvedValue({ supported: true, hubId: 'hub', hosts: [{ id: 'host', name: 'Build machine', source: 'ssh' }], projects: [] });
54
+ expect(await runRemoteProjectOperation(f.gateway, 'remote-hosts', {})).toEqual({ hosts: [{ name: 'Build machine', source: 'ssh', target }], failed: [], complete: true });
55
+ expect(f.release).toHaveBeenCalledOnce();
56
+ });
57
+
58
+ it('registers against the captured instance through the shared gateway without local or session mutations', async () => {
59
+ const f = fixture(); const signal = new AbortController().signal;
60
+ expect(await runRemoteProjectOperation(f.gateway, 'add-remote', { target, path: '/repo', label: 'Remote' }, signal)).toEqual({ project: { id: 'ref', path: '/repo', hostId: 'host' }, created: true, target });
61
+ expect(f.gateway.registerProject).toHaveBeenCalledExactlyOnceWith('host', { path: '/repo', label: 'Remote' }, { instanceId: 'instance', signal });
62
+ expect(f.request).not.toHaveBeenCalled();
63
+ expect(f.gateway.assertProjectDirectory).not.toHaveBeenCalled();
64
+ await expect(runRemoteProjectOperation(f.gateway, 'add-remote', { target: { ...target, hubId: 'other' }, path: '/repo' })).rejects.toMatchObject({ code: 'remote_target_mismatch' });
65
+ expect(f.gateway.registerProject).toHaveBeenCalledOnce();
66
+ f.gateway.registerProject.mockRejectedValueOnce(new Error('offline'));
67
+ await expect(runRemoteProjectOperation(f.gateway, 'add-remote', { target, path: '/repo' })).rejects.toThrow('offline');
68
+ expect(f.gateway.registerProject).toHaveBeenCalledTimes(2);
69
+ });
70
+
71
+ it('stops discovery on cancellation instead of returning a false complete catalog', async () => {
72
+ const f = fixture(); const controller = new AbortController();
73
+ f.gateway.acquireTask.mockImplementationOnce(async () => { controller.abort(); throw controller.signal.reason; });
74
+ await expect(runRemoteProjectOperation(f.gateway, 'remote-hosts', {}, controller.signal)).rejects.toMatchObject({ name: 'AbortError' });
75
+ });
76
+
77
+ it('discovers authenticated targets, releases leases and preserves partial failures', async () => {
78
+ const f = fixture();
79
+ expect(await runRemoteProjectOperation(f.gateway, 'remote-projects', {})).toEqual({ projects: [{ id: 'p', path: '/repo', target }], failed: [], complete: true });
80
+ expect(f.release).toHaveBeenCalledTimes(1);
81
+ f.gateway.acquireTask.mockRejectedValueOnce(new Error('private transport details'));
82
+ expect(await runRemoteProjectOperation(f.gateway, 'remote-projects', {})).toEqual({ projects: [], failed: [{ hostId: 'host', code: 'remote_unavailable' }], complete: false });
83
+ });
84
+
85
+ it('rejects wrong Hub, retarget and wrong session directory before message access', async () => {
86
+ const f = fixture();
87
+ await expect(runRemoteProjectOperation(f.gateway, 'read-session', { ...input, target: { ...target, hubId: 'other' } })).rejects.toMatchObject({ code: 'remote_target_mismatch' });
88
+ expect(f.gateway.acquireTask).not.toHaveBeenCalled();
89
+ f.gateway.acquireTask.mockResolvedValueOnce({ target: { ...target, instanceId: 'replacement' }, release: f.release });
90
+ await expect(runRemoteProjectOperation(f.gateway, 'read-session', input)).rejects.toMatchObject({ code: 'remote_target_mismatch' });
91
+ await expect(runRemoteProjectOperation(f.gateway, 'read-session', { ...input, directory: '/other' })).rejects.toMatchObject({ code: 'remote_target_mismatch' });
92
+ expect(f.json).not.toHaveBeenCalled();
93
+ expect(f.release).toHaveBeenCalledTimes(2);
94
+ });
95
+
96
+ it('uses lease-backed generated SDK requests and only bounded transient message pages', async () => {
97
+ const f = fixture();
98
+ const signal = new AbortController().signal;
99
+ const listed = await runRemoteProjectOperation(f.gateway, 'sessions', { target, directory: '/repo' }, signal);
100
+ expect(listed).toMatchObject({ sessions: [{ sessionID: 'ses_one', directory: '/repo', target }], nextCursor: 'next' });
101
+ const [route] = f.request.mock.calls[0];
102
+ expect(new URL(route, 'http://remote.invalid').searchParams.get('directory')).toBe('/repo');
103
+ const read = await runRemoteProjectOperation(f.gateway, 'read-session', input, signal);
104
+ expect(read).toMatchObject({ session: { target }, messages: { complete: true } });
105
+ expect(f.json).toHaveBeenCalledWith('/api/yuri/sessions/ses_one/messages?directory=%2Frepo&turns=3', { signal });
106
+ expect(f.release).toHaveBeenCalledTimes(2);
107
+ });
108
+
109
+ it('preserves caller-owned write IDs and never retries a failed prompt', async () => {
110
+ configureServerOpenCodeFetchGate(() => ({ executionAllowed: false }));
111
+ try {
112
+ const f = fixture();
113
+ expect(await runRemoteProjectOperation(f.gateway, 'create-session', input)).toMatchObject({ session: { sessionID: 'ses_one', target } });
114
+ const created = JSON.parse(Buffer.from(f.request.mock.calls[0][1].body).toString());
115
+ expect(created).toMatchObject({ id: 'ses_one' });
116
+ f.request.mockClear();
117
+ expect(await runRemoteProjectOperation(f.gateway, 'prompt-session', { ...input, messageID: 'msg_one', text: 'continue' })).toMatchObject({ admitted: true, messageID: 'msg_one' });
118
+ const call = f.request.mock.calls.find(([, init]) => init.method === 'POST');
119
+ expect(JSON.parse(Buffer.from(call[1].body).toString())).toMatchObject({ id: 'msg_one', text: 'continue', delivery: 'steer' });
120
+ f.request.mockRejectedValue(new Error('network'));
121
+ await expect(runRemoteProjectOperation(f.gateway, 'prompt-session', { ...input, messageID: 'msg_one', text: 'continue' })).rejects.toThrow();
122
+ expect(f.release).toHaveBeenCalledTimes(3);
123
+ } finally { configureServerOpenCodeFetchGate(null); }
124
+ });
125
+ });
@@ -1,10 +1,12 @@
1
1
  import path from 'node:path';
2
2
  import { authorizeScheduledTaskSkillRequest } from '../scheduled-tasks/session-skill-contract.js';
3
+ import { remoteProjectOperations, validRemoteProjectInput, runRemoteProjectOperation } from './projects-remote.js';
3
4
 
4
5
  export const PROJECTS_SKILL_PATH = '/api/yuri/session-skills/projects';
5
6
 
6
7
  const projectResult = ({ id, path, label }) => ({ id, path, ...(label ? { label } : {}) });
7
8
  const validInput = (operation, input) => {
9
+ if (remoteProjectOperations.includes(operation)) return validRemoteProjectInput(operation, input);
8
10
  if (!input || typeof input !== 'object' || Array.isArray(input)) return false;
9
11
  const allowed = operation === 'add' ? ['path', 'label'] : [];
10
12
  if (Object.keys(input).some((key) => !allowed.includes(key))) return false;
@@ -14,19 +16,40 @@ const validInput = (operation, input) => {
14
16
  };
15
17
 
16
18
  /** Session-bound Host registration; the shared project registry owns persistence. */
17
- export function registerProjectsSkill(app, { express, getIsSharedOpenCodeService, getOpenCodeAuthHeaders, createClient, registerProject, readSettingsFromDiskStrict, sanitizeProjects }) {
19
+ export function registerProjectsSkill(app, { express, getIsSharedOpenCodeService, getOpenCodeAuthHeaders, createClient, registerProject, readSettingsFromDiskStrict, sanitizeProjects, remoteHostGateway }) {
18
20
  app.post(PROJECTS_SKILL_PATH, express.json({ limit: '16kb' }), async (req, res) => {
19
21
  res.setHeader('Cache-Control', 'no-store');
20
22
  if (!getIsSharedOpenCodeService() || !authorizeScheduledTaskSkillRequest(req, getOpenCodeAuthHeaders())) return res.status(403).json({ error: 'Forbidden' });
21
23
  const { sessionID, operation, input = {} } = req.body ?? {};
22
24
  if (typeof sessionID !== 'string' || !sessionID || sessionID.length > 256
23
- || !['describe', 'list', 'add'].includes(operation) || !validInput(operation, input)) return res.status(400).json({ code: 'invalid_input', error: 'Invalid project input' });
25
+ || !['describe', 'list', 'add', ...remoteProjectOperations].includes(operation) || !validInput(operation, input)) return res.status(400).json({ code: 'invalid_input', error: 'Invalid project input' });
24
26
  try {
25
27
  const session = await createClient().session.get({ sessionID });
26
28
  const hostOrigin = `http://${req.socket.localAddress === '::1' ? '[::1]' : '127.0.0.1'}:${req.socket.localPort}`;
27
29
  if (session.metadata?.yuri?.scheduledTaskSkill?.hostOrigin !== hostOrigin) return res.status(403).json({ error: 'Session is not bound to this Host' });
28
- if (operation === 'describe') return res.json({ supported: true, inputs: { add: '{path: existing absolute Host directory, label?: display name}', list: '{}' },
29
- completion: 'add returns the persisted project and created=true/false. Registration does not clone/create files, open a session or change an existing active selection. Retry the same path safely after an interrupted response.' });
30
+ if (operation === 'describe') return res.json({ supported: true, remoteSupported: Boolean(remoteHostGateway?.supported && remoteHostGateway?.acquireTask), inputs: { add: '{path: existing absolute Host directory, label?: display name}', list: '{}',
31
+ 'remote-hosts': '{}', 'add-remote': '{target: {hubId,hostId,instanceId} from remote-hosts, path: existing absolute remote directory, label?}',
32
+ 'remote-projects': '{}', sessions: '{target, directory, cursor?}', 'read-session': '{target, directory, sessionID, cursor?}',
33
+ 'create-session': '{target, directory, sessionID: new caller-generated ID, title?}', 'prompt-session': '{target, directory, sessionID, messageID: stable caller-generated ID, text}' },
34
+ completion: 'add and add-remote return the persisted project and created=true/false. add-remote registers on the target Host, then saves the Hub reference. Registration does not clone/create files, open a session or change an existing active selection. Retry the same target and path safely after an interrupted response.' });
35
+ if (remoteProjectOperations.includes(operation)) {
36
+ const controller = new AbortController();
37
+ const abort = () => controller.abort();
38
+ req.once('aborted', abort);
39
+ res.once('close', abort);
40
+ if (req.aborted || res.destroyed) abort();
41
+ const timeout = ['create-session', 'prompt-session'].includes(operation) ? 300_000 : 25_000;
42
+ try {
43
+ const result = await runRemoteProjectOperation(remoteHostGateway, operation, input,
44
+ AbortSignal.any([controller.signal, AbortSignal.timeout(timeout)]));
45
+ if (!controller.signal.aborted) return res.json(result);
46
+ return;
47
+ } finally {
48
+ req.removeListener('aborted', abort);
49
+ res.removeListener('close', abort);
50
+ controller.abort();
51
+ }
52
+ }
30
53
  if (operation === 'list') {
31
54
  const settings = await readSettingsFromDiskStrict();
32
55
  if (!settings || typeof settings !== 'object' || Array.isArray(settings)
@@ -36,8 +59,9 @@ export function registerProjectsSkill(app, { express, getIsSharedOpenCodeService
36
59
  const { project, created } = await registerProject(input);
37
60
  return res.json({ project: projectResult(project), created });
38
61
  } catch (error) {
39
- const code = ['validation_error', 'project_unavailable'].includes(error?.code) ? error.code : 'project_operation_failed';
40
- return res.status(code === 'validation_error' ? 400 : 503).json({ code, error: 'Project operation was not confirmed; check the path or retry the same path after recovery' });
62
+ if (res.destroyed) return;
63
+ const code = ['validation_error', 'project_unavailable', 'remote_unavailable', 'remote_target_mismatch', 'remote_response_invalid'].includes(error?.code) ? error.code : 'project_operation_failed';
64
+ return res.status(code === 'validation_error' ? 400 : 503).json({ code, error: 'Project operation was not confirmed; inspect the same target before retrying. Never retry against the local Host.' });
41
65
  }
42
66
  });
43
67
  }
@@ -12,7 +12,7 @@ import { createProjectDirectoryRuntime } from '../opencode/project-directory-run
12
12
  import { registerProjectsSkill, PROJECTS_SKILL_PATH } from './projects.js';
13
13
 
14
14
  describe('session project registration API', () => {
15
- let root, workspace, settingsPath, runtime, server, origin, getSession, binding, registerProject, shared, failWrites, tips;
15
+ let root, workspace, settingsPath, runtime, server, origin, getSession, binding, registerProject, shared, failWrites, tips, gateway;
16
16
  const auth = { Authorization: `Basic ${Buffer.from('opencode:fixture').toString('base64')}` };
17
17
  beforeEach(async () => {
18
18
  root = await fs.mkdtemp(path.join(os.tmpdir(), 'project-skill-'));
@@ -31,9 +31,11 @@ describe('session project registration API', () => {
31
31
  registerProject = vi.fn((input) => registry.register(input));
32
32
  getSession = vi.fn(async () => ({ metadata: { yuri: { scheduledTaskSkill: { hostOrigin: binding } } } }));
33
33
  const app = express();
34
+ gateway = { supported: true, acquireTask: vi.fn(), registerProject: vi.fn(), list: vi.fn(async () => ({ supported: true, hubId: 'hub', hosts: [], projects: [] })) };
34
35
  registerProjectsSkill(app, { express, getIsSharedOpenCodeService: () => shared, getOpenCodeAuthHeaders: () => auth,
35
36
  createClient: () => ({ session: { get: getSession } }), registerProject, readSettingsFromDiskStrict: runtime.readSettingsFromDiskStrict,
36
37
  sanitizeProjects: normalization.sanitizeProjects,
38
+ remoteHostGateway: gateway,
37
39
  });
38
40
  server = await new Promise((resolve) => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
39
41
  origin = `http://127.0.0.1:${server.address().port}`; binding = origin;
@@ -86,6 +88,41 @@ describe('session project registration API', () => {
86
88
  expect(registerProject).not.toHaveBeenCalled();
87
89
  });
88
90
 
91
+ it('keeps remote discovery under the existing service and per-session admission gate', async () => {
92
+ expect(await (await request('describe')).json()).toMatchObject({ remoteSupported: true });
93
+ expect(await (await request('remote-projects')).json()).toEqual({ projects: [], failed: [], complete: true });
94
+ gateway.list.mockClear();
95
+ for (const headers of [{}, { Authorization: 'Bearer browser' }, { ...auth, Origin: origin }]) expect((await request('remote-projects', {}, headers)).status).toBe(403);
96
+ binding = 'http://127.0.0.1:1';
97
+ expect((await request('remote-projects')).status).toBe(403);
98
+ expect(gateway.list).not.toHaveBeenCalled();
99
+ expect(gateway.acquireTask).not.toHaveBeenCalled();
100
+ });
101
+
102
+ it('advertises and gates remote machine discovery and registration independently of local registration', async () => {
103
+ const target = { hubId: 'hub', hostId: 'host', instanceId: 'instance' };
104
+ const input = { target, path: '/remote/repo', label: 'Remote' };
105
+ const described = await (await request('describe')).json();
106
+ expect(described.inputs).toMatchObject({ 'remote-hosts': '{}', 'add-remote': expect.stringContaining('instanceId') });
107
+ expect(await (await request('remote-hosts')).json()).toEqual({ hosts: [], failed: [], complete: true });
108
+ gateway.registerProject.mockResolvedValue({ project: { id: 'remote-ref', path: input.path, hostId: target.hostId }, created: true });
109
+ expect(await (await request('add-remote', input)).json()).toMatchObject({ project: { id: 'remote-ref', path: input.path }, created: true, target });
110
+ expect(gateway.registerProject).toHaveBeenCalledExactlyOnceWith('host', { path: input.path, label: 'Remote' }, { instanceId: 'instance', signal: expect.any(AbortSignal) });
111
+ expect(registerProject).not.toHaveBeenCalled();
112
+ for (const value of [{ ...input, path: 'relative' }, { ...input, target: { hostId: 'host' } }, { ...input, label: '' }, { ...input, activate: true }]) expect((await request('add-remote', value)).status).toBe(400);
113
+ for (const operation of ['remote-hosts', 'add-remote']) {
114
+ for (const headers of [{}, { Authorization: 'Bearer browser' }, { ...auth, Origin: origin }]) expect((await request(operation, operation === 'add-remote' ? input : {}, headers)).status).toBe(403);
115
+ }
116
+ gateway.registerProject.mockRejectedValueOnce(new Error('private-token /local/path'));
117
+ const failed = await request('add-remote', input);
118
+ expect(failed.status).toBe(503);
119
+ expect(await failed.text()).not.toMatch(/private-token|local\/path/);
120
+ binding = 'http://127.0.0.1:1';
121
+ expect((await request('add-remote', input)).status).toBe(403);
122
+ expect((await request('remote-hosts')).status).toBe(403);
123
+ expect(gateway.registerProject).toHaveBeenCalledTimes(2);
124
+ });
125
+
89
126
  it('never reports corrupt reads or failed persistence as successful empty or added results', async () => {
90
127
  for (const corrupt of ['{broken', '[]', 'null', '{"projects":{}}']) {
91
128
  await fs.writeFile(settingsPath, corrupt);
@@ -100,4 +137,32 @@ describe('session project registration API', () => {
100
137
  expect(await fs.readFile(settingsPath, 'utf8')).toBe('{"projects":[]}');
101
138
  expect(tips).not.toHaveBeenCalled();
102
139
  });
140
+
141
+ it('releases remote task demand when the bound caller disconnects', async () => {
142
+ const target = { hubId: 'hub', hostId: 'host', instanceId: 'instance' };
143
+ let entered;
144
+ const started = new Promise((resolve) => { entered = resolve; });
145
+ let released;
146
+ const stopped = new Promise((resolve) => { released = resolve; });
147
+ const release = vi.fn(released);
148
+ gateway.assertProjectDirectory = vi.fn();
149
+ gateway.acquireTask.mockImplementation(async (_id, { signal }) => ({ target, release,
150
+ request: async () => {
151
+ entered();
152
+ await new Promise((_resolve, reject) => {
153
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
154
+ });
155
+ },
156
+ }));
157
+ const controller = new AbortController();
158
+ const pending = fetch(`${origin}${PROJECTS_SKILL_PATH}`, { method: 'POST', signal: controller.signal,
159
+ headers: { 'content-type': 'application/json', ...auth },
160
+ body: JSON.stringify({ sessionID: 'ses_one', operation: 'sessions', input: { target, directory: '/repo' } }),
161
+ }).catch(() => null);
162
+ await started;
163
+ controller.abort();
164
+ await pending;
165
+ await stopped;
166
+ expect(release).toHaveBeenCalledOnce();
167
+ });
103
168
  });
@@ -31,10 +31,10 @@ export function createCustomizationSkillInstaller({ yuriDataDir }) {
31
31
  };
32
32
  return async (client, sessionID, { remoteBinding, projectBinding } = {}) => {
33
33
  const file = await prepare(Boolean(remoteBinding), Boolean(projectBinding));
34
- const projects = projectBinding ? ` For project registration, read references/projects.md and run the bound project API helper.\nBound project helper: ${sessionSkillCommand(process.execPath, path.join(path.dirname(file), 'projects.mjs'), Buffer.from(JSON.stringify({ ...projectBinding, sessionID })).toString('base64url'), 'describe')}\n` : ' No bound project helper is provided; project registration is unavailable through this session skill.';
34
+ const projects = projectBinding ? ` For local/remote project registration, discovering authorized remote machines, or reading/creating/continuing remote sessions, read references/projects.md and run the bound project API helper.\nBound project helper: ${sessionSkillCommand(process.execPath, path.join(path.dirname(file), 'projects.mjs'), Buffer.from(JSON.stringify({ ...projectBinding, sessionID })).toString('base64url'), 'describe')}\n` : ' No bound project helper is provided; project registration and remote project/session access are unavailable through this session skill.';
35
35
  const remote = remoteBinding ? ` For SSH setup/config sync or Relay pairing, use only this bound helper after reading references/remote-connections.md. Bound local desktop helper: ${remoteConnectionsCommand(process.execPath, path.join(path.dirname(file), 'remote-connections.mjs'), Buffer.from(JSON.stringify({ ...remoteBinding, sessionID })).toString('base64url'), 'describe')}` : ' No bound SSH/Relay command is provided: these operations are unavailable in this session. Report that limit and stop this branch; use native Settings or a new supported local desktop session. A script or another capability\'s binding does not enable it. There is no credential/filesystem fallback for this capability.';
36
36
  await client.session.instructions.entry.put({ sessionID, key: 'yuri.customization',
37
- value: `Yuri customization: for adding a directory as a project in Yuri, SSH connections, configuration sync, Relay pairing, appearance (themes, CSS/layout, Logo, macOS Dock), work-status widgets, global pages/tabs, custom file parsing/previews, preview exports, or GUI panels/commands/settings, read ${JSON.stringify(file)} first. Use the matching reference and apply changes only when requested.${projects}${remote}`,
37
+ value: `Yuri customization: for adding a directory as a project in Yuri (local or remote), remote sessions, SSH connections, configuration sync, Relay pairing, appearance (themes, CSS/layout, Logo, macOS Dock), work-status widgets, global pages/tabs, custom file parsing/previews, preview exports, or GUI panels/commands/settings, read ${JSON.stringify(file)} first. Use the matching reference and apply changes only when requested.${projects}${remote}`,
38
38
  });
39
39
  };
40
40
  }
@@ -54,6 +54,10 @@ describe('built-in customization instructions', () => {
54
54
  const projectFile = JSON.parse(projectEntry.match(/read (".*?") first/)[1]);
55
55
  expect(projectFile).not.toBe(boundFile);
56
56
  expect(projectEntry).toContain('Bound project helper:');
57
+ expect(projectEntry).toContain('local/remote project registration');
58
+ expect(projectEntry).toContain('discovering authorized remote machines');
59
+ expect(await fs.readFile(path.join(path.dirname(projectFile), 'references', 'projects.md'), 'utf8')).toContain('commands.add-remote');
60
+ expect(await fs.readFile(path.join(path.dirname(projectFile), 'projects.mjs'), 'utf8')).toContain("'remote-hosts', 'add-remote'");
57
61
  expect(projectEntry).toContain('No bound SSH/Relay command is provided');
58
62
  expect(await fs.readFile(path.join(path.dirname(projectFile), 'projects.mjs'), 'utf8')).toContain('/api/yuri/session-skills/projects');
59
63
  await expect(fs.stat(path.join(path.dirname(projectFile), 'remote-connections.mjs'))).rejects.toMatchObject({ code: 'ENOENT' });
@@ -1,12 +1,14 @@
1
1
  ---
2
2
  name: yuri-customization
3
- description: Add existing directories as Yuri projects through its API, configure SSH connections, configuration sync and Relay pairing, or customize its GUI through plugins for appearance, pages, widgets, previews, panels and settings.
3
+ description: Register local or remote Yuri projects, discover authorized remote machines and read/create/continue remote sessions, configure SSH connections, configuration sync and Relay pairing, or customize its GUI through plugins for appearance, pages, widgets, previews, panels and settings.
4
4
  ---
5
5
 
6
6
  # Yuri customization
7
7
 
8
8
  For adding an existing directory to Yuri's project list, follow [projects](references/projects.md) using this session's bound project API helper. Registration is separate from creating files, cloning or opening a conversation.
9
9
 
10
+ For adding a remote project on an authorized machine or working with its sessions, use the same bound project helper and the [remote project workflow](references/projects.md#connected-remote-projects-and-sessions). This grants no SSH setup or new connection permission.
11
+
10
12
  For SSH setup, configuration sync or Relay pairing, first check this session's pointer for its exact bound local desktop helper command. Without that command, report unavailable and stop this branch: a script file or another capability's binding does not enable it. With the command, follow [remote connections](references/remote-connections.md). For UI changes, use the plugin workflow below. Its GUI contracts describe Yuri's supported subset of the experimental OpenCode GUI SDK 2.2.0, not every capability in the newest upstream Desktop.
11
13
 
12
14
  ## Workflow
@@ -1,11 +1,11 @@
1
- # Add a project
1
+ # Projects
2
2
 
3
3
  Register an existing directory through the **bound project API helper** in this
4
4
  session's Yuri customization pointer. This is a Host capability, not a GUI plugin
5
5
  or a desktop deep link. Registration does not create files, clone a repository,
6
6
  open a conversation or switch an existing active project.
7
7
 
8
- ## Workflow
8
+ ## Local project registration
9
9
 
10
10
  1. Resolve the user-requested directory to an absolute path on the bound Yuri
11
11
  Host. Reuse a known directory; directory creation/cloning is a separate action
@@ -41,7 +41,7 @@ workflow until a new supported session's bound describe succeeds.
41
41
  ## Interface and scope
42
42
 
43
43
  The helper calls `POST /api/yuri/session-skills/projects` with
44
- `{sessionID, operation: "describe" | "list" | "add", input}`. It uses the same
44
+ `{sessionID, operation, input}`, using operations returned by `describe`. It uses the same
45
45
  loopback service authentication and admitted-session Host binding as the other
46
46
  built-in session helpers. Only affected project metadata is returned, never full
47
47
  settings or credentials. Use the bound command rather than reconstructing auth or
@@ -61,3 +61,30 @@ this file. Contacts may instead have their own granted `yuri.projects` tools;
61
61
  those retain their own capability contract. When the helper is unavailable, use
62
62
  the intended Host's project UI or start a supported session. Keep desktop deep
63
63
  links for their existing navigation purpose, not as an API authorization fallback.
64
+
65
+ ## Connected remote projects and sessions
66
+
67
+ Use this branch to add a remote project on an authorized machine or discover, read, create or continue its sessions. Registration uses the remote machine's filesystem, not this session's local filesystem.
68
+
69
+ 1. Run the exact bound project `describe` command. Continue only when `remoteSupported:true`; use its returned commands unchanged. No bound helper or a terminal auth error means stop this branch.
70
+ 2. Choose the target from authenticated discovery:
71
+ - Existing projects: `commands.remote-projects` returns each project with `target:{hubId,hostId,instanceId}` and its raw `path`.
72
+ - A new remote project: `commands.remote-hosts` returns authorized machines as `{name,source,target}`, including machines with no project yet. Match the user's machine to this result; ask when ambiguous. `failed` and `complete:false` mean discovery is partial, not an empty catalog. Recover a failed connection rather than guessing another target.
73
+ - Keep all three target identities with the path and session ID; identical paths/IDs on different Hosts are separate resources. Use returned identities unchanged, not a hostname or SSH address as an ID.
74
+ 3. To register an existing remote directory, run `commands.add-remote` with JSON on stdin:
75
+
76
+ ```json
77
+ {"target":{"hubId":"<returned hubId>","hostId":"<returned hostId>","instanceId":"<returned instanceId>"},"path":"/workspace/my-project","label":"My remote project"}
78
+ ```
79
+
80
+ - Input: `path` is a literal absolute path on that machine (POSIX or Windows); `label` is optional, at most 80 characters. The remote Host validates/canonicalizes and registers it, then the Hub saves its sidebar reference and notifies connected clients.
81
+ - Completion: success returns `{project,created,target}`; `created:false` means the Hub reference already existed. Use the returned canonical `project.path` for session operations. Registration preserves the active project and does not open a session.
82
+ - Recovery: if interrupted or Hub persistence fails, retry the same target/path. The remote project is retained and registration deduplicates it. No local directory check, clone or filesystem creation is part of this operation.
83
+ 4. Supply JSON on stdin to the session operation requested by the user:
84
+ - `sessions`: `{target,directory,cursor?}` returns up to 20 metadata rows and `nextCursor`.
85
+ - `read-session`: `{target,directory,sessionID,cursor?}` returns session metadata plus a bounded, transient message page. Follow its continuation receipt to read more; do not copy raw tool output into Hub history, files or caches.
86
+ - `create-session`: `{target,directory,sessionID,title?}` creates an empty worker. Generate a new caller-owned session ID once and retain it through recovery. Read that same ID after an interrupted response before attempting another creation.
87
+ - `prompt-session`: `{target,directory,sessionID,messageID,text}` continues that exact worker. Generate a message ID once. `admitted:true` confirms submission, not task completion; use `read-session` for the outcome. After an ambiguous timeout inspect the same session/message ID before any retry; never resend with a new ID automatically.
88
+ 5. Report only confirmed outcomes. An unavailable/mismatched target fails explicitly and retains the original reference; recover that connection or ask the user, never retry against the local Host or another connection.
89
+
90
+ Remote session operations require a registered project scope; `add-remote` establishes that scope on an existing authorized connection. These operations do not configure SSH, synchronize credentials, pair Relay, clone, create directories, select the UI project or obtain new machine access. For a machine not yet authorized, first follow the separate [SSH/Relay workflow](remote-connections.md) with its own bound local desktop helper. After setup completes, rediscover the authenticated target through `remote-hosts`; a project helper alone does not grant that connection permission.