@yuriai/web 0.2.40-beta.4 → 0.2.40-beta.5
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.
- package/dist/assets/{AgentAvatar-BmT_6apW.js → AgentAvatar-B7KbxN8Y.js} +1 -1
- package/dist/assets/AssistantConversationSurface-BnK_KTBO.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-C34eOGCL.js → AssistantUnreadBadge-vu4ZhTft.js} +1 -1
- package/dist/assets/{AssistantView-0nXkM9VG.js → AssistantView-CEfEWUIr.js} +1 -1
- package/dist/assets/DiagramView-Dlzr08J_.js +1 -0
- package/dist/assets/{FadeInOnReveal-CCVdl9Vt.js → FadeInOnReveal-DMRmNsau.js} +1 -1
- package/dist/assets/{GuiPluginPage-BMt5AMqg.js → GuiPluginPage-DVug4z_p.js} +1 -1
- package/dist/assets/GuiPluginSurface-L43o6Xv8.js +1 -0
- package/dist/assets/{GuiPluginWindow-BVvzrnp1.js → GuiPluginWindow-tHXkS18H.js} +1 -1
- package/dist/assets/{Icon-B5nBc6dO.js → Icon-DizeYahT.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-Bv5mmf2U.js → ImageLoadingPlaceholder-BZC5m_km.js} +1 -1
- package/dist/assets/LoadingImage-Csw4L-Dr.js +1 -0
- package/dist/assets/MarkdownRenderer-D_0iKhQN.js +2 -0
- package/dist/assets/MarkdownRendererImpl-BZ0XgjS0.js +10 -0
- package/dist/assets/MarkstreamRendererImpl-DBd6Glg9.js +3 -0
- package/dist/assets/MobileDetailNavigation-xgwvsQuR.js +1 -0
- package/dist/assets/{MobileResizableSheet-D5PcZMuI.js → MobileResizableSheet-CQQ7O-2X.js} +1 -1
- package/dist/assets/MobileShareBridge-IO45gM2G.js +3 -0
- package/dist/assets/MobileSurface-DmYgZONB.js +2 -0
- package/dist/assets/{MultiRunWindow-rMqP99ID.js → MultiRunWindow-fJ3XfntS.js} +1 -1
- package/dist/assets/OnboardingScreen-MJS5T5rL.js +1 -0
- package/dist/assets/{OverlayScrollbar-Byx2H3pc.js → OverlayScrollbar-jtMYTn1y.js} +1 -1
- package/dist/assets/SettingsView-ZWFLpPSI.js +29 -0
- package/dist/assets/{SettingsWindow-U-RDDOS7.js → SettingsWindow-DGRmrIWz.js} +1 -1
- package/dist/assets/SetupTourDialog-BYbAubwA.js +1 -0
- package/dist/assets/TerminalView-CoJ6_9P1.js +8 -0
- package/dist/assets/ToolOutputDialog-5xBwOJ6a.js +16 -0
- package/dist/assets/VoiceSettings-CN33koSc.js +2 -0
- package/dist/assets/{YuriLogo-B58GIl2v.js → YuriLogo-CvyJy_R9.js} +1 -1
- package/dist/assets/YuriWordmark-DnFAS-Ko.js +1 -0
- package/dist/assets/{assistant-attachment-cache-Cmzt4xXE.js → assistant-attachment-cache-D-LmCflm.js} +1 -1
- package/dist/assets/bootstrap-eLlfzqAI.js +1 -0
- package/dist/assets/{capgoAdapter-B5NImlKh.js → capgoAdapter-CCLtBZL1.js} +1 -1
- package/dist/assets/{checkbox-Bdj4n5cI.js → checkbox-rOV6DjeG.js} +1 -1
- package/dist/assets/client-uz8O6TPX.js +7 -0
- package/dist/assets/{collapsible-D1JZOgJZ.js → collapsible-CKswuqAw.js} +1 -1
- package/dist/assets/{context-menu-DDX0ZFhc.js → context-menu-B4njwT_M.js} +1 -1
- package/dist/assets/{desktopHosts-DovfbQPm.js → desktopHosts-135cuRCE.js} +1 -1
- package/dist/assets/{desktopRelayRestore-D4pbpNKN.js → desktopRelayRestore-1aUztDPU.js} +1 -1
- package/dist/assets/{device-DNG0cNwQ.js → device-QL8KNSLM.js} +1 -1
- package/dist/assets/{diagram-C72TQWfh.js → diagram-BppQ_USn.js} +1 -1
- package/dist/assets/{dialog-CIKJalI5.js → dialog-Bg8MJnOV.js} +1 -1
- package/dist/assets/{es-D0Q_CV0t.js → es-Ba3NUCtE.js} +3 -3
- package/dist/assets/{fileMentionTouchSelection-tnd9RDDh.js → fileMentionTouchSelection-D-AdTJVr.js} +1 -1
- package/dist/assets/fileReferenceActions-cYqdsXFz.js +1 -0
- package/dist/assets/{fr-DrO5SAKl.js → fr-CRhp3hyT.js} +3 -3
- package/dist/assets/{gitApi-BI8OG_ts.js → gitApi-DVx_V1x6.js} +11 -7
- package/dist/assets/gitApiHttp-DvTBxvX8.js +3 -0
- package/dist/assets/historyImportQueries-D_9RlrLp.js +1 -0
- package/dist/assets/host-DrGjjO6K.js +1 -0
- package/dist/assets/{i18n-UaLestuf.js → i18n-RH7UieOS.js} +1 -1
- package/dist/assets/image-loading-DBqnxgDH.js +1 -0
- package/dist/assets/{input-gVHSS0EB.js → input-DRjuZMeA.js} +1 -1
- package/dist/assets/input-store-CjUOfpyA.js +1 -0
- package/dist/assets/insertionBoundaries-DZtQt2Ah.js +1 -0
- package/dist/assets/{ja-BNeP9_GU.js → ja-D-UPjDY2.js} +3 -3
- package/dist/assets/{ko-DRRFD_7l.js → ko-x-z9J5z7.js} +3 -3
- package/dist/assets/main-BMFY9mtb.js +2 -0
- package/dist/assets/main-D2s9J_jN.js +169 -0
- package/dist/assets/{markdownHeightCache-B-FoaQ1U.js → markdownHeightCache-BL99DlhC.js} +1 -1
- package/dist/assets/{markdownTheme-CHNl6tUv.js → markdownTheme-DFDWa8Gh.js} +1 -1
- package/dist/assets/mcpQueries-HzYMEVWd.js +1 -0
- package/dist/assets/miniChat-BbJ0GKpk.js +2 -0
- package/dist/assets/mobile-_zUth69Z.js +2 -0
- package/dist/assets/mobileBackNavigation--ZdrI-Yj.js +1 -0
- package/dist/assets/mobileConnections-C3eGEOPy.js +2 -0
- package/dist/assets/multirun-CDYNyLBH.js +3 -0
- package/dist/assets/{native-config-DqDXViVx.js → native-config-DOawZfln.js} +1 -1
- package/dist/assets/navigation-Ibk_Pw-q.js +2 -0
- package/dist/assets/{pl-BnW5wJrl.js → pl-Cqo1FJwM.js} +3 -3
- package/dist/assets/platform-wF65ZFgV.js +1 -0
- package/dist/assets/project-preview-2H-TmJkd.js +1 -0
- package/dist/assets/projectActions-50e_f9dI.js +1 -0
- package/dist/assets/projectMeta-D1Ytss9U.js +1 -0
- package/dist/assets/prompt-attachment-upload-BNhDXymd.js +1 -0
- package/dist/assets/{pt-BR-fZW8CCVQ.js → pt-BR-C930XU1k.js} +3 -3
- package/dist/assets/pwa-CXupOTsD.js +2 -0
- package/dist/assets/queue-abort-optimistic-CQXpIlq6.js +1 -0
- package/dist/assets/{react-DeB-Vc_L.js → react-CgRToPwO.js} +1 -1
- package/dist/assets/{readiness-CIlvQ-aQ.js → readiness-BfuZm6Yw.js} +2 -2
- package/dist/assets/relay-preview-frame-src-BPyz3nXA.js +1 -0
- package/dist/assets/remote-input-store-BOdCWpQY.js +1 -0
- package/dist/assets/remoteProjectQueries-CkxdZNw4.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-pJ59iC34.js +2 -0
- package/dist/assets/renderMobileApp-BQFC-gOA.js +29 -0
- package/dist/assets/{runtime-file-download-DMY1k1af.js → runtime-file-download-D11Nnedg.js} +1 -1
- package/dist/assets/runtime-file-resource-CuLP3xp7.js +6 -0
- package/dist/assets/runtimeConfig-tHm7o_0I.js +2 -0
- package/dist/assets/{runtimeEndpointReset-BOdd_mJM.css → runtimeEndpointReset-BUGfn7y0.css} +1 -1
- package/dist/assets/runtimeEndpointReset-BhHWFNvo.js +150 -0
- package/dist/assets/safeStorage-DTOhKN0V.js +1 -0
- package/dist/assets/scheduledTaskNavigation-BIDtQ4wN.js +1 -0
- package/dist/assets/{select-BwCKwnTH.js → select-B1On-Y4Z.js} +1 -1
- package/dist/assets/sessionLookup-RcyTTDOy.js +1 -0
- package/dist/assets/sortable-tabs-strip-nD1Me06z.js +1 -0
- package/dist/assets/{speechSettingsQueries-C5mPRWIv.js → speechSettingsQueries-BYhNpzDJ.js} +1 -1
- package/dist/assets/src-BZCFf9_1.css +2 -0
- package/dist/assets/{store-CzVMz42v.js → store-DunGyOfe.js} +4 -4
- package/dist/assets/terminalApi-madXrfqA.js +1 -0
- package/dist/assets/{textarea-CaTDyZrS.js → textarea-Qt06OhhX.js} +1 -1
- package/dist/assets/{tooltip-BvZzoiqg.js → tooltip-D382RCy1.js} +1 -1
- package/dist/assets/tour-CQMBn8gJ.js +1 -0
- package/dist/assets/{types-Bm8kDgSv.js → types-CHszLAS3.js} +1 -1
- package/dist/assets/{uk-C4OKsNRv.js → uk-OXQSdzuT.js} +3 -3
- package/dist/assets/{useAppFontEffects-C9IaiJgF.js → useAppFontEffects-CqXrCJVt.js} +63 -58
- package/dist/assets/useAppFontEffects-K31q-1OV.css +1 -0
- package/dist/assets/useAssistantUIStore-jOKVcBK8.js +1 -0
- package/dist/assets/useDesktopWindowControlsLayout-KH4UP7Gj.js +1 -0
- package/dist/assets/{useDictation-Sk20Gi0T.js → useDictation-Bs7TWO9r.js} +1 -1
- package/dist/assets/useEffectiveDirectory-CCKRdyK9.js +1 -0
- package/dist/assets/useFontPreferences-CPrl1_3z.js +1 -0
- package/dist/assets/{useMobileHtmlPreviewStore-C03uVLfX.js → useMobileHtmlPreviewStore-EOAzZiAy.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BNtVrnSw.js +13 -0
- package/dist/assets/usePluginsStore-bMuGciUE.js +1 -0
- package/dist/assets/useProjectRuntimeAPIs-BFCXBu2J.js +1 -0
- package/dist/assets/{useStreamingTextThrottle-CeKHHK13.js → useStreamingTextThrottle-C8xAqcgP.js} +1 -1
- package/dist/assets/{useThemeSystem-CNzUUkFn.js → useThemeSystem-C57Z9mV2.js} +1 -1
- package/dist/assets/useUIStore-Cfmg-aDQ.js +1 -0
- package/dist/assets/uuid-D-SDZijH.js +1 -0
- package/dist/assets/{vendor-base-ui-CzHs0bHY.js → vendor-base-ui-z2M4boRm.js} +1 -1
- package/dist/assets/{vendor-cmdk-C_tivUtr.js → vendor-cmdk-BgHvMv5l.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-accessibility-BOtnpZt5.js → vendor-dnd-kit-accessibility-gVi9ga0x.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-core-DK4OoOTr.js → vendor-dnd-kit-core-Dd5yS2-T.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-Cv69eQm1.js → vendor-dnd-kit-sortable-CV-SGi8y.js} +1 -1
- package/dist/assets/{vendor-framer-motion-DDMKlXiP.js → vendor-framer-motion-CF9BQLta.js} +1 -1
- package/dist/assets/{vendor-markstream-react-6zxyQLCD.js → vendor-markstream-react-TwEpkgfP.js} +3 -3
- package/dist/assets/vendor-motion-Dv27UnOI.js +1 -0
- package/dist/assets/{vendor-pierre-diffs-BFiZ3IhI.js → vendor-pierre-diffs-tqo4Z3TC.js} +1 -1
- package/dist/assets/{vendor-react-DlzBev0S.js → vendor-react-P8wFrkcT.js} +1 -1
- package/dist/assets/{vendor-react-drawio-Dyg1-39Q.js → vendor-react-drawio-CQW1YP2l.js} +1 -1
- package/dist/assets/vendor-reactuses-core-Dyjw5sZR.js +1 -0
- package/dist/assets/{vendor-sonner-BEHGipm5.js → vendor-sonner-B5HgJenP.js} +1 -1
- package/dist/assets/{vendor-stream-diffs-wcQxoPZk.js → vendor-stream-diffs-DCMtZcS3.js} +2 -2
- package/dist/assets/vendor-tanstack-query-core-BSjXNgF_.js +1 -0
- package/dist/assets/vendor-tanstack-react-query-B-KblYBV.js +1 -0
- package/dist/assets/{vendor-tanstack-react-virtual-DSFNK3qc.js → vendor-tanstack-react-virtual-BkuqzrEV.js} +1 -1
- package/dist/assets/{vendor-zustand-vDaAPGfl.js → vendor-zustand-Cwko4FG1.js} +1 -1
- package/dist/assets/{zh-CN-ieAs59w6.js → zh-CN-B5X8yCZV.js} +3 -3
- package/dist/assets/{zh-TW-WWTW1fkP.js → zh-TW-CF6zr1fk.js} +3 -3
- package/dist/index.html +32 -27
- package/dist/mini-chat.html +32 -27
- package/dist/mobile.html +2 -2
- package/package.json +3 -2
- package/server/index.d.ts +19 -0
- package/server/index.js +35 -5
- package/server/lib/client-auth/remote-clients.js +11 -0
- package/server/lib/content-search/DOCUMENTATION.md +5 -0
- package/server/lib/content-search/routes.js +4 -0
- package/server/lib/content-search/routes.test.js +10 -0
- package/server/lib/event-stream/DOCUMENTATION.md +5 -0
- package/server/lib/event-stream/runtime.js +3 -0
- package/server/lib/event-stream/upstream-reader.js +1 -1
- package/server/lib/gui-customization/skill/references/remote-connections.md +11 -0
- package/server/lib/message-queue/DOCUMENTATION.md +4 -0
- package/server/lib/message-queue/service.js +2 -1
- package/server/lib/message-queue/service.test.js +11 -0
- package/server/lib/notifications/emitter-runtime.js +5 -0
- package/server/lib/opencode/DOCUMENTATION.md +28 -0
- package/server/lib/opencode/core-routes.js +14 -2
- package/server/lib/opencode/core-routes.test.js +28 -0
- package/server/lib/opencode/feature-routes-runtime.js +6 -1
- package/server/lib/opencode/proxy.js +1 -0
- package/server/lib/opencode/routes.js +18 -4
- package/server/lib/opencode/routes.test.js +22 -0
- package/server/lib/opencode/settings-helpers.js +26 -0
- package/server/lib/opencode/settings-helpers.test.js +20 -0
- package/server/lib/opencode/settings-runtime.js +5 -3
- package/server/lib/opencode/settings-runtime.test.js +35 -0
- package/server/lib/preview/DOCUMENTATION.md +73 -0
- package/server/lib/preview/file-preview-path.js +37 -0
- package/server/lib/preview/file-target.js +38 -0
- package/server/lib/preview/file-target.test.js +111 -0
- package/server/lib/preview/proxy-runtime.js +110 -17
- package/server/lib/projects/DOCUMENTATION.md +6 -0
- package/server/lib/relay/tunnel-host.js +1 -0
- package/server/lib/remote-hosts/DOCUMENTATION.md +269 -0
- package/server/lib/remote-hosts/configuration.js +15 -0
- package/server/lib/remote-hosts/deadline.js +22 -0
- package/server/lib/remote-hosts/deadline.test.js +64 -0
- package/server/lib/remote-hosts/fixtures/settings-server.mjs +26 -0
- package/server/lib/remote-hosts/gateway.js +644 -0
- package/server/lib/remote-hosts/json-lifecycle.test.js +55 -0
- package/server/lib/remote-hosts/preview-scope.js +23 -0
- package/server/lib/remote-hosts/relay-client.ts +3 -0
- package/server/lib/remote-hosts/routes.js +432 -0
- package/server/lib/remote-hosts/routes.test.js +1176 -0
- package/server/lib/remote-hosts/settings-production.test.js +145 -0
- package/server/lib/remote-hosts/store.js +110 -0
- package/server/lib/remote-hosts/store.test.js +33 -0
- package/server/lib/remote-hosts/transport.js +113 -0
- package/server/lib/session-folders/routes.js +1 -0
- package/server/lib/transcript-cache/DOCUMENTATION.md +4 -0
- package/server/lib/transcript-cache/routes.js +3 -0
- package/server/lib/transcript-cache/service.js +15 -0
- package/server/lib/transcript-cache/service.test.js +13 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +18 -0
- package/server/lib/ui-auth/ui-auth.js +30 -2
- package/server/lib/ui-auth/ui-auth.test.js +46 -1
- package/dist/assets/AssistantConversationSurface-B-D-mLgs.js +0 -3
- package/dist/assets/DiagramView-BU6jWxKJ.js +0 -1
- package/dist/assets/GuiPluginSurface-kxAcgmf1.js +0 -1
- package/dist/assets/LoadingImage-BzBw_1lI.js +0 -1
- package/dist/assets/MarkdownRenderer-CoMohPOZ.js +0 -2
- package/dist/assets/MarkdownRendererImpl-DoZW1UKH.js +0 -10
- package/dist/assets/MarkstreamRendererImpl-B3zd5x2O.js +0 -3
- package/dist/assets/MobileDetailNavigation-bEZ_NA03.js +0 -1
- package/dist/assets/MobileShareBridge-Cjukxazk.js +0 -3
- package/dist/assets/MobileTabPageHeader-Da1maXx-.js +0 -2
- package/dist/assets/OnboardingScreen-CZhqHzAj.js +0 -1
- package/dist/assets/SettingsView-7Bea2DvF.js +0 -29
- package/dist/assets/SetupTourDialog-CKec5tUy.js +0 -1
- package/dist/assets/TerminalView-CS1oSAuY.js +0 -8
- package/dist/assets/ToolOutputDialog-BWhrFvvI.js +0 -10
- package/dist/assets/VoiceSettings-7aFmJq9Z.js +0 -2
- package/dist/assets/YuriWordmark--S-QEpRp.js +0 -1
- package/dist/assets/appThemeRegistry-LyWTE-mT.js +0 -1
- package/dist/assets/bootstrap-BhC95qVC.js +0 -1
- package/dist/assets/fileQueries-D9l0crnM.js +0 -1
- package/dist/assets/fileReferenceActions-BmquJskG.js +0 -1
- package/dist/assets/gitApiHttp-D4d-rgcR.js +0 -9
- package/dist/assets/historyImportQueries-DkB2_92i.js +0 -1
- package/dist/assets/host-kMLXU0hK.js +0 -1
- package/dist/assets/image-loading-BrDob6MW.js +0 -1
- package/dist/assets/insertionBoundaries-B-yZI6iY.js +0 -1
- package/dist/assets/main-BfAN93rT.js +0 -169
- package/dist/assets/main-DYWwmI_W.js +0 -2
- package/dist/assets/mcpQueries-CehWHIB1.js +0 -1
- package/dist/assets/miniChat-BlkcLQBr.js +0 -2
- package/dist/assets/mobile-I3Xe5NtO.js +0 -2
- package/dist/assets/mobileBackNavigation-BFUH-c-G.js +0 -1
- package/dist/assets/mobileConnections-BFvtbJXX.js +0 -2
- package/dist/assets/multirun-DdEjp77z.js +0 -3
- package/dist/assets/pathNormalization-ewtPqJWn.js +0 -1
- package/dist/assets/platform-DMsFWy1a.js +0 -1
- package/dist/assets/projectActions-C-9Z8R7y.js +0 -1
- package/dist/assets/projectMeta-BKgum5WN.js +0 -1
- package/dist/assets/pwa-BvKUY4Hk.js +0 -2
- package/dist/assets/queue-abort-optimistic-BcbiNk8t.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-DIjWdFHu.js +0 -2
- package/dist/assets/renderMobileApp-CE0QyOH0.js +0 -29
- package/dist/assets/runtime-file-resource-CL7EVzOG.js +0 -2
- package/dist/assets/runtimeConfig-uhjQn4kK.js +0 -2
- package/dist/assets/runtimeEndpointReset-DezNESKT.js +0 -149
- package/dist/assets/scheduledTaskNavigation-FMDNRUnX.js +0 -1
- package/dist/assets/sessionLookup-DzKZsy-W.js +0 -1
- package/dist/assets/sortable-tabs-strip-m5JQrTx4.js +0 -1
- package/dist/assets/src-HgtAe3Q4.css +0 -2
- package/dist/assets/terminalApi-DK4KmfFn.js +0 -1
- package/dist/assets/touch-gestures-CErgaXZ7.js +0 -1
- package/dist/assets/tour-DDI0Zg7l.js +0 -1
- package/dist/assets/useAppFontEffects-RpgNbjA4.css +0 -1
- package/dist/assets/useAssistantUIStore-nNYL140o.js +0 -1
- package/dist/assets/useDesktopWindowControlsLayout-C3M12PjJ.js +0 -1
- package/dist/assets/useEffectiveDirectory-Do4UqfZR.js +0 -1
- package/dist/assets/useFontPreferences-DxzruDDQ.js +0 -1
- package/dist/assets/useMobileNavigationStore-InwdmuDX.js +0 -17
- package/dist/assets/usePluginsStore-BH4-CNcj.js +0 -1
- package/dist/assets/useUIStore-vvNwcOk3.js +0 -1
- package/dist/assets/useWorkerHighlightedLines-0XahwAbS.js +0 -7
- package/dist/assets/vendor-motion-C9oiAdx-.js +0 -1
- package/dist/assets/vendor-reactuses-core-CuTmqEMK.js +0 -1
- package/dist/assets/vendor-tanstack-query-core-Y_YoRHtC.js +0 -1
- package/dist/assets/vendor-tanstack-react-query-B-Wpqq5J.js +0 -1
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { createSessionIndexService } from '../session-index/service.js';
|
|
3
|
+
import { applySessionIndexEvent } from '../session-index/event-ingest.js';
|
|
4
|
+
import { createUpstreamSseReader } from '../event-stream/upstream-reader.js';
|
|
5
|
+
import { createRemoteTransport } from './transport.js';
|
|
6
|
+
import { remoteDeadlineSignal } from './deadline.js';
|
|
7
|
+
|
|
8
|
+
export const remoteFailure = (code, status = 503) => Object.assign(new Error(code), { code, status });
|
|
9
|
+
const publicError = (error) => {
|
|
10
|
+
const code = error?.status === 401 || error?.status === 403 ? 'remote_authorization_required'
|
|
11
|
+
: ['remote_incompatible', 'remote_ssh_authentication_failed', 'remote_ssh_unavailable', 'remote_relay_unavailable', 'remote_service_starting'].includes(error?.code) ? error.code
|
|
12
|
+
: error?.code === 'host_unavailable' ? 'host_unavailable' : 'remote_unavailable';
|
|
13
|
+
return { code, message: code };
|
|
14
|
+
};
|
|
15
|
+
const fingerprint = (host) => crypto.createHash('sha256').update(JSON.stringify(host)).digest('hex');
|
|
16
|
+
const directoryKey = (value) => value.replace(/\\/g, '/').replace(/\/+$/, '') || '/';
|
|
17
|
+
const statusEvent = (payload) => /^(session\.(created|updated|deleted|renamed|moved|status|idle|error|execution\.(started|succeeded|failed|interrupted)|retry|model\.selected|inbox\.(enqueued|delivered))|yuri:session-(index-changed|status|activity|metadata|folders-changed|order-changed|unread-changed)|yuri:project.*|yuri:worktree-topology-changed|yuri:notification)$/.test((payload?.type || '').replace(/\.\d+$/, ''));
|
|
18
|
+
export const projectRemoteStatusEvent = (payload) => {
|
|
19
|
+
if (!statusEvent(payload)) return null;
|
|
20
|
+
const type = payload.type.replace(/\.\d+$/, '');
|
|
21
|
+
if (type.startsWith('session.inbox.')) return { type: 'yuri:session-index-changed', properties: { cause: 'change' } };
|
|
22
|
+
if (!type.startsWith('session.')) return payload;
|
|
23
|
+
const select = (value) => {
|
|
24
|
+
if (!value || typeof value !== 'object') return value;
|
|
25
|
+
const result = Object.fromEntries(['id', 'sessionID', 'title', 'directory', 'parentID', 'hasChildren', 'location', 'time', 'model', 'status']
|
|
26
|
+
.filter((key) => Object.hasOwn(value, key)).map((key) => [key, value[key]]));
|
|
27
|
+
if (value.info) result.info = select(value.info);
|
|
28
|
+
if (value.metadata?.yuri) {
|
|
29
|
+
const yuri = value.metadata.yuri;
|
|
30
|
+
result.metadata = { yuri: Object.fromEntries(['assistant', 'assigned', 'scheduledTask', 'smallModel', 'llm', 'archive', 'titleRefresh', 'sessionStatus']
|
|
31
|
+
.filter((key) => yuri[key] && typeof yuri[key] === 'object').map((key) => [key,
|
|
32
|
+
Object.fromEntries(['assistantID', 'name', 'from', 'taskID', 'purpose', 'archivedAt', 'activityUpdatedAt', 'type', 'changedAt']
|
|
33
|
+
.filter((field) => ['string', 'number'].includes(typeof yuri[key][field])).map((field) => [field, yuri[key][field]]))])) };
|
|
34
|
+
}
|
|
35
|
+
if (value.reason === 'shutdown') result.reason = 'shutdown';
|
|
36
|
+
return result;
|
|
37
|
+
};
|
|
38
|
+
return { type: payload.type, ...(payload.created ? { created: payload.created } : {}),
|
|
39
|
+
...(payload.durable ? { durable: { seq: payload.durable.seq } } : {}),
|
|
40
|
+
...(payload.data ? { data: select(payload.data) } : {}),
|
|
41
|
+
...(payload.properties ? { properties: select(payload.properties) } : {}) };
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export function createRemoteHostGateway({ store, indexDbPath, adapter, broadcast = () => {},
|
|
45
|
+
transportFactory = createRemoteTransport, onNotification = null, maxContentSubscriptions = 8,
|
|
46
|
+
requestTimeoutMs = 15000, operationTimeoutMs = 300000 }) {
|
|
47
|
+
const connections = new Map();
|
|
48
|
+
const scopes = new Map();
|
|
49
|
+
const indexes = new Map();
|
|
50
|
+
const leases = new Map();
|
|
51
|
+
const observers = new Map();
|
|
52
|
+
const statusObservers = new Set();
|
|
53
|
+
const interactiveHosts = new Map();
|
|
54
|
+
const priorityRequests = new Map();
|
|
55
|
+
const contentChannels = new Map();
|
|
56
|
+
const ownerGenerations = new Map();
|
|
57
|
+
let stopped = false;
|
|
58
|
+
let reconcilePromise = null;
|
|
59
|
+
let reconcilePending = false;
|
|
60
|
+
let refreshActive = 0;
|
|
61
|
+
const refreshQueue = new Set();
|
|
62
|
+
const indexFor = (hostId) => {
|
|
63
|
+
let service = indexes.get(hostId);
|
|
64
|
+
if (!service) {
|
|
65
|
+
service = createSessionIndexService({ dbPath: indexDbPath,
|
|
66
|
+
getRuntimeConfig: () => ({ apiBaseUrl: `hub:${store.hubId}:remote-host:${hostId}` }) });
|
|
67
|
+
indexes.set(hostId, service);
|
|
68
|
+
}
|
|
69
|
+
return service;
|
|
70
|
+
};
|
|
71
|
+
const descriptors = async () => {
|
|
72
|
+
const hosts = adapter ? await adapter.listHosts() : [];
|
|
73
|
+
if (stopped) return hosts;
|
|
74
|
+
const present = new Set();
|
|
75
|
+
for (const host of hosts) {
|
|
76
|
+
present.add(host.id);
|
|
77
|
+
const identity = fingerprint(host);
|
|
78
|
+
if (scopes.get(host.id)?.fingerprint !== identity) {
|
|
79
|
+
scopes.set(host.id, { fingerprint: identity, generation: crypto.randomUUID() });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
for (const id of scopes.keys()) if (!present.has(id)) scopes.delete(id);
|
|
83
|
+
return hosts;
|
|
84
|
+
};
|
|
85
|
+
const stateFor = (id) => connections.get(id)?.state || 'idle';
|
|
86
|
+
const directoryResolver = (id) => {
|
|
87
|
+
const projects = store.projects(id);
|
|
88
|
+
const worktrees = store.organization(id).worktrees?.projectDirectories || {};
|
|
89
|
+
const roots = projects.map((project) => ({ project, directory: project.path, root: directoryKey(project.path) }));
|
|
90
|
+
const linked = projects.flatMap((project) => (worktrees[project.path] || [])
|
|
91
|
+
.map((root) => ({ project, directory: root, root: directoryKey(root) })));
|
|
92
|
+
return (directory) => {
|
|
93
|
+
const key = directoryKey(directory);
|
|
94
|
+
const match = (candidates) => {
|
|
95
|
+
let best;
|
|
96
|
+
for (const candidate of candidates) if ((key === candidate.root || key.startsWith(candidate.root === '/' ? '/' : `${candidate.root}/`))
|
|
97
|
+
&& (!best || candidate.root.length > best.root.length)) best = candidate;
|
|
98
|
+
return best;
|
|
99
|
+
};
|
|
100
|
+
return match(roots) || match(linked);
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
const assertProjectDirectory = (id, directory) => {
|
|
104
|
+
if (typeof directory !== 'string' || directory.includes('\0')
|
|
105
|
+
|| directory.split(/[\\/]/).some((segment) => segment === '.' || segment === '..')) throw remoteFailure('project_not_found', 404);
|
|
106
|
+
const owner = directoryResolver(id)(directory);
|
|
107
|
+
if (!owner) throw remoteFailure('project_not_found', 404);
|
|
108
|
+
return owner.directory;
|
|
109
|
+
};
|
|
110
|
+
const hostView = (host) => ({ id: host.id, name: host.name || host.label || host.id,
|
|
111
|
+
source: host.source, available: true, state: stateFor(host.id), ...store.receipt(host.id),
|
|
112
|
+
scopeGeneration: scopes.get(host.id)?.generation,
|
|
113
|
+
generation: connections.get(host.id)?.generation,
|
|
114
|
+
...(connections.get(host.id)?.version ? { version: connections.get(host.id).version,
|
|
115
|
+
capabilities: { remoteProjects: true } } : {}) });
|
|
116
|
+
const setState = (connection, state, error) => {
|
|
117
|
+
if (connections.get(connection.host.id) !== connection || stopped) return;
|
|
118
|
+
const changed = connection.state !== state;
|
|
119
|
+
connection.state = state;
|
|
120
|
+
if (error) store.saveReceipt(connection.host.id, { lastError: publicError(error) });
|
|
121
|
+
if (changed || error) broadcast({ type: 'yuri:host-status', properties: {
|
|
122
|
+
hubId: store.hubId, hostId: connection.host.id, host: hostView(connection.host) } });
|
|
123
|
+
};
|
|
124
|
+
const emit = (hostId, payload, directory) => broadcast({ type: 'yuri:host-event', properties: {
|
|
125
|
+
hubId: store.hubId, hostId, generation: connections.get(hostId)?.generation,
|
|
126
|
+
...(directory ? { directory } : {}), payload } });
|
|
127
|
+
const closeConnection = (connection) => {
|
|
128
|
+
connection.controller.abort();
|
|
129
|
+
connection.reader?.stop();
|
|
130
|
+
connection.transport?.close();
|
|
131
|
+
for (const [id, lease] of leases) if (lease.hostId === connection.host.id) {
|
|
132
|
+
releaseLease(id);
|
|
133
|
+
}
|
|
134
|
+
if (connections.get(connection.host.id) === connection) connections.delete(connection.host.id);
|
|
135
|
+
};
|
|
136
|
+
const current = (connection) => !stopped && !connection.controller.signal.aborted
|
|
137
|
+
&& connections.get(connection.host.id) === connection;
|
|
138
|
+
const resolveHost = async (id) => {
|
|
139
|
+
const host = (await descriptors()).find((entry) => entry.id === id);
|
|
140
|
+
if (!host) {
|
|
141
|
+
const old = connections.get(id);
|
|
142
|
+
if (old) closeConnection(old);
|
|
143
|
+
for (const project of store.projects(id)) store.markProject(project.id, 'host-unavailable');
|
|
144
|
+
throw remoteFailure('host_unavailable', 404);
|
|
145
|
+
}
|
|
146
|
+
const old = connections.get(id);
|
|
147
|
+
if (old && !old.preparing && (old.fingerprint !== fingerprint(host)
|
|
148
|
+
|| old.scopeGeneration !== scopes.get(id)?.generation)) closeConnection(old);
|
|
149
|
+
return host;
|
|
150
|
+
};
|
|
151
|
+
const ensure = async (id) => {
|
|
152
|
+
if (stopped || !observers.size) throw remoteFailure('gateway_no_clients');
|
|
153
|
+
const host = await resolveHost(id);
|
|
154
|
+
if (stopped || !observers.size) throw remoteFailure('gateway_no_clients');
|
|
155
|
+
let connection = connections.get(id);
|
|
156
|
+
if (!connection) {
|
|
157
|
+
store.saveHost(host);
|
|
158
|
+
connection = { host, fingerprint: fingerprint(host), scopeGeneration: scopes.get(id)?.generation,
|
|
159
|
+
generation: crypto.randomUUID(), state: 'idle', controller: new AbortController(), failures: 0, topologyDirty: true };
|
|
160
|
+
connections.set(id, connection);
|
|
161
|
+
}
|
|
162
|
+
if (!connection.ready) {
|
|
163
|
+
setState(connection, 'connecting');
|
|
164
|
+
connection.ready = (async () => {
|
|
165
|
+
if (connection.host.source === 'ssh' && adapter.prepareHost) {
|
|
166
|
+
connection.preparing = true;
|
|
167
|
+
const prepared = await adapter.prepareHost(id);
|
|
168
|
+
const latest = await resolveHost(id);
|
|
169
|
+
if (!current(connection) || fingerprint(prepared) !== fingerprint(latest)) throw remoteFailure('stale_host', 409);
|
|
170
|
+
connection.host = prepared;
|
|
171
|
+
connection.fingerprint = fingerprint(prepared);
|
|
172
|
+
connection.scopeGeneration = scopes.get(id)?.generation;
|
|
173
|
+
store.saveHost(prepared);
|
|
174
|
+
connection.preparing = false;
|
|
175
|
+
}
|
|
176
|
+
const transport = await transportFactory(connection.host, { signal: connection.controller.signal });
|
|
177
|
+
if (!current(connection)) { transport.close(); throw remoteFailure('stale_host', 409); }
|
|
178
|
+
connection.transport = transport;
|
|
179
|
+
let capability = transport.capabilities;
|
|
180
|
+
if (!capability) {
|
|
181
|
+
const response = await transport.fetch('/api/hosts/capabilities', {
|
|
182
|
+
signal: remoteDeadlineSignal(requestTimeoutMs, [connection.controller.signal]),
|
|
183
|
+
});
|
|
184
|
+
if (response.status === 401 || response.status === 403) throw remoteFailure('remote_authorization_required', response.status);
|
|
185
|
+
capability = response.ok ? await response.json().catch(() => null) : null;
|
|
186
|
+
}
|
|
187
|
+
if (!capability?.remoteProjects || capability.protocol !== 1 || !capability?.instanceId
|
|
188
|
+
|| capability.opencode?.compatible === false) throw remoteFailure('remote_incompatible', 409);
|
|
189
|
+
if (capability.opencode?.ready === false && !capability.opencode?.version) throw remoteFailure('remote_service_starting');
|
|
190
|
+
connection.version = capability.version;
|
|
191
|
+
connection.instanceId = capability.instanceId;
|
|
192
|
+
await resolveHost(id);
|
|
193
|
+
if (!current(connection)) throw remoteFailure('stale_host', 409);
|
|
194
|
+
return connection;
|
|
195
|
+
})().catch((error) => {
|
|
196
|
+
connection.preparing = false;
|
|
197
|
+
connection.ready = null;
|
|
198
|
+
connection.transport?.close();
|
|
199
|
+
connection.transport = null;
|
|
200
|
+
setState(connection, error?.status === 401 || error?.status === 403 ? 'unauthorized'
|
|
201
|
+
: error?.code === 'remote_incompatible' ? 'incompatible' : 'offline', error);
|
|
202
|
+
throw error;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
return connection.ready;
|
|
206
|
+
};
|
|
207
|
+
const request = async (id, route, init = {}, { refresh = false, streaming = false, longRunning = false } = {}) => {
|
|
208
|
+
init.signal?.throwIfAborted();
|
|
209
|
+
if (!refresh && (/^\/api\/session(?:\/|\?)/.test(route) || (init.method && !['GET', 'HEAD'].includes(init.method)))) {
|
|
210
|
+
for (const connection of connections.values()) {
|
|
211
|
+
if (connection.refreshController) { connection.refreshPreempted = true; connection.refreshController.abort(); }
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const connection = await ensure(id);
|
|
215
|
+
const generation = connection.fingerprint;
|
|
216
|
+
const deadlineMs = longRunning ? operationTimeoutMs : requestTimeoutMs;
|
|
217
|
+
const headerDeadline = new AbortController();
|
|
218
|
+
const headerTimer = setTimeout(() => headerDeadline.abort(), deadlineMs);
|
|
219
|
+
let response;
|
|
220
|
+
try {
|
|
221
|
+
response = await connection.transport.fetch(route, { ...init,
|
|
222
|
+
signal: streaming ? AbortSignal.any([connection.controller.signal, headerDeadline.signal,
|
|
223
|
+
...(init.signal ? [init.signal] : [])]) : remoteDeadlineSignal(deadlineMs,
|
|
224
|
+
[connection.controller.signal, headerDeadline.signal, ...(init.signal ? [init.signal] : [])]) });
|
|
225
|
+
} finally {
|
|
226
|
+
clearTimeout(headerTimer);
|
|
227
|
+
}
|
|
228
|
+
const latest = await resolveHost(id);
|
|
229
|
+
if (!current(connection) || fingerprint(latest) !== generation) {
|
|
230
|
+
await response.body?.cancel(); throw remoteFailure('stale_host', 409);
|
|
231
|
+
}
|
|
232
|
+
if (response.status === 401 || response.status === 403) {
|
|
233
|
+
setState(connection, 'unauthorized', remoteFailure('remote_authorization_required', response.status));
|
|
234
|
+
connection.reader?.stop();
|
|
235
|
+
connection.reader = null;
|
|
236
|
+
connection.transport?.close();
|
|
237
|
+
connection.ready = null;
|
|
238
|
+
for (const [leaseId, lease] of leases) if (lease.hostId === id) {
|
|
239
|
+
releaseLease(leaseId);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return response;
|
|
243
|
+
};
|
|
244
|
+
const json = async (id, route, init, options) => {
|
|
245
|
+
init?.signal?.throwIfAborted();
|
|
246
|
+
const connection = await ensure(id);
|
|
247
|
+
const consumption = new AbortController();
|
|
248
|
+
try {
|
|
249
|
+
const response = await request(id, route, { ...init,
|
|
250
|
+
signal: init?.signal ? AbortSignal.any([init.signal, consumption.signal]) : consumption.signal }, options);
|
|
251
|
+
if (!response.ok) { await response.body?.cancel(); throw remoteFailure('remote_request_failed', response.status); }
|
|
252
|
+
const value = await response.json();
|
|
253
|
+
await resolveHost(id);
|
|
254
|
+
if (!current(connection)) throw remoteFailure('stale_host', 409);
|
|
255
|
+
return value;
|
|
256
|
+
} finally {
|
|
257
|
+
consumption.abort();
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
const refreshWorktrees = async (connection, references, signal) => {
|
|
261
|
+
const previous = store.organization(connection.host.id).worktrees || {};
|
|
262
|
+
const projectDirectories = { ...previous.projectDirectories };
|
|
263
|
+
const stale = new Set(previous.staleProjectDirectories || []);
|
|
264
|
+
const refreshAll = connection.topologyDirty;
|
|
265
|
+
let changed = refreshAll;
|
|
266
|
+
connection.topologyDirty = false;
|
|
267
|
+
for (const project of references) {
|
|
268
|
+
if (!refreshAll && Object.hasOwn(projectDirectories, project.path) && !stale.has(project.path)) continue;
|
|
269
|
+
changed = true;
|
|
270
|
+
try {
|
|
271
|
+
const rows = await json(connection.host.id, `/api/git/worktrees?directory=${encodeURIComponent(project.path)}`, { signal }, { refresh: true });
|
|
272
|
+
if (!Array.isArray(rows) || rows.some((row) => typeof row?.path !== 'string')) throw remoteFailure('remote_invalid_snapshot');
|
|
273
|
+
const projectKey = directoryKey(project.path);
|
|
274
|
+
const checkout = rows.map((row) => directoryKey(row.path))
|
|
275
|
+
.filter((root) => projectKey === root || projectKey.startsWith(root === '/' ? '/' : `${root}/`))
|
|
276
|
+
.sort((a, b) => b.length - a.length)[0];
|
|
277
|
+
const suffix = checkout && projectKey !== checkout
|
|
278
|
+
? projectKey.slice(checkout === '/' ? 1 : checkout.length + 1) : '';
|
|
279
|
+
projectDirectories[project.path] = checkout ? rows.map((row) => suffix
|
|
280
|
+
? `${row.path.replace(/[\\/]+$/, '')}${row.path.includes('\\') ? '\\' : '/'}${suffix.replace(/\//g, row.path.includes('\\') ? '\\' : '/')}`
|
|
281
|
+
: row.path) : [];
|
|
282
|
+
stale.delete(project.path);
|
|
283
|
+
} catch {
|
|
284
|
+
if (signal.aborted || !current(connection)) { connection.topologyDirty = true; return; }
|
|
285
|
+
stale.add(project.path);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (signal.aborted || !current(connection)) return;
|
|
289
|
+
const roots = new Set(references.map((project) => project.path));
|
|
290
|
+
store.saveOrganization(connection.host.id, 'worktrees', {
|
|
291
|
+
projectDirectories: Object.fromEntries(Object.entries(projectDirectories).filter(([root]) => roots.has(root))),
|
|
292
|
+
staleProjectDirectories: [...stale].filter((root) => roots.has(root)),
|
|
293
|
+
});
|
|
294
|
+
return changed;
|
|
295
|
+
};
|
|
296
|
+
const refresh = async (connection) => {
|
|
297
|
+
if (!current(connection)) return;
|
|
298
|
+
const controller = new AbortController();
|
|
299
|
+
connection.refreshController = controller;
|
|
300
|
+
try {
|
|
301
|
+
let snapshot = await json(connection.host.id, '/api/yuri/session-index', { signal: controller.signal }, { refresh: true });
|
|
302
|
+
if (!current(connection) || controller.signal.aborted) return;
|
|
303
|
+
if (!Array.isArray(snapshot.directories)) throw remoteFailure('remote_invalid_snapshot');
|
|
304
|
+
const references = store.projects(connection.host.id);
|
|
305
|
+
const topologyChanged = await refreshWorktrees(connection, references, controller.signal);
|
|
306
|
+
if (!current(connection) || controller.signal.aborted) return;
|
|
307
|
+
if (topologyChanged) {
|
|
308
|
+
const worktrees = store.organization(connection.host.id).worktrees?.projectDirectories || {};
|
|
309
|
+
const directories = [...new Set(references.flatMap((project) => [project.path, ...(worktrees[project.path] || [])]))];
|
|
310
|
+
let queued;
|
|
311
|
+
try {
|
|
312
|
+
queued = await json(connection.host.id, '/api/yuri/session-index/sync', {
|
|
313
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
314
|
+
body: JSON.stringify({ directories }), signal: controller.signal,
|
|
315
|
+
}, { refresh: true });
|
|
316
|
+
} catch (error) { connection.topologyDirty = true; throw error; }
|
|
317
|
+
if (Array.isArray(queued.directories)) snapshot = queued;
|
|
318
|
+
if (!current(connection) || controller.signal.aborted) return;
|
|
319
|
+
}
|
|
320
|
+
const service = indexFor(connection.host.id);
|
|
321
|
+
const ownerFor = directoryResolver(connection.host.id);
|
|
322
|
+
for (const directory of snapshot.directories) if (ownerFor(directory.directory)) {
|
|
323
|
+
service.replaceDirectory(directory);
|
|
324
|
+
for (const session of directory.sessions || []) {
|
|
325
|
+
const status = session.metadata?.yuri?.sessionStatus;
|
|
326
|
+
if (status?.type) service.updateStatus(session.id, status.type, status.changedAt || Date.now());
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const previousPins = service.snapshot().pinnedSessionIds;
|
|
330
|
+
const pins = new Set(snapshot.pinnedSessionIds || []);
|
|
331
|
+
for (const pin of previousPins) if (!pins.has(pin)) service.clearPinned(pin);
|
|
332
|
+
for (const pin of pins) service.setPinned(pin);
|
|
333
|
+
const remote = await json(connection.host.id, '/api/projects', { signal: controller.signal }, { refresh: true });
|
|
334
|
+
if (!Array.isArray(remote.projects) || !current(connection) || controller.signal.aborted) return;
|
|
335
|
+
for (const reference of references) {
|
|
336
|
+
const project = remote.projects.find((p) => p.path === reference.path && !p.hostId);
|
|
337
|
+
if (project) store.refreshProject(reference, project);
|
|
338
|
+
else store.markProject(reference.id, 'remote-removed');
|
|
339
|
+
}
|
|
340
|
+
for (const [kind, route] of [['unread', '/api/yuri/session-unread'], ['folders', '/api/session-folders'], ['order', '/api/session-folders/order']]) {
|
|
341
|
+
const organization = await json(connection.host.id, route, { signal: controller.signal }, { refresh: true });
|
|
342
|
+
if (!current(connection) || controller.signal.aborted) return;
|
|
343
|
+
store.saveOrganization(connection.host.id, kind, organization);
|
|
344
|
+
}
|
|
345
|
+
store.saveReceipt(connection.host.id, { lastSyncedAt: Date.now(), lastError: undefined });
|
|
346
|
+
connection.snapshotReady = !snapshot.sync?.active || snapshot.directories.length > 0;
|
|
347
|
+
emit(connection.host.id, { type: 'yuri:session-index-changed', properties: { cause: 'change' } });
|
|
348
|
+
} catch (error) {
|
|
349
|
+
if (!controller.signal.aborted) setState(connection, 'degraded', error);
|
|
350
|
+
} finally {
|
|
351
|
+
if (connection.refreshController === controller) connection.refreshController = null;
|
|
352
|
+
if (connection.refreshPreempted && current(connection) && statusObservers.size) {
|
|
353
|
+
connection.refreshPreempted = false; refreshQueue.add(connection.host.id);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
const pump = () => {
|
|
358
|
+
if (stopped) return;
|
|
359
|
+
const prioritizedHosts = new Set(priorityRequests.values());
|
|
360
|
+
for (const id of [...refreshQueue]) {
|
|
361
|
+
if (refreshActive >= 2) break;
|
|
362
|
+
const connection = connections.get(id);
|
|
363
|
+
if (!connection) { refreshQueue.delete(id); continue; }
|
|
364
|
+
if (connection.refreshing || prioritizedHosts.has(id)) continue;
|
|
365
|
+
refreshQueue.delete(id);
|
|
366
|
+
refreshActive++;
|
|
367
|
+
connection.refreshing = true;
|
|
368
|
+
void refresh(connection).finally(() => {
|
|
369
|
+
refreshActive--; connection.refreshing = false; pump();
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
const enqueueRefresh = (connection) => { refreshQueue.add(connection.host.id); pump(); };
|
|
374
|
+
const startStatus = (connection) => {
|
|
375
|
+
if (connection.reader || !statusObservers.size || !store.projects(connection.host.id).length) return;
|
|
376
|
+
const id = connection.host.id;
|
|
377
|
+
connection.reader = createUpstreamSseReader({
|
|
378
|
+
buildUrl: () => 'http://remote.invalid/api/hosts/status-stream',
|
|
379
|
+
fetchImpl: async (_url, init) => {
|
|
380
|
+
try {
|
|
381
|
+
const connected = await ensure(id);
|
|
382
|
+
return connected.transport.fetch('/api/hosts/status-stream', { ...init,
|
|
383
|
+
signal: AbortSignal.any([init.signal, connection.controller.signal]) });
|
|
384
|
+
} catch (error) {
|
|
385
|
+
connection.failures++; throw error;
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
signal: connection.controller.signal,
|
|
389
|
+
reconnectDelayMs: () => Math.min(30000, 500 * 2 ** Math.min(connection.failures, 6)) * (0.8 + Math.random() * 0.4),
|
|
390
|
+
stallTimeoutMs: 1500,
|
|
391
|
+
onConnect: () => {
|
|
392
|
+
if (!current(connection)) return;
|
|
393
|
+
connection.failures = 0;
|
|
394
|
+
connection.topologyDirty = true;
|
|
395
|
+
connection.snapshotReady = false;
|
|
396
|
+
store.saveReceipt(id, { lastConnectedAt: Date.now(), lastError: undefined });
|
|
397
|
+
setState(connection, 'connected'); enqueueRefresh(connection);
|
|
398
|
+
},
|
|
399
|
+
onEvent: (event) => {
|
|
400
|
+
if (!current(connection) || !statusEvent(event.payload)) return;
|
|
401
|
+
const data = event.payload.data || event.payload.properties || {};
|
|
402
|
+
const sessionId = data.sessionID || data.sessionId || data.info?.id || data.id;
|
|
403
|
+
const directory = event.directory && event.directory !== 'global' ? event.directory
|
|
404
|
+
: data.location?.directory || data.directory || data.info?.directory
|
|
405
|
+
|| (sessionId ? indexFor(id).findBySessionId(sessionId)?.directory : null);
|
|
406
|
+
if (sessionId && (!directory || !directoryResolver(id)(directory))) return;
|
|
407
|
+
if (applySessionIndexEvent(indexFor(id), event, Date.now())) {
|
|
408
|
+
store.saveReceipt(id, { lastSyncedAt: Date.now() });
|
|
409
|
+
}
|
|
410
|
+
let payload = event.payload;
|
|
411
|
+
if (payload.type === 'yuri:notification') {
|
|
412
|
+
const notification = { ...payload.properties, instanceId: payload.properties?.instanceId || connection.instanceId,
|
|
413
|
+
hostId: id, hubId: store.hubId, directory: directory || payload.properties?.directory };
|
|
414
|
+
onNotification?.(notification);
|
|
415
|
+
payload = { ...payload, properties: { ...notification, desktopNotificationDelivered: Boolean(onNotification) } };
|
|
416
|
+
}
|
|
417
|
+
emit(id, payload, directory || event.directory);
|
|
418
|
+
if (event.payload.type === 'yuri:worktree-topology-changed' || /^yuri:project/.test(event.payload.type)) connection.topologyDirty = true;
|
|
419
|
+
if (/^yuri:session-(index|unread|order|folders|metadata)/.test(event.payload.type)
|
|
420
|
+
|| /^yuri:project/.test(event.payload.type) || event.payload.type === 'yuri:worktree-topology-changed') enqueueRefresh(connection);
|
|
421
|
+
},
|
|
422
|
+
onDisconnect: ({ reason }) => {
|
|
423
|
+
if (reason !== 'stopped') {
|
|
424
|
+
connection.failures++;
|
|
425
|
+
connection.snapshotReady = false;
|
|
426
|
+
if (!['unauthorized', 'incompatible'].includes(connection.state)) setState(connection, 'offline');
|
|
427
|
+
}
|
|
428
|
+
},
|
|
429
|
+
onError: ({ status }) => {
|
|
430
|
+
connection.failures++;
|
|
431
|
+
setState(connection, status === 401 || status === 403 ? 'unauthorized' : 'offline');
|
|
432
|
+
if (status === 401 || status === 403) {
|
|
433
|
+
connection.transport?.close(); connection.ready = null;
|
|
434
|
+
for (const [leaseId, lease] of leases) if (lease.hostId === id) releaseLease(leaseId);
|
|
435
|
+
}
|
|
436
|
+
},
|
|
437
|
+
});
|
|
438
|
+
void connection.reader.start();
|
|
439
|
+
};
|
|
440
|
+
const reconcile = () => {
|
|
441
|
+
if (reconcilePromise) { reconcilePending = true; return reconcilePromise; }
|
|
442
|
+
reconcilePromise = (async () => {
|
|
443
|
+
const hosts = await descriptors();
|
|
444
|
+
if (stopped) return;
|
|
445
|
+
const needed = new Set(statusObservers.size ? store.projects().map((p) => p.hostId) : []);
|
|
446
|
+
for (const project of store.projects()) if (!hosts.some((host) => host.id === project.hostId)) store.markProject(project.id, 'host-unavailable');
|
|
447
|
+
for (const connection of connections.values()) {
|
|
448
|
+
const host = hosts.find((h) => h.id === connection.host.id);
|
|
449
|
+
if (!host) {
|
|
450
|
+
setState(connection, 'offline', remoteFailure('host_unavailable', 404));
|
|
451
|
+
emit(connection.host.id, { type: 'yuri:projects-changed', properties: {} });
|
|
452
|
+
}
|
|
453
|
+
if (!observers.size || (!needed.has(connection.host.id) && !interactiveHosts.has(connection.host.id))
|
|
454
|
+
|| !host || (!connection.preparing && (fingerprint(host) !== connection.fingerprint
|
|
455
|
+
|| scopes.get(connection.host.id)?.generation !== connection.scopeGeneration))) closeConnection(connection);
|
|
456
|
+
}
|
|
457
|
+
if (!observers.size || stopped) return;
|
|
458
|
+
await Promise.allSettled([...needed].map(async (id) => {
|
|
459
|
+
try { const connection = await ensure(id); startStatus(connection); }
|
|
460
|
+
catch {
|
|
461
|
+
// A failed first connection still needs the bounded SSE retry owner.
|
|
462
|
+
const connection = connections.get(id);
|
|
463
|
+
if (connection) startStatus(connection);
|
|
464
|
+
}
|
|
465
|
+
}));
|
|
466
|
+
})().catch((error) => {
|
|
467
|
+
for (const connection of connections.values()) setState(connection, 'degraded', error);
|
|
468
|
+
}).finally(() => {
|
|
469
|
+
reconcilePromise = null;
|
|
470
|
+
if (reconcilePending && !stopped) { reconcilePending = false; void reconcile(); }
|
|
471
|
+
});
|
|
472
|
+
return reconcilePromise;
|
|
473
|
+
};
|
|
474
|
+
const releaseLease = (id) => {
|
|
475
|
+
const lease = leases.get(id);
|
|
476
|
+
if (!lease) return;
|
|
477
|
+
leases.delete(id);
|
|
478
|
+
lease.channel.users.delete(id);
|
|
479
|
+
if (!lease.channel.users.size) {
|
|
480
|
+
lease.channel.reader.stop(); contentChannels.delete(lease.channel.key);
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
const releaseOwner = (owner) => {
|
|
484
|
+
ownerGenerations.set(owner, (ownerGenerations.get(owner) || 0) + 1);
|
|
485
|
+
for (const [id, lease] of leases) if (lease.owner === owner) releaseLease(id);
|
|
486
|
+
};
|
|
487
|
+
const observe = (resource, owner, { status = true } = {}) => {
|
|
488
|
+
if (observers.has(resource)) return () => {};
|
|
489
|
+
if (status) statusObservers.add(resource);
|
|
490
|
+
observers.set(resource, owner); void reconcile();
|
|
491
|
+
return () => {
|
|
492
|
+
observers.delete(resource);
|
|
493
|
+
statusObservers.delete(resource);
|
|
494
|
+
if (![...statusObservers].some((entry) => observers.get(entry) === owner)) releaseOwner(owner);
|
|
495
|
+
if (!statusObservers.size) {
|
|
496
|
+
refreshQueue.clear();
|
|
497
|
+
for (const connection of connections.values()) {
|
|
498
|
+
connection.reader?.stop(); connection.reader = null;
|
|
499
|
+
connection.refreshController?.abort();
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (!observers.size) {
|
|
503
|
+
refreshQueue.clear();
|
|
504
|
+
for (const connection of [...connections.values()]) closeConnection(connection);
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
};
|
|
508
|
+
const unsubscribeAdapter = adapter?.subscribe?.(() => {
|
|
509
|
+
if (stopped || (!scopes.size && !store.projects().length && !connections.size)) return;
|
|
510
|
+
// Observe each saved-catalog change, even while no transport is retained, so
|
|
511
|
+
// removing and re-adding an identical Host cannot resurrect an old scope.
|
|
512
|
+
void descriptors().then(() => {
|
|
513
|
+
if (!stopped && (store.projects().length || connections.size)) void reconcile();
|
|
514
|
+
}).catch(() => {
|
|
515
|
+
if (!stopped && (store.projects().length || connections.size)) void reconcile();
|
|
516
|
+
});
|
|
517
|
+
}) || (() => {});
|
|
518
|
+
return {
|
|
519
|
+
store, request, json, reconcile, observe, ensure, releaseOwner, assertProjectDirectory, supported: Boolean(adapter),
|
|
520
|
+
projectReferencesChanged(id) {
|
|
521
|
+
const connection = connections.get(id);
|
|
522
|
+
if (connection && statusObservers.size) { connection.topologyDirty = true; enqueueRefresh(connection); }
|
|
523
|
+
void reconcile();
|
|
524
|
+
},
|
|
525
|
+
retainHost(hostId, resource, priority = false) {
|
|
526
|
+
let consumers = interactiveHosts.get(hostId);
|
|
527
|
+
if (!consumers) { consumers = new Set(); interactiveHosts.set(hostId, consumers); }
|
|
528
|
+
consumers.add(resource);
|
|
529
|
+
if (priority) priorityRequests.set(resource, hostId);
|
|
530
|
+
return () => {
|
|
531
|
+
consumers.delete(resource);
|
|
532
|
+
priorityRequests.delete(resource);
|
|
533
|
+
if (!consumers.size) {
|
|
534
|
+
interactiveHosts.delete(hostId);
|
|
535
|
+
if (!stopped && !store.projects(hostId).length) {
|
|
536
|
+
refreshQueue.delete(hostId);
|
|
537
|
+
const connection = connections.get(hostId);
|
|
538
|
+
if (connection) closeConnection(connection);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
pump();
|
|
542
|
+
};
|
|
543
|
+
},
|
|
544
|
+
async list() {
|
|
545
|
+
const hosts = await descriptors();
|
|
546
|
+
for (const host of hosts) store.saveHost(host);
|
|
547
|
+
for (const p of store.projects()) if (!hosts.some((h) => h.id === p.hostId)) store.markProject(p.id, 'host-unavailable');
|
|
548
|
+
const removed = new Set(store.projects().filter((p) => p.remoteState === 'host-unavailable' && !hosts.some((h) => h.id === p.hostId)).map((p) => p.hostId));
|
|
549
|
+
const unavailable = [...removed].map((id) => ({ ...(store.savedHosts().find((host) => host.id === id) || { id, name: id, source: 'direct' }),
|
|
550
|
+
...store.receipt(id), state: 'offline', available: false }));
|
|
551
|
+
return { supported: Boolean(adapter), hubId: store.hubId, hosts: [...hosts.map(hostView), ...unavailable], projects: store.projects(),
|
|
552
|
+
...(!adapter ? { reason: 'pc_hub_required' } : {}) };
|
|
553
|
+
},
|
|
554
|
+
async connect(id) { const connection = await ensure(id); startStatus(connection); return hostView(connection.host); },
|
|
555
|
+
summaries(id) {
|
|
556
|
+
const references = new Set(store.projects(id).map((p) => directoryKey(p.path)));
|
|
557
|
+
if (!references.size) throw remoteFailure('project_not_found', 404);
|
|
558
|
+
const stale = stateFor(id) !== 'connected' || !connections.get(id)?.snapshotReady;
|
|
559
|
+
const snapshot = indexFor(id).snapshot();
|
|
560
|
+
const ownerFor = directoryResolver(id);
|
|
561
|
+
return { ...snapshot, ...store.organization(id), hostId: id, hubId: store.hubId, stale, ...store.receipt(id),
|
|
562
|
+
directories: snapshot.directories.filter((d) => ownerFor(d.directory)).map((d) => ({ ...d,
|
|
563
|
+
sessions: stale ? d.sessions.map((s) => ({ ...s, metadata: { ...s.metadata, yuri: { ...s.metadata?.yuri,
|
|
564
|
+
sessionStatus: { type: 'unknown', lastKnown: s.metadata?.yuri?.sessionStatus?.type } } } })) : d.sessions })) };
|
|
565
|
+
},
|
|
566
|
+
async subscribe(id, input, owner) {
|
|
567
|
+
const ownerGeneration = ownerGenerations.get(owner) || 0;
|
|
568
|
+
if (input?.sessionId !== undefined && (typeof input.sessionId !== 'string' || !input.sessionId || input.sessionId.length > 512)) {
|
|
569
|
+
throw remoteFailure('validation_error', 400);
|
|
570
|
+
}
|
|
571
|
+
assertProjectDirectory(id, input?.directory);
|
|
572
|
+
const connection = await ensure(id);
|
|
573
|
+
if ((ownerGenerations.get(owner) || 0) !== ownerGeneration || ![...observers.values()].includes(owner)) {
|
|
574
|
+
throw remoteFailure('remote_authorization_required', 401);
|
|
575
|
+
}
|
|
576
|
+
const leaseId = crypto.randomUUID();
|
|
577
|
+
const key = JSON.stringify([id, input.directory, input.sessionId || '']);
|
|
578
|
+
const shared = contentChannels.get(key);
|
|
579
|
+
if (shared) {
|
|
580
|
+
shared.users.add(leaseId);
|
|
581
|
+
leases.set(leaseId, { hostId: id, directory: input.directory, owner, channel: shared });
|
|
582
|
+
if (shared.readyGeneration) emit(id, { type: 'yuri:content-ready', properties: {
|
|
583
|
+
id: leaseId, sessionId: input.sessionId, channelId: shared.id, readyGeneration: shared.readyGeneration } }, input.directory);
|
|
584
|
+
return { id: leaseId, channelId: shared.id, readyGeneration: shared.readyGeneration };
|
|
585
|
+
}
|
|
586
|
+
if (contentChannels.size >= maxContentSubscriptions) throw remoteFailure('content_capacity', 429);
|
|
587
|
+
const route = `/api/event?directory=${encodeURIComponent(input.directory)}`;
|
|
588
|
+
let channel;
|
|
589
|
+
const reader = createUpstreamSseReader({ buildUrl: () => `http://remote.invalid${route}`,
|
|
590
|
+
signal: connection.controller.signal,
|
|
591
|
+
fetchImpl: (_url, init) => connection.transport.fetch(route, init),
|
|
592
|
+
reconnectDelayMs: () => Math.min(30000, 500 * 2 ** Math.min(channel.failures, 6)) * (0.8 + Math.random() * 0.4),
|
|
593
|
+
onConnect: () => {
|
|
594
|
+
if (!current(connection) || contentChannels.get(key) !== channel) return;
|
|
595
|
+
channel.failures = 0;
|
|
596
|
+
channel.readyGeneration = crypto.randomUUID();
|
|
597
|
+
for (const activeLease of channel.users) emit(id, { type: 'yuri:content-ready', properties: {
|
|
598
|
+
id: activeLease, sessionId: input.sessionId, channelId: channel.id, readyGeneration: channel.readyGeneration } }, input.directory);
|
|
599
|
+
},
|
|
600
|
+
onDisconnect: ({ reason }) => { if (reason !== 'stopped') channel.failures++; },
|
|
601
|
+
onError: ({ status }) => {
|
|
602
|
+
channel.failures++;
|
|
603
|
+
if (status === 401 || status === 403) {
|
|
604
|
+
channel.failures = Math.max(channel.failures, 6);
|
|
605
|
+
setState(connection, 'unauthorized', remoteFailure('remote_authorization_required', status));
|
|
606
|
+
connection.transport?.close(); connection.ready = null;
|
|
607
|
+
for (const [leaseId, lease] of leases) if (lease.hostId === id) releaseLease(leaseId);
|
|
608
|
+
}
|
|
609
|
+
},
|
|
610
|
+
onEvent: (event) => {
|
|
611
|
+
if (!current(connection)) return;
|
|
612
|
+
const data = event.payload?.properties || event.payload?.data;
|
|
613
|
+
const session = data?.sessionID || data?.info?.sessionID || data?.part?.sessionID;
|
|
614
|
+
if (input.sessionId && session && session !== input.sessionId) return;
|
|
615
|
+
if (!statusEvent(event.payload)) emit(id, event.payload, event.directory || input.directory);
|
|
616
|
+
} });
|
|
617
|
+
channel = { id: crypto.randomUUID(), key, reader, users: new Set([leaseId]), readyGeneration: null, failures: 0 };
|
|
618
|
+
contentChannels.set(key, channel);
|
|
619
|
+
leases.set(leaseId, { hostId: id, directory: input.directory, owner, channel });
|
|
620
|
+
void reader.start();
|
|
621
|
+
return { id: leaseId, channelId: channel.id };
|
|
622
|
+
},
|
|
623
|
+
release(id, leaseId, owner) {
|
|
624
|
+
const lease = leases.get(leaseId);
|
|
625
|
+
if (!lease || lease.hostId !== id || lease.owner !== owner) throw remoteFailure('subscription_not_found', 404);
|
|
626
|
+
releaseLease(leaseId);
|
|
627
|
+
},
|
|
628
|
+
async openWebSocket(id, route, protocols, options) {
|
|
629
|
+
const connection = await ensure(id);
|
|
630
|
+
const socket = await connection.transport.openWebSocket(route, protocols, options);
|
|
631
|
+
await resolveHost(id);
|
|
632
|
+
if (!current(connection)) { socket.close(); throw remoteFailure('stale_host', 409); }
|
|
633
|
+
return socket;
|
|
634
|
+
},
|
|
635
|
+
stop() {
|
|
636
|
+
unsubscribeAdapter();
|
|
637
|
+
stopped = true; refreshQueue.clear(); observers.clear(); statusObservers.clear();
|
|
638
|
+
for (const connection of [...connections.values()]) closeConnection(connection);
|
|
639
|
+
for (const service of indexes.values()) service.close();
|
|
640
|
+
scopes.clear();
|
|
641
|
+
store.close();
|
|
642
|
+
},
|
|
643
|
+
};
|
|
644
|
+
}
|