@yuriai/web 0.2.28 → 0.2.29-beta.4
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-GVufO03R.js +1 -0
- package/dist/assets/AssistantContactStatus-AG7iGeRF.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-DqThZdCe.js → AssistantUnreadBadge-BMCaH0Cc.js} +1 -1
- package/dist/assets/{AssistantView-DPUDCXoY.js → AssistantView-C5ACV-pb.js} +1 -1
- package/dist/assets/{DiagramView-CHVLoYrV.js → DiagramView-DJDzscnd.js} +1 -1
- package/dist/assets/{FadeInOnReveal-Cj3JXYvE.js → FadeInOnReveal-8NiBU75a.js} +1 -1
- package/dist/assets/{GuiPluginSurface-CBZYeKHb.js → GuiPluginSurface-DfLl4Gd9.js} +1 -1
- package/dist/assets/{GuiPluginWindow-_Z5wycnH.js → GuiPluginWindow-CW0-Tapi.js} +1 -1
- package/dist/assets/{Icon-CeRMtJa8.js → Icon-CLLDJn-P.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-DjLaKB4o.js → ImageLoadingPlaceholder-DTWzB26a.js} +1 -1
- package/dist/assets/LoadingImage-B89ghYMH.js +1 -0
- package/dist/assets/MarkdownRenderer-YzZqs3v5.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-_plqOlsV.js → MarkdownRendererImpl-BjjAFHTQ.js} +3 -3
- package/dist/assets/MarkstreamRendererImpl-D8tam--u.js +3 -0
- package/dist/assets/{MobileDetailNavigation-SeT764Ps.js → MobileDetailNavigation-B-AuJG6R.js} +1 -1
- package/dist/assets/{MobileResizableSheet-BY1-oo_E.js → MobileResizableSheet-CAj4YGtu.js} +1 -1
- package/dist/assets/{MobileShareBridge-Dw8gLtJD.js → MobileShareBridge-B8X_MEk1.js} +2 -2
- package/dist/assets/MobileTabPageHeader-vvveBlBV.js +2 -0
- package/dist/assets/MultiRunWindow-C0dOS6fA.js +1 -0
- package/dist/assets/{OnboardingScreen-CGqabMbp.js → OnboardingScreen-BdU6Tyax.js} +1 -1
- package/dist/assets/{OverlayScrollbar-AGSWQKg-.js → OverlayScrollbar-CzQC0JQI.js} +1 -1
- package/dist/assets/SettingsView-C0HSdVvS.css +1 -0
- package/dist/assets/SettingsView-aWGqxCrZ.js +30 -0
- package/dist/assets/SettingsWindow-rX0TNPNO.js +1 -0
- package/dist/assets/{TerminalView-OHqpkHzz.js → TerminalView-BArR-jEl.js} +3 -3
- package/dist/assets/ToolOutputDialog-Bdwio4o_.js +10 -0
- package/dist/assets/YuriLogo-BZC0ckt0.js +1 -0
- package/dist/assets/{appThemeRegistry-9j-rCSlE.js → appThemeRegistry-DOuA757r.js} +1 -1
- package/dist/assets/appearance--vFosLNi.js +1 -0
- package/dist/assets/{assistant-attachment-cache-B_qRvy-k.js → assistant-attachment-cache-DMw2Smc8.js} +1 -1
- package/dist/assets/{button-Bjh2BSXh.js → button-BF2cNEuq.js} +1 -1
- package/dist/assets/{capgoAdapter-DERfot6h.js → capgoAdapter-BBnW57us.js} +1 -1
- package/dist/assets/collapsible-CS5qCQRU.js +1 -0
- package/dist/assets/context-menu-C6l4ycZG.js +1 -0
- package/dist/assets/desktopRelayRestore-C7pjf6fE.js +1 -0
- package/dist/assets/{device-BcRP6Tjd.js → device-DN1GigI_.js} +1 -1
- package/dist/assets/{diagram-CXVm2vzI.js → diagram-D9-jif9d.js} +1 -1
- package/dist/assets/dialog-r7RRePv5.js +1 -0
- package/dist/assets/{dropdown-menu.styles-M78xpvb2.js → dropdown-menu.styles-CX8oXdks.js} +1 -1
- package/dist/assets/es-C8kGYKZo.js +15 -0
- package/dist/assets/{fileMentionTouchSelection-B9NbPN9D.js → fileMentionTouchSelection-dpFpcetU.js} +2 -2
- package/dist/assets/{fileQueries-BeXkd3o6.js → fileQueries-DWj9yB2g.js} +1 -1
- package/dist/assets/{fileReferenceActions-CrIAce3K.js → fileReferenceActions-BBLYnGEx.js} +1 -1
- package/dist/assets/{fr-CIGqV46N.js → fr-BV_9HcN9.js} +3 -3
- package/dist/assets/{gitApi-CY3D5CF0.js → gitApi-b2Mo4rXl.js} +1 -1
- package/dist/assets/{gitApiHttp-B7vYwgBh.js → gitApiHttp-DGAlAuET.js} +4 -4
- package/dist/assets/host-DB6QzbOw.js +1 -0
- package/dist/assets/image-loading-BUouaouB.js +1 -0
- package/dist/assets/input-DvF_mp0Y.js +1 -0
- package/dist/assets/insertionBoundaries-BviApxnS.js +1 -0
- package/dist/assets/{ja-DAhnTq6V.js → ja-CIMpz4Z2.js} +3 -3
- package/dist/assets/{ko-FbMgNKcI.js → ko-DPUsuWV1.js} +3 -3
- package/dist/assets/magpie-BuRvkGVQ.svg +1 -0
- package/dist/assets/main-BchAIbLD.js +2 -0
- package/dist/assets/main-Cp31rg32.js +169 -0
- package/dist/assets/{markdownHeightCache-DVWGXtAX.js → markdownHeightCache-D02GlOiy.js} +1 -1
- package/dist/assets/{markdownTheme-hpURsgju.js → markdownTheme-CHNl6tUv.js} +1 -1
- package/dist/assets/{mcpQueries-CdOYmUdO.js → mcpQueries-Cksi876R.js} +1 -1
- package/dist/assets/miniChat-BbuRxk9z.js +2 -0
- package/dist/assets/mobile-CBiiV7GW.js +2 -0
- package/dist/assets/{mobileBackNavigation-CgZndzFA.js → mobileBackNavigation-BsbWBz8h.js} +1 -1
- package/dist/assets/multirun-Ce977k1P.js +3 -0
- package/dist/assets/native-CILcYDJz.js +1 -0
- package/dist/assets/{native-config-BpsFKLGl.js → native-config-5BNfonUF.js} +1 -1
- package/dist/assets/persistence-Dta0OwIa.js +3 -0
- package/dist/assets/{pl-DzX0cbiQ.js → pl-ChxP5OZm.js} +3 -3
- package/dist/assets/projectMeta-KTYl7ter.js +1 -0
- package/dist/assets/pt-BR-9N8nJVqC.js +15 -0
- package/dist/assets/{queue-abort-optimistic-DCLBpirg.js → queue-abort-optimistic-CJmevpBJ.js} +1 -1
- package/dist/assets/{react-DRe85o5s.js → react-Bwr5-XPi.js} +1 -1
- package/dist/assets/readiness-CdCOcZnK.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-wFpIvOFT.js +2 -0
- package/dist/assets/renderMobileApp-QJ2XwXGj.js +28 -0
- package/dist/assets/{runtime-file-download-Cf1WxfeW.js → runtime-file-download-o29morT6.js} +1 -1
- package/dist/assets/{runtime-file-resource-UJjHUF2C.js → runtime-file-resource-qB_oVdE6.js} +1 -1
- package/dist/assets/{runtimeConfig-BBgkLVr_.js → runtimeConfig-IuT6iZ4x.js} +1 -1
- package/dist/assets/runtimeEndpointReset-DEWSVYyD.js +149 -0
- package/dist/assets/scheduledTaskNavigation-BqkeRfVc.js +1 -0
- package/dist/assets/sessionLookup-mvlGQJTe.js +1 -0
- package/dist/assets/sortable-tabs-strip-Dc4Jr4ml.js +1 -0
- package/dist/assets/{speechSettingsQueries-CBSEAKyj.js → speechSettingsQueries-DEGyglgn.js} +2 -2
- package/dist/assets/src-DME3XM8W.css +2 -0
- package/dist/assets/{store-DVfZQktm.js → store-BPYoxYhv.js} +4 -4
- package/dist/assets/{terminalApi-rl9mZAlB.js → terminalApi-CPVNQ5DH.js} +1 -1
- package/dist/assets/{textarea-C6VQ7dHH.js → textarea-CIhiRPB2.js} +1 -1
- package/dist/assets/theme-validation-BGYdrOu7.js +1 -0
- package/dist/assets/themes-BgDJcxRc.js +1 -0
- package/dist/assets/tooltip-BoAbDVNP.js +1 -0
- package/dist/assets/{touch-gestures-K2_ZOkKW.js → touch-gestures-CErgaXZ7.js} +1 -1
- package/dist/assets/types-COEinOJU.js +2 -0
- package/dist/assets/uk-C-aeGNQI.js +15 -0
- package/dist/assets/{useAppFontEffects-CEgDiZHu.js → useAppFontEffects-C__cAJlw.js} +43 -43
- package/dist/assets/{useAssistantUIStore-CfaQV3ID.js → useAssistantUIStore-CYyXdd5c.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-BYt7I5so.js +1 -0
- package/dist/assets/{useEffectiveDirectory-BOYMJ6k7.js → useEffectiveDirectory-CcDsvhjq.js} +1 -1
- package/dist/assets/{useFontPreferences-DeqW9nRx.js → useFontPreferences-UzjDmx4b.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BgM0EvUr.js +17 -0
- package/dist/assets/{useThemeSystem-CGF5jnIh.js → useThemeSystem-CNzUUkFn.js} +1 -1
- package/dist/assets/useUIStore-BDZCXouA.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-EcJThS4x.js → useWorkerHighlightedLines-ZOArIAed.js} +1 -1
- package/dist/assets/vendor-base-ui-CzHs0bHY.js +1 -0
- package/dist/assets/{vendor-cmdk-C3oBVL9X.js → vendor-cmdk-C_tivUtr.js} +1 -1
- package/dist/assets/vendor-codemirror-autocomplete-C0FrlFqZ.js +12 -0
- package/dist/assets/vendor-codemirror-commands-5saeUOVY.js +1 -0
- package/dist/assets/vendor-codemirror-lang-angular-Cm7vBE3E.js +23 -0
- package/dist/assets/vendor-codemirror-lang-cpp-BjixvwC2.js +1 -0
- package/dist/assets/vendor-codemirror-lang-go-DFb2d_8t.js +11 -0
- package/dist/assets/vendor-codemirror-lang-java-CHitPigf.js +1 -0
- package/dist/assets/vendor-codemirror-lang-jinja-B8yrwpok.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-json-mLulNbwB.js → vendor-codemirror-lang-json-DowyFczU.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-CNvptX3P.js → vendor-codemirror-lang-less-B1_0-sTl.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-liquid-FIsA7YFN.js +1 -0
- package/dist/assets/vendor-codemirror-lang-markdown-npWBZIoE.js +6 -0
- package/dist/assets/vendor-codemirror-lang-php-wyEc0fdz.js +1 -0
- package/dist/assets/vendor-codemirror-lang-python-OPRdU26g.js +9 -0
- package/dist/assets/{vendor-codemirror-lang-rust-CtafR0gt.js → vendor-codemirror-lang-rust-DgovszuH.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-sass-BdU-i07o.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-sql-C6q09UUZ.js → vendor-codemirror-lang-sql-DUutq98l.js} +2 -2
- package/dist/assets/{vendor-codemirror-lang-vue-DIB78UsR.js → vendor-codemirror-lang-vue-CuRNbe8H.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-C_JVdOCF.js → vendor-codemirror-lang-wast-CGFAOCoB.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-xml-CMKBqGXF.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-yaml-BO0hIfQM.js → vendor-codemirror-lang-yaml-CH9a1QiY.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-Ctd4WxgW.js → vendor-codemirror-language-data-B3pLWvv-.js} +2 -2
- package/dist/assets/vendor-codemirror-search-hZY-L2l8.js +2 -0
- package/dist/assets/{vendor-dnd-kit-accessibility-DxpFzZhi.js → vendor-dnd-kit-accessibility-BOtnpZt5.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-core-B3g3zWQd.js → vendor-dnd-kit-core-DK4OoOTr.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-BKewx0Py.js → vendor-dnd-kit-sortable-Cv69eQm1.js} +1 -1
- package/dist/assets/{vendor-framer-motion-C1twy-GF.js → vendor-framer-motion-DDMKlXiP.js} +1 -1
- package/dist/assets/vendor-lodash-es-BS45jPoZ.js +1 -0
- package/dist/assets/{vendor-markstream-react-BlbOg72y.js → vendor-markstream-react-DfLaSG3W.js} +3 -3
- package/dist/assets/vendor-motion-C9oiAdx-.js +1 -0
- package/dist/assets/{vendor-pierre-diffs-Bj9Nqn6w.js → vendor-pierre-diffs-BFiZ3IhI.js} +2 -2
- package/dist/assets/{vendor-react-D5d-V1vN.js → vendor-react-DlzBev0S.js} +1 -1
- package/dist/assets/{vendor-react-drawio-C-iPmmED.js → vendor-react-drawio-Dyg1-39Q.js} +1 -1
- package/dist/assets/vendor-reactuses-core-DWo5Wn6R.js +1 -0
- package/dist/assets/{vendor-replit-codemirror-vim-DCdAdxvE.js → vendor-replit-codemirror-vim-BmQmU1lR.js} +6 -6
- package/dist/assets/{vendor-sonner-r2EJnfoo.js → vendor-sonner-BEHGipm5.js} +1 -1
- package/dist/assets/{vendor-stream-diffs-BnLmeqg2.js → vendor-stream-diffs-wcQxoPZk.js} +2 -2
- package/dist/assets/{vendor-tanstack-react-query-C4SG3JZB.js → vendor-tanstack-react-query-B2psfNaU.js} +1 -1
- package/dist/assets/{vendor-tanstack-react-virtual-BeZn51tF.js → vendor-tanstack-react-virtual-DSFNK3qc.js} +1 -1
- package/dist/assets/{vendor-zustand-B43HCgwC.js → vendor-zustand-vDaAPGfl.js} +1 -1
- package/dist/assets/zh-CN-DOchDQti.js +15 -0
- package/dist/assets/zh-TW-Dtigv2CE.js +15 -0
- package/dist/index.html +18 -18
- package/dist/mini-chat.html +18 -18
- package/dist/mobile.html +18 -18
- package/package.json +2 -1
- package/server/lib/config-sync/DOCUMENTATION.md +1 -0
- package/server/lib/config-sync/config-sync.test.js +22 -0
- package/server/lib/config-sync/constants.js +0 -3
- package/server/lib/gui-customization/DOCUMENTATION.md +45 -0
- package/server/lib/gui-customization/session-skill.js +58 -0
- package/server/lib/gui-customization/session-skill.test.js +53 -0
- package/server/lib/gui-customization/skill/SKILL.md +33 -0
- package/server/lib/gui-customization/skill/references/appearance.md +79 -0
- package/server/lib/gui-customization/skill/references/file-previews.md +113 -0
- package/server/lib/gui-customization/skill/references/global-pages.md +81 -0
- package/server/lib/gui-customization/skill/references/gui-api.md +37 -0
- package/server/lib/gui-customization/skill/references/preview-exports.md +74 -0
- package/server/lib/gui-customization/skill/references/workflow.md +81 -0
- package/server/lib/opencode/DOCUMENTATION.md +74 -1
- package/server/lib/opencode/config-entity-routes.js +2 -4
- package/server/lib/opencode/config-entity-routes.test.js +16 -13
- package/server/lib/opencode/core-routes.js +2 -0
- package/server/lib/opencode/core-routes.test.js +2 -2
- package/server/lib/opencode/custom-provider-models.d.ts +2 -0
- package/server/lib/opencode/custom-provider-models.js +71 -0
- package/server/lib/opencode/custom-provider-models.test.js +90 -0
- package/server/lib/opencode/custom-provider.d.ts +2 -0
- package/server/lib/opencode/custom-provider.js +107 -0
- package/server/lib/opencode/custom-provider.test.js +211 -0
- package/server/lib/opencode/feature-routes-runtime.js +5 -0
- package/server/lib/opencode/provider-catalog.js +14 -0
- package/server/lib/opencode/provider-catalog.test.js +15 -0
- package/server/lib/opencode/provider-configuration.test.js +64 -0
- package/server/lib/opencode/provider-model-config.d.ts +1 -0
- package/server/lib/opencode/provider-model-config.js +39 -0
- package/server/lib/opencode/provider-model-config.test.js +69 -0
- package/server/lib/opencode/provider-sources.d.ts +10 -0
- package/server/lib/opencode/provider-sources.js +52 -0
- package/server/lib/opencode/provider-sources.test.js +73 -0
- package/server/lib/opencode/providers.d.ts +5 -0
- package/server/lib/opencode/providers.js +28 -0
- package/server/lib/opencode/routes.js +50 -1
- package/server/lib/remote-desktop/DOCUMENTATION.md +6 -2
- package/server/lib/remote-desktop/runtime.js +3 -2
- package/server/lib/remote-desktop/runtime.test.js +20 -0
- package/server/lib/scheduled-tasks/session-skill.js +3 -0
- package/server/lib/scheduled-tasks/session-skill.test.js +4 -2
- package/shared/custom-provider-protocol.d.ts +4 -0
- package/shared/custom-provider-protocol.js +32 -0
- package/dist/assets/AgentAvatar-BybF1ayP.js +0 -1
- package/dist/assets/AssistantContactStatus-BwpxTn0d.js +0 -3
- package/dist/assets/LoadingImage-DG3otL5V.js +0 -1
- package/dist/assets/MarkdownRenderer-C8rv6z7p.js +0 -2
- package/dist/assets/MarkstreamRendererImpl-bs8HZ4Ra.js +0 -3
- package/dist/assets/MobileTabPageHeader-EsrOCLyg.js +0 -2
- package/dist/assets/MultiRunWindow-C-Qw_g7N.js +0 -1
- package/dist/assets/SettingsView-BLfFnnnX.js +0 -29
- package/dist/assets/SettingsView-BRIvklfP.css +0 -1
- package/dist/assets/SettingsWindow-lyYO8Byy.js +0 -1
- package/dist/assets/ToolOutputDialog-DU4Pb1s0.js +0 -10
- package/dist/assets/YuriLogo-Bb6yHagP.js +0 -1
- package/dist/assets/collapsible-BEAHoxNi.js +0 -1
- package/dist/assets/context-menu-BxLcot-3.js +0 -1
- package/dist/assets/desktopRelayRestore-D1UX7HW2.js +0 -1
- package/dist/assets/dialog-nshKUSE5.js +0 -1
- package/dist/assets/es-N9ZkQwG9.js +0 -15
- package/dist/assets/host-CnVx34Dh.js +0 -1
- package/dist/assets/image-loading-D6kOgU4w.js +0 -1
- package/dist/assets/input-3Re4pmHm.js +0 -1
- package/dist/assets/insertionBoundaries-DK7XYF8d.js +0 -1
- package/dist/assets/main-B_THXYMs.js +0 -2
- package/dist/assets/main-CpcudEZb.js +0 -169
- package/dist/assets/miniChat-DxZiTnAZ.js +0 -2
- package/dist/assets/mobile-BJuATiaC.js +0 -2
- package/dist/assets/multirun-BlaYsQi2.js +0 -3
- package/dist/assets/native-BYMhr-xH.js +0 -1
- package/dist/assets/persistence-CWuLIq1J.js +0 -3
- package/dist/assets/projectMeta-CnXHTolN.js +0 -1
- package/dist/assets/pt-BR-C5yvwyDK.js +0 -15
- package/dist/assets/readiness-U16Qor79.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-n-nhgy1V.js +0 -2
- package/dist/assets/renderMobileApp-DBj_7RlD.js +0 -28
- package/dist/assets/runtimeEndpointReset-BvSQVFfx.js +0 -149
- package/dist/assets/scheduledTaskNavigation-EomDNVu2.js +0 -1
- package/dist/assets/sessionLookup-C_CCp7MJ.js +0 -1
- package/dist/assets/sortable-tabs-strip-p16Pn6Zz.js +0 -1
- package/dist/assets/src-u-YDfCVw.css +0 -2
- package/dist/assets/tooltip-Dnc6GA-X.js +0 -1
- package/dist/assets/types-DnZw0gLD.js +0 -2
- package/dist/assets/uk-zbDcUpBy.js +0 -15
- package/dist/assets/useDesktopWindowControlsLayout-B2o4IFmd.js +0 -1
- package/dist/assets/useMobileNavigationStore-DlvrZQ49.js +0 -17
- package/dist/assets/useUIStore-C6CE42oh.js +0 -1
- package/dist/assets/vendor-base-ui-BQjbsJ43.js +0 -1
- package/dist/assets/vendor-codemirror-autocomplete-7c2L_4dM.js +0 -12
- package/dist/assets/vendor-codemirror-commands-B8KrBQ9B.js +0 -1
- package/dist/assets/vendor-codemirror-lang-angular-DXOgWEVj.js +0 -23
- package/dist/assets/vendor-codemirror-lang-cpp-Dh8C3xqP.js +0 -1
- package/dist/assets/vendor-codemirror-lang-go-BXAJ1_dh.js +0 -11
- package/dist/assets/vendor-codemirror-lang-java-DAyCHRhk.js +0 -1
- package/dist/assets/vendor-codemirror-lang-jinja-0TICrMfO.js +0 -1
- package/dist/assets/vendor-codemirror-lang-liquid-8g5seytq.js +0 -1
- package/dist/assets/vendor-codemirror-lang-markdown-CV1IO6Qs.js +0 -6
- package/dist/assets/vendor-codemirror-lang-php-xP7rf28_.js +0 -1
- package/dist/assets/vendor-codemirror-lang-python-YM2WVLHF.js +0 -9
- package/dist/assets/vendor-codemirror-lang-sass-B4iav_Ps.js +0 -1
- package/dist/assets/vendor-codemirror-lang-xml-DIuzY_d4.js +0 -1
- package/dist/assets/vendor-codemirror-search-DiPwvA-6.js +0 -2
- package/dist/assets/vendor-lodash-es-DfLbG5Af.js +0 -1
- package/dist/assets/vendor-motion-BmLx2V78.js +0 -1
- package/dist/assets/vendor-reactuses-core-BcebBLwF.js +0 -1
- package/dist/assets/zh-CN-BHRJ7CF3.js +0 -15
- package/dist/assets/zh-TW-BFI_YFd-.js +0 -15
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-DgJnLT1Y.js","assets/rolldown-runtime-hePW80VL.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{C as t,D as n,k as r}from"./runtime-auth-DBn9yahL.js";import{c as i,f as a,i as o,n as s,r as c,s as l}from"./runtime-switch-DEZ1K7qW.js";import{n as u}from"./runtime-fetch-D0YWp3FJ.js";import{l as d,w as f}from"./desktop-JwYqThiw.js";import{t as p}from"./runtimeAPIRegistry-C2VogTny.js";import{a as m,r as h}from"./vendor-zustand-
|
|
2
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{C as t,D as n,k as r}from"./runtime-auth-DBn9yahL.js";import{c as i,f as a,i as o,n as s,r as c,s as l}from"./runtime-switch-DEZ1K7qW.js";import{n as u}from"./runtime-fetch-D0YWp3FJ.js";import{l as d,w as f}from"./desktop-JwYqThiw.js";import{t as p}from"./runtimeAPIRegistry-C2VogTny.js";import{a as m,r as h}from"./vendor-zustand-vDaAPGfl.js";import{st as g}from"./vendor-base-ui-CzHs0bHY.js";import{B as ee,R as te,V as ne}from"./vendor-opencode-client-cQ47ywrT.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{S as re}from"./useUIStore-BDZCXouA.js";import{It as ie,Pt as ae,at as oe,ft as se,i as ce,ot as le,tt as ue,vt as de}from"./persistence-Dta0OwIa.js";import{n as fe}from"./vendor-react-DlzBev0S.js";import{i as pe}from"./vendor-pathe-vBmvQE8f.js";import{n as me}from"./runtime-file-resource-qB_oVdE6.js";import{o as he}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";var ge=(e,t)=>e!==t,_=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0};function _e(e){let t=_(e.id),n=_(e.name),r=_(e.displayName),i=t??n;if(!i)return{...e,id:``,name:``,displayName:r??``};if(n===i&&r)return{...e,id:i,name:i,displayName:r};let a=r??n??i;return{...e,id:i,name:i,displayName:a}}function ve(e){return e?_(e.displayName)??_(e.name)??_(e.id)??``:``}function ye(e,t){let n=_(t);if(!n||!e?.length)return;let r=e.find(e=>_(e.name)===n);if(r)return r;let i=e.find(e=>_(e.id)===n);if(i)return i;let a=e.find(e=>_(e.displayName)===n);if(a)return a}function be(e,t){let n=_(t);if(!n)return;let r=ye(e,n);return r?_(r.name)??_(r.id)??n:n}function xe(e){return Array.from(new Set(Array.from(e.matchAll(de()),e=>e[1])),e=>({id:e,name:e}))}function v(e){return{...e,directory:e.location?.directory}}function Se(e){let t={};for(let n of e){let e=n;!e||e.type!==`document`||!e.info||typeof e.info!=`object`||Object.assign(t,e.info)}return t}var y=e(g(),1),Ce=fe();function b(e,t){return e.findIndex(e=>e.id===t)}function we(e,t){if(!t)return e.slice();let n=b(e,t);return n<0?e.slice():e.slice(0,n)}function Te(e,t,n){let r=b(e,n);return r<0?!1:b(e,t)>=r}function Ee(e,t){if(!t){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role===`user`)return n}return}let n=b(e,t);if(!(n<0))for(let t=n-1;t>=0;--t){let n=e[t];if(n?.role===`user`)return n}}function De(e,t){let n=b(e,t);if(!(n<0))for(let t=n+1;t<e.length;t+=1){let n=e[t];if(n?.role===`user`)return n}}var Oe=`yuri:sync:debug`,ke;function Ae(){if(ke!==void 0)return ke;try{ke=typeof localStorage<`u`&&localStorage.getItem(Oe)===`1`}catch{ke=!1}return ke}function x(e,...t){Ae()&&(`${e}`,[...t])}var je={pipeline:{coalesced:(e,t)=>x(`pipeline`,`coalesced`,e,t),flush:e=>x(`pipeline`,`flush`,`${e} events`)},reducer:{messageUpdatedUnchanged:(e,t,n,r,i)=>x(`reducer`,`message.updated UNCHANGED (skipped)`,{sessionID:e,messageID:t,role:n,finish:r,completed:i}),partUpdatedNoExistingParts:(e,t,n)=>x(`reducer`,`message.part.updated NO EXISTING PARTS`,{messageID:e,partID:t,partType:n}),partDeltaNoParts:(e,t)=>x(`reducer`,`message.part.delta DROPPED (no parts array)`,{messageID:e,partID:t}),partDeltaNotFound:(e,t)=>x(`reducer`,`message.part.delta DROPPED (partID not found)`,{messageID:e,partID:t}),partSkipped:(e,t,n)=>x(`reducer`,`message.part.updated SKIPPED (type filtered)`,{messageID:e,partID:t,partType:n})},dispatch:{eventNoChange:(e,t,n)=>x(`dispatch`,`event → no change`,{eventType:e,sessionID:t,messageID:n}),eventApplied:(e,t,n)=>x(`dispatch`,`event → applied`,{eventType:e,sessionID:t,messageID:n})},recovery:{materializing:e=>x(`recovery`,`materializing session`,e)}};function Me(e,t){let n=new Set(t),r=new Map,i=[],a;for(let t of e){if(!n.has(t)){i.push(t);continue}i.length>0&&r.set(t,i),i=[],a=t}let o=[],s=new Set,c=e=>{s.has(e)||(s.add(e),o.push(e))};for(let e of t){for(let t of r.get(e)??[])c(t);if(c(e),e===a)for(let e of i)c(e)}if(!a)for(let e of i)c(e);return o}var Ne=`desc`;function Pe(e){return!S(e)||e.type!==`compaction`?!1:e.status===`running`||e.status===`completed`||e.status===`failed`}function Fe(e){if(e)return e.find(Pe)}var Ie=e=>e?e.toLowerCase().includes(`application/json`):!1,Le=e=>e?e.toLowerCase().includes(`text/html`):!1;function S(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function C(e){return typeof e==`string`&&e.length>0?e:void 0}function Re(e){if(!S(e))return null;let t=C(e.id);return t?{...e,id:t}:null}function ze(e,t,n){return`${e}:${t}:${n}`}function Be(e,t,n,r,i=`text`,a){return i===`reasoning`?{id:ze(t,i,n),sessionID:e,messageID:t,type:`reasoning`,text:r}:{id:ze(t,i,n),sessionID:e,messageID:t,type:`text`,text:r,...a?.synthetic===!0?{synthetic:!0}:{}}}function Ve(e){return e?e.nativeType===`synthetic`||e.type===`synthetic`:!1}function He(e,t){return!e?.id||Ve(e)||(e.clientRole??e.role)!==`user`?!1:!Array.isArray(t)||t.length===0||!(t.some(e=>e.type===`subtask`||e.type===`compaction`)||t.every(e=>!!e.synthetic))}function Ue(e){if(typeof e==`string`&&e.length!==0)return e.replace(/^evt_/,`msg_`)}function We(e){let t=e.content;return Array.isArray(t)?t.flatMap(e=>S(e)&&e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(`
|
|
3
3
|
`):typeof e.output==`string`?e.output:void 0}function Ge(e){return e===`patch`?`apply_patch`:e}function Ke(e,t,n){let r=C(n.id)??`${t}:tool`,i=Ge(C(n.name))??`tool`,a=S(n.state)?n.state:{},o=C(a.status)??`completed`,s=o===`streaming`?`pending`:o,c=S(n.time)?n.time:{};return{id:r,sessionID:e,messageID:t,type:`tool`,tool:i,callID:r,state:{status:s,input:a.input??{},output:We(a),error:S(a.error)?C(a.error.message):C(a.error),metadata:S(a.metadata)?a.metadata:{},time:{...typeof c.ran==`number`&&Number.isFinite(c.ran)?{start:c.ran}:{},...typeof c.completed==`number`&&Number.isFinite(c.completed)?{end:c.completed}:{}}}}}function qe(e){return S(e)?{created:typeof e.created==`number`?e.created:0,...typeof e.streamed==`number`?{streamed:e.streamed}:{},...typeof e.completed==`number`?{completed:e.completed}:{},...typeof e.start==`number`?{start:e.start}:{},...typeof e.end==`number`?{end:e.end}:{}}:{created:0}}function Je(e){if(!S(e))return;let t=S(e.cache)?{...typeof e.cache.read==`number`?{read:e.cache.read}:{},...typeof e.cache.write==`number`?{write:e.cache.write}:{}}:void 0,n={...typeof e.input==`number`?{input:e.input}:{},...typeof e.output==`number`?{output:e.output}:{},...typeof e.reasoning==`number`?{reasoning:e.reasoning}:{},...t&&(t.read!==void 0||t.write!==void 0)?{cache:t}:{}};return Object.keys(n).length>0?n:void 0}function Ye(e,t){let n=S(t.metadata)?t.metadata:void 0,r=n&&S(n.model)?n.model:void 0,i=S(t.model)?t.model:r,a=i?C(i.id)??C(i.modelID)??C(t.modelID):C(t.modelID),o=i?C(i.providerID)??C(t.providerID):C(t.providerID),s=(i?C(i.variant):void 0)??C(t.variant)??(n?C(n.variant):void 0);a&&(e.modelID=a),o&&(e.providerID=o),s&&(e.variant=s),(a||o||s)&&(e.model={...o?{providerID:o}:{},...a?{modelID:a}:{},...s?{variant:s}:{}});let c=C(t.agent)??C(t.mode)??(n?C(n.agent):void 0);c&&(e.agent=c)}function Xe(e,t,n){return{id:t.id,sessionID:e,role:n,time:qe(t.time)}}function Ze(e,t){let n=Re(t);if(!n)return null;let r=n.id,i=C(n.type)??`unknown`,a=C(n.role)??C(n.clientRole);if(i===`idle`||i===`model-switched`||i===`agent-selected`||i===`agent-switched`||i===`location-switched`||a===`idle`)return null;if(i===`user`){let t=Xe(e,n,`user`);Ye(t,n);let i=[],a=C(n.text);a&&i.push(Be(e,r,0,a));let o=n.files;return Array.isArray(o)&&o.forEach((t,n)=>{if(!S(t))return;let a=C(t.mime)??`application/octet-stream`,o=S(t.source)?t.source:{},s=o.type===`uri`?C(o.uri):void 0,c=C(t.data),l=s||(c?`data:${a};base64,${c}`:``),u={id:`${r}:file:${n}`,sessionID:e,messageID:r,type:`file`,mime:a,filename:C(t.name),url:l};i.push(u)}),{info:t,parts:i}}if(i===`assistant`){let t=Xe(e,n,`assistant`);if(S(n.model)){t.modelID=C(n.model.id)??C(n.model.modelID)??C(n.modelID),t.providerID=C(n.model.providerID)??C(n.providerID);let e=C(n.model.variant)??C(n.variant);(t.modelID||t.providerID||e)&&(t.model={...t.providerID?{providerID:t.providerID}:{},...t.modelID?{modelID:t.modelID}:{},...e?{variant:e}:{}})}else{let e=C(n.modelID),r=C(n.providerID),i=C(n.variant);e&&(t.modelID=e),r&&(t.providerID=r),(e||r||i)&&(t.model={...r?{providerID:r}:{},...e?{modelID:e}:{},...i?{variant:i}:{}})}let i=C(n.agent);i&&(t.agent=i);let a=C(n.finish)??C(n.rawFinish);a&&(t.finish=a),S(n.error)&&(t.error={type:C(n.error.type)??`error`,message:C(n.error.message)??``,...typeof n.error.status==`number`?{status:n.error.status}:{}}),typeof n.cost==`number`&&Number.isFinite(n.cost)&&(t.cost=n.cost);let o=Je(n.tokens);o&&(t.tokens=o);let s=[],c=Array.isArray(n.content)?n.content:[],l=0,u=0;for(let t of c){if(!S(t))continue;let n=C(t.type);if(n===`text`&&typeof t.text==`string`){s.push(Be(e,r,l++,t.text));continue}if(n===`reasoning`&&typeof t.text==`string`){s.push(Be(e,r,u++,t.text,`reasoning`));continue}n===`tool`&&s.push(Ke(e,r,t))}return{info:t,parts:s}}if(i===`shell`){let t=Xe(e,n,`user`),i=C(n.command)??``,a=S(n.output)&&typeof n.output.output==`string`?n.output.output:``,o=n.status===`running`?`running`:n.status===`exited`&&n.exit===0?`completed`:`error`;return{info:t,parts:[{id:ze(r,`text`,0),sessionID:e,messageID:r,type:`text`,text:i,shellAction:{command:i,output:a,status:o,shellID:C(n.shellID)}}]}}if(i===`synthetic`){let t={...Xe(e,n,`user`),nativeType:`synthetic`},i=C(n.description);i&&(t.description=i),S(n.metadata)&&(t.metadata=n.metadata);let a=C(n.shellID);a&&(t.shellID=a);let o=C(n.sessionID)&&n.sessionID!==e?C(n.sessionID):C(n.childSessionID)??C(n.taskSessionID);o&&(t.childSessionID=o);let s=C(n.text)??i??``;return{info:t,parts:s?[Be(e,r,0,s,`text`,{synthetic:!0})]:[{id:ze(r,`text`,0),sessionID:e,messageID:r,type:`text`,text:``,synthetic:!0}]}}if(i===`system`)return null;if(i===`compaction`){let t=n.status===`failed`?`failed`:n.status===`completed`?`completed`:`running`,i={...Xe(e,n,`assistant`),clientRole:`compaction`},a=S(n.error)?{type:C(n.error.type)??`error`,message:C(n.error.message)??``,...typeof n.error.status==`number`?{status:n.error.status}:{}}:void 0;return{info:i,parts:[{id:`${r}:compaction`,sessionID:e,messageID:r,type:`compaction`,status:t,reason:n.reason===`auto`?`auto`:`manual`,...typeof n.summary==`string`?{summary:n.summary}:{},...typeof n.recent==`string`?{recent:n.recent}:{},...a?{error:a}:{}}]}}return{info:Xe(e,n,`assistant`),parts:[Be(e,r,0,C(n.text)??`[${i}]`)]}}function Qe(e,t,n=Ne,r=20){if(!S(e))throw Error(`session projection: expected JSON object`);if(!Array.isArray(e.data))throw Error(`session projection: data must be an array`);let i=[];for(let n of e.data){let e=Ze(t,n);e&&i.push(e)}n===`desc`&&i.reverse();let a=S(e.cursor)?e.cursor:void 0,o=C(a?n===`asc`?a.previous:a.next:e.cursor),s=!o||e.data.length<r,c=i.filter(e=>He(e.info,e.parts)).length;return{records:i,cursor:s?void 0:o,complete:s,turnCount:c}}async function $e(e){let t=e.limit??20,n=e.order??`desc`,r=`/api/session/${encodeURIComponent(e.sessionID)}/message`,i={directory:e.directory,limit:String(t)};e.cursor?i.cursor=/^msg_[A-Za-z0-9_]+$/.test(e.cursor)?btoa(JSON.stringify({id:e.cursor,order:n,direction:n===`desc`?`next`:`previous`})).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``):e.cursor:i.order=n;let a=await u(r,{method:`GET`,query:i,signal:e.signal});if(!a.ok)throw Error(`session projection failed (${a.status})`);let o=a.headers.get(`content-type`);if(Le(o))throw Error(`session projection: unexpected HTML response`);Ie(o);let s;try{s=await a.json()}catch{throw Error(`session projection: malformed JSON`)}return Qe(s,e.sessionID,n,t)}function et(e){let t=e.fetched.filter(e=>!!e.info?.id),n=e.previous.filter(e=>!!e.info?.id),r=e.touched??new Set,i=new Map(t.map(e=>[e.info.id,e])),a=new Map(n.map(e=>[e.info.id,e])),o=new Set(e.coverageMessageIDs??t.map(e=>e.info.id)),s=n.findIndex(e=>o.has(e.info.id));if(!e.completeTail)for(let[e,t]of n.entries())i.has(t.info.id)||(s===-1||e<s)&&i.set(t.info.id,t);for(let e of r){let t=a.get(e);t?i.set(e,t):i.delete(e)}let c=n.map(e=>e.info.id).filter(e=>i.has(e)),l=t.map(e=>e.info.id).filter(e=>i.has(e)),u=l.some(e=>a.has(e));return(!e.completeTail&&!u?[...new Set([...c,...l])]:Me(c,l)).map(e=>i.get(e))}var tt=e=>e?e.toLowerCase().includes(`application/json`):!1,nt=e=>e?e.toLowerCase().includes(`text/html`):!1;function rt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function it(e){return typeof e==`string`&&e.length>0?e:void 0}function at(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function ot(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function st(e){try{return(await e.text()).trim()}catch{return``}}async function ct(e,t){let n=e.headers.get(`content-type`);if(nt(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!tt(n)&&r==null)throw Error(`${t}: empty response`);return r}var lt=new Map,ut=e=>lt.get(e)??0,dt=m((e,t)=>({runningBySession:{},setRunning(t,n){lt.set(t,ut(t)+1),e(e=>{let r={...e.runningBySession};return n?r[t]=!0:delete r[t],{runningBySession:r}})},isRunning(e){return t().runningBySession[e]===!0},reset(){lt.clear(),e({runningBySession:{}})}}));function w(e,t){dt.getState().setRunning(e,t)}function ft(e){return dt.getState().isRunning(e)}function pt(e){return!ft(e.sessionID)}function mt(e){let t=rt(e)?e:null,n=t&&rt(t.data)?t.data:t;if(!n)throw Error(`session compact: expected inbox item`);let r=it(n.id),i=it(n.sessionID);if(!r||!i)throw Error(`session compact: inbox item missing id`);if(n.type&&n.type!==`compaction`)throw Error(`session compact: expected compaction inbox item`);return{id:r,sessionID:i,type:`compaction`,delivery:n.delivery===`queue`?`queue`:n.delivery===`steer`?`steer`:void 0,timeCreated:at(n.timeCreated)}}function ht(e){let t=rt(e)?e:null,n=t&&Array.isArray(t.data)?t.data:Array.isArray(e)?e:null;if(!n)throw Error(`session inbox: expected list`);let r=[];for(let e of n)!rt(e)||e.type!==`compaction`||r.push(mt(e));return r}function gt(e,t){t.some(e=>e.type===`compaction`)&&w(e,!0)}function _t(e,t){for(let n=t.length-1;n>=0;--n){let r=(t[n]?.parts??[]).find(Pe);if(r){w(e,r.status===`running`);return}}}async function vt(e){let t=`/api/session/${encodeURIComponent(e.sessionID)}/compact`,n={};e.messageID&&(n.id=e.messageID),e.delivery&&(n.delivery=e.delivery);let r=await u(t,{method:`POST`,headers:{"Content-Type":`application/json`},query:{directory:e.directory},body:JSON.stringify(n),signal:e.signal});r.ok||ot(`session compact`,r.status,await st(r));let i=mt(await ct(r,`session compact`));return w(i.sessionID,!0),i}var yt=`compaction:`;function bt(e,t){return t&&t.length>0?t:`${yt}${e}`}function xt(e,t){let n=e.message[t]??[];for(let t=n.length-1;t>=0;--t){let r=n[t];if((e.part[r.id]??[]).some(e=>Pe(e)&&e.status===`running`))return r.id}}function St(e,t,n,r,i=Date.now()){let a=e.message[t]?[...e.message[t]]:[];a.some(e=>e.id===n)||(a.push({id:n,sessionID:t,role:`assistant`,clientRole:`compaction`,time:{created:i}}),e.message[t]=a);let o=e.part[n]?[...e.part[n]]:[],s=o.findIndex(Pe),c=r(s>=0?o[s]:{id:`${n}:compaction`,sessionID:t,messageID:n,type:`compaction`,status:`running`,reason:`manual`});s>=0?o[s]=c:o.push(c),e.part[n]=o}function Ct(e,t){let n=String(t.type??``);if(!n.startsWith(`session.compaction.`))return!1;let r=rt(t.properties)?t.properties:null;if(!r)return!1;let i=it(r.sessionID);if(!i)return!1;let a=it(r.inputID),o=xt(e,i),s=n===`session.compaction.started`?a??Ue(t.id)??bt(i):a??o??Ue(t.id)??bt(i);if(n===`session.compaction.started`)return!e.part[s]?.some(Pe)&&(St(e,i,s,e=>({...e,status:`running`,reason:r.reason===`auto`?`auto`:`manual`,...typeof r.recent==`string`?{recent:r.recent}:{}}),at(r.eventCreated)),w(i,!0),!0);if(n===`session.compaction.delta`){if(!o)return!1;let t=typeof r.text==`string`?r.text:``;return t?(St(e,i,s,e=>({...e,status:`running`,summary:(e.summary??``)+t})),w(i,!0),!0):!1}if(n===`session.compaction.ended`)return w(i,!1),o?(St(e,i,s,e=>({...e,status:`completed`,reason:r.reason===`auto`?`auto`:`manual`,summary:typeof r.text==`string`?r.text:e.summary,...typeof r.recent==`string`?{recent:r.recent}:{}}),at(r.eventCreated)),!0):!1;if(n===`session.compaction.failed`){if(w(i,!1),!o&&!a)return!1;let t=rt(r.error)?r.error:{};return St(e,i,s,e=>({...e,status:`failed`,reason:r.reason===`auto`?`auto`:`manual`,error:{type:it(t.type)??`error`,message:it(t.message)??``,...typeof t.status==`number`?{status:t.status}:{}}}),at(r.eventCreated)),!0}return!1}var wt=new Set([`patch`,`step-start`,`step-finish`]),Tt=[`text`,`output`],Et=new Set([`completed`,`error`,`aborted`,`failed`,`timeout`,`cancelled`]);function Dt(e,t){if(!e||t.length===0)return(e??``)+t;if(e.endsWith(t))return e;let n=Math.min(e.length,t.length);for(let r=n;r>0;r--)if(e.endsWith(t.slice(0,r)))return e+t.slice(r);return e+t}function Ot(e,t){let n=[];for(let r of Tt){let i=e[r],a=t[r];typeof i==`string`&&typeof a==`string`&&i.length!==0&&a.length!==0&&(a===i||a.startsWith(i)||i.startsWith(a))&&n.push(r)}return n}function kt(e){let t=e.state?.time?.end;if(typeof t==`number`)return t;let n=e.time?.end;return typeof n==`number`?n:void 0}function At(e){if(e.type!==`tool`)return;let t=e.state?.status;return typeof t==`string`?t:void 0}function jt(e,t){if(e.type!==`tool`||t.type!==`tool`)return!1;let n=At(e),r=At(t);if(n&&Et.has(n)&&(!r||!Et.has(r)))return!0;let i=kt(e),a=kt(t);return typeof i==`number`&&typeof a!=`number`}function Mt(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return e===t;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}var Nt=[`agent`,`mode`,`providerID`,`modelID`,`variant`],Pt=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ft=[`input`,`output`,`reasoning`];function It(e){if(!e||typeof e!=`object`)return!1;let t=e;return Ft.some(e=>typeof t[e]==`number`&&Number.isFinite(t[e])&&t[e]>0)}function Lt(e){if(!e||typeof e!=`object`)return!1;let t=e;return Ft.every(e=>typeof t[e]!=`number`||!Number.isFinite(t[e])||t[e]<=0)}function Rt(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function zt(e,t){let n={...e,...t},r=e,i=t,a=n;for(let e of Nt){let t=Rt(i[e]),n=Rt(r[e]);t?a[e]=t:n?a[e]=n:delete a[e]}let o=i.model,s=r.model;return Pt(o)?a.model=o:Pt(s)?a.model=s:delete a.model,(e.time||t.time)&&(n.time={...e.time,...t.time}),It(r.tokens)&&Lt(i.tokens)&&(a.tokens=r.tokens),n}function Bt(e,t){if(e.time.streamed!==t.time.streamed||e.role!==t.role||e.finish!==t.finish||e.time?.completed!==t.time?.completed)return!1;for(let n of[`summary`,`error`,`cost`,`tokens`,`structured`,`model`,`tools`,`format`,`variant`,`agent`,`mode`,`providerID`,`modelID`,`system`])if(!Mt(e[n],t[n]))return!1;return!0}function Vt(e,t,n){if(!t)return!1;let r=e.message[t];return r?b(r,n)>=0:!1}function Ht(e,t){switch(t.type){case`message.updated`:{let n=t.properties.info,r=n,i=typeof r.type==`string`?r.type:void 0,a=typeof r.role==`string`?r.role:void 0;if(i===`idle`||i===`model-switched`||i===`agent-selected`||i===`agent-switched`||i===`location-switched`||a===`idle`)return!1;let o=e.message[n.sessionID],s=!!o&&o.every(t=>t.role!==`assistant`||e.part[t.id]!==void 0);if(n.role===`assistant`&&s&&e.part[n.id]===void 0&&(e.part[n.id]=[]),!o)return e.message[n.sessionID]=[n],!0;let c=b(o,n.id);if(c>=0){let t=o[c],r=zt(t,n);if(Bt(t,r))return je.reducer.messageUpdatedUnchanged(n.sessionID,n.id,n.role,n.finish,n.time?.completed),!1;let i=[...o];i[c]=r,e.message[n.sessionID]=i}else e.message[n.sessionID]=[...o,n];return!0}case`message.removed`:{let n=t.properties,r=e.message[n.sessionID];if(r){let t=b(r,n.messageID);if(t>=0){let i=[...r];i.splice(t,1),e.message[n.sessionID]=i}}return delete e.part[n.messageID],!0}case`message.part.updated`:{let n=t.properties,r=n.part;if(wt.has(r.type))return je.reducer.partSkipped(r.messageID,r.id,r.type),!1;let i=r.messageID,a=n.sessionID??r.sessionID;if(!i)return!1;let o=!Vt(e,a,i),s=e.part[i];if(!s)return je.reducer.partUpdatedNoExistingParts(i,r.id,r.type),e.part[i]=[r],!o||{changed:!0,materialization:{type:`incomplete-session-snapshot`,reason:`missing-owning-message`,sessionID:a,messageID:i,partID:r.id}};let c=[...s],l=c.findIndex(e=>e.id===r.id);if(l>=0){let e=c[l];if(jt(e,r))return!1;let t=Ot(e,r);c[l]=t.length>0?{...r,__dedupeNextDeltaFields:t}:r}else{let e=r.type===`text`||r.type===`file`?c.findIndex(e=>e.type===r.type&&e.__yuriOptimistic===!0):-1;e>=0?c[e]=r:c.push(r)}return e.part[i]=c,!o||{changed:!0,materialization:{type:`incomplete-session-snapshot`,reason:`missing-owning-message`,sessionID:a,messageID:i,partID:r.id}}}case`message.part.removed`:{let n=t.properties,r=e.part[n.messageID];if(!r)return!1;let i=r.findIndex(e=>e.id===n.partID);if(i>=0){let t=[...r];return t.splice(i,1),t.length===0?delete e.part[n.messageID]:e.part[n.messageID]=t,!0}return!1}case`message.part.delta`:{let n=t.properties,r=e.part[n.messageID];if(!r)return je.reducer.partDeltaNoParts(n.messageID,n.partID),{changed:!1,materialization:{type:`incomplete-session-snapshot`,reason:`orphan-delta`,sessionID:n.sessionID,messageID:n.messageID,partID:n.partID}};let i=r.findIndex(e=>e.id===n.partID);if(i<0)return je.reducer.partDeltaNotFound(n.messageID,n.partID),{changed:!1,materialization:{type:`incomplete-session-snapshot`,reason:`missing-delta-part`,sessionID:n.sessionID,messageID:n.messageID,partID:n.partID}};let a=r[i],o=a[n.field],s=a.__dedupeNextDeltaFields??[],c=s.includes(n.field),l=[...r];return l[i]={...a,[n.field]:c?Dt(o,n.delta):(o??``)+n.delta,__dedupeNextDeltaFields:s.filter(e=>e!==n.field)},e.part[n.messageID]=l,!0}default:return nn(e,t)}}function T(e){return!e||typeof e!=`object`||Array.isArray(e)?null:e}function E(e){return typeof e==`string`&&e.length>0?e:void 0}function Ut(e,t,n){return`${e}:${t}:${n}`}function Wt(e){return typeof e?.created==`number`&&Number.isFinite(e.created)&&e.created>0?e.created:Date.now()}function D(e){let t=e.eventCreated;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:void 0}function Gt(e,t,n,r){let i=e.message[t],a=i?b(i,n):-1;if(a>=0&&i){let n=i[a],o=n.time?.created,s=!1,c={...n,time:{...n.time}};if((o===void 0||o<=0)&&typeof r?.created==`number`&&r.created>0&&(c.time={...c.time,created:r.created},s=!0),!Rt(n.agent)&&r?.agent&&(c.agent=r.agent,s=!0),!Rt(n.modelID)&&r?.modelID&&(c.modelID=r.modelID,s=!0),!Rt(n.providerID)&&r?.providerID&&(c.providerID=r.providerID,s=!0),!Rt(n.variant)&&r?.variant&&(c.variant=r.variant,s=!0),!n.model&&r?.model&&(c.model=r.model,s=!0),!s)return!1;let l=[...i];return l[a]=c,e.message[t]=l,!0}let o={id:n,sessionID:t,role:`assistant`,time:{created:Wt(r)},...r?.agent?{agent:r.agent}:{},...r?.modelID?{modelID:r.modelID}:{},...r?.providerID?{providerID:r.providerID}:{},...r?.variant?{variant:r.variant}:{},...r?.model?{model:r.model}:{}};return e.message[t]=i?[...i,o]:[o],!0}function Kt(e){let t=E(e.agent),n=T(e.model),r=n?E(n.id)??E(n.modelID):void 0,i=n?E(n.providerID):void 0,a=n?E(n.variant):void 0;return{...t?{agent:t}:{},...r?{modelID:r}:{},...i?{providerID:i}:{},...a?{variant:a}:{},...r||i||a?{model:{...i?{providerID:i}:{},...r?{modelID:r}:{},...a?{variant:a}:{}}}:{}}}function qt(e){let t=T(e);if(!t)return;let n=T(t.cache),r={...typeof t.input==`number`?{input:t.input}:{},...typeof t.output==`number`?{output:t.output}:{},...typeof t.reasoning==`number`?{reasoning:t.reasoning}:{},...n?{cache:{...typeof n.read==`number`?{read:n.read}:{},...typeof n.write==`number`?{write:n.write}:{}}}:{}};return Object.keys(r).length>0?r:void 0}function Jt(e,t,n,r){let i=e.message[t];if(!i)return e.message[t]=[r],!0;let a=b(i,n);if(a<0)return e.message[t]=[...i,r],!0;let o=i[a],s=zt(o,r);if(Bt(o,s)&&o.time?.created===s.time?.created)return!1;let c=[...i];return c[a]=s,e.message[t]=c,!0}function Yt(e,t,n){let r=e.message[t];if(!r)return;let i=b(r,n);if(i<0)return;let a=r[i]?.time?.created;return typeof a==`number`&&Number.isFinite(a)&&a>0?a:void 0}function Xt(e,t,n,r,i){let a=D(i);if(t===`session.step.started`)return Gt(e,n,r,{created:a,...Kt(i)});if(t===`session.step.streamed`)return a?(Gt(e,n,r,{created:a}),Jt(e,n,r,{id:r,sessionID:n,role:`assistant`,time:{created:Yt(e,n,r)??a,streamed:a}})):!1;if(t===`session.step.ended`){Gt(e,n,r,{created:a});let t=E(i.finish),o=qt(i.tokens),s=typeof i.cost==`number`&&Number.isFinite(i.cost)?i.cost:void 0;return Jt(e,n,r,{id:r,sessionID:n,role:`assistant`,time:{created:Yt(e,n,r)??Wt({created:a}),...a?{completed:a}:{}},...t?{finish:t}:{},...o?{tokens:o}:{},...s===void 0?{}:{cost:s}})}if(t===`session.step.failed`){Gt(e,n,r,{created:a});let t=T(i.error),o=qt(i.tokens),s=typeof i.cost==`number`&&Number.isFinite(i.cost)?i.cost:void 0;return Jt(e,n,r,{id:r,sessionID:n,role:`assistant`,time:{created:Yt(e,n,r)??Wt({created:a}),...a?{completed:a}:{}},finish:`error`,...t?{error:{type:E(t.type)??`error`,message:E(t.message)??``,...typeof t.status==`number`?{status:t.status}:{}}}:E(i.error)?{error:{type:`error`,message:E(i.error)}}:{},...o?{tokens:o}:{},...s===void 0?{}:{cost:s}})}return!1}function Zt(e){if(Array.isArray(e))return e.flatMap(e=>{let t=T(e);return t&&t.type===`text`&&typeof t.text==`string`?[t.text]:[]}).join(`
|
|
4
|
-
`)}function Qt(e,t,n,r){let i=Ut(n,t,r),a=e.findIndex(e=>e.id===i);return a>=0?a:e.map((e,t)=>({part:e,index:t})).filter(e=>e.part.type===t)[r]?.index??-1}function $t(e,t,n,r,i,a,o){Gt(e,t,n,o);let s=e.part[n]?[...e.part[n]]:[],c=Qt(s,r,n,i);if(c<0){let e={id:Ut(n,r,i),sessionID:t,messageID:n,type:r,text:``};s.push(e),c=s.length-1}let l=s[c],u=typeof a==`function`?a(l.text??``):a;return s[c]={...l,text:u},e.part[n]=s,!0}function en(e,t){return e.findIndex(e=>e.id===t||e.callID===t||e.type===`tool`&&e.id===t)}function O(e,t,n,r,i,a,o){Gt(e,t,n,o);let s=e.part[n]?[...e.part[n]]:[],c=en(s,r);return c<0&&(s.push({id:r,sessionID:t,messageID:n,type:`tool`,tool:Ge(i)??`tool`,callID:r,state:{status:`pending`,input:``,output:void 0,metadata:{}}}),c=s.length-1),s[c]=a(s[c]),e.part[n]=s,!0}function tn(e,t,n){return e.message[t]?.find(t=>e.part[t.id]?.some(e=>e.type===`text`&&e.shellAction?.shellID===n))?.id}function nn(e,t){let n=String(t.type);if(n.startsWith(`session.compaction.`))return Ct(e,t);let r=T(t.properties);if(!r)return!1;let i=E(r.sessionID);if(i&&(n===`session.shell.started`||n===`session.shell.ended`)){let a=T(r.shell),o=E(a?.id);if(!a||!o)return!1;let s=e.message[i]??[],c=tn(e,i,o),l=c?s.find(e=>e.id===c):void 0,u=l?.id??(n===`session.shell.started`?Ue(t.id):void 0);if(!u||n===`session.shell.started`&&l)return!1;let d=Ze(i,{id:u,type:`shell`,shellID:o,command:a.command,status:a.status,exit:a.exit,output:r.output,time:{created:l?.time.created??D(r),...n===`session.shell.ended`?{completed:D(r)}:{}}});return!d||l&&Mt(l,d.info)&&Mt(e.part[u],d.parts)?!1:(e.message[i]=l?s.map(e=>e.id===u?d.info:e):[...s,d.info],e.part[u]=d.parts,!0)}if(i&&n===`session.synthetic`){let n=Ue(t.id);if(!n)return!1;let a=Ze(i,{id:n,type:`synthetic`,text:r.text,description:r.description,metadata:r.metadata,time:{created:D(r)}});if(!a)return!1;let o=e.message[i]??[],s=o.find(e=>e.id===n);return s&&Mt(s,a.info)&&Mt(e.part[n],a.parts)?!1:(e.message[i]=s?o.map(e=>e.id===n?a.info:e):[...o,a.info],e.part[n]=a.parts,!0)}if(n===`session.revert.committed`)return!1;let a=E(r.assistantMessageID);if(!i||!a)return!1;let o=typeof r.ordinal==`number`?r.ordinal:0,s={created:D(r)};if(n===`session.step.started`||n===`session.step.streamed`||n===`session.step.ended`||n===`session.step.failed`)return Xt(e,n,i,a,r);if(n===`session.text.started`)return $t(e,i,a,`text`,o,``,s);if(n===`session.text.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?$t(e,i,a,`text`,o,e=>e+t,s):!1}if(n===`session.text.ended`)return $t(e,i,a,`text`,o,typeof r.text==`string`?r.text:``,s);if(n===`session.reasoning.started`)return $t(e,i,a,`reasoning`,o,``,s);if(n===`session.reasoning.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?$t(e,i,a,`reasoning`,o,e=>e+t,s):!1}if(n===`session.reasoning.ended`)return $t(e,i,a,`reasoning`,o,typeof r.text==`string`?r.text:``,s);let c=E(r.id);if(!c)return!1;let l=E(r.name);if(n===`session.tool.input.started`)return O(e,i,a,c,l,e=>e,s);if(n===`session.tool.input.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?O(e,i,a,c,l,e=>{let n=T(e.state)??{};if(E(n.status)&&n.status!==`pending`&&n.status!==`streaming`)return e;let r=typeof n.input==`string`?n.input+t:t;return{...e,state:{...n,status:`pending`,input:r}}},s):!1}if(n===`session.tool.input.ended`){let t=typeof r.text==`string`?r.text:``;return O(e,i,a,c,l,e=>{let n=T(e.state)??{};return{...e,state:{...n,input:t}}},s)}return n===`session.tool.called`?O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r);return{...e,state:{...t,status:`pending`,input:r.input??t.input??{},metadata:T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),start:n}}}}},s):n===`session.tool.progress`?O(e,i,a,c,l,e=>{let t=T(e.state)??{};return{...e,state:{...t,metadata:T(r.metadata)??T(t.metadata)??{}}}},s):n===`session.tool.success`?O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r);return{...e,state:{...t,status:`completed`,input:t.input??r.input??{},output:Zt(r.content),metadata:T(r.metadata)??T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),end:n}}}}},s):n===`session.tool.failed`&&O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r),i=T(r.error);return{...e,state:{...t,status:`error`,input:t.input??{},output:Zt(r.content),error:i?E(i.message)??E(r.error):E(r.error),metadata:T(r.metadata)??T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),end:n}}}}},s)}function rn(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function an(e){let t=e.id;return typeof t==`string`&&t.length>0?t:void 0}function k(e){return e.slim===!0}function on(e,t){if(!e||e.length===0||!t.some(e=>k(e)))return t;let n=new Map;for(let t of e){let e=an(t);e&&!k(t)&&n.set(e,t)}if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!k(e))return e;let t=an(e);if(!t)return e;let i=n.get(t);return i?(r=!0,i):e});return r?i:t}function sn(e,t){return e===t||e.length===t.length&&e.every((e,n)=>e===t[n])?t:e}function cn(e){let t=e.clientRole??e.role;return typeof t==`string`?t:``}function ln(e){return cn(e)!==`assistant`||!rn(e)}function un(e,t,n){if(!e||e.length===0)return t;let r=on(e,t);if(ln(n))return sn(r,e);let i=new Set;for(let e of r){let t=an(e);t&&i.add(t)}let a=new Map,o=[],s,c=0;for(let t of e){let e=an(t);if(e&&i.has(e)){s=e;continue}if(!e)continue;if(c+=1,!s){o.push(t);continue}let n=a.get(s);if(n){n.push(t);continue}a.set(s,[t])}if(c===0)return sn(r,e);let l=[...o];for(let e of r){l.push(e);let t=an(e);if(!t)continue;let n=a.get(t);n&&l.push(...n)}return sn(l,e)}var A=e=>Object.freeze(e),dn=Object.freeze({initial:A({id:`initial`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),prepend:A({id:`history`,onStale:`drop`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),recovery:A({id:`recovery`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),"reconcile-page":A({id:`reconcile-page`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`keep-unless-full`}),materialize:A({id:`materialize`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`})}),fn=A({id:`recovery-backfill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),pn=A({id:`send-gap-fill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),mn=dn.initial;function hn(e){let t=dn[e.purpose]??mn;return!e.stale||t.onStale===`drop`?t:fn}function gn(e,t){return e.preserveStreaming===`none`?!1:e.preserveStreaming===`all`||t===`assistant`}var _n=e=>structuredClone(e),vn=e=>({transport:e.transport,generation:e.generation,directory:e.directory,sessionID:e.sessionID});function yn(e){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID])}function bn(e,t){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID,t])}function xn(e){return JSON.stringify([e.transport,e.generation])}function Sn(e,t){return e.created===t.created?e.messageID<t.messageID?-1:+(e.messageID>t.messageID):e.created-t.created}function Cn(e){let t=e.time?.created;return{created:typeof t==`number`&&Number.isFinite(t)?t:0,messageID:e.id}}function wn(e){return ln(e)}function Tn(e){return k(e)?`slim`:`full`}function En(e){return e.some(e=>k(e))?`slim`:`full`}var Dn=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(Dn);let t=e,n={};for(let e of Object.keys(t).sort()){let r=t[e];r!==void 0&&(n[e]=Dn(r))}return n},On=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n};async function kn(e,t){let n=JSON.stringify(Dn({info:e,parts:t})),r=new TextEncoder().encode(n);return{hash:On(await crypto.subtle.digest(`SHA-256`,r)),byteSize:r.byteLength}}var An=e=>({scope:vn(e.scope),messageID:e.messageID,info:_n(e.info),parts:_n(e.parts),partCompleteness:e.partCompleteness.slice(),completeness:e.completeness,contentHash:e.contentHash,byteSize:e.byteSize,lastAccessedAt:e.lastAccessedAt,sortKey:{created:e.sortKey.created,messageID:e.sortKey.messageID}}),jn=e=>{let t=0;return()=>{let n=e();return t=n>t?n:t+1,t}},Mn=(e,t)=>{let n=t.slice().sort((e,t)=>Sn(e.sortKey,t.sortKey)).map(An);return{scope:vn(e),records:n,byteSize:n.reduce((e,t)=>e+t.byteSize,0)}},Nn=e=>_n(e),Pn=e=>vn(e),Fn=(e=Date.now)=>jn(e),In=e=>An(e),Ln=(e,t)=>Mn(e,t.slice());function Rn(e){return wn(e.info)?e.existing?.completeness===`full`&&e.incomingCompleteness===`slim`?{status:`skipped`,reason:`slim-downgrade`}:e.incomingHash!==void 0&&e.existing?.contentHash===e.incomingHash?{status:`skipped`,reason:`unchanged`}:{status:`written`}:{status:`skipped`,reason:`not-settled`}}var zn=[`text`,`output`],Bn={pending:1,started:2,running:3,completed:4,error:4};function Vn(e,t){return e.filter(e=>!!e?.id&&!t.has(e.type))}function Hn(e,t){if(!e||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.id!==i.id||JSON.stringify(r)!==JSON.stringify(i))return!1}return!0}function Un(e){let t=e.state?.time?.end;if(typeof t==`number`)return t;let n=e.time?.end;return typeof n==`number`?n:void 0}function Wn(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Gn(e){return Un(e)===void 0&&zn.some(t=>{let n=Wn(e,t);return typeof n==`string`&&n.length>0})}function Kn(e){let t=e.state;if(!(!t||typeof t!=`object`))return t}function qn(e){let t=Kn(e)?.status;return typeof t==`string`?t:void 0}function Jn(e){return e?Bn[e]??0:0}function Yn(e,t){if(Gn(e))return!0;if(Un(e)===void 0){if(e.type===`tool`){let n=qn(e);return n===`completed`||n===`error`?t:!0}return!0}return t}function Xn(e){let t=e.state?.time;if(!t||typeof t!=`object`)return;let n=typeof t.start==`number`?t.start:void 0,r=typeof t.end==`number`?t.end:void 0;if(n!==void 0||r!==void 0)return{start:n,end:r}}function Zn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0}function Qn(e,t,n){if(e.type!==`tool`||t.type!==`tool`)return n;let r=Kn(e);if(!r)return n;let i=Kn(n)??{},a=Kn(t)??{},o={...i},s=!1,c=qn(e),l=qn(t);Jn(c)>Jn(l)&&c&&(o={...o,status:c},s=!0);let u=r.input,d=a.input;Zn(u)&&!Zn(d)&&(o={...o,input:u},s=!0);let f=r.output,p=a.output;typeof f==`string`&&f.length>0?(typeof p!=`string`||p.length<f.length)&&(typeof p!=`string`||p.length===0||f.startsWith(p))&&(o={...o,output:f},s=!0):f!==void 0&&p===void 0&&(o={...o,output:f},s=!0);let m=r.metadata;return Zn(m)&&!Zn(a.metadata)&&(o={...o,metadata:m},s=!0),s?n===t?{...t,state:o}:{...n,state:o}:n}function $n(e,t){if(!e||Un(t)!==void 0)return t;let n=t;for(let r of zn){let i=Wn(e,r);if(!i)continue;let a=Wn(t,r);if(typeof a==`string`&&a.length>=i.length||typeof a==`string`&&a.length>0&&!i.startsWith(a))continue;n===t&&(n={...t});let o=n;o[r]=i}let r=Xn(e);if(r){let e=Xn(t),i=e?.start??r.start,a=e?.end??r.end;if(i!==e?.start||a!==e?.end){n===t&&(n={...t});let e=n;e.state={...n.state??{},time:{start:i,end:a}}}}return n=Qn(e,t,n),n}function er(e,t){if(!e||e.length===0||!t.some(e=>k(e)))return t;let n=new Map;for(let t of e)t.id&&!k(t)&&n.set(t.id,t);if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!k(e)||!e.id)return e;let t=n.get(e.id);return t?(r=!0,t):e});return r?i:t}function tr(e){return e.__yuriOptimistic===!0}function nr(e){return!!(e&&e.length>0&&e.some(tr))}function rr(e){return e.length===0||e.some(e=>k(e))}function ir(e,t,n,r,i,a){if(a===`keep-unless-full`&&e&&nr(e)&&rr(t))return e;let o=er(e,t);if(!e||e.length===0||!r)return o;let s=new Map(e.map(e=>[e.id,e])),c=o,l=!1;for(let e=0;e<o.length;e+=1){let t=o[e],n=$n(s.get(t.id),t);n!==t&&(l||(c=[...o]),c[e]=n,l=!0)}let u=new Set(o.map(e=>e.id)),d=o.some(e=>k(e)),f=e.filter(e=>!!e?.id&&!u.has(e.id)&&!n.has(e.type)&&(Yn(e,i)||d&&!k(e)));if(f.length===0)return c;let p=new Set(f.map(e=>e.id)),m=new Map,h=[];for(let t of e)p.has(t.id)?h.push(t):u.has(t.id)&&h.length>0&&(m.set(t.id,h),h=[]);let g=[];for(let e of c){for(let t of m.get(e.id)??[])g.push(t);g.push(e)}for(let e of h)g.push(e);return g}var ar=e=>e,or=e=>{let t=ar(e).finish;return typeof t==`string`&&t.length>0},sr=e=>typeof ar(e).time?.completed==`number`,cr=e=>!!ar(e).error;function lr(e,t){let n=ar(t),r=n.finish,i=n.time?.completed,a=n.time?.streamed,o=n.error,s=e.tokens,c=t.tokens,l=!or(e)&&typeof r==`string`&&r.length>0,u=!sr(e)&&typeof i==`number`,d=e.time.streamed===void 0&&typeof a==`number`&&Number.isFinite(a),f=!cr(e)&&!!o,p=!It(s)&&It(c);if(!l&&!u&&!d&&!f&&!p)return e;let m={...e};return l&&(m.finish=r),(u||d)&&(m.time={...ar(e).time,...u?{completed:i}:{},...d?{streamed:a}:{}}),f&&(m.error=o),p&&(m.tokens=c),m}function ur(e,t,n,r){if(t.length===0)return e;let i=new Map(t.map(e=>[e.id,e])),a=!1,o=[];for(let t of e){let e=n(t,i.get(t.id));e!==t&&(a=!0),o.push(e)}let s=new Set(e.map(e=>e.id));if(!t.some(e=>s.has(e.id)))return r===`prepend`?[...t,...o]:r===`by-created`?dr(o,t):[...o,...t];let c=new Map(t.map(e=>[e.id,e]));for(let e of o)c.set(e.id,e);let l=Me(e.map(e=>e.id),t.map(e=>e.id)).map(e=>c.get(e));return!a&&l.length===e.length&&l.every((t,n)=>t===e[n])?e:l}function dr(e,t){let n=e.slice();for(let e of t){let t=Cn(e),r=n.length;for(let e=0;e<n.length;e+=1)if(Sn(t,Cn(n[e]))<0){r=e;break}n.splice(r,0,e)}return n}function fr(e,t,n){return ur(e,t,(e,t)=>t?lr(e,t):e,n)}function pr(e,t,n){return ur(e,t,(e,t)=>!t||JSON.stringify(e)===JSON.stringify(t)?e:zt(e,t),n)}function mr(e,t,n,r={}){let i=r.skipPartTypes??new Set,a=r.merge??mn,o=r.placeUnanchoredNewMessages??`append`,s=n.filter(e=>!!e?.info?.id),c=s.map(e=>e.info),l=e.message[t],u=l??[],d=a.messages===`upsert`?pr(u,c,o):fr(u,c,o),f=d!==u||l===void 0&&s.length===0,p=!1,m={...e.part},h=a.parts===`skip-existing`;for(let e of s){let t=e.info.id;if(h&&m[t])continue;let n=e.info.role===`assistant`,r=m[t],o=ir(r,Vn(e.parts??[],i),i,gn(a,e.info.role),rn(e.info),a.protectOptimistic);(r?Hn(r,o):o.length===0&&!n)||o.length===0&&!n||(m[t]=o,p=!0)}return{message:f?{...e.message,[t]:d}:e.message,part:p?m:e.part,messages:d,messagesChanged:f,partsChanged:p}}function hr(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function gr(e){let t=e.messages;if(!t)return{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]};let n=t.length>0?t[t.length-1]?.id:void 0,r=[];for(let i of t)i.role===`assistant`&&(e.parts[i.id]||i.id===n&&hr(i)||r.push(i.id));return{hasMessages:!0,renderable:r.length===0,missingPartMessageIDs:r}}var _r=(e,t)=>e<t?-1:+(e>t);function vr(e){return e.filter(e=>!!e?.id)}function yr(e,t){if(t.length===0)return{...e,confirmed:[]};let n=[...e.session],r=new Map(e.part.map(e=>[e.id,vr(e.part)])),i=[];for(let e of t){if(n.findIndex(t=>t.id===e.message.id)<0){n.push(e.message),r.set(e.message.id,vr(e.parts));continue}let t=r.get(e.message.id);if(t&&t.length>0){i.push(e.message.id);continue}r.set(e.message.id,vr(e.parts))}return{cursor:e.cursor,complete:e.complete,session:n,part:[...r.entries()].sort((e,t)=>_r(e[0],t[0])).map(([e,t])=>({id:e,part:t})),confirmed:i}}var br={kind:`unknown`,loadedTurns:0},xr=3e4,Sr=12e5,Cr={project:``,projectMeta:void 0,icon:void 0,provider:{all:[],connected:[],default:{}},config:{},path:{state:``,config:``,worktree:``,directory:``,home:``},status:`loading`,agent:[],command:[],session:[],sessionTotal:0,session_status:{},session_status_observed_at:{},session_status_event_at:{},session_status_event_sequence:{},session_interrupt_acknowledged_at:{},session_execution_version:{},session_status_snapshot_at:void 0,session_error_at:{},session_execution_recovery:{},session_diff:{},todo:{},permission:{},question:{},lsp:[],vcs:void 0,limit:20},wr={ready:!1,path:{state:``,config:``,worktree:``,directory:``,home:``},projects:[],providers:{all:[],connected:[],default:{}},providerAuth:{},config:{},reload:void 0,sessionTodo:{}};function Tr(e,t){return e===void 0||t===void 0?!1:t>e}var Er=class extends Error{};function Dr(e,t,n){if(n===`reconcile-page`)return e??br;let r=0;typeof t.turnCount==`number`&&Number.isFinite(t.turnCount)?r=Math.max(0,Math.floor(t.turnCount)):typeof t.requestedTurnLimit==`number`&&Number.isFinite(t.requestedTurnLimit)?r=Math.max(0,Math.floor(t.requestedTurnLimit)):t.records.length>0&&(r=1);let i=e?.loadedTurns??0,a=n===`prepend`?i+r:r;if(t.complete)return{kind:`exhausted`,loadedTurns:a};let o=typeof t.cursor==`string`&&t.cursor.length>0?t.cursor:void 0;if(!o)throw new Er(`session message page: complete=false requires non-empty cursor`);if(n===`prepend`&&e?.kind===`has-more`&&e.cursor===o)throw new Er(`session message page: prepend returned the same cursor without progress`);if(t.records.length===0&&(n!==`prepend`||e?.kind!==`has-more`||e.cursor===o)&&n!==`initial`)throw new Er(`session message page: complete=false with zero records makes no progress`);return{kind:`has-more`,cursor:o,loadedTurns:a}}function Or(e,t){return!e||!t?e===t:e.kind!==t.kind||e.loadedTurns!==t.loadedTurns?!1:e.kind===`has-more`&&t.kind===`has-more`?e.cursor===t.cursor:!0}function kr(e,t,n,r){let i=Tr(r.capturedRevision,r.liveRevision),a=hn({purpose:r.purpose,stale:i}),o=e.session_history_boundary?.[t];if(!n.ok)return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:e.message[t]??[],boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[],error:n.error};if(i&&a.onStale===`drop`){let n=e.message[t]??[];if(n.length>0)return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:n,boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[]}}let s=r.optimistic??[],c=yr({session:n.records.map(e=>e.info),part:n.records.map(e=>({id:e.info.id,part:e.parts??[]})),cursor:n.cursor,complete:n.complete},s),l=mr(e,t,c.session.map(e=>({info:e,parts:c.part.find(t=>t.id===e.id)?.part??[]})),{skipPartTypes:r.skipPartTypes,merge:a,placeUnanchoredNewMessages:r.purpose===`prepend`?`prepend`:r.purpose===`reconcile-page`?`by-created`:`append`}),u;try{u=Dr(o,{ok:!0,records:n.records,cursor:c.cursor,complete:c.complete,turnCount:n.turnCount,requestedTurnLimit:n.requestedTurnLimit},r.purpose)}catch(n){if(!(n instanceof Er))throw n;return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:e.message[t]??[],boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[],error:n.message}}let d=!Or(o,u),f=l.messagesChanged,p=l.partsChanged,m=f||p||d,h=[];c.confirmed.length>0&&h.push({type:`clear-optimistic`,messageIDs:c.confirmed});let g=d||!o?u:o;return{applied:!0,merge:a,changed:m,messagesChanged:f,partsChanged:p,boundaryChanged:d,message:l.message,part:l.part,messages:l.messages,boundary:g,meta:{limit:g.loadedTurns,cursor:g.kind===`has-more`?g.cursor:void 0,complete:g.kind===`exhausted`},confirmedOptimisticIDs:c.confirmed,commands:h}}var Ar=new Set([`tool`,`reasoning`,`file`,`text`]),jr=new Set([`tool`,`reasoning`,`file`]);function Mr(e){return e.some(e=>k(e)&&Ar.has(e.type))}function Nr(e,t){let n=!1,r=!1;for(let t of e)jr.has(t.type)&&(n=!0,k(t)&&(r=!0));return n?r?!0:t?rn(t):!1:!1}var Pr=e=>{if(!e)return``;let t=e.clientRole??e.role;return typeof t==`string`?t:``};function Fr(e,t){return He(e,t)}function Ir(e){let t=0;for(let n of e.messageOrder)Fr(e.messagesByID[n],e.partsByMessageID[n])&&(t+=1);return t}var Lr=(e,t)=>{let n=e.messageOrder.lastIndexOf(t);if(n<0)return[];let r=[];for(let i=n+1;i<e.messageOrder.length;i+=1){let n=e.messageOrder[i],a=e.messagesByID[n];if(!a)continue;if(Fr(a,e.partsByMessageID[n]))break;if(Pr(a)!==`assistant`)continue;let o=a.parentID;typeof o==`string`&&o.length>0&&o!==t||r.push(a)}return r},Rr=(e,t)=>rn(e)?!0:Array.isArray(t)&&t.length>0;function zr(e){let t;for(let n=e.messageOrder.length-1;n>=0;--n){let r=e.messageOrder[n];if(Fr(e.messagesByID[r],e.partsByMessageID[r])){t=r;break}}return t?Lr(e,t).some(t=>Rr(t,e.partsByMessageID[t.id])):!1}function Br(e){return e.materializeActive?`p2`:e.prependActive||e.earlierHistoryLoaded?`p1`:e.p0Satisfied?`p0`:`idle`}var Vr=new Set([`stop`,`length`]);function Hr(e){let t=e.messageOrder[e.messageOrder.length-1];if(!t)return!1;let n=e.messagesByID[t];if(!n||Pr(n)!==`assistant`||n.error)return!1;let r=n.finish;return typeof r!=`string`||!Vr.has(r)?!1:typeof n.time?.completed!=`number`||r===`stop`&&!It(n.tokens)}function Ur(e,t){return t.kind===`has-more`?{sessionID:e,boundary:t,hasPreviousPage:!0,isComplete:!1,cursor:t.cursor,loadedTurns:t.loadedTurns}:t.kind===`exhausted`?{sessionID:e,boundary:t,hasPreviousPage:!1,isComplete:!0,cursor:null,loadedTurns:t.loadedTurns}:{sessionID:e,boundary:t,hasPreviousPage:!1,isComplete:!1,cursor:null,loadedTurns:t.loadedTurns}}function Wr(e){let t={},n={},r=[];for(let i of e.messages){if(!i?.id)continue;r.push(i.id),t[i.id]=i;let a=e.parts[i.id];a&&(n[i.id]=a)}return{sessionID:e.sessionID,messageOrder:r,messagesByID:t,partsByMessageID:n,boundary:e.boundary,liveRevision:e.liveRevision??0}}var Gr=`message.updated,message.removed,message.part.updated,message.part.removed,message.part.delta,session.step.started,session.step.streamed,session.shell.started,session.shell.ended,session.step.ended,session.step.failed,session.text.started,session.text.delta,session.text.ended,session.reasoning.started,session.reasoning.delta,session.reasoning.ended,session.tool.input.started,session.tool.input.delta,session.tool.input.ended,session.tool.called,session.tool.progress,session.tool.success,session.tool.failed,session.compaction.started,session.compaction.delta,session.compaction.ended,session.compaction.failed,session.synthetic,session.revert.committed`.split(`,`);function Kr(e){return Gr.includes(e)}function j(e){return e.trim()}function qr(e){return`${j(e.directory)}\n${e.sessionID}`}function Jr(e,t){return e.session_history_boundary?.[t]??br}function Yr(e){return e.filter(e=>!!e?.id)}function Xr(e,t){return e.kind!==t.kind||e.loadedTurns!==t.loadedTurns?!1:e.kind===`has-more`&&t.kind===`has-more`?e.cursor===t.cursor:!0}function Zr(e,t,n){n.applied&&e.setState(e=>{let r={};if(n.messagesChanged&&(r.message=n.message),n.partsChanged&&(r.part=n.part),n.boundary&&(n.boundaryChanged||!e.session_history_boundary?.[t]))r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary};else if(n.boundary&&n.boundaryChanged===!1){let i=e.session_history_boundary?.[t];(!i||!Xr(i,n.boundary))&&(r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary})}return!r.message&&!r.part&&!r.session_history_boundary&&n.boundary&&(r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary}),!r.message&&!r.part&&!r.session_history_boundary?{}:r})}function Qr(e,t,n){let r=e.getState(),i=n.page,a=kr(r,t,{ok:!0,records:i.records.map(e=>({info:e.info,parts:e.parts?[...e.parts]:[]})),cursor:i.cursor,complete:i.complete,turnCount:i.turnCount,requestedTurnLimit:i.requestedTurnLimit},{purpose:n.purpose,skipPartTypes:n.skipPartTypes,optimistic:n.optimistic?n.optimistic.map(e=>({message:e.message,parts:[...e.parts]})):void 0,capturedRevision:n.capturedLiveRevision,liveRevision:n.liveRevision});return a.applied?(Zr(e,t,a),{applied:!0,changed:a.changed,boundary:a.boundary,meta:a.meta,confirmedOptimisticIDs:a.confirmedOptimisticIDs}):{applied:!1,changed:!1,error:a.error}}function $r(e,t){if(t.length===0)return{applied:!1,changed:!1};let n=e.getState(),r={message:{...n.message??{}},part:{...n.part??{}}},i=!1,a=!1,o;for(let e of t){if(!Kr(e.type))continue;i=!0;let t=Ht(r,e),n=typeof t==`boolean`?t:t.changed,s=typeof t==`boolean`?void 0:t.materialization;s&&!o&&(o=s),n&&(a=!0)}return i?a?(e.setState({message:r.message,part:r.part}),{applied:!0,changed:!0,...o?{materialization:o}:{}}):{applied:!0,changed:!1,...o?{materialization:o}:{}}:{applied:!1,changed:!1}}function ei(e,t){return $r(e,[t.event])}function ti(e,t){return $r(e,t.events)}function ni(e,t,n){if(n.records.length===0)return{applied:!1,changed:!1};let r=e.getState(),i=mr({message:r.message??{},part:r.part??{}},t,n.records.map(e=>({info:e.info,parts:e.parts?[...e.parts]:[]})),{skipPartTypes:n.skipPartTypes,merge:n.merge});return!i.messagesChanged&&!i.partsChanged?{applied:!0,changed:!1}:(e.setState({...i.messagesChanged?{message:i.message}:{},...i.partsChanged?{part:i.part}:{}}),{applied:!0,changed:!0})}function ri(e,t,n){let r=e.getState(),i=r.message?.[t],a=r.part?.[n]!==void 0;if(!i&&!a)return{applied:!0,changed:!1};let o={...r.message??{}},s=!1;if(i){let e=[...i],r=e.findIndex(e=>e.id===n);r>=0&&(e.splice(r,1),o[t]=e,s=!0)}let c={...r.part??{}},l=!1;return c[n]!==void 0&&(delete c[n],l=!0),!s&&!l?{applied:!0,changed:!1}:(e.setState({...s?{message:o}:{},...l?{part:c}:{}}),{applied:!0,changed:!0})}function ii(e,t,n,r,i){r.setOptimisticShadow?.({directory:i,sessionID:t,message:n.message,parts:n.parts});let a=e.getState(),o={...a.message??{}},s={...a.part??{}},c=o[t]?[...o[t]]:[];return c.some(e=>e.id===n.message.id)||c.push(n.message),o[t]=c,s[n.message.id]=Yr(n.parts),e.setState({message:o,part:s}),{applied:!0,changed:!0}}function ai(e,t,n,r,i){r.clearOptimisticShadow?.({directory:i,sessionID:t,messageID:n});let a=e.getState(),o={...a.message??{}},s={...a.part??{}},c=!1,l=o[t];if(l){let e=[...l],r=e.findIndex(e=>e.id===n);r>=0&&(e.splice(r,1),o[t]=e,c=!0)}return s[n]!==void 0&&(delete s[n],c=!0),c&&e.setState({message:o,part:s}),{applied:!0,changed:c}}function oi(e,t,n,r){return n.clearOptimisticShadow?.({directory:r,sessionID:e,messageID:t}),{applied:!0,changed:!1}}function si(e,t){let n=e.getState(),r=n.message?.[t],i=n.session_history_boundary?.[t],a=!!(r&&r.length>0),o=i!==void 0,s=new Set;if(r)for(let e of r)e?.id&&s.add(e.id);let c=!1,l={...n.part??{}};for(let e of s)l[e]!==void 0&&(delete l[e],c=!0);for(let[e,n]of Object.entries(l))s.has(e)||n?.some(e=>e.sessionID===t)&&(delete l[e],c=!0);if(!a&&!o&&!c)return!1;let u={...n.message??{}};delete u[t];let d={...n.session_history_boundary??{}};return delete d[t],e.setState({message:u,part:l,session_history_boundary:d}),!0}function ci(e,t,n){let r=si(e,t);if(!n.page)return{applied:!0,changed:r};let i=Qr(e,t,{type:`http-page`,purpose:`initial`,page:n.page,capturedLiveRevision:n.capturedLiveRevision,liveRevision:n.liveRevision,skipPartTypes:n.skipPartTypes});return{...i,changed:r||i.changed,applied:i.applied||r}}function li(e){let t=new Map,n=new Map,r=r=>{let i=qr(r);if(n.has(i))return;let a=j(r.directory),o=e.getStore(a),s=r.sessionID,c=o.getState().message?.[s],l=Jr(o.getState(),s),u=new Map;for(let e of c??[])u.set(e.id,o.getState().part?.[e.id]);let d=o.subscribe(e=>{let n=e.message?.[s],a=Jr(e,s),o=!1,d=new Map;for(let t of n??[]){let n=e.part?.[t.id];d.set(t.id,n),u.get(t.id)!==n&&(o=!0)}u.size!==d.size&&(o=!0);let f=n!==c,p=Xr(a,l);if(c=n,l=a,u=d,!f&&!o&&p)return;let m=t.get(i);if(!(!m||m.size===0))for(let e of m)e(r)});n.set(i,d)},i=e=>{let r=t.get(e);if(r&&r.size>0)return;let i=n.get(e);i&&(i(),n.delete(e)),t.delete(e)},a={getTranscript(t){let n=j(t.directory),r=e.getStore(n).getState(),i=t.sessionID,a=r.message?.[i]??[],o=e.getLiveRevision?.(n,i)??0;return Wr({sessionID:i,messages:a,parts:r.part??{},boundary:Jr(r,i),liveRevision:o})},getPagination(t){let n=j(t.directory),r=e.getStore(n).getState();return Ur(t.sessionID,Jr(r,t.sessionID))},getRequestState(t){let n=j(t.directory);return e.getRequestState?.(n,t.sessionID)??{sessionID:t.sessionID,status:`idle`}},getHydrationState(e){let t=a.getTranscript(e),n=zr(t);return{sessionID:e.sessionID,p0Satisfied:n,phase:Br({p0Satisfied:n,earlierHistoryLoaded:Ir(t)>1})}},getMessage(e,t){return a.getTranscript(e).messagesByID[t]},getParts(t,n){let r=j(t.directory);return e.getStore(r).getState().part?.[n]??[]},hasSession(t){let n=j(t.directory),r=e.getStore(n).getState().message;return r?Object.prototype.hasOwnProperty.call(r,t.sessionID):!1},apply(t,n){let r=j(t.directory),i=e.getStore(r),a=t.sessionID;switch(n.type){case`http-page`:return Qr(i,a,n);case`sse-event`:return ei(i,n);case`sse-event-batch`:return ti(i,n);case`optimistic-add`:return ii(i,a,n,e,r);case`optimistic-confirm`:return oi(a,n.messageID,e,r);case`optimistic-remove`:return ai(i,a,n.messageID,e,r);case`reset`:return ci(i,a,n);case`materialize-snapshots`:return ni(i,a,n);case`remove-message`:return ri(i,a,n.messageID);case`revert-committed`:{let e=i.getState(),t=e.message?.[a];if(!Array.isArray(t)||t.length===0)return{applied:!0,changed:!1};let r=t.findIndex(e=>e.id===n.to);if(r<0)return{applied:!0,changed:!1};let o=t.slice(r),s=t.slice(0,r),c={...e.message??{}};c[a]=s;let l={...e.part??{}};for(let e of o)delete l[e.id];return i.setState({message:c,part:l}),{applied:!0,changed:o.length>0}}default:return{applied:!1,changed:!1}}},subscribe(e,n){let a=qr(e),o=t.get(a);return o||(o=new Set,t.set(a,o)),o.add(n),r(e),()=>{let e=t.get(a);e&&(e.delete(n),i(a))}}};return a}var ui=new Set,di=new Set;function fi(e,t){return`${e}\n${t}`}function pi(){for(let e of di)e()}function mi(e,t){!e||!t||(ui.add(fi(e,t)),pi())}function hi(e,t){!e||!t||ui.delete(fi(e,t))&&pi()}function gi(e,t){if(!e)return!1;if(t)return ui.has(fi(t,e));let n=`\n${e}`;for(let e of ui)if(e.endsWith(n))return!0;return!1}function _i(e){return di.add(e),()=>{di.delete(e)}}var vi=[],yi=new Map,bi=new Map,xi=0,Si=()=>{let e=vi.findIndex(e=>e.priority===`user`);if(e>=0){let[t]=vi.splice(e,1);return t}return vi.shift()},Ci=()=>{for(;xi<4;){let e=Si();if(!e)return;yi.delete(e.key),xi+=1,Promise.resolve().then(()=>e.run()).then(t=>{e.resolve(t)},t=>{e.reject(t)}).finally(()=>{--xi,bi.delete(e.key),Ci()})}};function wi(e,t,n){let r=n?.priority??`background`,i=bi.get(e);if(i){let t=yi.get(e);return t&&r===`user`&&t.priority!==`user`&&(t.priority=`user`),i}let a,o,s=new Promise((e,t)=>{a=e,o=t}),c={key:e,priority:r,run:()=>t(),resolve:e=>{a(e)},reject:o};return vi.push(c),yi.set(e,c),bi.set(e,s),Ci(),s}var Ti=null,Ei=0,Di=new Set;function Oi(){Ei+=1;for(let e of Di)e()}function ki(e){return e}function Ai(e){return Di.add(e),()=>{Di.delete(e)}}function ji(){return Ei}function Mi(e){return Ti?.repository===e?e:(Ti={kind:`query`,repository:e},Oi(),e)}function Ni(){Ti&&(Ti=null,Oi())}function M(){return Ti?.repository??null}function Pi(){let e=M();if(!e)throw Error(`TranscriptRepository is not bound — SyncProvider must mount first`);return e}function Fi(e,t){let n=M();if(n)return n;let r=ki(t);return li({getStore:e=>r})}function N(e,t,n){return{directory:e.trim(),sessionID:t,...n?.transport===void 0?{}:{transport:n.transport},...n?.generation===void 0?{}:{generation:n.generation}}}function Ii(e){try{let t=M(),n=o(),r=s();return t?.getCacheBudget?.().listCanonicalScopesForSession(e,{transport:n,generation:r})?.map(e=>N(e.directory,e.sessionID,{transport:e.transport,generation:e.generation}))??[]}catch{return[]}}function Li(e,t){let n=M();return n?n.apply(e,t):null}async function Ri(e,t,n){let r=Pi();if(typeof r.fetchPreviousPage!=`function`)throw Error(`TranscriptRepository does not support fetchPreviousPage`);await r.fetchPreviousPage(N(e,t),n)}async function zi(e,t){let n=Pi();if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support ensureInitial`);await n.ensureInitial(N(e,t))}async function Bi(e,t){let n=Pi(),r=N(e,t);if(typeof n.destructiveReset==`function`){await n.destructiveReset(r);return}if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support retryInitial`);await n.ensureInitial(r)}async function Vi(e,t,n){let r=Pi();if(typeof r.refreshFromAuthority!=`function`)throw Error(`TranscriptRepository does not support refreshFromAuthority`);if(n?.background){await r.refreshFromAuthority(N(e,t));return}mi(e,t);try{await r.refreshFromAuthority(N(e,t))}finally{hi(e,t)}}async function Hi(e,t,n,r){let i=Pi();if(typeof i.materializeMessage!=`function`)throw Error(`TranscriptRepository does not support materializeMessage`);let a=N(e,t);await wi(`${e}\n${t}\n${n}`,()=>i.materializeMessage(a,n),{priority:r?.priority??`background`})}function Ui(e,t,n){let r=M();return!r||typeof r.getMessageMaterializationState!=`function`?{sessionID:t,messageID:n,status:`idle`}:r.getMessageMaterializationState(N(e,t),n)}function Wi(e,t){M()?.purgeSession?.(N(e,t))}var P=null;function Gi(e){P&&P!==e&&P.cancelAll(`reregister`),P=e}function Ki(e){P?.captureCheckpoints(e)}function qi(e){P?.onCompensation(e)}async function Ji(e){return P?P.ensureOnObserve(e):null}function Yi(e){P?.cancelAll(e)}var Xi=e=>typeof e==`number`&&Number.isFinite(e)?e:0,Zi=e=>Xi(e.input)+Xi(e.output)+Xi(e.reasoning)+Xi(e.cache?.read)+Xi(e.cache?.write),Qi=e=>e?.type===`compaction`,$i=e=>!!e&&e.some(Qi),ea=(e,t)=>e.clientRole===`compaction`||e.type===`compaction`||$i(t),ta=(e,t)=>{for(let n=e.length-1;n>=0;--n){let r=e[n],i=r.id?t(r.id):void 0;if(ea(r,i)){let e=i?.find(Qi)?.status??r.status;if(e===`running`||e===`failed`)continue;return{compacted:!0}}if(r.role!==`assistant`)continue;let a=r.tokens;if(!a)continue;let o=Zi(a);if(o>0)return{messageId:r.id??``,totalTokens:o,tokens:a}}return null},na=(e,t,n)=>{if(!e)return null;let r=`compacted`in e,i=r?0:e.totalTokens;return{...r?{pending:!0}:{},totalTokens:i,percentage:t>0?Math.round(i/t*100):0,contextLimit:t||0,outputLimit:n||void 0,normalizedOutput:!r&&n>0?Math.round(Xi(e.tokens.output)/n*100):void 0,thresholdLimit:t>0?t:2e5,lastMessageId:r?void 0:e.messageId}},ra=[],ia=[],aa={sessionID:``,messageOrder:[],messagesByID:{},partsByMessageID:{},boundary:br,liveRevision:0};Ur(``,br);var oa={sessionID:``,phase:`idle`,p0Satisfied:!1};function F(e,t){return Fi(e,t)}var sa=new Set;function ca(e,t){return`${e}\n${t}`}function la(e,t){if(!t)return;let n=ca(e,t);sa.has(n)||(sa.add(n),Ji(N(e,t)).catch(()=>{}).finally(()=>{sa.delete(n)}))}function ua(e,t){if(e&&t){sa.delete(ca(e,t));return}sa.clear()}function da(e,t,n,r,i=Object.is,a){let o=(0,y.useRef)(r);o.current=r;let s=(0,y.useRef)(i);s.current=i;let c=(0,y.useRef)(void 0),l=a?.enabled!==!1,u=(0,y.useCallback)(()=>{if(!e||!l){let e=o.current(aa);return(c.current===void 0||!s.current(c.current,e))&&(c.current=e),c.current}let r=F(t,n).getTranscript(N(t,e)),i=o.current(r);return(c.current===void 0||!s.current(c.current,i))&&(c.current=i),c.current},[t,l,e,n]),d=(0,y.useCallback)(r=>{if(!e||!l)return()=>void 0;la(t,e);let i=F(t,n).subscribe(N(t,e),()=>{r()}),a=Ai(()=>{i(),c.current=void 0,ua(t,e),la(t,e),i=F(t,n).subscribe(N(t,e),()=>{r()}),r()});return()=>{a(),i()}},[t,l,e,n]);return y.useSyncExternalStore(d,u,u)}function fa(e,t,n,r,i,a){return da(e,t,n,r,i===void 0?Object.is:i,a)}function pa(e,t){if(e.messageOrder.length===0)return ra;if(t&&t.length>0){let n=!0,r=0;for(let i of e.messageOrder){let a=e.messagesByID[i];if(a){if(r>=t.length||t[r]!==a){n=!1;break}r+=1}}if(n&&r===t.length)return t}let n=[];for(let t of e.messageOrder){let r=e.messagesByID[t];r&&n.push(r)}return n}function ma(e,t){return e.messageOrder.length===0?t?.resolved===!0?gr({messages:ra,parts:e.partsByMessageID}):{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]}:gr({messages:pa(e),parts:e.partsByMessageID})}function ha(e,t,n,r){let i=(0,Ce.c)(4),a;return i[0]!==t||i[1]!==e||i[2]!==n?(a=r=>{if(!e)return{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]};let i=F(t,n).hasSession?.(N(t,e));return ma(r,{resolved:i===!0||void 0})},i[0]=t,i[1]=e,i[2]=n,i[3]=a):a=i[3],da(e,t,n,a,ga,r)}function ga(e,t){return e.hasMessages===t.hasMessages&&e.renderable===t.renderable&&e.missingPartMessageIDs.length===t.missingPartMessageIDs.length&&e.missingPartMessageIDs.every((e,n)=>e===t.missingPartMessageIDs[n])}function _a(e,t,n,r,i){let a=(0,Ce.c)(3),o;return a[0]!==r||a[1]!==i?(o=e=>na(ta(pa(e),t=>e.partsByMessageID[t]),r,i),a[0]=r,a[1]=i,a[2]=o):o=a[2],da(e,t,n,o,va)}function va(e,t){return e===t||!!(e&&t&&e.pending===t.pending&&e.totalTokens===t.totalTokens&&e.percentage===t.percentage&&e.contextLimit===t.contextLimit&&e.outputLimit===t.outputLimit&&e.normalizedOutput===t.normalizedOutput&&e.lastMessageId===t.lastMessageId)}function ya(e,t,n,r){return da(e,t,n,xa,ba,r)}function ba(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function xa(e){return pa(e)}function Sa(e,t){if(e===t)return!0;if(e.sessionID!==t.sessionID||e.liveRevision!==t.liveRevision||e.boundary.kind!==t.boundary.kind||e.boundary.loadedTurns!==t.boundary.loadedTurns||e.boundary.kind===`has-more`&&t.boundary.kind===`has-more`&&e.boundary.cursor!==t.boundary.cursor||e.messageOrder.length!==t.messageOrder.length)return!1;for(let n=0;n<e.messageOrder.length;n+=1){let r=e.messageOrder[n];if(r!==t.messageOrder[n]||e.messagesByID[r]!==t.messagesByID[r]||e.partsByMessageID[r]!==t.partsByMessageID[r])return!1}return!0}function Ca(e,t,n,r){return da(e,t,n,wa,Sa,r)}function wa(e){return e}function Ta(e,t,n,r){if(e.length===0)return()=>void 0;let i=[],a=()=>{for(let e of i)e();i=[]},o=()=>{let r=new Set;for(let a of e){let e=`${a.directory}\n${a.sessionID}`;if(r.has(e))continue;r.add(e);let o=M();if(o){i.push(o.subscribe(N(a.directory,a.sessionID),t));continue}let s=n?.(a.directory);if(!s)continue;let c=Fi(a.directory,s);i.push(c.subscribe(N(a.directory,a.sessionID),t))}},s=()=>{a(),o(),t()};o();let c=Ai(s),l=r?.subscribeRebuild?.(s);return()=>{l?.(),c(),a()}}function Ea(e,t){return e.length===0?``:e.map(e=>{let n=Ra(e.directory,e.sessionID,t?.(e.directory)),r=n[n.length-1];return`${e.sessionID}:${r?.id??``}:${r?.role??``}:${r?.time?.completed??``}`}).join(`\0`)}function Da(e,t,n){return da(e,t,n,Oa)}function Oa(e){return e.messageOrder.length}function ka(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(!1),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current=!1,!1;let r=F(t,n),a=r.hasSession?.(N(t,e))??r.getTranscript(N(t,e)).messageOrder.length>0;return i.current=a,i.current},r[0]=t,r[1]=e,r[2]=n,r[3]=a):a=r[3];let o=a,s;r[4]!==t||r[5]!==e||r[6]!==n?(s=r=>e?F(t,n).subscribe(N(t,e),()=>{r()}):Aa,r[4]=t,r[5]=e,r[6]=n,r[7]=s):s=r[7];let c=s;return y.useSyncExternalStore(c,o,o)}function Aa(){}function ja(e,t,n,r){let i=(0,Ce.c)(10),a=(0,y.useRef)(void 0),o;i[0]!==t||i[1]!==e||i[2]!==r||i[3]!==n?(o=()=>{if(!e)return a.current=ia,ia;let i=F(t,n),o=r||e,s=i.getParts(N(t,o),e),c=s.length===0?ia:s;if(a.current===void 0||a.current!==c){if(a.current&&a.current.length===c.length&&a.current.every((e,t)=>e===c[t]))return a.current;a.current=c}return a.current},i[0]=t,i[1]=e,i[2]=r,i[3]=n,i[4]=o):o=i[4];let s=o,c;i[5]!==t||i[6]!==e||i[7]!==r||i[8]!==n?(c=i=>{if(!e)return Na;let a=F(t,n);return r?a.subscribe(N(t,r),()=>{i()}):Ma},i[5]=t,i[6]=e,i[7]=r,i[8]=n,i[9]=c):c=i[9];let l=c;return y.useSyncExternalStore(l,s,s)}function Ma(){}function Na(){}function Pa(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(oa),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current!==oa&&(i.current=oa),i.current;let r=F(t,n).getHydrationState?.(N(t,e))??{sessionID:e,phase:`idle`,p0Satisfied:!1},a=i.current;return a.sessionID===r.sessionID&&a.phase===r.phase&&a.p0Satisfied===r.p0Satisfied?a:(i.current=r,r)},r[0]=t,r[1]=e,r[2]=n,r[3]=a):a=r[3];let o=a,s;r[4]!==t||r[5]!==e||r[6]!==n?(s=r=>{if(!e)return Fa;la(t,e);let a=F(t,n).subscribe(N(t,e),()=>{r()}),o=Ai(()=>{a(),i.current=oa,ua(t,e),la(t,e),a=F(t,n).subscribe(N(t,e),()=>{r()}),r()});return()=>{o(),a()}},r[4]=t,r[5]=e,r[6]=n,r[7]=s):s=r[7];let c=s;return y.useSyncExternalStore(c,o,o)}function Fa(){}function Ia(e,t,n){let r=(0,Ce.c)(2),i;return r[0]===e?i=r[1]:(i=t=>Ur(e,t.boundary),r[0]=e,r[1]=i),da(e,t,n,i,La)}function La(e,t){return e.sessionID===t.sessionID&&e.hasPreviousPage===t.hasPreviousPage&&e.isComplete===t.isComplete&&e.cursor===t.cursor&&e.loadedTurns===t.loadedTurns&&e.boundary.kind===t.boundary.kind&&e.boundary.loadedTurns===t.boundary.loadedTurns&&(e.boundary.kind!==`has-more`||t.boundary.kind!==`has-more`||e.boundary.cursor===t.boundary.cursor)}function Ra(e,t,n){if(!t)return[];let r=M();if(r){let n=r.getTranscript(N(e,t));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}if(!n)return[];let i=Fi(e,n).getTranscript(N(e,t));return i.messageOrder.map(e=>i.messagesByID[e]).filter(e=>!!e)}var I=null,za=``,Ba=null,Va=new Set,Ha=null,Ua=new Map,Wa=new Map;function Ga(e,t,n,r){I=t,Ha!==t&&(Ha=null,Ua=new Map,Wa=new Map),za=n,r&&(Ba=r)}function Ka(e,t){Ba?.(e,t)}function qa(){if(!I)throw Error(`ChildStoreManager not initialized — is SyncProvider mounted?`);return I}function Ja(e){let t=I;if(!t)return;let n=e||za;if(n)return t.getState(n)}function Ya(e){let t=Ja(e)?.config;return t&&Object.keys(t).length>0?t:void 0}function Xa(e){return Va.add(e),()=>{Va.delete(e)}}function Za(e,t){if(e)for(let n of Va)n(e,t)}function Qa(e){return Ja(e)?.session??[]}function $a(){return Array.from(eo().values())}function eo(){let e=I;if(!e)return Wa;let t=Ha!==e||Ua.size!==e.children.size;for(let[n,r]of e.children)if(Ua.get(n)!==r.getState().session){t=!0;break}if(!t)return Wa;let n=new Map,r=new Map;for(let[t,i]of e.children){let e=i.getState().session;n.set(t,e);for(let t of e)t?.id&&r.set(t.id,t)}return Ha=e,Ua=n,Wa=r,Wa}function to(e,t,n){if(n){let r=[];for(let[i,a]of n)if(a.session.some(t=>t.id===e)&&a.hasTranscript===!0){if(i===t)return i;r.push(i)}return r.length===1?r[0]:void 0}let r=[];try{let n=M();if(I){for(let[i,a]of I.children)if(a.getState().session.some(t=>t.id===e)&&(n??Fi(i,a)).hasSession?.(N(i,e))){if(i===t)return i;r.push(i)}}if(r.length===0&&n){let i=n.getCacheBudget?.().listCanonical();if(i){for(let n of i)if(n.scope.sessionID===e){if(n.scope.directory===t)return n.scope.directory;r.push(n.scope.directory)}}}}catch{}let i=[...new Set(r)];return i.length===1?i[0]:void 0}function no(e,t){if(!e)return[];try{let n=M(),r=t??za;if(n){let t=n.getTranscript(N(r,e));return t.messageOrder.map(e=>t.messagesByID[e]).filter(e=>!!e)}if(I){let t=I.getChild(r);if(t){let n=Fi(r,t).getTranscript(N(r,e));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}}}catch{}return[]}function ro(e,t){if(!e)return[];try{let n=M(),r=t??za;if(n)return[...n.getParts(N(r,e),e)];if(I){let t=I.getChild(r);if(t)return[...Fi(r,t).getParts(N(r,e),e)]}}catch{}return[]}var L=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},io=`default`;function ao(e){let t=L(e);if(t&&t!==io)return t}function oo(e){let t=e?.model;return L(t?.id)??L(t?.modelID)}function so(e){let t=e?.model;return L(t?.providerID)}function co(e){let t=e?.model;return ao(t?.variant)}function lo(e){let t=ao(e.variant);return{id:e.modelID.trim(),providerID:e.providerID.trim(),...t?{variant:t}:{}}}function uo(e,t,n){let r=L(n.providerID),i=L(n.modelID);if(!r||!i)return{agent:L(n.agent)};let a=(Ja(t)?.session??$a()).find(t=>t.id===e),o=lo({providerID:r,modelID:i,variant:n.variant}),s=oo(a),c=so(a),l=co(a),u=ao(o.variant),d=!a||!s||!c||c!==o.providerID||s!==o.id||l!==u,f=L(n.agent),p=L(a?.agent);return{model:d?o:void 0,agent:f&&p!==f?f:void 0}}function fo(e,t,n){if(e&&!(!n.model&&!n.agent))try{let r=qa(),i=typeof t==`string`&&t.length>0?t:void 0;if(!i)return;let a=r.getChild?.(i)??r.ensureChild?.(i,{bootstrap:!1});if(!a?.getState||!a?.setState)return;a.setState(t=>{let r=t.session;if(!Array.isArray(r))return t;let i=r.findIndex(t=>t.id===e);if(i<0)return t;let a=r[i];if(!a)return t;let o=n.model?{id:n.model.id??n.model.modelID??``,providerID:n.model.providerID,...n.model.variant?{variant:n.model.variant}:{}}:a.model,s={...a,...n.model&&o?.id&&o.providerID?{model:o}:{},...n.agent?{agent:n.agent}:{}};if(s===a)return t;let c=r.slice();return c[i]=s,{...t,session:c}})}catch{}}var po=new Set([`image/heic`,`image/heif`]),mo=!1,ho=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},go=e=>po.has((e.type||``).toLowerCase()),_o=async e=>{let t=new Uint8Array(await e.arrayBuffer()),n=``,r=32768;for(let e=0;e<t.byteLength;e+=r){let i=t.subarray(e,Math.min(e+r,t.byteLength));n+=String.fromCharCode(...i)}return btoa(n)},vo=(e,t)=>{let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new Blob([r],{type:t})},yo=async e=>{if(!go(e)||mo)return null;let t=ho();if(!t||typeof t.isNativePlatform!=`function`||!t.isNativePlatform())return null;let n=t.Plugins?.YuriMedia?.transcode;if(typeof n!=`function`)return null;try{let t=await n({data:await _o(e),mime:e.type.toLowerCase(),quality:.9});if(typeof t?.data!=`string`||!t.data)return null;let r=typeof t.mime==`string`&&t.mime?t.mime:`image/jpeg`;return vo(t.data,r)}catch(e){return mo=!0,console.warn(`Native HEIC transcode failed`,e),null}},bo=e=>e.trim().toLowerCase(),xo=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,So=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(bo)),r=[],i=0;for(;i<e.length;){let t=e.indexOf(`[`,i);if(t===-1)break;let a=e.indexOf(`]`,t+1);if(a===-1)break;if(e[a+1]!==`(`){let i=se(e.slice(t+1,a)).trim();n.has(bo(i))&&r.push({start:t,end:a+1})}i=a+1}return r},Co=(e,t)=>{let n=t.start,r=t.end;return r<e.length&&/\s/.test(e[r])?r+=1:n>0&&/\s/.test(e[n-1])&&--n,{start:n,end:r}},wo=(e,t,n,r)=>{let i=So(e,t);if(i.length===0)return{text:e,mentions:[...n],composerReferences:r===void 0?void 0:[...r],changed:!1};let a=e,o=[...n],s=r===void 0?[]:[...r];for(let e=i.length-1;e>=0;--e){let{start:t,end:n}=Co(a,i[e]),r=n-t;a=`${a.slice(0,t)}${a.slice(n)}`,o=o.flatMap(e=>e.range.end<=t?[e]:e.range.start>=n?[{...e,range:{start:e.range.start-r,end:e.range.end-r}}]:[]),s=s.flatMap(e=>e.end<=t?[e]:e.start>=n?[{...e,start:e.start-r,end:e.end-r}]:[])}return{text:a,mentions:o,composerReferences:r===void 0?void 0:s,changed:!0}},To=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),Eo={"image/avif":`avif`,"image/bmp":`bmp`,"image/gif":`gif`,"image/heic":`heic`,"image/heif":`heif`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/png":`png`,"image/svg+xml":`svg`,"image/tiff":`tiff`,"image/webp":`webp`},Do=e=>e.trim().toLowerCase(),Oo=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),ko=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>Oo(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},Ao=e=>Eo[e?.trim().toLowerCase()??``]??`png`,jo=e=>{let t=ko(e.name),n=Ao(e.type),r=t.lastIndexOf(`.`);if(r>0&&r<t.length-1){let e=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(e))return{base:t.slice(0,r).trim()||`image`,ext:e}}return{base:t.trim()||`image`,ext:n}},Mo=e=>{let{base:t}=jo({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(To.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&To.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},No=(e,t)=>`${e}.${t}`,Po=(e,t,n)=>{let r=No(e,t);if(!n.has(Do(r)))return r;for(let r=2;r<2**53-1;r+=1){let i=No(`${e}-${r}`,t);if(!n.has(Do(i)))return i}return No(`${e}-${Date.now()}`,t)},Fo=(e,t)=>{for(let n=1;n<2**53-1;n+=1){let r=No(`image-${n}`,e);if(!Array.from(t).some(e=>e.startsWith(`image-${n}.`))&&!t.has(Do(r)))return r}return No(`image-${Date.now()}`,e)},Io=(e,t)=>{let n=new Set(t.map(Do));return e.map(e=>{let{base:t,ext:r}=jo(e),i=Mo(No(t,r))?Fo(r,n):Po(t,r,n);return n.add(Do(i)),i})},Lo=e=>e.map(e=>le(e)).join(` `),Ro=(e,t,n)=>{if(t===n)return[];let r=[];for(let i of e){let e=[le(i),`[${i}]`],a=e.some(e=>t.includes(e)),o=e.some(e=>n.includes(e));a&&!o&&r.push(i)}return r},zo=(e,t)=>{if(t.length>=e.length)return null;let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n+=1;let i=0;for(;i<e.length-n&&i<t.length-n&&e[e.length-1-i]===t[t.length-1-i];)i+=1;let a=e.length-i;return t.length-i!==n||a<=n?null:{start:n,end:a}},Bo=(e,t,n)=>{if(e===t||n.length===0)return null;let r=[...n],i=zo(e,t);if(i){let t=Zo(e,r,{key:`Backspace`,selectionStart:i.start,selectionEnd:i.end});if(t)return t}let a=Ro(r,e,t);return a.length===0?null:{text:t,caret:t.length,removedFilenames:a}},Vo=e=>e.replaceAll(`[${oe}`,`[`),Ho=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Uo=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},Wo=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Uo(t)||!Ho.test(t)&&!Ho.test(r))continue;let i=`[${r}]`;n=n.split(le(t)).join(i).split(`[${t}]`).join(i)}return n},Go=(e,t)=>{let n=e;for(let e of t??[]){if(e.source!==`vscode`||e.vscodeSource!==`selection`||!e.vscodePath)continue;let t=e.filename.match(/:(\d+(?:-\d+)?)$/)?.[1];if(!t)continue;let r=`[${e.vscodePath}:${t}]`;n=n.split(le(e.filename)).join(r).split(`[${e.filename}]`).join(r)}return n},Ko=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),qo=`application/x-directory`,Jo=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,Yo=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),Xo=(e,t,n)=>{if(t===`Backspace`){let t=n;for(;t>0&&/\s/.test(e[t-1]);)--t;for(;t>0&&!/\s/.test(e[t-1]);)--t;return{start:t,end:n}}let r=n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;for(;r<e.length&&!/\s/.test(e[r]);)r+=1;return{start:n,end:r}},Zo=(e,t,n)=>{let r=Math.max(0,Math.min(n.selectionStart,e.length)),i=Math.max(r,Math.min(n.selectionEnd,e.length)),a;if(a=r===i?n.altKey?Xo(e,n.key,r):n.key===`Backspace`?{start:Math.max(0,r-1),end:r}:{start:r,end:Math.min(e.length,r+1)}:{start:r,end:i},a.start===a.end)return null;let o=So(e,t).filter(e=>e.start<a.end&&e.end>a.start);if(o.length===0)return null;let s=Math.min(a.start,...o.map(e=>e.start)),c=Math.max(a.end,...o.map(e=>e.end));return c<e.length&&/\s/.test(e[c])&&(s===0||/\s/.test(e[s-1]))?c+=1:c===e.length&&s>0&&/\s/.test(e[s-1])&&--s,{text:`${e.slice(0,s)}${e.slice(c)}`,caret:s,removedFilenames:o.map(t=>se(e.slice(t.start+1,t.end-1)).trim())}},Qo=`<system-reminder>`,$o=`</system-reminder>`,es=/[ \t]*<system-reminder>[\s\S]*?<\/system-reminder>[ \t]*/g,ts=/[ \t]*<system-reminder>[\s\S]*$/,ns=e=>{let t=e.trim();return t?t.startsWith(Qo)&&t.endsWith($o)?t:`${Qo}\n${t}\n${$o}`:``},rs=e=>e.includes(Qo)?e.replace(es,``).replace(ts,``).trim():e,is=class extends Error{status;code;constructor(e,t,n=`Failed to upload prompt attachment`){super(n),this.name=`PromptAttachmentUploadError`,this.status=e,this.code=t}},as=`file://`,os=e=>{let t=e.trim();if(t.toLowerCase().startsWith(as))return t;let n=pe(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${as}/${n}`:`${as}${n}`},ss=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(as))return t;let n=t.slice(7);n.toLowerCase().startsWith(`localhost/`)&&(n=n.slice(9));let r=n.split(`/`).map(e=>{if(/^[A-Za-z]:$/.test(e))return e;try{return decodeURIComponent(e)}catch{return e}}).join(`/`);return/^\/[A-Za-z]:/.test(r)?r.slice(1):r},cs=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),ls=e=>typeof e==`object`&&!!e&&!Array.isArray(e),us=async e=>{let t;try{t=await e.json()}catch{throw new is(e.status,`unavailable`)}if(!ls(t)||typeof t.path!=`string`||!t.path)throw new is(e.status,`unavailable`);let n=typeof t.mime==`string`&&t.mime?t.mime:`application/octet-stream`,r=typeof t.size==`number`&&Number.isSafeInteger(t.size)?t.size:0,i=typeof t.sha256==`string`?t.sha256:``;return{path:t.path,url:os(t.path),mime:n,size:r,sha256:i}},ds=e=>{let t=typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n=e?.replace(/[^a-z0-9._-]+/gi,`-`).replace(/^-+|-+$/g,``).slice(0,32);return n?`att-${t}-${n}`:`att-${t}`},fs=(e,t)=>{if(!e.startsWith(`data:`))return null;let n=e.indexOf(`,`);if(n===-1)return null;let r=e.slice(5,n),i=e.slice(n+1),a=r.split(`;`,1)[0]?.trim()||t||`application/octet-stream`;try{if(r.toLowerCase().includes(`;base64`)){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new Blob([t],{type:a})}return new Blob([decodeURIComponent(i)],{type:a})}catch{return null}},ps=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),ms=async e=>{let t=me(),n=e.mime||e.body.type||`application/octet-stream`,r=e.body.type===n?e.body:new Blob([e.body],{type:n});if(!Number.isSafeInteger(r.size)||r.size<0)throw new is(413,`too-large`);let i=await cs(r),a=ds(e.filename),o;try{o=await u(`/api/fs/prompt-attachments/${encodeURIComponent(a)}?storage=temporary`,{method:`PUT`,headers:{"Content-Type":n,"Content-Length":String(r.size),"X-Yuri-Content-Length":String(r.size),"X-Yuri-Sha256":i,"X-Yuri-Mime":n,...e.filename?{"X-Yuri-Filename":encodeURIComponent(e.filename)}:{}},body:r,signal:e.signal})}catch{throw new is(0,`unavailable`)}if(o.status===413)throw new is(413,`too-large`);if(!o.ok)throw new is(o.status,o.status>=500||o.status===0?`unavailable`:`rejected`);let s=await us(o);if(s.size!==r.size)throw new is(o.status,`unavailable`);return await t(r,s.sha256),{...s,mime:n}},hs=500,gs=()=>{if(typeof window>`u`)return!1;try{return new URLSearchParams(window.location.search).get(`startupTrace`)===`1`||window.localStorage?.getItem(`YURI_STARTUP_TRACE`)===`1`}catch{return!1}},_s=()=>gs(),R=(e,t)=>{if(!gs())return;let n=typeof performance<`u`?performance.now():Date.now();window.__YURI_STARTUP_TRACE_START__??=n,window.__YURI_STARTUP_TRACE__??=[],window.__YURI_STARTUP_TRACE__.push({t:Math.round(n-window.__YURI_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__YURI_STARTUP_TRACE__.length>hs&&window.__YURI_STARTUP_TRACE__.splice(0,window.__YURI_STARTUP_TRACE__.length-hs)};typeof window<`u`&&(window.__YURI_STARTUP_TRACE_SUMMARY__=()=>{let e=typeof window<`u`?window.__YURI_STARTUP_TRACE__??[]:[],t=e.findIndex(e=>e.name===`ModelControls:ready`),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(e=>e.name.includes(`checkConnection`)||e.name.includes(`checkHealth`)||e.name.includes(`initializeApp`)||e.name.includes(`initApp`)||e.name.includes(`loadProviders`)||e.name.includes(`loadAgents`)||e.name.includes(`config.defaults`)||e.name.includes(`ModelControls`)||e.name.includes(`activateDirectory`)||e.name.includes(`opencodeClient:setDirectory`))});var vs=async(e,t,n)=>{let r=typeof performance<`u`?performance.now():Date.now();R(`${e}:start`,n);try{let n=await t(),i=typeof performance<`u`?performance.now():Date.now();return R(`${e}:end`,{durationMs:Math.round(i-r)}),n}catch(t){let n=typeof performance<`u`?performance.now():Date.now();throw R(`${e}:error`,{durationMs:Math.round(n-r),error:t instanceof Error?t.message:String(t)}),t}},ys=e=>({kind:`session-inbox`,requestID:e.requestID,queueItemID:e.id,operationID:e.id,messageID:e.id,content:e.payload.text,createdAt:e.timeCreated,delivery:e.delivery,attachmentCount:Array.isArray(e.payload.files)?e.payload.files.length:0}),bs=[],xs=[],z=new Map,Ss=512,Cs=0;function ws(){return Cs}function B(){return{transportIdentity:o(),generation:s()}}function Ts(e){return o()===e.transportIdentity&&s()===e.generation}function Es(e,t,n){return`${n?.transportIdentity??o()}\0${n?.generation??s()}\0${e}\0${t}`}function Ds(e=B()){if(z.size===0)return;let t=`${e.transportIdentity}\0${e.generation}\0`;for(let e of z.keys())e.startsWith(t)||z.delete(e);for(;z.size>Ss;){let e=z.keys().next().value;if(e===void 0)break;z.delete(e)}}function Os(e,t,n,r){let i=r??B();Ds(i),Cs+=1,z.set(Es(e,t,i),{kind:n,mark:Cs})}function ks(e,t,n){let r=n?.scope;Ds(r??B());let i=z.get(Es(e,t,r));if(!i)return!0;let a=n?.startedMark;return a!==void 0&&i.mark>a?!1:(z.delete(Es(e,t,r)),!0)}function As(e,t,n){return Ds(n??B()),z.get(Es(e,t,n))?.kind??null}var js=(e,t,n)=>{let r={...e};return n.length===0?delete r[t]:r[t]=n,r},V=m((e,t)=>({bySession:{},remember(t){return!As(t.sessionID,t.id)&&(e(e=>{let n=e.bySession[t.sessionID]??[],r=n.findIndex(e=>e.id===t.id),i={...t,requestID:t.id};if(r>=0){let a=n.slice();return a[r]=i,{bySession:{...e.bySession,[t.sessionID]:a}}}return{bySession:{...e.bySession,[t.sessionID]:[...n,i]}}}),!0)},forget(t,n,r){r&&Os(t,n,r),e(e=>{let r=e.bySession[t];if(!r?.length)return e;let i=r.filter(e=>e.id!==n);return i.length===r.length?e:{bySession:js(e.bySession,t,i)}})},forgetSession(t){e(e=>{if(!e.bySession[t])return e;let n={...e.bySession};return delete n[t],{bySession:n}})},forgetPromoted(t,n){let r=new Set(n);e(e=>{let n=e.bySession[t];if(!n?.length)return e;let i=new Set(n.filter(e=>r.has(e.id)).map(e=>e.id));if(i.size===0)return e;for(let e of i)Os(t,e,`consumed`);return{bySession:js(e.bySession,t,n.filter(e=>!i.has(e.id)))}})},replaceFromAuthority(t,n,r){let i=r?.startedMark,a=[];for(let e of n)ks(t,e.id,{startedMark:i})&&a.push(e);e(e=>{let n=new Map((e.bySession[t]??[]).map(e=>[e.id,e])),i=r?.observedItems&&new Map(r.observedItems.map(e=>[e.id,e])),o=a.map(e=>({...e,requestID:e.id}));if(i){let e=new Map(o.map((e,t)=>[e.id,t]));for(let t of n.values()){if(i.get(t.id)===t)continue;let n=e.get(t.id);n===void 0?o.push(t):o[n]=t}}return{bySession:js(e.bySession,t,o)}})},updateDelivery(t,n,r){e(e=>{if(As(t,n))return e;let i=e.bySession[t];if(!i?.length)return e;let a=i.findIndex(e=>e.id===n);if(a<0||i[a].delivery===r)return e;let o=i.slice();return o[a]={...i[a],delivery:r},{bySession:{...e.bySession,[t]:o}}})},list(e){return t().bySession[e]??bs}}));function Ms(e){return V.getState().remember(e)}function Ns(e,t){return ks(e.sessionID,e.id,t)?V.getState().remember(e):!1}function Ps(e,t,n){V.getState().forget(e,t,n)}function Fs(e,t){V.getState().forgetPromoted(e,t)}function Is(e,t,n){V.getState().replaceFromAuthority(e,t,n)}function Ls(e,t,n){V.getState().updateDelivery(e,t,n)}function Rs(e){return!!e&&typeof e==`object`&&e.kind===`session-inbox`}var zs=e=>e?e.toLowerCase().includes(`application/json`):!1,Bs=e=>e?e.toLowerCase().includes(`text/html`):!1;function H(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function U(e){return typeof e==`string`&&e.length>0?e:void 0}function Vs(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Hs(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function Us(e){try{let t=(await e.text()).trim();if(!t)return``;try{let e=JSON.parse(t);if(typeof e.error==`string`&&e.error.trim())return e.error.trim();if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}return t}catch{return``}}function Ws(e){return e?{directory:e}:{}}function Gs(e,t){let n=`/api/session/${encodeURIComponent(e)}/inbox`;return t?`${n}/${encodeURIComponent(t)}`:n}async function Ks(e,t){let n=e.headers.get(`content-type`);if(Bs(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!zs(n)&&r==null)throw Error(`${t}: empty response`);return r}function qs(e){let t=H(e)?e:null,n=t&&H(t.data)?t.data:t;if(!n)throw Error(`session prompt: expected inbox item`);let r=U(n.type);if(r&&r!==`user`)throw Error(`session prompt: expected user inbox item, got ${r}`);let i=U(n.id),a=U(n.sessionID);if(!i||!a)throw Error(`session prompt: inbox item missing id`);let o=H(n.payload)?n.payload:{},s=n.delivery===`queue`?`queue`:`steer`,c=H(n.time)?n.time:null;return{id:i,sessionID:a,timeCreated:Vs(n.timeCreated)??Vs(c?.created)??Date.now(),type:`user`,delivery:s,payload:{text:U(o.text)??U(n.text)??``,...o.files===void 0?{}:{files:o.files},...o.agents===void 0?{}:{agents:o.agents},...o.skills===void 0?{}:{skills:o.skills},...H(o.metadata)?{metadata:o.metadata}:{}}}}function Js(e){let t=H(e)?e:null,n=t&&Array.isArray(t.data)?t.data:Array.isArray(e)?e:null;if(!n)throw Error(`session inbox: expected list`);let r=[];for(let e of n)H(e)&&(e.type&&e.type!==`user`||r.push(qs(e)));return r}function Ys(e){return{runtimeKey:c(),generation:s(),directory:e,overlay:B()}}function W(e){return c()===e.runtimeKey&&s()===e.generation&&Ts(e.overlay)}function Xs(e){let t=Error(`${e}: runtime switched`);throw t.name=`RuntimeGenerationMismatchError`,t}async function Zs(e){let t=e.commit??Ys(e.directory);W(t)||Xs(`session prompt`);let n=`/api/session/${encodeURIComponent(e.sessionID)}/prompt`,r={id:e.messageID,text:e.text,delivery:e.delivery===`queue`?`queue`:`steer`};e.files?.length&&(r.files=e.files),e.agents?.length&&(r.agents=e.agents),e.skills?.length&&(r.skills=e.skills),e.metadata&&(r.metadata=e.metadata);let i=await u(n,{method:`POST`,headers:{"Content-Type":`application/json`},query:{directory:t.directory},body:JSON.stringify(r),signal:e.signal});if(W(t)||Xs(`session prompt`),!i.ok){let e=await Us(i);Hs(`Failed to send message`,i.status,e)}let a=qs(await Ks(i,`session prompt`));return W(t)||Xs(`session prompt`),Ms(a),a}function Qs(e){let t=e?.status;return typeof t!=`number`||!Number.isFinite(t)||t===408||t===429?!1:t>=400&&t<500}async function $s(e){let t=e.inputID.trim();if(!t)return{status:`unknown`};let n=e.commit??Ys(e.directory??``);if(!W(n))return{status:`unknown`};try{let r=await tc({sessionID:e.sessionID,directory:n.directory||e.directory,signal:e.signal});if(!W(n)||!r.current)return{status:`unknown`};let i=r.items.find(e=>e.id===t);if(i)return Ns(i,{startedMark:r.startedMark})?{status:`pending`,item:i}:{status:`unknown`}}catch{}if(!W(n))return{status:`unknown`};try{let r=await $e({sessionID:e.sessionID,directory:n.directory||e.directory||``,limit:40,...e.signal?{signal:e.signal}:{}});if(!W(n))return{status:`unknown`};if(r.records.some(e=>e?.info?.id===t))return Ps(e.sessionID,t,`consumed`),{status:`promoted`,id:t}}catch{}return{status:`unknown`}}function ec(e){let t=typeof e.type==`string`?e.type:``,n=e.properties&&typeof e.properties==`object`?e.properties:null;if(!n)return!1;let r=U(n.sessionID),i=U(n.inboxID)??U(n.id);if(!r||!i)return!1;if(t===`session.inbox.enqueued`){let e=n.item,t=H(e)?U(e.type):void 0;if(t&&t!==`user`)return!1;try{return Ns(qs(H(e)?{...e,id:i,sessionID:r,type:t??`user`}:{id:i,sessionID:r,type:`user`,delivery:`steer`,payload:{text:``}})),!0}catch{return!1}}if(t===`session.inbox.cancelled`)return Ps(r,i,`cancelled`),!0;if(t===`session.inbox.delivered`)return Ps(r,i,`consumed`),!0;if(t===`session.inbox.delivery.changed`){let e=n.delivery===`queue`?`queue`:n.delivery===`steer`?`steer`:null;return e?(Ls(r,i,e),!0):!1}return!1}async function tc(e){let t=B(),n=ws(),r=ut(e.sessionID),i={method:`GET`,query:Ws(e.directory),signal:e.signal},a=await u(`/api/sessions/${encodeURIComponent(e.sessionID)}/delivery`,i);(a.status===404||a.status===501||Bs(a.headers.get(`content-type`)))&&(a=await u(Gs(e.sessionID),i)),a.ok||Hs(`session inbox`,a.status,await Us(a));let o=await Ks(a,`session inbox`),s=Js(o),c=Ts(t);return c&&ut(e.sessionID)===r&&(H(o)&&typeof o.compactionRunning==`boolean`?w(e.sessionID,o.compactionRunning):gt(e.sessionID,ht(o))),{items:s,startedMark:n,scope:t,current:c}}async function nc(e){let t=B(),n=await u(Gs(e.sessionID,e.inboxID),{method:`PATCH`,headers:{"Content-Type":`application/json`},query:Ws(e.directory),body:JSON.stringify({delivery:e.delivery}),signal:e.signal});n.ok||Hs(e.delivery===`steer`?`session inbox steer`:`session inbox queue`,n.status,await Us(n)),Ts(t)&&(As(e.sessionID,e.inboxID)||Ls(e.sessionID,e.inboxID,e.delivery))}async function rc(e){await nc({...e,delivery:`steer`})}async function ic(e){await nc({...e,delivery:`queue`})}async function ac(e){let t=await u(Gs(e.sessionID,e.inboxID),{method:`DELETE`,query:Ws(e.directory),signal:e.signal});t.ok||Hs(`session inbox cancel`,t.status,await Us(t))}function oc(e,t,n){Is(e,t,n)}async function sc(e){let t=B();if(await ac(e),!Ts(t))return{overlay:V.getState().list(e.sessionID),transcriptRows:[]};Ps(e.sessionID,e.inboxID,`cancelled`);try{let n=await tc({sessionID:e.sessionID,directory:e.directory,signal:e.signal});if(!Ts(t)||!n.current)return{overlay:V.getState().list(e.sessionID),transcriptRows:[]};oc(e.sessionID,n.items,{startedMark:n.startedMark})}catch{}return{overlay:V.getState().list(e.sessionID),transcriptRows:[]}}async function cc(e){let t=`/api/session/${encodeURIComponent(e.sessionID)}/interrupt`,n={};e.directory&&(n.directory=e.directory),e.resume!==void 0&&(n.resume=String(e.resume));let r=await u(t,{method:`POST`,query:n,signal:e.signal});if(!r.ok)throw Error(`Session interrupt failed (${r.status})`)}async function lc(e){return e.promotedIDs.includes(e.optimisticID)?`confirmed`:(e.removeOptimistic(e.optimisticID),await e.refreshFromAuthority(),`refreshed`)}var uc=`session-revert-busy`,dc=e=>e?e.toLowerCase().includes(`text/html`):!1;function fc(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function pc(e){return typeof e==`string`&&e.length>0?e:void 0}function mc(e,t,n){if(t===409)throw hc();let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);if(i.status=t,t===404&&n)try{let e=JSON.parse(n);fc(e)&&e._tag===`MessageNotFoundError`&&(i.name=`MessageNotFoundError`)}catch{}throw i}function hc(){let e=Error(uc);return e.name=`SessionRevertBusyError`,e}function gc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`SessionRevertBusyError`||t.message===`session-revert-busy`}async function _c(e){try{return(await e.text()).trim()}catch{return``}}async function vc(e,t){if(dc(e.headers.get(`content-type`)))throw Error(`${t}: unexpected HTML response`);if(e.status===204)return null;let n=await e.text();if(!n.trim()){if(e.ok)return null;throw Error(`${t}: empty response`)}try{return JSON.parse(n)}catch{throw Error(`${t}: malformed JSON`)}}function yc(e){return e?{directory:e}:{}}function bc(e,t){return`/api/session/${encodeURIComponent(e)}/revert/${t}`}function xc(e){let t=fc(e)?e:null,n=t&&fc(t.data)?t.data:t;if(!n)throw Error(`session revert: expected revert payload`);let r=pc(n.messageID);if(!r)throw Error(`session revert: missing messageID`);let i=Array.isArray(n.files)?n.files.flatMap(e=>{if(!fc(e))throw Error(`session revert: invalid file diff`);let t=pc(e.file)??pc(e.path);if(!t||e.status!==`added`&&e.status!==`deleted`&&e.status!==`modified`||typeof e.additions!=`number`||typeof e.deletions!=`number`||typeof e.patch!=`string`)throw Error(`session revert: invalid file diff`);return[{file:t,status:e.status,additions:e.additions,deletions:e.deletions,patch:e.patch}]}):void 0;return{messageID:r,...pc(n.partID)?{partID:pc(n.partID)}:{},...pc(n.snapshot)?{snapshot:pc(n.snapshot)}:{},...i?{files:i}:{}}}function Sc(e){return e?.files?e.files.flatMap(e=>{let t=typeof e.file==`string`&&e.file.length>0?e.file:typeof e.path==`string`&&e.path.length>0?e.path:``;return t?[t]:[]}):[]}async function Cc(e){let t=await u(bc(e.sessionID,`stage`),{method:`POST`,headers:{"Content-Type":`application/json`},query:yc(e.directory),body:JSON.stringify({messageID:e.messageID,files:e.files!==!1}),signal:e.signal});return t.ok||mc(`session revert stage`,t.status,await _c(t)),xc(await vc(t,`session revert stage`))}async function wc(e){let t=await u(`/api/session/${encodeURIComponent(e.sessionID)}/revert`,{method:`DELETE`,query:yc(e.directory),signal:e.signal});t.ok||mc(`session revert clear`,t.status,await _c(t))}async function Tc(e){let t=await u(bc(e.sessionID,`commit`),{method:`POST`,query:yc(e.directory),signal:e.signal});t.ok||mc(`session revert commit`,t.status,await _c(t))}var Ec=e=>e?e.toLowerCase().includes(`text/html`):!1;function Dc(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function Oc(e){try{return(await e.text()).trim()}catch{return``}}function kc(e){return e?{directory:e}:{}}function Ac(e,t){return`/api/session/${encodeURIComponent(e)}/permission/${encodeURIComponent(t)}/reply`}async function jc(e){let t=await u(Ac(e.sessionID,e.requestID),{method:`POST`,headers:{"Content-Type":`application/json`},query:kc(e.directory),body:JSON.stringify({decision:e.reply,...e.message?{message:e.message}:{}}),signal:e.signal});if(t.ok||Dc(`session permission reply`,t.status,await Oc(t)),t.status!==204&&Ec(t.headers.get(`content-type`)))throw Error(`session permission reply: unexpected HTML response`)}function Mc(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function Nc(e){let t=typeof e.directory==`string`?e.directory:``;return{state:``,config:``,worktree:typeof e.project?.directory==`string`?e.project.directory:t,directory:t,home:``}}function Pc(e){return e.worktree||e.canonical||``}function Fc(e,t){let n={};if(t.size===0)return n;for(let[r,i]of Object.entries(e))t.has(r)&&i?.type===`running`&&(n[r]={type:`busy`});return n}function Ic(e){return{id:e.id,sessionID:e.sessionID,permission:e.action,patterns:Array.isArray(e.resources)?e.resources:[],metadata:e.metadata??{},always:Array.isArray(e.save)?e.save:[],...e.source?.messageID?{tool:{messageID:e.source.messageID,callID:e.source.id??``}}:{}}}function Lc(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.kind===`question`}function Rc(e){let t=e.metadata&&typeof e.metadata.tool==`object`&&e.metadata.tool&&!Array.isArray(e.metadata.tool)?e.metadata.tool:void 0,n=typeof e.tool?.messageID==`string`&&e.tool.messageID.length>0?e.tool.messageID:typeof t?.messageID==`string`&&t.messageID.length>0?t.messageID:void 0;if(n)return{messageID:n,callID:typeof e.tool?.id==`string`?e.tool.id:typeof t?.id==`string`?t.id:``}}function zc(e){let t=e.fields;if(!t||t.length===0){let t=typeof e.title==`string`&&e.title.length>0?e.title:`Form`;return[{question:t,header:t,options:[]}]}return t.map(t=>{let n=typeof t.title==`string`&&t.title.length>0?t.title:t.key;return{question:typeof t.description==`string`&&t.description.length>0?t.description:typeof e.title==`string`&&e.title.length>0?e.title:n,header:n,options:(t.options??[]).map(e=>({label:e.label||e.value||``,description:typeof e.description==`string`?e.description:``})).filter(e=>e.label.length>0),...t.type===`multiselect`?{multiple:!0}:{}}})}function Bc(e){let t=e.questions&&e.questions.length>0?e.questions.map(e=>({question:e.question,header:e.header,options:e.options??[],...e.multiple?{multiple:!0}:{}})):zc(e),n=Rc(e);return{id:e.id,sessionID:e.sessionID,questions:t,...n?{tool:n}:{}}}function Vc(e,t){let n={};for(let r=0;r<t.length;r+=1){let i=t[r],a=(e[r]??[]).map(e=>i.options?.find(t=>(t.label||t.value)===e)?.value??e),o=a[0]??``;if(i.type===`multiselect`)n[i.key]=a;else if(i.type===`number`||i.type===`integer`){let e=Number(o);if(!o.trim()||!Number.isFinite(e)||i.type===`integer`&&!Number.isInteger(e))throw Error(`Invalid numeric answer for ${i.key}`);n[i.key]=e}else if(i.type===`boolean`){if(o!==`true`&&o!==`false`)throw Error(`Invalid boolean answer for ${i.key}`);n[i.key]=o===`true`}else n[i.key]=o}return n}var Hc=3,Uc=3e4,Wc=32e3,Gc=36e5,Kc=6e5,qc=new Set([429,502,503,504]),Jc=new Map;function Yc(){let e=Date.now();for(let[t,n]of Jc)n.consecutiveErrors===0&&e-n.lastErrorAt>Gc&&Jc.delete(t)}typeof setInterval<`u`&&setInterval(Yc,Kc).unref?.();function Xc(e){let t=Jc.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Uc},Jc.set(e,t)),t}function Zc(e){if(!e)return;let t=Jc.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function Qc(e,t){if(!e)return;let n=Xc(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),$c(t)&&n.consecutiveErrors>=Hc&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function $c(e){return e!==void 0&&qc.has(e)}function el(e){let t=Jc.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Wc*4),!1):!0:!1}function tl(e){if(!(!e||!el(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var nl=`/api`,rl=1e4,il=4e3,al=3e3,ol=1e3,sl=1500,cl=12e3;function ll(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function G(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function ul(e){if(e instanceof ne&&e.reason===`UnexpectedStatus`){let t=e.cause;if(t&&typeof t==`object`&&`status`in t){let e=t.status;if(typeof e==`number`)return e}}if(e&&typeof e==`object`&&`status`in e){let t=e.status;if(typeof t==`number`)return t}}function dl(e){return e===404||e===405||e===501}function K(e){if(typeof e!=`string`)return;let t=e.trim();if(t)return{location:{directory:t}}}function fl(e){let t=e.replace(/\/+$/,``);if(t.endsWith(`/api`)){let e=t.slice(0,-4);if(e.length>0)return e}return hl(_l()||`/`)}function pl(e){return!e||typeof e.id!=`string`||e.id.length===0||typeof e.sessionID!=`string`||e.sessionID.length===0?null:{id:e.id,sessionID:e.sessionID,permission:e.action,patterns:Array.isArray(e.resources)?e.resources:[],metadata:e.metadata??{},always:Array.isArray(e.save)?e.save:[],...e.source?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}}var ml=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,hl=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if(ml.test(t)||typeof window>`u`)return t;let n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(e){return console.warn(`Failed to normalize OpenCode base URL:`,e),t}},gl=()=>{try{return a().api(`/api`)}catch{return null}},_l=()=>{try{return a().api(`/`)}catch{return null}},vl=e=>{let t=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof t?.timeout==`function`)return{signal:t.timeout(e),cleanup:()=>void 0};let n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},yl=e=>{let t=e.filter(e=>e!=null);if(t.length===0)return{signal:new AbortController().signal,cleanup:()=>void 0};if(t.length===1)return{signal:t[0],cleanup:()=>void 0};let n=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof n?.any==`function`)return{signal:n.any(t),cleanup:()=>void 0};let r=new AbortController,i=()=>r.abort();for(let e of t){if(e.aborted){r.abort();break}e.addEventListener(`abort`,i)}return{signal:r.signal,cleanup:()=>{for(let e of t)e.removeEventListener(`abort`,i)}}},bl=e=>{let t=e.session?.message,n=t&&typeof t==`object`&&typeof t.get==`function`?t.get.bind(t):null;if(!n)return e;let r=Object.assign((e,t)=>n(e,t),t);return{...e,session:{...e.session,message:r}}},xl=e=>bl(te.make({baseUrl:e.baseUrl,...e.headers?{headers:e.headers}:{},fetch:(e,t)=>{let n=new URL(e instanceof Request?e.url:e.toString()),r=`${n.pathname}${n.search}`;if(e instanceof Request){let n=hl(a().api(r));return u(new Request(n,e),t)}return u(r,t)}})),Sl=20971520,Cl=e=>{let{referenceOnly:t,...n}=e;return wl(e)&&!t?n:{type:`text`,synthetic:!0,text:ns(`Attachment ${JSON.stringify(e.filename||`file`)}: ${JSON.stringify(ss(e.url))}\nRead or process this file with tools as needed; its contents are not included in the message.`.replace(/</g,`\\u003c`))}},wl=e=>typeof e.mime==`string`&&e.mime.startsWith(`image/`)?!0:typeof e.filename==`string`&&/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i.test(e.filename),Tl=e=>{let t=[];for(let n of e){if(!wl(n))continue;let e=typeof n.filename==`string`?n.filename.trim():``,r=typeof n.url==`string`?n.url:``;if(!e||!r.toLowerCase().startsWith(`file://`))continue;let i=ss(r).trim();i&&t.push({filename:e,path:i})}return t},El=async(e,t)=>{let n=[],r=e.files?.length?await Promise.all(e.files.map(e=>t(e))):[],i=e.additionalParts?.length?await Promise.all(e.additionalParts.map(async e=>({text:e.text,synthetic:e.synthetic,files:e.files?.length?await Promise.all(e.files.map(e=>t(e))):[]}))):[],a=e=>Wo(e,Tl([...r,...i.flatMap(e=>e.files)]));if(e.prefaceText&&e.prefaceText.trim()&&n.push({type:`text`,text:a(e.prefaceText),synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()&&n.push({type:`text`,text:a(e.text)}),n.push(...r.map(Cl)),i.length>0)for(let e of i){if(e.text&&e.text.trim()){let t={type:`text`,text:a(e.text)};e.synthetic&&(t.synthetic=!0),n.push(t)}n.push(...e.files.map(Cl))}if(e.agentMentions&&e.agentMentions.length>0)for(let t of e.agentMentions){if(!t?.name)continue;let e={type:`agent`,name:t.name};t.source&&(e.source=t.source),n.push(e)}if(n.length===0)throw Error(`Message must have at least one part (text or file)`);return n},Dl=e=>e.replace(/\\/g,`/`),Ol=400,kl=()=>{let e=p();return e&&e.runtime?.isDesktop&&e.files?e.files:null},q=new class{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;healthInFlight=new Map;healthCache=new Map;healthCacheGeneration=0;liveLocationsFlight=null;sessionBoundaryQueues=new Map;constructor(e=nl){let t=gl()||e;this.baseUrl=hl(t),this.client=xl({baseUrl:fl(this.baseUrl)})}getBaseUrl(){return hl(gl()||this.baseUrl)}reconnectToRuntimeBaseUrl(){let e=hl(gl()||nl);e!==this.baseUrl&&(this.baseUrl=e,this.client=xl({baseUrl:fl(this.baseUrl)}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear(),this.clearHealthCache(),this.liveLocationsFlight=null)}getSdkClient(){return this.client}getScopedSdkClient(e){return this.getScopedApiClient(e)}async checkLocationReleaseUse(e,t){let n=this.normalizeCandidatePath(e),r=await this.listLiveLocationDirectories();if(!r)throw Error(`Live Location inventory unavailable`);if(r&&n&&!r.has(n))return`free`;let i=this.getScopedSdkClient(e),a={location:{directory:e}},[o,s]=await Promise.all([i.shell.list(a,{signal:t}),i.form.list(a,{signal:t})]);return o.data.some(e=>e.status===`running`)||s.data.length>0?`busy`:`free`}listLiveLocationDirectories(){let e=Date.now();if(this.liveLocationsFlight&&this.liveLocationsFlight.expiresAt>e)return this.liveLocationsFlight.promise;let t=this.client.debug.location.list().then(e=>{if(!Array.isArray(e))return null;let t=new Set;for(let n of e){let e=this.normalizeCandidatePath(n?.directory??null);e&&t.add(e)}return t}).catch(()=>null);return this.liveLocationsFlight={promise:t,expiresAt:e+sl},t}async resolveBlockingRequestDirectories(e){let t=new Set;for(let n of e??[]){let e=this.normalizeCandidatePath(n??null);e&&t.add(e)}if(t.size===0)return[];let n=await this.listLiveLocationDirectories();if(!n)throw Error(`Live Location inventory unavailable`);return Array.from(t).filter(e=>n.has(e))}async releaseLocation(e,t){await this.getScopedSdkClient(e).debug.location.evict({location:{directory:e}},{signal:t})}getScopedApiClient(e){let t=(this.normalizeCandidatePath(e)??e)||``,n=this.scopedClients.get(t);if(n)return n;let r=xl({baseUrl:fl(this.baseUrl)});return this.scopedClients.set(t,r),r}normalizeCandidatePath(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return(n.length>1?n.replace(/\/+$/,``):n)||null}deriveHomeDirectory(e){let t=e.match(/^([A-Za-z]:)(?:\/|$)/);if(t){let n=t[1],r=e.slice(n.length+ +(e.charAt(n.length)===`/`)).split(`/`).filter(Boolean);return r.length>=2?{homeDirectory:`${n}/${r[0]}/${r[1]}`,username:r[1]}:r.length===1?{homeDirectory:`${n}/${r[0]}`,username:r[0]}:{homeDirectory:n,username:void 0}}let n=e.startsWith(`/`),r=e.split(`/`).filter(Boolean);return r.length>=2&&(r[0]===`Users`||r[0]===`home`)?{homeDirectory:`${n?`/`:``}${r[0]}/${r[1]}`,username:r[1]}:n?r.length===0?{homeDirectory:`/`,username:void 0}:{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:r.length>0?{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:{homeDirectory:`/`,username:void 0}}setDirectory(e){let t=this.normalizeCandidatePath(e)??e;this.currentDirectory!==t&&R(`opencodeClient:setDirectory`,{previous:this.currentDirectory??null,next:t??null}),this.currentDirectory=t}getDirectory(){return this.currentDirectory}runSessionBoundary(e,t){let n=e.trim();if(!n)return t();let r=this.sessionBoundaryQueues.get(n)??Promise.resolve(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s=()=>t().then(i,a),c=r.then(s,s);return this.sessionBoundaryQueues.set(n,c.then(()=>void 0,()=>void 0)),o}assertCapturedRuntime(e,t,n){if(s()!==e||c()!==t){let e=Error(`${n}: runtime switched`);throw e.name=`RuntimeGenerationMismatchError`,e}}async switchSessionModel(e,t,n){let r=s(),i=c(),a=`id`in t&&typeof t.id==`string`&&t.id?t.id:t.modelID,o=t.providerID;if(!e||!a||!o)throw Error(`switchSessionModel requires sessionID, model.id, and providerID`);let l=typeof t.variant==`string`&&t.variant.trim()?t.variant.trim():void 0,u={id:a,providerID:o,...l?{variant:l}:{}},d=this.normalizeCandidatePath(n)??this.currentDirectory??``,f=this.getScopedSdkClient(d);this.assertCapturedRuntime(r,i,`session model switch`),await f.session.switchModel({sessionID:e,model:u}),this.assertCapturedRuntime(r,i,`session model switch`),fo(e,d||n,{model:u})}async switchSessionAgent(e,t,n){let r=s(),i=c(),a=typeof t==`string`?t.trim():``;if(!e||!a)throw Error(`switchSessionAgent requires sessionID and agent`);let o=this.normalizeCandidatePath(n)??this.currentDirectory??``,l=this.getScopedSdkClient(o);this.assertCapturedRuntime(r,i,`session agent switch`),await l.session.switchAgent({sessionID:e,agent:a}),this.assertCapturedRuntime(r,i,`session agent switch`),fo(e,o||n,{agent:a})}async generateSessionAside(e){let t=typeof e.sessionId==`string`?e.sessionId.trim():``;if(!t)throw Error(`generateSessionAside requires sessionId`);let n=typeof e.prompt==`string`?e.prompt:``,r=this.normalizeCandidatePath(e.directory)??this.currentDirectory??``,i=await this.getScopedSdkClient(r).session.generate({sessionID:t,prompt:n},e.signal?{signal:e.signal}:void 0);if(!i||typeof i.text!=`string`)throw Error(`session.generate returned invalid payload`);return{text:i.text}}async applySendSelection(e,t,n){t.model&&await this.switchSessionModel(e,t.model,n),t.agent&&await this.switchSessionAgent(e,t.agent,n)}async withDirectory(e,t){let n=async()=>{if(e==null)return t();let n=this.currentDirectory,r=this.normalizeCandidatePath(e)??e;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory===r&&(this.currentDirectory=n)}},r=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=r.then(()=>void 0,()=>void 0),r}getApiClient(){return this.client}async getSystemInfo(){let e=new Set,t=t=>{let n=this.normalizeCandidatePath(t);n&&e.add(n)};try{let e=await this.client.location.get(K(this.currentDirectory));e&&(t(e.directory),t(e.project?.directory),t(e.project?.canonical))}catch{}if(!e.size)try{let e=await this.client.location.get(K(this.currentDirectory));t(e?.project?.directory),t(e?.project?.canonical)}catch{}if(!e.size)try{(await this.listSessions()).forEach(e=>t(e.directory))}catch{}if(t(this.currentDirectory),typeof window<`u`)try{t(ae(`lastDirectory`)),t(ae(`homeDirectory`))}catch{}if(!e.size&&typeof process<`u`&&typeof process.cwd==`function`&&t(process.cwd()),!e.size)return{homeDirectory:`/`,username:void 0};let[n]=Array.from(e);return this.deriveHomeDirectory(n)}async probeDirectory(e){let t=this.normalizeCandidatePath(e);if(!t)return!1;try{let e=await this.client.location.get({location:{directory:t}}),n=typeof e?.directory==`string`?e.directory:null;return!!(n&&n.trim().length>0)}catch{return!1}}async listSessions(){let e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data.map(v):[]}async searchSessionsByTitle(e){let t=e.search.trim(),n=await this.client.session.list({search:t||void 0,parentID:null,limit:e.limit??30,order:`desc`},e.signal?{signal:e.signal}:void 0);if(!Array.isArray(n?.data))throw Error(`session.list search returned no data`);return n.data.map(v)}async createSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;if(e?.metadata,e?.parentID){let t=await this.client.session.fork({sessionID:e.parentID});return e.title?(await this.client.session.update({sessionID:t.id,title:e.title}),v(await this.client.session.get({sessionID:t.id}))):v(t)}return v(await this.client.session.create({...n?{location:{directory:n}}:{},title:e?.title}))}async getSession(e,t){return v(await this.client.session.get({sessionID:e}))}async deleteSession(e,t){return await this.client.session.remove({sessionID:e}),!0}async deleteSessionMessage(e,t,n){throw G(`session.deleteMessage`)}async updateSession(e,t,n){let r=t.title!==void 0,i=t.metadata!==void 0,a=t.time!==void 0&&Object.prototype.hasOwnProperty.call(t.time,`archived`);if(!r&&!i&&!a)throw G(`session.update`);let o=this.normalizeCandidatePath(n)??this.currentDirectory,l=s(),d=c(),f=()=>{if(s()!==l||c()!==d){let e=Error(`session.update discarded: runtime switched`);throw e.name=`RuntimeGenerationMismatchError`,e}},p=[],m=null,h=null,g=e=>{if(p.length===0)throw e;let t=ll(e),n=Error(`session.update partial failure after ${p.join(`,`)}: ${t}`);throw n.name=`SessionUpdatePartialFailureError`,n.cause=e,n.completed=[...p],n};try{if(r&&(await this.client.session.update({sessionID:e,title:t.title}),f(),p.push(`title`),m=v(await this.client.session.get({sessionID:e})),f()),i){let n={patch:t.metadata};o&&(n.directory=o);let r=await u(`/api/yuri/sessions/${encodeURIComponent(e)}/metadata`,{method:`PUT`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(n)});if(f(),!r.ok){let e=Error(`session.metadata update failed (${r.status})`);throw e.status=r.status,e}let i=await r.json().catch(()=>null);f(),h=typeof i==`object`&&i&&!Array.isArray(i)&&`metadata`in i&&i.metadata!==null&&typeof i.metadata==`object`&&!Array.isArray(i.metadata)?i.metadata:null,p.push(`metadata`)}if(a){let n=t.time?.archived,r;if(n==null)r=0;else if(typeof n==`number`&&Number.isFinite(n))r=n>0?Math.trunc(n):0;else throw Error(`archivedAt must be a finite number or null`);let i={archivedAt:r};o&&(i.directory=o);let a=await u(`/api/yuri/sessions/${encodeURIComponent(e)}/archive`,{method:`PUT`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(i)});if(f(),!a.ok){let e=Error(`session.archive update failed (${a.status})`);throw e.status=a.status,e}let s=await a.json().catch(()=>null);f();let c=typeof s==`object`&&s&&!Array.isArray(s)&&`session`in s?s.session:null;if(!c||typeof c!=`object`||Array.isArray(c))throw Error(`session.archive update failed: empty response`);m=v(c),p.push(`archive`)}return m||(m=await this.getSession(e,n),f()),h&&!a?{...m,metadata:h}:m}catch(e){return g(e)}}async getSessionMessages(e,t){return(await $e({sessionID:e,directory:this.currentDirectory??``,...typeof t==`number`?{limit:t}:{}})).records}async getSessionDiff(e,t){let n=this.normalizeCandidatePath(e.directory)??this.currentDirectory,r=typeof e.messageID==`string`&&e.messageID.trim().length>0?e.messageID.trim():void 0,i=new URLSearchParams;n&&i.set(`directory`,n),r&&i.set(`messageID`,r);let a=i.toString(),o=await u(`/api/session/${encodeURIComponent(e.sessionID)}/diff${a?`?${a}`:``}`,{method:`GET`,headers:{Accept:`application/json`},signal:t?.signal});if(!o.ok){let e=Error(`session.diff failed (${o.status})`);throw e.status=o.status,e}let s=await o.json().catch(()=>null),c=typeof s==`object`&&s&&Array.isArray(s.data)?s.data:null;if(!c)throw Error(`session.diff failed: empty response`);return c}async getSessionTodos(e){throw G(`session.todo`)}shouldNormalizeToTextPlain(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`text/`)&&t!==`text/plain`?!0:[`application/json`,`application/xml`,`application/javascript`,`application/typescript`,`application/x-yaml`,`application/yaml`,`application/toml`,`application/x-sh`,`application/x-shellscript`,`application/octet-stream`,`image/svg+xml`].includes(t)}isHeicMime(e){if(!e)return!1;let t=e.toLowerCase();return t===`image/heic`||t===`image/heif`}async convertHeicToJpeg(t){try{let n=fs(t.url,t.mime);if(!n)return t;let r=await yo(n)??await(await he(async()=>{let{default:t}=await import(`./vendor-heic2any-DgJnLT1Y.js`).then(t=>e(t.t(),1));return{default:t}},__vite__mapDeps([0,1]))).default({blob:n,toType:`image/jpeg`,quality:.9}),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)}),a=t.filename;return a&&=a.replace(/\.heic$/i,`.jpg`).replace(/\.heif$/i,`.jpg`),{mime:`image/jpeg`,filename:a,url:i}}catch(e){return console.warn(`Failed to convert HEIC to JPEG:`,e),t}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let t=e.url;if(e.url.startsWith(`data:`)){let n=e.url.indexOf(`,`);if(n!==-1){let r=e.url.substring(5,n),i=e.url.substring(n);t=`data:${r.replace(/^[^;,]+/,`text/plain`)}${i}`}}return{mime:`text/plain`,filename:e.filename,url:t}}async toNormalizedFilePartInput(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c(),i=wl(e)?await this.normalizeFilePart(e):e;this.assertCapturedRuntime(n,r,`prompt attachment normalize`);let a=i.url,o;if(ps(a)){let e=a.startsWith(`blob:`)?await fetch(a).then(e=>e.blob()):fs(a,i.mime);if(!e)throw Error(`Failed to materialize attachment bytes for ${i.filename??`file`}`);this.assertCapturedRuntime(n,r,`prompt attachment upload`);let t=await ms({body:e,mime:i.mime,filename:i.filename});this.assertCapturedRuntime(n,r,`prompt attachment upload`),a=t.url,o=t.size}if(wl(i)&&o===void 0&&a.toLowerCase().startsWith(`file://`)){let e=ss(a),t=p()?.files;if(t?.statFile)o=(await t.statFile(e)).size;else{let t=await u(`/api/fs/stat`,{query:{path:e}});if(!t.ok)throw Error(`Failed to inspect prompt attachment`);o=(await t.json()).size}this.assertCapturedRuntime(n,r,`prompt attachment stat`)}return{...e.id?{id:e.id}:{},type:`file`,mime:i.mime,filename:i.filename,url:a,...wl(i)&&(o===void 0||!Number.isSafeInteger(o)||o<0||o>Sl)?{referenceOnly:!0}:{}}}async buildMessageParts(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c();return El(e,e=>this.toNormalizedFilePartInput(e,{generation:n,runtimeKey:r}))}async sendMessage(e){let t=s(),n=c(),r=()=>{this.assertCapturedRuntime(t,n,`session prompt discarded`)};r();let i=e.messageId??ue(`msg`),a=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,o=Ys(a??``),l=await this.buildMessageParts({text:e.text,prefaceText:e.prefaceText,prefaceTextSynthetic:e.prefaceTextSynthetic,files:e.files,additionalParts:e.additionalParts,agentMentions:e.agentMentions},{generation:t,runtimeKey:n});r(),W(o)||this.assertCapturedRuntime(t,n,`session prompt discarded`),e.format&&(e.id,e.providerID,e.modelID,e.agent,e.variant,this.baseUrl,e.format.type),tl(e.providerID);let u=l.flatMap(e=>e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(`
|
|
4
|
+
`)}function Qt(e,t,n,r){let i=Ut(n,t,r),a=e.findIndex(e=>e.id===i);return a>=0?a:e.map((e,t)=>({part:e,index:t})).filter(e=>e.part.type===t)[r]?.index??-1}function $t(e,t,n,r,i,a,o){Gt(e,t,n,o);let s=e.part[n]?[...e.part[n]]:[],c=Qt(s,r,n,i);if(c<0){let e={id:Ut(n,r,i),sessionID:t,messageID:n,type:r,text:``};s.push(e),c=s.length-1}let l=s[c],u=typeof a==`function`?a(l.text??``):a;return s[c]={...l,text:u},e.part[n]=s,!0}function en(e,t){return e.findIndex(e=>e.id===t||e.callID===t||e.type===`tool`&&e.id===t)}function O(e,t,n,r,i,a,o){Gt(e,t,n,o);let s=e.part[n]?[...e.part[n]]:[],c=en(s,r);return c<0&&(s.push({id:r,sessionID:t,messageID:n,type:`tool`,tool:Ge(i)??`tool`,callID:r,state:{status:`pending`,input:``,output:void 0,metadata:{}}}),c=s.length-1),s[c]=a(s[c]),e.part[n]=s,!0}function tn(e,t,n){return e.message[t]?.find(t=>e.part[t.id]?.some(e=>e.type===`text`&&e.shellAction?.shellID===n))?.id}function nn(e,t){let n=String(t.type);if(n.startsWith(`session.compaction.`))return Ct(e,t);let r=T(t.properties);if(!r)return!1;let i=E(r.sessionID);if(i&&(n===`session.shell.started`||n===`session.shell.ended`)){let a=T(r.shell),o=E(a?.id);if(!a||!o)return!1;let s=e.message[i]??[],c=tn(e,i,o),l=c?s.find(e=>e.id===c):void 0,u=l?.id??(n===`session.shell.started`?Ue(t.id):void 0);if(!u||n===`session.shell.started`&&l)return!1;let d=Ze(i,{id:u,type:`shell`,shellID:o,command:a.command,status:a.status,exit:a.exit,output:r.output,time:{created:l?.time.created??D(r),...n===`session.shell.ended`?{completed:D(r)}:{}}});return!d||l&&Mt(l,d.info)&&Mt(e.part[u],d.parts)?!1:(e.message[i]=l?s.map(e=>e.id===u?d.info:e):[...s,d.info],e.part[u]=d.parts,!0)}if(i&&n===`session.synthetic`){let n=Ue(t.id);if(!n)return!1;let a=Ze(i,{id:n,type:`synthetic`,text:r.text,description:r.description,metadata:r.metadata,time:{created:D(r)}});if(!a)return!1;let o=e.message[i]??[],s=o.find(e=>e.id===n);return s&&Mt(s,a.info)&&Mt(e.part[n],a.parts)?!1:(e.message[i]=s?o.map(e=>e.id===n?a.info:e):[...o,a.info],e.part[n]=a.parts,!0)}if(n===`session.revert.committed`)return!1;let a=E(r.assistantMessageID);if(!i||!a)return!1;let o=typeof r.ordinal==`number`?r.ordinal:0,s={created:D(r)};if(n===`session.step.started`||n===`session.step.streamed`||n===`session.step.ended`||n===`session.step.failed`)return Xt(e,n,i,a,r);if(n===`session.text.started`)return $t(e,i,a,`text`,o,``,s);if(n===`session.text.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?$t(e,i,a,`text`,o,e=>e+t,s):!1}if(n===`session.text.ended`)return $t(e,i,a,`text`,o,typeof r.text==`string`?r.text:``,s);if(n===`session.reasoning.started`)return $t(e,i,a,`reasoning`,o,``,s);if(n===`session.reasoning.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?$t(e,i,a,`reasoning`,o,e=>e+t,s):!1}if(n===`session.reasoning.ended`)return $t(e,i,a,`reasoning`,o,typeof r.text==`string`?r.text:``,s);let c=E(r.id);if(!c)return!1;let l=E(r.name);if(n===`session.tool.input.started`)return O(e,i,a,c,l,e=>e,s);if(n===`session.tool.input.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?O(e,i,a,c,l,e=>{let n=T(e.state)??{};if(E(n.status)&&n.status!==`pending`&&n.status!==`streaming`)return e;let r=typeof n.input==`string`?n.input+t:t;return{...e,state:{...n,status:`pending`,input:r}}},s):!1}if(n===`session.tool.input.ended`){let t=typeof r.text==`string`?r.text:``;return O(e,i,a,c,l,e=>{let n=T(e.state)??{};return{...e,state:{...n,input:t}}},s)}return n===`session.tool.called`?O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r);return{...e,state:{...t,status:`pending`,input:r.input??t.input??{},metadata:T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),start:n}}}}},s):n===`session.tool.progress`?O(e,i,a,c,l,e=>{let t=T(e.state)??{};return{...e,state:{...t,metadata:T(r.metadata)??T(t.metadata)??{}}}},s):n===`session.tool.success`?O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r);return{...e,state:{...t,status:`completed`,input:t.input??r.input??{},output:Zt(r.content),metadata:T(r.metadata)??T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),end:n}}}}},s):n===`session.tool.failed`&&O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r),i=T(r.error);return{...e,state:{...t,status:`error`,input:t.input??{},output:Zt(r.content),error:i?E(i.message)??E(r.error):E(r.error),metadata:T(r.metadata)??T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),end:n}}}}},s)}function rn(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function an(e){let t=e.id;return typeof t==`string`&&t.length>0?t:void 0}function k(e){return e.slim===!0}function on(e,t){if(!e||e.length===0||!t.some(e=>k(e)))return t;let n=new Map;for(let t of e){let e=an(t);e&&!k(t)&&n.set(e,t)}if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!k(e))return e;let t=an(e);if(!t)return e;let i=n.get(t);return i?(r=!0,i):e});return r?i:t}function sn(e,t){return e===t||e.length===t.length&&e.every((e,n)=>e===t[n])?t:e}function cn(e){let t=e.clientRole??e.role;return typeof t==`string`?t:``}function ln(e){return cn(e)!==`assistant`||!rn(e)}function un(e,t,n){if(!e||e.length===0)return t;let r=on(e,t);if(ln(n))return sn(r,e);let i=new Set;for(let e of r){let t=an(e);t&&i.add(t)}let a=new Map,o=[],s,c=0;for(let t of e){let e=an(t);if(e&&i.has(e)){s=e;continue}if(!e)continue;if(c+=1,!s){o.push(t);continue}let n=a.get(s);if(n){n.push(t);continue}a.set(s,[t])}if(c===0)return sn(r,e);let l=[...o];for(let e of r){l.push(e);let t=an(e);if(!t)continue;let n=a.get(t);n&&l.push(...n)}return sn(l,e)}var A=e=>Object.freeze(e),dn=Object.freeze({initial:A({id:`initial`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),prepend:A({id:`history`,onStale:`drop`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),recovery:A({id:`recovery`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),"reconcile-page":A({id:`reconcile-page`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`keep-unless-full`}),materialize:A({id:`materialize`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`})}),fn=A({id:`recovery-backfill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),pn=A({id:`send-gap-fill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),mn=dn.initial;function hn(e){let t=dn[e.purpose]??mn;return!e.stale||t.onStale===`drop`?t:fn}function gn(e,t){return e.preserveStreaming===`none`?!1:e.preserveStreaming===`all`||t===`assistant`}var _n=e=>structuredClone(e),vn=e=>({transport:e.transport,generation:e.generation,directory:e.directory,sessionID:e.sessionID});function yn(e){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID])}function bn(e,t){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID,t])}function xn(e){return JSON.stringify([e.transport,e.generation])}function Sn(e,t){return e.created===t.created?e.messageID<t.messageID?-1:+(e.messageID>t.messageID):e.created-t.created}function Cn(e){let t=e.time?.created;return{created:typeof t==`number`&&Number.isFinite(t)?t:0,messageID:e.id}}function wn(e){return ln(e)}function Tn(e){return k(e)?`slim`:`full`}function En(e){return e.some(e=>k(e))?`slim`:`full`}var Dn=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(Dn);let t=e,n={};for(let e of Object.keys(t).sort()){let r=t[e];r!==void 0&&(n[e]=Dn(r))}return n},On=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n};async function kn(e,t){let n=JSON.stringify(Dn({info:e,parts:t})),r=new TextEncoder().encode(n);return{hash:On(await crypto.subtle.digest(`SHA-256`,r)),byteSize:r.byteLength}}var An=e=>({scope:vn(e.scope),messageID:e.messageID,info:_n(e.info),parts:_n(e.parts),partCompleteness:e.partCompleteness.slice(),completeness:e.completeness,contentHash:e.contentHash,byteSize:e.byteSize,lastAccessedAt:e.lastAccessedAt,sortKey:{created:e.sortKey.created,messageID:e.sortKey.messageID}}),jn=e=>{let t=0;return()=>{let n=e();return t=n>t?n:t+1,t}},Mn=(e,t)=>{let n=t.slice().sort((e,t)=>Sn(e.sortKey,t.sortKey)).map(An);return{scope:vn(e),records:n,byteSize:n.reduce((e,t)=>e+t.byteSize,0)}},Nn=e=>_n(e),Pn=e=>vn(e),Fn=(e=Date.now)=>jn(e),In=e=>An(e),Ln=(e,t)=>Mn(e,t.slice());function Rn(e){return wn(e.info)?e.existing?.completeness===`full`&&e.incomingCompleteness===`slim`?{status:`skipped`,reason:`slim-downgrade`}:e.incomingHash!==void 0&&e.existing?.contentHash===e.incomingHash?{status:`skipped`,reason:`unchanged`}:{status:`written`}:{status:`skipped`,reason:`not-settled`}}var zn=[`text`,`output`],Bn={pending:1,started:2,running:3,completed:4,error:4};function Vn(e,t){return e.filter(e=>!!e?.id&&!t.has(e.type))}function Hn(e,t){if(!e||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.id!==i.id||JSON.stringify(r)!==JSON.stringify(i))return!1}return!0}function Un(e){let t=e.state?.time?.end;if(typeof t==`number`)return t;let n=e.time?.end;return typeof n==`number`?n:void 0}function Wn(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Gn(e){return Un(e)===void 0&&zn.some(t=>{let n=Wn(e,t);return typeof n==`string`&&n.length>0})}function Kn(e){let t=e.state;if(!(!t||typeof t!=`object`))return t}function qn(e){let t=Kn(e)?.status;return typeof t==`string`?t:void 0}function Jn(e){return e?Bn[e]??0:0}function Yn(e,t){if(Gn(e))return!0;if(Un(e)===void 0){if(e.type===`tool`){let n=qn(e);return n===`completed`||n===`error`?t:!0}return!0}return t}function Xn(e){let t=e.state?.time;if(!t||typeof t!=`object`)return;let n=typeof t.start==`number`?t.start:void 0,r=typeof t.end==`number`?t.end:void 0;if(n!==void 0||r!==void 0)return{start:n,end:r}}function Zn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0}function Qn(e,t,n){if(e.type!==`tool`||t.type!==`tool`)return n;let r=Kn(e);if(!r)return n;let i=Kn(n)??{},a=Kn(t)??{},o={...i},s=!1,c=qn(e),l=qn(t);Jn(c)>Jn(l)&&c&&(o={...o,status:c},s=!0);let u=r.input,d=a.input;Zn(u)&&!Zn(d)&&(o={...o,input:u},s=!0);let f=r.output,p=a.output;typeof f==`string`&&f.length>0?(typeof p!=`string`||p.length<f.length)&&(typeof p!=`string`||p.length===0||f.startsWith(p))&&(o={...o,output:f},s=!0):f!==void 0&&p===void 0&&(o={...o,output:f},s=!0);let m=r.metadata;return Zn(m)&&!Zn(a.metadata)&&(o={...o,metadata:m},s=!0),s?n===t?{...t,state:o}:{...n,state:o}:n}function $n(e,t){if(!e||Un(t)!==void 0)return t;let n=t;for(let r of zn){let i=Wn(e,r);if(!i)continue;let a=Wn(t,r);if(typeof a==`string`&&a.length>=i.length||typeof a==`string`&&a.length>0&&!i.startsWith(a))continue;n===t&&(n={...t});let o=n;o[r]=i}let r=Xn(e);if(r){let e=Xn(t),i=e?.start??r.start,a=e?.end??r.end;if(i!==e?.start||a!==e?.end){n===t&&(n={...t});let e=n;e.state={...n.state??{},time:{start:i,end:a}}}}return n=Qn(e,t,n),n}function er(e,t){if(!e||e.length===0||!t.some(e=>k(e)))return t;let n=new Map;for(let t of e)t.id&&!k(t)&&n.set(t.id,t);if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!k(e)||!e.id)return e;let t=n.get(e.id);return t?(r=!0,t):e});return r?i:t}function tr(e){return e.__yuriOptimistic===!0}function nr(e){return!!(e&&e.length>0&&e.some(tr))}function rr(e){return e.length===0||e.some(e=>k(e))}function ir(e,t,n,r,i,a){if(a===`keep-unless-full`&&e&&nr(e)&&rr(t))return e;let o=er(e,t);if(!e||e.length===0||!r)return o;let s=new Map(e.map(e=>[e.id,e])),c=o,l=!1;for(let e=0;e<o.length;e+=1){let t=o[e],n=$n(s.get(t.id),t);n!==t&&(l||(c=[...o]),c[e]=n,l=!0)}let u=new Set(o.map(e=>e.id)),d=o.some(e=>k(e)),f=e.filter(e=>!!e?.id&&!u.has(e.id)&&!n.has(e.type)&&(Yn(e,i)||d&&!k(e)));if(f.length===0)return c;let p=new Set(f.map(e=>e.id)),m=new Map,h=[];for(let t of e)p.has(t.id)?h.push(t):u.has(t.id)&&h.length>0&&(m.set(t.id,h),h=[]);let g=[];for(let e of c){for(let t of m.get(e.id)??[])g.push(t);g.push(e)}for(let e of h)g.push(e);return g}var ar=e=>e,or=e=>{let t=ar(e).finish;return typeof t==`string`&&t.length>0},sr=e=>typeof ar(e).time?.completed==`number`,cr=e=>!!ar(e).error;function lr(e,t){let n=ar(t),r=n.finish,i=n.time?.completed,a=n.time?.streamed,o=n.error,s=e.tokens,c=t.tokens,l=!or(e)&&typeof r==`string`&&r.length>0,u=!sr(e)&&typeof i==`number`,d=e.time.streamed===void 0&&typeof a==`number`&&Number.isFinite(a),f=!cr(e)&&!!o,p=!It(s)&&It(c);if(!l&&!u&&!d&&!f&&!p)return e;let m={...e};return l&&(m.finish=r),(u||d)&&(m.time={...ar(e).time,...u?{completed:i}:{},...d?{streamed:a}:{}}),f&&(m.error=o),p&&(m.tokens=c),m}function ur(e,t,n,r){if(t.length===0)return e;let i=new Map(t.map(e=>[e.id,e])),a=!1,o=[];for(let t of e){let e=n(t,i.get(t.id));e!==t&&(a=!0),o.push(e)}let s=new Set(e.map(e=>e.id));if(!t.some(e=>s.has(e.id)))return r===`prepend`?[...t,...o]:r===`by-created`?dr(o,t):[...o,...t];let c=new Map(t.map(e=>[e.id,e]));for(let e of o)c.set(e.id,e);let l=Me(e.map(e=>e.id),t.map(e=>e.id)).map(e=>c.get(e));return!a&&l.length===e.length&&l.every((t,n)=>t===e[n])?e:l}function dr(e,t){let n=e.slice();for(let e of t){let t=Cn(e),r=n.length;for(let e=0;e<n.length;e+=1)if(Sn(t,Cn(n[e]))<0){r=e;break}n.splice(r,0,e)}return n}function fr(e,t,n){return ur(e,t,(e,t)=>t?lr(e,t):e,n)}function pr(e,t,n){return ur(e,t,(e,t)=>!t||JSON.stringify(e)===JSON.stringify(t)?e:zt(e,t),n)}function mr(e,t,n,r={}){let i=r.skipPartTypes??new Set,a=r.merge??mn,o=r.placeUnanchoredNewMessages??`append`,s=n.filter(e=>!!e?.info?.id),c=s.map(e=>e.info),l=e.message[t],u=l??[],d=a.messages===`upsert`?pr(u,c,o):fr(u,c,o),f=d!==u||l===void 0&&s.length===0,p=!1,m={...e.part},h=a.parts===`skip-existing`;for(let e of s){let t=e.info.id;if(h&&m[t])continue;let n=e.info.role===`assistant`,r=m[t],o=ir(r,Vn(e.parts??[],i),i,gn(a,e.info.role),rn(e.info),a.protectOptimistic);(r?Hn(r,o):o.length===0&&!n)||o.length===0&&!n||(m[t]=o,p=!0)}return{message:f?{...e.message,[t]:d}:e.message,part:p?m:e.part,messages:d,messagesChanged:f,partsChanged:p}}function hr(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function gr(e){let t=e.messages;if(!t)return{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]};let n=t.length>0?t[t.length-1]?.id:void 0,r=[];for(let i of t)i.role===`assistant`&&(e.parts[i.id]||i.id===n&&hr(i)||r.push(i.id));return{hasMessages:!0,renderable:r.length===0,missingPartMessageIDs:r}}var _r=(e,t)=>e<t?-1:+(e>t);function vr(e){return e.filter(e=>!!e?.id)}function yr(e,t){if(t.length===0)return{...e,confirmed:[]};let n=[...e.session],r=new Map(e.part.map(e=>[e.id,vr(e.part)])),i=[];for(let e of t){if(n.findIndex(t=>t.id===e.message.id)<0){n.push(e.message),r.set(e.message.id,vr(e.parts));continue}let t=r.get(e.message.id);if(t&&t.length>0){i.push(e.message.id);continue}r.set(e.message.id,vr(e.parts))}return{cursor:e.cursor,complete:e.complete,session:n,part:[...r.entries()].sort((e,t)=>_r(e[0],t[0])).map(([e,t])=>({id:e,part:t})),confirmed:i}}var br={kind:`unknown`,loadedTurns:0},xr=3e4,Sr=12e5,Cr={project:``,projectMeta:void 0,icon:void 0,provider:{all:[],connected:[],default:{}},config:{},path:{state:``,config:``,worktree:``,directory:``,home:``},status:`loading`,agent:[],command:[],session:[],sessionTotal:0,session_status:{},session_status_observed_at:{},session_status_event_at:{},session_status_event_sequence:{},session_interrupt_acknowledged_at:{},session_execution_version:{},session_status_snapshot_at:void 0,session_error_at:{},session_execution_recovery:{},session_diff:{},todo:{},permission:{},question:{},lsp:[],vcs:void 0,limit:20},wr={ready:!1,path:{state:``,config:``,worktree:``,directory:``,home:``},projects:[],providers:{all:[],connected:[],default:{}},providerAuth:{},config:{},reload:void 0,sessionTodo:{}};function Tr(e,t){return e===void 0||t===void 0?!1:t>e}var Er=class extends Error{};function Dr(e,t,n){if(n===`reconcile-page`)return e??br;let r=0;typeof t.turnCount==`number`&&Number.isFinite(t.turnCount)?r=Math.max(0,Math.floor(t.turnCount)):typeof t.requestedTurnLimit==`number`&&Number.isFinite(t.requestedTurnLimit)?r=Math.max(0,Math.floor(t.requestedTurnLimit)):t.records.length>0&&(r=1);let i=e?.loadedTurns??0,a=n===`prepend`?i+r:r;if(t.complete)return{kind:`exhausted`,loadedTurns:a};let o=typeof t.cursor==`string`&&t.cursor.length>0?t.cursor:void 0;if(!o)throw new Er(`session message page: complete=false requires non-empty cursor`);if(n===`prepend`&&e?.kind===`has-more`&&e.cursor===o)throw new Er(`session message page: prepend returned the same cursor without progress`);if(t.records.length===0&&(n!==`prepend`||e?.kind!==`has-more`||e.cursor===o)&&n!==`initial`)throw new Er(`session message page: complete=false with zero records makes no progress`);return{kind:`has-more`,cursor:o,loadedTurns:a}}function Or(e,t){return!e||!t?e===t:e.kind!==t.kind||e.loadedTurns!==t.loadedTurns?!1:e.kind===`has-more`&&t.kind===`has-more`?e.cursor===t.cursor:!0}function kr(e,t,n,r){let i=Tr(r.capturedRevision,r.liveRevision),a=hn({purpose:r.purpose,stale:i}),o=e.session_history_boundary?.[t];if(!n.ok)return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:e.message[t]??[],boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[],error:n.error};if(i&&a.onStale===`drop`){let n=e.message[t]??[];if(n.length>0)return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:n,boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[]}}let s=r.optimistic??[],c=yr({session:n.records.map(e=>e.info),part:n.records.map(e=>({id:e.info.id,part:e.parts??[]})),cursor:n.cursor,complete:n.complete},s),l=mr(e,t,c.session.map(e=>({info:e,parts:c.part.find(t=>t.id===e.id)?.part??[]})),{skipPartTypes:r.skipPartTypes,merge:a,placeUnanchoredNewMessages:r.purpose===`prepend`?`prepend`:r.purpose===`reconcile-page`?`by-created`:`append`}),u;try{u=Dr(o,{ok:!0,records:n.records,cursor:c.cursor,complete:c.complete,turnCount:n.turnCount,requestedTurnLimit:n.requestedTurnLimit},r.purpose)}catch(n){if(!(n instanceof Er))throw n;return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:e.message[t]??[],boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[],error:n.message}}let d=!Or(o,u),f=l.messagesChanged,p=l.partsChanged,m=f||p||d,h=[];c.confirmed.length>0&&h.push({type:`clear-optimistic`,messageIDs:c.confirmed});let g=d||!o?u:o;return{applied:!0,merge:a,changed:m,messagesChanged:f,partsChanged:p,boundaryChanged:d,message:l.message,part:l.part,messages:l.messages,boundary:g,meta:{limit:g.loadedTurns,cursor:g.kind===`has-more`?g.cursor:void 0,complete:g.kind===`exhausted`},confirmedOptimisticIDs:c.confirmed,commands:h}}var Ar=new Set([`tool`,`reasoning`,`file`,`text`]),jr=new Set([`tool`,`reasoning`,`file`]);function Mr(e){return e.some(e=>k(e)&&Ar.has(e.type))}function Nr(e,t){let n=!1,r=!1;for(let t of e)jr.has(t.type)&&(n=!0,k(t)&&(r=!0));return n?r?!0:t?rn(t):!1:!1}var Pr=e=>{if(!e)return``;let t=e.clientRole??e.role;return typeof t==`string`?t:``};function Fr(e,t){return He(e,t)}function Ir(e){let t=0;for(let n of e.messageOrder)Fr(e.messagesByID[n],e.partsByMessageID[n])&&(t+=1);return t}var Lr=(e,t)=>{let n=e.messageOrder.lastIndexOf(t);if(n<0)return[];let r=[];for(let i=n+1;i<e.messageOrder.length;i+=1){let n=e.messageOrder[i],a=e.messagesByID[n];if(!a)continue;if(Fr(a,e.partsByMessageID[n]))break;if(Pr(a)!==`assistant`)continue;let o=a.parentID;typeof o==`string`&&o.length>0&&o!==t||r.push(a)}return r},Rr=(e,t)=>rn(e)?!0:Array.isArray(t)&&t.length>0;function zr(e){let t;for(let n=e.messageOrder.length-1;n>=0;--n){let r=e.messageOrder[n];if(Fr(e.messagesByID[r],e.partsByMessageID[r])){t=r;break}}return t?Lr(e,t).some(t=>Rr(t,e.partsByMessageID[t.id])):!1}function Br(e){return e.materializeActive?`p2`:e.prependActive||e.earlierHistoryLoaded?`p1`:e.p0Satisfied?`p0`:`idle`}var Vr=new Set([`stop`,`length`]);function Hr(e){let t=e.messageOrder[e.messageOrder.length-1];if(!t)return!1;let n=e.messagesByID[t];if(!n||Pr(n)!==`assistant`||n.error)return!1;let r=n.finish;return typeof r!=`string`||!Vr.has(r)?!1:typeof n.time?.completed!=`number`||r===`stop`&&!It(n.tokens)}function Ur(e,t){return t.kind===`has-more`?{sessionID:e,boundary:t,hasPreviousPage:!0,isComplete:!1,cursor:t.cursor,loadedTurns:t.loadedTurns}:t.kind===`exhausted`?{sessionID:e,boundary:t,hasPreviousPage:!1,isComplete:!0,cursor:null,loadedTurns:t.loadedTurns}:{sessionID:e,boundary:t,hasPreviousPage:!1,isComplete:!1,cursor:null,loadedTurns:t.loadedTurns}}function Wr(e){let t={},n={},r=[];for(let i of e.messages){if(!i?.id)continue;r.push(i.id),t[i.id]=i;let a=e.parts[i.id];a&&(n[i.id]=a)}return{sessionID:e.sessionID,messageOrder:r,messagesByID:t,partsByMessageID:n,boundary:e.boundary,liveRevision:e.liveRevision??0}}var Gr=`message.updated,message.removed,message.part.updated,message.part.removed,message.part.delta,session.step.started,session.step.streamed,session.shell.started,session.shell.ended,session.step.ended,session.step.failed,session.text.started,session.text.delta,session.text.ended,session.reasoning.started,session.reasoning.delta,session.reasoning.ended,session.tool.input.started,session.tool.input.delta,session.tool.input.ended,session.tool.called,session.tool.progress,session.tool.success,session.tool.failed,session.compaction.started,session.compaction.delta,session.compaction.ended,session.compaction.failed,session.synthetic,session.revert.committed`.split(`,`);function Kr(e){return Gr.includes(e)}function j(e){return e.trim()}function qr(e){return`${j(e.directory)}\n${e.sessionID}`}function Jr(e,t){return e.session_history_boundary?.[t]??br}function Yr(e){return e.filter(e=>!!e?.id)}function Xr(e,t){return e.kind!==t.kind||e.loadedTurns!==t.loadedTurns?!1:e.kind===`has-more`&&t.kind===`has-more`?e.cursor===t.cursor:!0}function Zr(e,t,n){n.applied&&e.setState(e=>{let r={};if(n.messagesChanged&&(r.message=n.message),n.partsChanged&&(r.part=n.part),n.boundary&&(n.boundaryChanged||!e.session_history_boundary?.[t]))r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary};else if(n.boundary&&n.boundaryChanged===!1){let i=e.session_history_boundary?.[t];(!i||!Xr(i,n.boundary))&&(r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary})}return!r.message&&!r.part&&!r.session_history_boundary&&n.boundary&&(r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary}),!r.message&&!r.part&&!r.session_history_boundary?{}:r})}function Qr(e,t,n){let r=e.getState(),i=n.page,a=kr(r,t,{ok:!0,records:i.records.map(e=>({info:e.info,parts:e.parts?[...e.parts]:[]})),cursor:i.cursor,complete:i.complete,turnCount:i.turnCount,requestedTurnLimit:i.requestedTurnLimit},{purpose:n.purpose,skipPartTypes:n.skipPartTypes,optimistic:n.optimistic?n.optimistic.map(e=>({message:e.message,parts:[...e.parts]})):void 0,capturedRevision:n.capturedLiveRevision,liveRevision:n.liveRevision});return a.applied?(Zr(e,t,a),{applied:!0,changed:a.changed,boundary:a.boundary,meta:a.meta,confirmedOptimisticIDs:a.confirmedOptimisticIDs}):{applied:!1,changed:!1,error:a.error}}function $r(e,t){if(t.length===0)return{applied:!1,changed:!1};let n=e.getState(),r={message:{...n.message??{}},part:{...n.part??{}}},i=!1,a=!1,o;for(let e of t){if(!Kr(e.type))continue;i=!0;let t=Ht(r,e),n=typeof t==`boolean`?t:t.changed,s=typeof t==`boolean`?void 0:t.materialization;s&&!o&&(o=s),n&&(a=!0)}return i?a?(e.setState({message:r.message,part:r.part}),{applied:!0,changed:!0,...o?{materialization:o}:{}}):{applied:!0,changed:!1,...o?{materialization:o}:{}}:{applied:!1,changed:!1}}function ei(e,t){return $r(e,[t.event])}function ti(e,t){return $r(e,t.events)}function ni(e,t,n){if(n.records.length===0)return{applied:!1,changed:!1};let r=e.getState(),i=mr({message:r.message??{},part:r.part??{}},t,n.records.map(e=>({info:e.info,parts:e.parts?[...e.parts]:[]})),{skipPartTypes:n.skipPartTypes,merge:n.merge});return!i.messagesChanged&&!i.partsChanged?{applied:!0,changed:!1}:(e.setState({...i.messagesChanged?{message:i.message}:{},...i.partsChanged?{part:i.part}:{}}),{applied:!0,changed:!0})}function ri(e,t,n){let r=e.getState(),i=r.message?.[t],a=r.part?.[n]!==void 0;if(!i&&!a)return{applied:!0,changed:!1};let o={...r.message??{}},s=!1;if(i){let e=[...i],r=e.findIndex(e=>e.id===n);r>=0&&(e.splice(r,1),o[t]=e,s=!0)}let c={...r.part??{}},l=!1;return c[n]!==void 0&&(delete c[n],l=!0),!s&&!l?{applied:!0,changed:!1}:(e.setState({...s?{message:o}:{},...l?{part:c}:{}}),{applied:!0,changed:!0})}function ii(e,t,n,r,i){r.setOptimisticShadow?.({directory:i,sessionID:t,message:n.message,parts:n.parts});let a=e.getState(),o={...a.message??{}},s={...a.part??{}},c=o[t]?[...o[t]]:[];return c.some(e=>e.id===n.message.id)||c.push(n.message),o[t]=c,s[n.message.id]=Yr(n.parts),e.setState({message:o,part:s}),{applied:!0,changed:!0}}function ai(e,t,n,r,i){r.clearOptimisticShadow?.({directory:i,sessionID:t,messageID:n});let a=e.getState(),o={...a.message??{}},s={...a.part??{}},c=!1,l=o[t];if(l){let e=[...l],r=e.findIndex(e=>e.id===n);r>=0&&(e.splice(r,1),o[t]=e,c=!0)}return s[n]!==void 0&&(delete s[n],c=!0),c&&e.setState({message:o,part:s}),{applied:!0,changed:c}}function oi(e,t,n,r){return n.clearOptimisticShadow?.({directory:r,sessionID:e,messageID:t}),{applied:!0,changed:!1}}function si(e,t){let n=e.getState(),r=n.message?.[t],i=n.session_history_boundary?.[t],a=!!(r&&r.length>0),o=i!==void 0,s=new Set;if(r)for(let e of r)e?.id&&s.add(e.id);let c=!1,l={...n.part??{}};for(let e of s)l[e]!==void 0&&(delete l[e],c=!0);for(let[e,n]of Object.entries(l))s.has(e)||n?.some(e=>e.sessionID===t)&&(delete l[e],c=!0);if(!a&&!o&&!c)return!1;let u={...n.message??{}};delete u[t];let d={...n.session_history_boundary??{}};return delete d[t],e.setState({message:u,part:l,session_history_boundary:d}),!0}function ci(e,t,n){let r=si(e,t);if(!n.page)return{applied:!0,changed:r};let i=Qr(e,t,{type:`http-page`,purpose:`initial`,page:n.page,capturedLiveRevision:n.capturedLiveRevision,liveRevision:n.liveRevision,skipPartTypes:n.skipPartTypes});return{...i,changed:r||i.changed,applied:i.applied||r}}function li(e){let t=new Map,n=new Map,r=r=>{let i=qr(r);if(n.has(i))return;let a=j(r.directory),o=e.getStore(a),s=r.sessionID,c=o.getState().message?.[s],l=Jr(o.getState(),s),u=new Map;for(let e of c??[])u.set(e.id,o.getState().part?.[e.id]);let d=o.subscribe(e=>{let n=e.message?.[s],a=Jr(e,s),o=!1,d=new Map;for(let t of n??[]){let n=e.part?.[t.id];d.set(t.id,n),u.get(t.id)!==n&&(o=!0)}u.size!==d.size&&(o=!0);let f=n!==c,p=Xr(a,l);if(c=n,l=a,u=d,!f&&!o&&p)return;let m=t.get(i);if(!(!m||m.size===0))for(let e of m)e(r)});n.set(i,d)},i=e=>{let r=t.get(e);if(r&&r.size>0)return;let i=n.get(e);i&&(i(),n.delete(e)),t.delete(e)},a={getTranscript(t){let n=j(t.directory),r=e.getStore(n).getState(),i=t.sessionID,a=r.message?.[i]??[],o=e.getLiveRevision?.(n,i)??0;return Wr({sessionID:i,messages:a,parts:r.part??{},boundary:Jr(r,i),liveRevision:o})},getPagination(t){let n=j(t.directory),r=e.getStore(n).getState();return Ur(t.sessionID,Jr(r,t.sessionID))},getRequestState(t){let n=j(t.directory);return e.getRequestState?.(n,t.sessionID)??{sessionID:t.sessionID,status:`idle`}},getHydrationState(e){let t=a.getTranscript(e),n=zr(t);return{sessionID:e.sessionID,p0Satisfied:n,phase:Br({p0Satisfied:n,earlierHistoryLoaded:Ir(t)>1})}},getMessage(e,t){return a.getTranscript(e).messagesByID[t]},getParts(t,n){let r=j(t.directory);return e.getStore(r).getState().part?.[n]??[]},hasSession(t){let n=j(t.directory),r=e.getStore(n).getState().message;return r?Object.prototype.hasOwnProperty.call(r,t.sessionID):!1},apply(t,n){let r=j(t.directory),i=e.getStore(r),a=t.sessionID;switch(n.type){case`http-page`:return Qr(i,a,n);case`sse-event`:return ei(i,n);case`sse-event-batch`:return ti(i,n);case`optimistic-add`:return ii(i,a,n,e,r);case`optimistic-confirm`:return oi(a,n.messageID,e,r);case`optimistic-remove`:return ai(i,a,n.messageID,e,r);case`reset`:return ci(i,a,n);case`materialize-snapshots`:return ni(i,a,n);case`remove-message`:return ri(i,a,n.messageID);case`revert-committed`:{let e=i.getState(),t=e.message?.[a];if(!Array.isArray(t)||t.length===0)return{applied:!0,changed:!1};let r=t.findIndex(e=>e.id===n.to);if(r<0)return{applied:!0,changed:!1};let o=t.slice(r),s=t.slice(0,r),c={...e.message??{}};c[a]=s;let l={...e.part??{}};for(let e of o)delete l[e.id];return i.setState({message:c,part:l}),{applied:!0,changed:o.length>0}}default:return{applied:!1,changed:!1}}},subscribe(e,n){let a=qr(e),o=t.get(a);return o||(o=new Set,t.set(a,o)),o.add(n),r(e),()=>{let e=t.get(a);e&&(e.delete(n),i(a))}}};return a}var ui=new Set,di=new Set;function fi(e,t){return`${e}\n${t}`}function pi(){for(let e of di)e()}function mi(e,t){!e||!t||(ui.add(fi(e,t)),pi())}function hi(e,t){!e||!t||ui.delete(fi(e,t))&&pi()}function gi(e,t){if(!e)return!1;if(t)return ui.has(fi(t,e));let n=`\n${e}`;for(let e of ui)if(e.endsWith(n))return!0;return!1}function _i(e){return di.add(e),()=>{di.delete(e)}}var vi=[],yi=new Map,bi=new Map,xi=0,Si=()=>{let e=vi.findIndex(e=>e.priority===`user`);if(e>=0){let[t]=vi.splice(e,1);return t}return vi.shift()},Ci=()=>{for(;xi<4;){let e=Si();if(!e)return;yi.delete(e.key),xi+=1,Promise.resolve().then(()=>e.run()).then(t=>{e.resolve(t)},t=>{e.reject(t)}).finally(()=>{--xi,bi.delete(e.key),Ci()})}};function wi(e,t,n){let r=n?.priority??`background`,i=bi.get(e);if(i){let t=yi.get(e);return t&&r===`user`&&t.priority!==`user`&&(t.priority=`user`),i}let a,o,s=new Promise((e,t)=>{a=e,o=t}),c={key:e,priority:r,run:()=>t(),resolve:e=>{a(e)},reject:o};return vi.push(c),yi.set(e,c),bi.set(e,s),Ci(),s}var Ti=null,Ei=0,Di=new Set;function Oi(){Ei+=1;for(let e of Di)e()}function ki(e){return e}function Ai(e){return Di.add(e),()=>{Di.delete(e)}}function ji(){return Ei}function Mi(e){return Ti?.repository===e?e:(Ti={kind:`query`,repository:e},Oi(),e)}function Ni(){Ti&&(Ti=null,Oi())}function M(){return Ti?.repository??null}function Pi(){let e=M();if(!e)throw Error(`TranscriptRepository is not bound — SyncProvider must mount first`);return e}function Fi(e,t){let n=M();if(n)return n;let r=ki(t);return li({getStore:e=>r})}function N(e,t,n){return{directory:e.trim(),sessionID:t,...n?.transport===void 0?{}:{transport:n.transport},...n?.generation===void 0?{}:{generation:n.generation}}}function Ii(e){try{let t=M(),n=o(),r=s();return t?.getCacheBudget?.().listCanonicalScopesForSession(e,{transport:n,generation:r})?.map(e=>N(e.directory,e.sessionID,{transport:e.transport,generation:e.generation}))??[]}catch{return[]}}function Li(e,t){let n=M();return n?n.apply(e,t):null}async function Ri(e,t,n){let r=Pi();if(typeof r.fetchPreviousPage!=`function`)throw Error(`TranscriptRepository does not support fetchPreviousPage`);await r.fetchPreviousPage(N(e,t),n)}async function zi(e,t){let n=Pi();if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support ensureInitial`);await n.ensureInitial(N(e,t))}async function Bi(e,t){let n=Pi(),r=N(e,t);if(typeof n.destructiveReset==`function`){await n.destructiveReset(r);return}if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support retryInitial`);await n.ensureInitial(r)}async function Vi(e,t,n){let r=Pi();if(typeof r.refreshFromAuthority!=`function`)throw Error(`TranscriptRepository does not support refreshFromAuthority`);if(n?.background){await r.refreshFromAuthority(N(e,t));return}mi(e,t);try{await r.refreshFromAuthority(N(e,t))}finally{hi(e,t)}}async function Hi(e,t,n,r){let i=Pi();if(typeof i.materializeMessage!=`function`)throw Error(`TranscriptRepository does not support materializeMessage`);let a=N(e,t);await wi(`${e}\n${t}\n${n}`,()=>i.materializeMessage(a,n),{priority:r?.priority??`background`})}function Ui(e,t,n){let r=M();return!r||typeof r.getMessageMaterializationState!=`function`?{sessionID:t,messageID:n,status:`idle`}:r.getMessageMaterializationState(N(e,t),n)}function Wi(e,t){M()?.purgeSession?.(N(e,t))}var P=null;function Gi(e){P&&P!==e&&P.cancelAll(`reregister`),P=e}function Ki(e){P?.captureCheckpoints(e)}function qi(e){P?.onCompensation(e)}async function Ji(e){return P?P.ensureOnObserve(e):null}function Yi(e){P?.cancelAll(e)}var Xi=e=>typeof e==`number`&&Number.isFinite(e)?e:0,Zi=e=>Xi(e.input)+Xi(e.output)+Xi(e.reasoning)+Xi(e.cache?.read)+Xi(e.cache?.write),Qi=e=>e?.type===`compaction`,$i=e=>!!e&&e.some(Qi),ea=(e,t)=>e.clientRole===`compaction`||e.type===`compaction`||$i(t),ta=(e,t)=>{for(let n=e.length-1;n>=0;--n){let r=e[n],i=r.id?t(r.id):void 0;if(ea(r,i)){let e=i?.find(Qi)?.status??r.status;if(e===`running`||e===`failed`)continue;return{compacted:!0}}if(r.role!==`assistant`)continue;let a=r.tokens;if(!a)continue;let o=Zi(a);if(o>0)return{messageId:r.id??``,totalTokens:o,tokens:a}}return null},na=(e,t,n)=>{if(!e)return null;let r=`compacted`in e,i=r?0:e.totalTokens;return{...r?{pending:!0}:{},totalTokens:i,percentage:t>0?Math.round(i/t*100):0,contextLimit:t||0,outputLimit:n||void 0,normalizedOutput:!r&&n>0?Math.round(Xi(e.tokens.output)/n*100):void 0,thresholdLimit:t>0?t:2e5,lastMessageId:r?void 0:e.messageId}},ra=[],ia=[],aa={sessionID:``,messageOrder:[],messagesByID:{},partsByMessageID:{},boundary:br,liveRevision:0};Ur(``,br);var oa={sessionID:``,phase:`idle`,p0Satisfied:!1};function F(e,t){return Fi(e,t)}var sa=new Set;function ca(e,t){return`${e}\n${t}`}function la(e,t){if(!t)return;let n=ca(e,t);sa.has(n)||(sa.add(n),Ji(N(e,t)).catch(()=>{}).finally(()=>{sa.delete(n)}))}function ua(e,t){if(e&&t){sa.delete(ca(e,t));return}sa.clear()}function da(e,t,n,r,i=Object.is,a){let o=(0,y.useRef)(r);o.current=r;let s=(0,y.useRef)(i);s.current=i;let c=(0,y.useRef)(void 0),l=(0,y.useRef)(null),u=a?.enabled!==!1,d=(0,y.useMemo)(()=>()=>{let r=ji(),i=e&&u?F(t,n):null,a=i?.getTranscript(N(t,e))??aa,d=i?.hasSession?.(N(t,e)),f=o.current,p=s.current,m=l.current;if(m?.data===a&&m.select===f&&m.isEqual===p&&m.repository===i&&m.bindingRevision===r&&m.directory===t&&m.sessionID===e&&m.enabled===u&&m.resolved===d)return c.current;let h=f(a);return(c.current===void 0||!p(c.current,h))&&(c.current=h),l.current={data:a,select:f,isEqual:p,repository:i,bindingRevision:r,directory:t,sessionID:e,enabled:u,resolved:d},c.current},[t,u,e,n]),f=(0,y.useMemo)(()=>r=>{if(!e||!u)return()=>void 0;la(t,e);let i=F(t,n).subscribe(N(t,e),()=>{r()}),a=Ai(()=>{i(),c.current=void 0,l.current=null,ua(t,e),la(t,e),i=F(t,n).subscribe(N(t,e),()=>{r()}),r()});return()=>{a(),i()}},[t,u,e,n]);return y.useSyncExternalStore(f,d,d)}function fa(e,t,n,r,i,a){return da(e,t,n,r,i===void 0?Object.is:i,a)}function pa(e,t){if(e.messageOrder.length===0)return ra;if(t&&t.length>0){let n=!0,r=0;for(let i of e.messageOrder){let a=e.messagesByID[i];if(a){if(r>=t.length||t[r]!==a){n=!1;break}r+=1}}if(n&&r===t.length)return t}let n=[];for(let t of e.messageOrder){let r=e.messagesByID[t];r&&n.push(r)}return n}function ma(e,t){return e.messageOrder.length===0?t?.resolved===!0?gr({messages:ra,parts:e.partsByMessageID}):{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]}:gr({messages:pa(e),parts:e.partsByMessageID})}var ha=(e,t)=>e.hasMessages===t.hasMessages&&e.renderable===t.renderable&&e.missingPartMessageIDs.length===t.missingPartMessageIDs.length&&e.missingPartMessageIDs.every((e,n)=>e===t.missingPartMessageIDs[n]);function ga(e,t,n,r){let i=(0,Ce.c)(4),a;return i[0]!==t||i[1]!==e||i[2]!==n?(a=r=>{if(!e)return{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]};let i=F(t,n).hasSession?.(N(t,e));return ma(r,{resolved:i===!0||void 0})},i[0]=t,i[1]=e,i[2]=n,i[3]=a):a=i[3],da(e,t,n,a,ha,r)}function _a(e,t,n,r,i){let a=(0,Ce.c)(3),o;return a[0]!==r||a[1]!==i?(o=e=>na(ta(pa(e),t=>e.partsByMessageID[t]),r,i),a[0]=r,a[1]=i,a[2]=o):o=a[2],da(e,t,n,o,va)}function va(e,t){return e===t||!!(e&&t&&e.pending===t.pending&&e.totalTokens===t.totalTokens&&e.percentage===t.percentage&&e.contextLimit===t.contextLimit&&e.outputLimit===t.outputLimit&&e.normalizedOutput===t.normalizedOutput&&e.lastMessageId===t.lastMessageId)}var ya=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0};function ba(e,t,n,r){return da(e,t,n,pa,ya,r)}function xa(e,t){if(e===t)return!0;if(e.sessionID!==t.sessionID||e.liveRevision!==t.liveRevision||e.boundary.kind!==t.boundary.kind||e.boundary.loadedTurns!==t.boundary.loadedTurns||e.boundary.kind===`has-more`&&t.boundary.kind===`has-more`&&e.boundary.cursor!==t.boundary.cursor||e.messageOrder.length!==t.messageOrder.length)return!1;for(let n=0;n<e.messageOrder.length;n+=1){let r=e.messageOrder[n];if(r!==t.messageOrder[n]||e.messagesByID[r]!==t.messagesByID[r]||e.partsByMessageID[r]!==t.partsByMessageID[r])return!1}return!0}function Sa(e,t,n,r){return da(e,t,n,Ca,xa,r)}function Ca(e){return e}function wa(e,t,n,r){if(e.length===0)return()=>void 0;let i=[],a=()=>{for(let e of i)e();i=[]},o=()=>{let r=new Set;for(let a of e){let e=`${a.directory}\n${a.sessionID}`;if(r.has(e))continue;r.add(e);let o=M();if(o){i.push(o.subscribe(N(a.directory,a.sessionID),t));continue}let s=n?.(a.directory);if(!s)continue;let c=Fi(a.directory,s);i.push(c.subscribe(N(a.directory,a.sessionID),t))}},s=()=>{a(),o(),t()};o();let c=Ai(s),l=r?.subscribeRebuild?.(s);return()=>{l?.(),c(),a()}}function Ta(e,t){return e.length===0?``:e.map(e=>{let n=La(e.directory,e.sessionID,t?.(e.directory)),r=n[n.length-1];return`${e.sessionID}:${r?.id??``}:${r?.role??``}:${r?.time?.completed??``}`}).join(`\0`)}function Ea(e,t,n){return da(e,t,n,Da)}function Da(e){return e.messageOrder.length}function Oa(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(!1),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current=!1,!1;let r=F(t,n),a=r.hasSession?.(N(t,e))??r.getTranscript(N(t,e)).messageOrder.length>0;return i.current=a,i.current},r[0]=t,r[1]=e,r[2]=n,r[3]=a):a=r[3];let o=a,s;r[4]!==t||r[5]!==e||r[6]!==n?(s=r=>e?F(t,n).subscribe(N(t,e),()=>{r()}):ka,r[4]=t,r[5]=e,r[6]=n,r[7]=s):s=r[7];let c=s;return y.useSyncExternalStore(c,o,o)}function ka(){}function Aa(e,t,n,r){let i=(0,Ce.c)(10),a=(0,y.useRef)(void 0),o;i[0]!==t||i[1]!==e||i[2]!==r||i[3]!==n?(o=()=>{if(!e)return a.current=ia,ia;let i=F(t,n),o=r||e,s=i.getParts(N(t,o),e),c=s.length===0?ia:s;if(a.current===void 0||a.current!==c){if(a.current&&a.current.length===c.length&&a.current.every((e,t)=>e===c[t]))return a.current;a.current=c}return a.current},i[0]=t,i[1]=e,i[2]=r,i[3]=n,i[4]=o):o=i[4];let s=o,c;i[5]!==t||i[6]!==e||i[7]!==r||i[8]!==n?(c=i=>{if(!e)return Ma;let a=F(t,n);return r?a.subscribe(N(t,r),()=>{i()}):ja},i[5]=t,i[6]=e,i[7]=r,i[8]=n,i[9]=c):c=i[9];let l=c;return y.useSyncExternalStore(l,s,s)}function ja(){}function Ma(){}function Na(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(oa),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current!==oa&&(i.current=oa),i.current;let r=F(t,n).getHydrationState?.(N(t,e))??{sessionID:e,phase:`idle`,p0Satisfied:!1},a=i.current;return a.sessionID===r.sessionID&&a.phase===r.phase&&a.p0Satisfied===r.p0Satisfied?a:(i.current=r,r)},r[0]=t,r[1]=e,r[2]=n,r[3]=a):a=r[3];let o=a,s;r[4]!==t||r[5]!==e||r[6]!==n?(s=r=>{if(!e)return Pa;la(t,e);let a=F(t,n).subscribe(N(t,e),()=>{r()}),o=Ai(()=>{a(),i.current=oa,ua(t,e),la(t,e),a=F(t,n).subscribe(N(t,e),()=>{r()}),r()});return()=>{o(),a()}},r[4]=t,r[5]=e,r[6]=n,r[7]=s):s=r[7];let c=s;return y.useSyncExternalStore(c,o,o)}function Pa(){}function Fa(e,t,n){let r=(0,Ce.c)(2),i;return r[0]===e?i=r[1]:(i=t=>Ur(e,t.boundary),r[0]=e,r[1]=i),da(e,t,n,i,Ia)}function Ia(e,t){return e.sessionID===t.sessionID&&e.hasPreviousPage===t.hasPreviousPage&&e.isComplete===t.isComplete&&e.cursor===t.cursor&&e.loadedTurns===t.loadedTurns&&e.boundary.kind===t.boundary.kind&&e.boundary.loadedTurns===t.boundary.loadedTurns&&(e.boundary.kind!==`has-more`||t.boundary.kind!==`has-more`||e.boundary.cursor===t.boundary.cursor)}function La(e,t,n){if(!t)return[];let r=M();if(r){let n=r.getTranscript(N(e,t));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}if(!n)return[];let i=Fi(e,n).getTranscript(N(e,t));return i.messageOrder.map(e=>i.messagesByID[e]).filter(e=>!!e)}var I=null,Ra=``,za=null,Ba=new Set,Va=null,Ha=new Map,Ua=new Map;function Wa(e,t,n,r){I=t,Va!==t&&(Va=null,Ha=new Map,Ua=new Map),Ra=n,r&&(za=r)}function Ga(e,t){za?.(e,t)}function Ka(){if(!I)throw Error(`ChildStoreManager not initialized — is SyncProvider mounted?`);return I}function qa(e){let t=I;if(!t)return;let n=e||Ra;if(n)return t.getState(n)}function Ja(e){let t=qa(e)?.config;return t&&Object.keys(t).length>0?t:void 0}function Ya(e){return Ba.add(e),()=>{Ba.delete(e)}}function Xa(e,t){if(e)for(let n of Ba)n(e,t)}function Za(e){return qa(e)?.session??[]}function Qa(){return Array.from($a().values())}function $a(){let e=I;if(!e)return Ua;let t=Va!==e||Ha.size!==e.children.size;for(let[n,r]of e.children)if(Ha.get(n)!==r.getState().session){t=!0;break}if(!t)return Ua;let n=new Map,r=new Map;for(let[t,i]of e.children){let e=i.getState().session;n.set(t,e);for(let t of e)t?.id&&r.set(t.id,t)}return Va=e,Ha=n,Ua=r,Ua}function eo(e,t,n){if(n){let r=[];for(let[i,a]of n)if(a.session.some(t=>t.id===e)&&a.hasTranscript===!0){if(i===t)return i;r.push(i)}return r.length===1?r[0]:void 0}let r=[];try{let n=M();if(I){for(let[i,a]of I.children)if(a.getState().session.some(t=>t.id===e)&&(n??Fi(i,a)).hasSession?.(N(i,e))){if(i===t)return i;r.push(i)}}if(r.length===0&&n){let i=n.getCacheBudget?.().listCanonical();if(i){for(let n of i)if(n.scope.sessionID===e){if(n.scope.directory===t)return n.scope.directory;r.push(n.scope.directory)}}}}catch{}let i=[...new Set(r)];return i.length===1?i[0]:void 0}function to(e,t){if(!e)return[];try{let n=M(),r=t??Ra;if(n){let t=n.getTranscript(N(r,e));return t.messageOrder.map(e=>t.messagesByID[e]).filter(e=>!!e)}if(I){let t=I.getChild(r);if(t){let n=Fi(r,t).getTranscript(N(r,e));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}}}catch{}return[]}function no(e,t){if(!e)return[];try{let n=M(),r=t??Ra;if(n)return[...n.getParts(N(r,e),e)];if(I){let t=I.getChild(r);if(t)return[...Fi(r,t).getParts(N(r,e),e)]}}catch{}return[]}var L=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},ro=`default`;function io(e){let t=L(e);if(t&&t!==ro)return t}function ao(e){let t=e?.model;return L(t?.id)??L(t?.modelID)}function oo(e){let t=e?.model;return L(t?.providerID)}function so(e){let t=e?.model;return io(t?.variant)}function co(e){let t=io(e.variant);return{id:e.modelID.trim(),providerID:e.providerID.trim(),...t?{variant:t}:{}}}function lo(e,t,n){let r=L(n.providerID),i=L(n.modelID);if(!r||!i)return{agent:L(n.agent)};let a=(qa(t)?.session??Qa()).find(t=>t.id===e),o=co({providerID:r,modelID:i,variant:n.variant}),s=ao(a),c=oo(a),l=so(a),u=io(o.variant),d=!a||!s||!c||c!==o.providerID||s!==o.id||l!==u,f=L(n.agent),p=L(a?.agent);return{model:d?o:void 0,agent:f&&p!==f?f:void 0}}function uo(e,t,n){if(e&&!(!n.model&&!n.agent))try{let r=Ka(),i=typeof t==`string`&&t.length>0?t:void 0;if(!i)return;let a=r.getChild?.(i)??r.ensureChild?.(i,{bootstrap:!1});if(!a?.getState||!a?.setState)return;a.setState(t=>{let r=t.session;if(!Array.isArray(r))return t;let i=r.findIndex(t=>t.id===e);if(i<0)return t;let a=r[i];if(!a)return t;let o=n.model?{id:n.model.id??n.model.modelID??``,providerID:n.model.providerID,...n.model.variant?{variant:n.model.variant}:{}}:a.model,s={...a,...n.model&&o?.id&&o.providerID?{model:o}:{},...n.agent?{agent:n.agent}:{}};if(s===a)return t;let c=r.slice();return c[i]=s,{...t,session:c}})}catch{}}var fo=new Set([`image/heic`,`image/heif`]),po=!1,mo=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},ho=e=>fo.has((e.type||``).toLowerCase()),go=async e=>{let t=new Uint8Array(await e.arrayBuffer()),n=``,r=32768;for(let e=0;e<t.byteLength;e+=r){let i=t.subarray(e,Math.min(e+r,t.byteLength));n+=String.fromCharCode(...i)}return btoa(n)},_o=(e,t)=>{let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new Blob([r],{type:t})},vo=async e=>{if(!ho(e)||po)return null;let t=mo();if(!t||typeof t.isNativePlatform!=`function`||!t.isNativePlatform())return null;let n=t.Plugins?.YuriMedia?.transcode;if(typeof n!=`function`)return null;try{let t=await n({data:await go(e),mime:e.type.toLowerCase(),quality:.9});if(typeof t?.data!=`string`||!t.data)return null;let r=typeof t.mime==`string`&&t.mime?t.mime:`image/jpeg`;return _o(t.data,r)}catch(e){return po=!0,console.warn(`Native HEIC transcode failed`,e),null}},yo=e=>e.trim().toLowerCase(),bo=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,xo=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(yo)),r=[],i=0;for(;i<e.length;){let t=e.indexOf(`[`,i);if(t===-1)break;let a=e.indexOf(`]`,t+1);if(a===-1)break;if(e[a+1]!==`(`){let i=se(e.slice(t+1,a)).trim();n.has(yo(i))&&r.push({start:t,end:a+1})}i=a+1}return r},So=(e,t)=>{let n=t.start,r=t.end;return r<e.length&&/\s/.test(e[r])?r+=1:n>0&&/\s/.test(e[n-1])&&--n,{start:n,end:r}},Co=(e,t,n,r)=>{let i=xo(e,t);if(i.length===0)return{text:e,mentions:[...n],composerReferences:r===void 0?void 0:[...r],changed:!1};let a=e,o=[...n],s=r===void 0?[]:[...r];for(let e=i.length-1;e>=0;--e){let{start:t,end:n}=So(a,i[e]),r=n-t;a=`${a.slice(0,t)}${a.slice(n)}`,o=o.flatMap(e=>e.range.end<=t?[e]:e.range.start>=n?[{...e,range:{start:e.range.start-r,end:e.range.end-r}}]:[]),s=s.flatMap(e=>e.end<=t?[e]:e.start>=n?[{...e,start:e.start-r,end:e.end-r}]:[])}return{text:a,mentions:o,composerReferences:r===void 0?void 0:s,changed:!0}},wo=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),To={"image/avif":`avif`,"image/bmp":`bmp`,"image/gif":`gif`,"image/heic":`heic`,"image/heif":`heif`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/png":`png`,"image/svg+xml":`svg`,"image/tiff":`tiff`,"image/webp":`webp`},Eo=e=>e.trim().toLowerCase(),Do=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),Oo=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>Do(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},ko=e=>To[e?.trim().toLowerCase()??``]??`png`,Ao=e=>{let t=Oo(e.name),n=ko(e.type),r=t.lastIndexOf(`.`);if(r>0&&r<t.length-1){let e=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(e))return{base:t.slice(0,r).trim()||`image`,ext:e}}return{base:t.trim()||`image`,ext:n}},jo=e=>{let{base:t}=Ao({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(wo.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&wo.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},Mo=(e,t)=>`${e}.${t}`,No=(e,t,n)=>{let r=Mo(e,t);if(!n.has(Eo(r)))return r;for(let r=2;r<2**53-1;r+=1){let i=Mo(`${e}-${r}`,t);if(!n.has(Eo(i)))return i}return Mo(`${e}-${Date.now()}`,t)},Po=(e,t)=>{for(let n=1;n<2**53-1;n+=1){let r=Mo(`image-${n}`,e);if(!Array.from(t).some(e=>e.startsWith(`image-${n}.`))&&!t.has(Eo(r)))return r}return Mo(`image-${Date.now()}`,e)},Fo=(e,t)=>{let n=new Set(t.map(Eo));return e.map(e=>{let{base:t,ext:r}=Ao(e),i=jo(Mo(t,r))?Po(r,n):No(t,r,n);return n.add(Eo(i)),i})},Io=e=>e.map(e=>le(e)).join(` `),Lo=(e,t,n)=>{if(t===n)return[];let r=[];for(let i of e){let e=[le(i),`[${i}]`],a=e.some(e=>t.includes(e)),o=e.some(e=>n.includes(e));a&&!o&&r.push(i)}return r},Ro=(e,t)=>{if(t.length>=e.length)return null;let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n+=1;let i=0;for(;i<e.length-n&&i<t.length-n&&e[e.length-1-i]===t[t.length-1-i];)i+=1;let a=e.length-i;return t.length-i!==n||a<=n?null:{start:n,end:a}},zo=(e,t,n)=>{if(e===t||n.length===0)return null;let r=[...n],i=Ro(e,t);if(i){let t=Xo(e,r,{key:`Backspace`,selectionStart:i.start,selectionEnd:i.end});if(t)return t}let a=Lo(r,e,t);return a.length===0?null:{text:t,caret:t.length,removedFilenames:a}},Bo=e=>e.replaceAll(`[${oe}`,`[`),Vo=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Ho=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},Uo=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Ho(t)||!Vo.test(t)&&!Vo.test(r))continue;let i=`[${r}]`;n=n.split(le(t)).join(i).split(`[${t}]`).join(i)}return n},Wo=(e,t)=>{let n=e;for(let e of t??[]){if(e.source!==`vscode`||e.vscodeSource!==`selection`||!e.vscodePath)continue;let t=e.filename.match(/:(\d+(?:-\d+)?)$/)?.[1];if(!t)continue;let r=`[${e.vscodePath}:${t}]`;n=n.split(le(e.filename)).join(r).split(`[${e.filename}]`).join(r)}return n},Go=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),Ko=`application/x-directory`,qo=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,Jo=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),Yo=(e,t,n)=>{if(t===`Backspace`){let t=n;for(;t>0&&/\s/.test(e[t-1]);)--t;for(;t>0&&!/\s/.test(e[t-1]);)--t;return{start:t,end:n}}let r=n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;for(;r<e.length&&!/\s/.test(e[r]);)r+=1;return{start:n,end:r}},Xo=(e,t,n)=>{let r=Math.max(0,Math.min(n.selectionStart,e.length)),i=Math.max(r,Math.min(n.selectionEnd,e.length)),a;if(a=r===i?n.altKey?Yo(e,n.key,r):n.key===`Backspace`?{start:Math.max(0,r-1),end:r}:{start:r,end:Math.min(e.length,r+1)}:{start:r,end:i},a.start===a.end)return null;let o=xo(e,t).filter(e=>e.start<a.end&&e.end>a.start);if(o.length===0)return null;let s=Math.min(a.start,...o.map(e=>e.start)),c=Math.max(a.end,...o.map(e=>e.end));return c<e.length&&/\s/.test(e[c])&&(s===0||/\s/.test(e[s-1]))?c+=1:c===e.length&&s>0&&/\s/.test(e[s-1])&&--s,{text:`${e.slice(0,s)}${e.slice(c)}`,caret:s,removedFilenames:o.map(t=>se(e.slice(t.start+1,t.end-1)).trim())}},Zo=`<system-reminder>`,Qo=`</system-reminder>`,$o=/[ \t]*<system-reminder>[\s\S]*?<\/system-reminder>[ \t]*/g,es=/[ \t]*<system-reminder>[\s\S]*$/,ts=e=>{let t=e.trim();return t?t.startsWith(Zo)&&t.endsWith(Qo)?t:`${Zo}\n${t}\n${Qo}`:``},ns=e=>e.includes(Zo)?e.replace($o,``).replace(es,``).trim():e,rs=class extends Error{status;code;constructor(e,t,n=`Failed to upload prompt attachment`){super(n),this.name=`PromptAttachmentUploadError`,this.status=e,this.code=t}},is=`file://`,as=e=>{let t=e.trim();if(t.toLowerCase().startsWith(is))return t;let n=pe(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${is}/${n}`:`${is}${n}`},os=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(is))return t;let n=t.slice(7);n.toLowerCase().startsWith(`localhost/`)&&(n=n.slice(9));let r=n.split(`/`).map(e=>{if(/^[A-Za-z]:$/.test(e))return e;try{return decodeURIComponent(e)}catch{return e}}).join(`/`);return/^\/[A-Za-z]:/.test(r)?r.slice(1):r},ss=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),cs=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ls=async e=>{let t;try{t=await e.json()}catch{throw new rs(e.status,`unavailable`)}if(!cs(t)||typeof t.path!=`string`||!t.path)throw new rs(e.status,`unavailable`);let n=typeof t.mime==`string`&&t.mime?t.mime:`application/octet-stream`,r=typeof t.size==`number`&&Number.isSafeInteger(t.size)?t.size:0,i=typeof t.sha256==`string`?t.sha256:``;return{path:t.path,url:as(t.path),mime:n,size:r,sha256:i}},us=e=>{let t=typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n=e?.replace(/[^a-z0-9._-]+/gi,`-`).replace(/^-+|-+$/g,``).slice(0,32);return n?`att-${t}-${n}`:`att-${t}`},ds=(e,t)=>{if(!e.startsWith(`data:`))return null;let n=e.indexOf(`,`);if(n===-1)return null;let r=e.slice(5,n),i=e.slice(n+1),a=r.split(`;`,1)[0]?.trim()||t||`application/octet-stream`;try{if(r.toLowerCase().includes(`;base64`)){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new Blob([t],{type:a})}return new Blob([decodeURIComponent(i)],{type:a})}catch{return null}},fs=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),ps=async e=>{let t=me(),n=e.mime||e.body.type||`application/octet-stream`,r=e.body.type===n?e.body:new Blob([e.body],{type:n});if(!Number.isSafeInteger(r.size)||r.size<0)throw new rs(413,`too-large`);let i=await ss(r),a=us(e.filename),o;try{o=await u(`/api/fs/prompt-attachments/${encodeURIComponent(a)}?storage=temporary`,{method:`PUT`,headers:{"Content-Type":n,"Content-Length":String(r.size),"X-Yuri-Content-Length":String(r.size),"X-Yuri-Sha256":i,"X-Yuri-Mime":n,...e.filename?{"X-Yuri-Filename":encodeURIComponent(e.filename)}:{}},body:r,signal:e.signal})}catch{throw new rs(0,`unavailable`)}if(o.status===413)throw new rs(413,`too-large`);if(!o.ok)throw new rs(o.status,o.status>=500||o.status===0?`unavailable`:`rejected`);let s=await ls(o);if(s.size!==r.size)throw new rs(o.status,`unavailable`);return await t(r,s.sha256),{...s,mime:n}},ms=500,hs=()=>{if(typeof window>`u`)return!1;try{return new URLSearchParams(window.location.search).get(`startupTrace`)===`1`||window.localStorage?.getItem(`YURI_STARTUP_TRACE`)===`1`}catch{return!1}},gs=()=>hs(),R=(e,t)=>{if(!hs())return;let n=typeof performance<`u`?performance.now():Date.now();window.__YURI_STARTUP_TRACE_START__??=n,window.__YURI_STARTUP_TRACE__??=[],window.__YURI_STARTUP_TRACE__.push({t:Math.round(n-window.__YURI_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__YURI_STARTUP_TRACE__.length>ms&&window.__YURI_STARTUP_TRACE__.splice(0,window.__YURI_STARTUP_TRACE__.length-ms)};typeof window<`u`&&(window.__YURI_STARTUP_TRACE_SUMMARY__=()=>{let e=typeof window<`u`?window.__YURI_STARTUP_TRACE__??[]:[],t=e.findIndex(e=>e.name===`ModelControls:ready`),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(e=>e.name.includes(`checkConnection`)||e.name.includes(`checkHealth`)||e.name.includes(`initializeApp`)||e.name.includes(`initApp`)||e.name.includes(`loadProviders`)||e.name.includes(`loadAgents`)||e.name.includes(`config.defaults`)||e.name.includes(`ModelControls`)||e.name.includes(`activateDirectory`)||e.name.includes(`opencodeClient:setDirectory`))});var _s=async(e,t,n)=>{let r=typeof performance<`u`?performance.now():Date.now();R(`${e}:start`,n);try{let n=await t(),i=typeof performance<`u`?performance.now():Date.now();return R(`${e}:end`,{durationMs:Math.round(i-r)}),n}catch(t){let n=typeof performance<`u`?performance.now():Date.now();throw R(`${e}:error`,{durationMs:Math.round(n-r),error:t instanceof Error?t.message:String(t)}),t}},vs=e=>({kind:`session-inbox`,requestID:e.requestID,queueItemID:e.id,operationID:e.id,messageID:e.id,content:e.payload.text,createdAt:e.timeCreated,delivery:e.delivery,attachmentCount:Array.isArray(e.payload.files)?e.payload.files.length:0}),ys=[],bs=[],z=new Map,xs=512,Ss=0;function Cs(){return Ss}function B(){return{transportIdentity:o(),generation:s()}}function ws(e){return o()===e.transportIdentity&&s()===e.generation}function Ts(e,t,n){return`${n?.transportIdentity??o()}\0${n?.generation??s()}\0${e}\0${t}`}function Es(e=B()){if(z.size===0)return;let t=`${e.transportIdentity}\0${e.generation}\0`;for(let e of z.keys())e.startsWith(t)||z.delete(e);for(;z.size>xs;){let e=z.keys().next().value;if(e===void 0)break;z.delete(e)}}function Ds(e,t,n,r){let i=r??B();Es(i),Ss+=1,z.set(Ts(e,t,i),{kind:n,mark:Ss})}function Os(e,t,n){let r=n?.scope;Es(r??B());let i=z.get(Ts(e,t,r));if(!i)return!0;let a=n?.startedMark;return a!==void 0&&i.mark>a?!1:(z.delete(Ts(e,t,r)),!0)}function ks(e,t,n){return Es(n??B()),z.get(Ts(e,t,n))?.kind??null}var As=(e,t,n)=>{let r={...e};return n.length===0?delete r[t]:r[t]=n,r},V=m((e,t)=>({bySession:{},remember(t){return!ks(t.sessionID,t.id)&&(e(e=>{let n=e.bySession[t.sessionID]??[],r=n.findIndex(e=>e.id===t.id),i={...t,requestID:t.id};if(r>=0){let a=n.slice();return a[r]=i,{bySession:{...e.bySession,[t.sessionID]:a}}}return{bySession:{...e.bySession,[t.sessionID]:[...n,i]}}}),!0)},forget(t,n,r){r&&Ds(t,n,r),e(e=>{let r=e.bySession[t];if(!r?.length)return e;let i=r.filter(e=>e.id!==n);return i.length===r.length?e:{bySession:As(e.bySession,t,i)}})},forgetSession(t){e(e=>{if(!e.bySession[t])return e;let n={...e.bySession};return delete n[t],{bySession:n}})},forgetPromoted(t,n){let r=new Set(n);e(e=>{let n=e.bySession[t];if(!n?.length)return e;let i=new Set(n.filter(e=>r.has(e.id)).map(e=>e.id));if(i.size===0)return e;for(let e of i)Ds(t,e,`consumed`);return{bySession:As(e.bySession,t,n.filter(e=>!i.has(e.id)))}})},replaceFromAuthority(t,n,r){let i=r?.startedMark,a=[];for(let e of n)Os(t,e.id,{startedMark:i})&&a.push(e);e(e=>{let n=new Map((e.bySession[t]??[]).map(e=>[e.id,e])),i=r?.observedItems&&new Map(r.observedItems.map(e=>[e.id,e])),o=a.map(e=>({...e,requestID:e.id}));if(i){let e=new Map(o.map((e,t)=>[e.id,t]));for(let t of n.values()){if(i.get(t.id)===t)continue;let n=e.get(t.id);n===void 0?o.push(t):o[n]=t}}return{bySession:As(e.bySession,t,o)}})},updateDelivery(t,n,r){e(e=>{if(ks(t,n))return e;let i=e.bySession[t];if(!i?.length)return e;let a=i.findIndex(e=>e.id===n);if(a<0||i[a].delivery===r)return e;let o=i.slice();return o[a]={...i[a],delivery:r},{bySession:{...e.bySession,[t]:o}}})},list(e){return t().bySession[e]??ys}}));function js(e){return V.getState().remember(e)}function Ms(e,t){return Os(e.sessionID,e.id,t)?V.getState().remember(e):!1}function Ns(e,t,n){V.getState().forget(e,t,n)}function Ps(e,t){V.getState().forgetPromoted(e,t)}function Fs(e,t,n){V.getState().replaceFromAuthority(e,t,n)}function Is(e,t,n){V.getState().updateDelivery(e,t,n)}function Ls(e){return!!e&&typeof e==`object`&&e.kind===`session-inbox`}var Rs=e=>e?e.toLowerCase().includes(`application/json`):!1,zs=e=>e?e.toLowerCase().includes(`text/html`):!1;function H(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function U(e){return typeof e==`string`&&e.length>0?e:void 0}function Bs(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Vs(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function Hs(e){try{let t=(await e.text()).trim();if(!t)return``;try{let e=JSON.parse(t);if(typeof e.error==`string`&&e.error.trim())return e.error.trim();if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}return t}catch{return``}}function Us(e){return e?{directory:e}:{}}function Ws(e,t){let n=`/api/session/${encodeURIComponent(e)}/inbox`;return t?`${n}/${encodeURIComponent(t)}`:n}async function Gs(e,t){let n=e.headers.get(`content-type`);if(zs(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!Rs(n)&&r==null)throw Error(`${t}: empty response`);return r}function Ks(e){let t=H(e)?e:null,n=t&&H(t.data)?t.data:t;if(!n)throw Error(`session prompt: expected inbox item`);let r=U(n.type);if(r&&r!==`user`)throw Error(`session prompt: expected user inbox item, got ${r}`);let i=U(n.id),a=U(n.sessionID);if(!i||!a)throw Error(`session prompt: inbox item missing id`);let o=H(n.payload)?n.payload:{},s=n.delivery===`queue`?`queue`:`steer`,c=H(n.time)?n.time:null;return{id:i,sessionID:a,timeCreated:Bs(n.timeCreated)??Bs(c?.created)??Date.now(),type:`user`,delivery:s,payload:{text:U(o.text)??U(n.text)??``,...o.files===void 0?{}:{files:o.files},...o.agents===void 0?{}:{agents:o.agents},...o.skills===void 0?{}:{skills:o.skills},...H(o.metadata)?{metadata:o.metadata}:{}}}}function qs(e){let t=H(e)?e:null,n=t&&Array.isArray(t.data)?t.data:Array.isArray(e)?e:null;if(!n)throw Error(`session inbox: expected list`);let r=[];for(let e of n)H(e)&&(e.type&&e.type!==`user`||r.push(Ks(e)));return r}function Js(e){return{runtimeKey:c(),generation:s(),directory:e,overlay:B()}}function W(e){return c()===e.runtimeKey&&s()===e.generation&&ws(e.overlay)}function Ys(e){let t=Error(`${e}: runtime switched`);throw t.name=`RuntimeGenerationMismatchError`,t}async function Xs(e){let t=e.commit??Js(e.directory);W(t)||Ys(`session prompt`);let n=`/api/session/${encodeURIComponent(e.sessionID)}/prompt`,r={id:e.messageID,text:e.text,delivery:e.delivery===`queue`?`queue`:`steer`};e.files?.length&&(r.files=e.files),e.agents?.length&&(r.agents=e.agents),e.skills?.length&&(r.skills=e.skills),e.metadata&&(r.metadata=e.metadata);let i=await u(n,{method:`POST`,headers:{"Content-Type":`application/json`},query:{directory:t.directory},body:JSON.stringify(r),signal:e.signal});if(W(t)||Ys(`session prompt`),!i.ok){let e=await Hs(i);Vs(`Failed to send message`,i.status,e)}let a=Ks(await Gs(i,`session prompt`));return W(t)||Ys(`session prompt`),js(a),a}function Zs(e){let t=e?.status;return typeof t!=`number`||!Number.isFinite(t)||t===408||t===429?!1:t>=400&&t<500}async function Qs(e){let t=e.inputID.trim();if(!t)return{status:`unknown`};let n=e.commit??Js(e.directory??``);if(!W(n))return{status:`unknown`};try{let r=await ec({sessionID:e.sessionID,directory:n.directory||e.directory,signal:e.signal});if(!W(n)||!r.current)return{status:`unknown`};let i=r.items.find(e=>e.id===t);if(i)return Ms(i,{startedMark:r.startedMark})?{status:`pending`,item:i}:{status:`unknown`}}catch{}if(!W(n))return{status:`unknown`};try{let r=await $e({sessionID:e.sessionID,directory:n.directory||e.directory||``,limit:40,...e.signal?{signal:e.signal}:{}});if(!W(n))return{status:`unknown`};if(r.records.some(e=>e?.info?.id===t))return Ns(e.sessionID,t,`consumed`),{status:`promoted`,id:t}}catch{}return{status:`unknown`}}function $s(e){let t=typeof e.type==`string`?e.type:``,n=e.properties&&typeof e.properties==`object`?e.properties:null;if(!n)return!1;let r=U(n.sessionID),i=U(n.inboxID)??U(n.id);if(!r||!i)return!1;if(t===`session.inbox.enqueued`){let e=n.item,t=H(e)?U(e.type):void 0;if(t&&t!==`user`)return!1;try{return Ms(Ks(H(e)?{...e,id:i,sessionID:r,type:t??`user`}:{id:i,sessionID:r,type:`user`,delivery:`steer`,payload:{text:``}})),!0}catch{return!1}}if(t===`session.inbox.cancelled`)return Ns(r,i,`cancelled`),!0;if(t===`session.inbox.delivered`)return Ns(r,i,`consumed`),!0;if(t===`session.inbox.delivery.changed`){let e=n.delivery===`queue`?`queue`:n.delivery===`steer`?`steer`:null;return e?(Is(r,i,e),!0):!1}return!1}async function ec(e){let t=B(),n=Cs(),r=ut(e.sessionID),i={method:`GET`,query:Us(e.directory),signal:e.signal},a=await u(`/api/sessions/${encodeURIComponent(e.sessionID)}/delivery`,i);(a.status===404||a.status===501||zs(a.headers.get(`content-type`)))&&(a=await u(Ws(e.sessionID),i)),a.ok||Vs(`session inbox`,a.status,await Hs(a));let o=await Gs(a,`session inbox`),s=qs(o),c=ws(t);return c&&ut(e.sessionID)===r&&(H(o)&&typeof o.compactionRunning==`boolean`?w(e.sessionID,o.compactionRunning):gt(e.sessionID,ht(o))),{items:s,startedMark:n,scope:t,current:c}}async function tc(e){let t=B(),n=await u(Ws(e.sessionID,e.inboxID),{method:`PATCH`,headers:{"Content-Type":`application/json`},query:Us(e.directory),body:JSON.stringify({delivery:e.delivery}),signal:e.signal});n.ok||Vs(e.delivery===`steer`?`session inbox steer`:`session inbox queue`,n.status,await Hs(n)),ws(t)&&(ks(e.sessionID,e.inboxID)||Is(e.sessionID,e.inboxID,e.delivery))}async function nc(e){await tc({...e,delivery:`steer`})}async function rc(e){await tc({...e,delivery:`queue`})}async function ic(e){let t=await u(Ws(e.sessionID,e.inboxID),{method:`DELETE`,query:Us(e.directory),signal:e.signal});t.ok||Vs(`session inbox cancel`,t.status,await Hs(t))}function ac(e,t,n){Fs(e,t,n)}async function oc(e){let t=B();if(await ic(e),!ws(t))return{overlay:V.getState().list(e.sessionID),transcriptRows:[]};Ns(e.sessionID,e.inboxID,`cancelled`);try{let n=await ec({sessionID:e.sessionID,directory:e.directory,signal:e.signal});if(!ws(t)||!n.current)return{overlay:V.getState().list(e.sessionID),transcriptRows:[]};ac(e.sessionID,n.items,{startedMark:n.startedMark})}catch{}return{overlay:V.getState().list(e.sessionID),transcriptRows:[]}}async function sc(e){let t=`/api/session/${encodeURIComponent(e.sessionID)}/interrupt`,n={};e.directory&&(n.directory=e.directory),e.resume!==void 0&&(n.resume=String(e.resume));let r=await u(t,{method:`POST`,query:n,signal:e.signal});if(!r.ok)throw Error(`Session interrupt failed (${r.status})`)}async function cc(e){return e.promotedIDs.includes(e.optimisticID)?`confirmed`:(e.removeOptimistic(e.optimisticID),await e.refreshFromAuthority(),`refreshed`)}var lc=`session-revert-busy`,uc=e=>e?e.toLowerCase().includes(`text/html`):!1;function dc(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function fc(e){return typeof e==`string`&&e.length>0?e:void 0}function pc(e,t,n){if(t===409)throw mc();let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);if(i.status=t,t===404&&n)try{let e=JSON.parse(n);dc(e)&&e._tag===`MessageNotFoundError`&&(i.name=`MessageNotFoundError`)}catch{}throw i}function mc(){let e=Error(lc);return e.name=`SessionRevertBusyError`,e}function hc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`SessionRevertBusyError`||t.message===`session-revert-busy`}async function gc(e){try{return(await e.text()).trim()}catch{return``}}async function _c(e,t){if(uc(e.headers.get(`content-type`)))throw Error(`${t}: unexpected HTML response`);if(e.status===204)return null;let n=await e.text();if(!n.trim()){if(e.ok)return null;throw Error(`${t}: empty response`)}try{return JSON.parse(n)}catch{throw Error(`${t}: malformed JSON`)}}function vc(e){return e?{directory:e}:{}}function yc(e,t){return`/api/session/${encodeURIComponent(e)}/revert/${t}`}function bc(e){let t=dc(e)?e:null,n=t&&dc(t.data)?t.data:t;if(!n)throw Error(`session revert: expected revert payload`);let r=fc(n.messageID);if(!r)throw Error(`session revert: missing messageID`);let i=Array.isArray(n.files)?n.files.flatMap(e=>{if(!dc(e))throw Error(`session revert: invalid file diff`);let t=fc(e.file)??fc(e.path);if(!t||e.status!==`added`&&e.status!==`deleted`&&e.status!==`modified`||typeof e.additions!=`number`||typeof e.deletions!=`number`||typeof e.patch!=`string`)throw Error(`session revert: invalid file diff`);return[{file:t,status:e.status,additions:e.additions,deletions:e.deletions,patch:e.patch}]}):void 0;return{messageID:r,...fc(n.partID)?{partID:fc(n.partID)}:{},...fc(n.snapshot)?{snapshot:fc(n.snapshot)}:{},...i?{files:i}:{}}}function xc(e){return e?.files?e.files.flatMap(e=>{let t=typeof e.file==`string`&&e.file.length>0?e.file:typeof e.path==`string`&&e.path.length>0?e.path:``;return t?[t]:[]}):[]}async function Sc(e){let t=await u(yc(e.sessionID,`stage`),{method:`POST`,headers:{"Content-Type":`application/json`},query:vc(e.directory),body:JSON.stringify({messageID:e.messageID,files:e.files!==!1}),signal:e.signal});return t.ok||pc(`session revert stage`,t.status,await gc(t)),bc(await _c(t,`session revert stage`))}async function Cc(e){let t=await u(`/api/session/${encodeURIComponent(e.sessionID)}/revert`,{method:`DELETE`,query:vc(e.directory),signal:e.signal});t.ok||pc(`session revert clear`,t.status,await gc(t))}async function wc(e){let t=await u(yc(e.sessionID,`commit`),{method:`POST`,query:vc(e.directory),signal:e.signal});t.ok||pc(`session revert commit`,t.status,await gc(t))}var Tc=e=>e?e.toLowerCase().includes(`text/html`):!1;function Ec(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function Dc(e){try{return(await e.text()).trim()}catch{return``}}function Oc(e){return e?{directory:e}:{}}function kc(e,t){return`/api/session/${encodeURIComponent(e)}/permission/${encodeURIComponent(t)}/reply`}async function Ac(e){let t=await u(kc(e.sessionID,e.requestID),{method:`POST`,headers:{"Content-Type":`application/json`},query:Oc(e.directory),body:JSON.stringify({decision:e.reply,...e.message?{message:e.message}:{}}),signal:e.signal});if(t.ok||Ec(`session permission reply`,t.status,await Dc(t)),t.status!==204&&Tc(t.headers.get(`content-type`)))throw Error(`session permission reply: unexpected HTML response`)}function jc(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function Mc(e){let t=typeof e.directory==`string`?e.directory:``;return{state:``,config:``,worktree:typeof e.project?.directory==`string`?e.project.directory:t,directory:t,home:``}}function Nc(e){return e.worktree||e.canonical||``}function Pc(e,t){let n={};if(t.size===0)return n;for(let[r,i]of Object.entries(e))t.has(r)&&i?.type===`running`&&(n[r]={type:`busy`});return n}function Fc(e){return{id:e.id,sessionID:e.sessionID,permission:e.action,patterns:Array.isArray(e.resources)?e.resources:[],metadata:e.metadata??{},always:Array.isArray(e.save)?e.save:[],...e.source?.messageID?{tool:{messageID:e.source.messageID,callID:e.source.id??``}}:{}}}function Ic(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.kind===`question`}function Lc(e){let t=e.metadata&&typeof e.metadata.tool==`object`&&e.metadata.tool&&!Array.isArray(e.metadata.tool)?e.metadata.tool:void 0,n=typeof e.tool?.messageID==`string`&&e.tool.messageID.length>0?e.tool.messageID:typeof t?.messageID==`string`&&t.messageID.length>0?t.messageID:void 0;if(n)return{messageID:n,callID:typeof e.tool?.id==`string`?e.tool.id:typeof t?.id==`string`?t.id:``}}function Rc(e){let t=e.fields;if(!t||t.length===0){let t=typeof e.title==`string`&&e.title.length>0?e.title:`Form`;return[{question:t,header:t,options:[]}]}return t.map(t=>{let n=typeof t.title==`string`&&t.title.length>0?t.title:t.key;return{question:typeof t.description==`string`&&t.description.length>0?t.description:typeof e.title==`string`&&e.title.length>0?e.title:n,header:n,options:(t.options??[]).map(e=>({label:e.label||e.value||``,description:typeof e.description==`string`?e.description:``})).filter(e=>e.label.length>0),...t.type===`multiselect`?{multiple:!0}:{}}})}function zc(e){let t=e.questions&&e.questions.length>0?e.questions.map(e=>({question:e.question,header:e.header,options:e.options??[],...e.multiple?{multiple:!0}:{}})):Rc(e),n=Lc(e);return{id:e.id,sessionID:e.sessionID,questions:t,...n?{tool:n}:{}}}function Bc(e,t){let n={};for(let r=0;r<t.length;r+=1){let i=t[r],a=(e[r]??[]).map(e=>i.options?.find(t=>(t.label||t.value)===e)?.value??e),o=a[0]??``;if(i.type===`multiselect`)n[i.key]=a;else if(i.type===`number`||i.type===`integer`){let e=Number(o);if(!o.trim()||!Number.isFinite(e)||i.type===`integer`&&!Number.isInteger(e))throw Error(`Invalid numeric answer for ${i.key}`);n[i.key]=e}else if(i.type===`boolean`){if(o!==`true`&&o!==`false`)throw Error(`Invalid boolean answer for ${i.key}`);n[i.key]=o===`true`}else n[i.key]=o}return n}var Vc=3,Hc=3e4,Uc=32e3,Wc=36e5,Gc=6e5,Kc=new Set([429,502,503,504]),qc=new Map;function Jc(){let e=Date.now();for(let[t,n]of qc)n.consecutiveErrors===0&&e-n.lastErrorAt>Wc&&qc.delete(t)}typeof setInterval<`u`&&setInterval(Jc,Gc).unref?.();function Yc(e){let t=qc.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Hc},qc.set(e,t)),t}function Xc(e){if(!e)return;let t=qc.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function Zc(e,t){if(!e)return;let n=Yc(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Qc(t)&&n.consecutiveErrors>=Vc&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Qc(e){return e!==void 0&&Kc.has(e)}function $c(e){let t=qc.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Uc*4),!1):!0:!1}function el(e){if(!(!e||!$c(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var tl=`/api`,nl=1e4,rl=4e3,il=3e3,al=1e3,ol=1500,sl=12e3;function cl(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function G(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function ll(e){if(e instanceof ne&&e.reason===`UnexpectedStatus`){let t=e.cause;if(t&&typeof t==`object`&&`status`in t){let e=t.status;if(typeof e==`number`)return e}}if(e&&typeof e==`object`&&`status`in e){let t=e.status;if(typeof t==`number`)return t}}function ul(e){return e===404||e===405||e===501}function K(e){if(typeof e!=`string`)return;let t=e.trim();if(t)return{location:{directory:t}}}function dl(e){let t=e.replace(/\/+$/,``);if(t.endsWith(`/api`)){let e=t.slice(0,-4);if(e.length>0)return e}return ml(gl()||`/`)}function fl(e){return!e||typeof e.id!=`string`||e.id.length===0||typeof e.sessionID!=`string`||e.sessionID.length===0?null:{id:e.id,sessionID:e.sessionID,permission:e.action,patterns:Array.isArray(e.resources)?e.resources:[],metadata:e.metadata??{},always:Array.isArray(e.save)?e.save:[],...e.source?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}}var pl=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ml=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if(pl.test(t)||typeof window>`u`)return t;let n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(e){return console.warn(`Failed to normalize OpenCode base URL:`,e),t}},hl=()=>{try{return a().api(`/api`)}catch{return null}},gl=()=>{try{return a().api(`/`)}catch{return null}},_l=e=>{let t=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof t?.timeout==`function`)return{signal:t.timeout(e),cleanup:()=>void 0};let n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},vl=e=>{let t=e.filter(e=>e!=null);if(t.length===0)return{signal:new AbortController().signal,cleanup:()=>void 0};if(t.length===1)return{signal:t[0],cleanup:()=>void 0};let n=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof n?.any==`function`)return{signal:n.any(t),cleanup:()=>void 0};let r=new AbortController,i=()=>r.abort();for(let e of t){if(e.aborted){r.abort();break}e.addEventListener(`abort`,i)}return{signal:r.signal,cleanup:()=>{for(let e of t)e.removeEventListener(`abort`,i)}}},yl=e=>{let t=e.session?.message,n=t&&typeof t==`object`&&typeof t.get==`function`?t.get.bind(t):null;if(!n)return e;let r=Object.assign((e,t)=>n(e,t),t);return{...e,session:{...e.session,message:r}}},bl=e=>yl(te.make({baseUrl:e.baseUrl,...e.headers?{headers:e.headers}:{},fetch:(e,t)=>{let n=new URL(e instanceof Request?e.url:e.toString()),r=`${n.pathname}${n.search}`;if(e instanceof Request){let n=ml(a().api(r));return u(new Request(n,e),t)}return u(r,t)}})),xl=20971520,Sl=e=>{let{referenceOnly:t,...n}=e;return Cl(e)&&!t?n:{type:`text`,synthetic:!0,text:ts(`Attachment ${JSON.stringify(e.filename||`file`)}: ${JSON.stringify(os(e.url))}\nRead or process this file with tools as needed; its contents are not included in the message.`.replace(/</g,`\\u003c`))}},Cl=e=>typeof e.mime==`string`&&e.mime.startsWith(`image/`)?!0:typeof e.filename==`string`&&/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i.test(e.filename),wl=e=>{let t=[];for(let n of e){if(!Cl(n))continue;let e=typeof n.filename==`string`?n.filename.trim():``,r=typeof n.url==`string`?n.url:``;if(!e||!r.toLowerCase().startsWith(`file://`))continue;let i=os(r).trim();i&&t.push({filename:e,path:i})}return t},Tl=async(e,t)=>{let n=[],r=e.files?.length?await Promise.all(e.files.map(e=>t(e))):[],i=e.additionalParts?.length?await Promise.all(e.additionalParts.map(async e=>({text:e.text,synthetic:e.synthetic,files:e.files?.length?await Promise.all(e.files.map(e=>t(e))):[]}))):[],a=e=>Uo(e,wl([...r,...i.flatMap(e=>e.files)]));if(e.prefaceText&&e.prefaceText.trim()&&n.push({type:`text`,text:a(e.prefaceText),synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()&&n.push({type:`text`,text:a(e.text)}),n.push(...r.map(Sl)),i.length>0)for(let e of i){if(e.text&&e.text.trim()){let t={type:`text`,text:a(e.text)};e.synthetic&&(t.synthetic=!0),n.push(t)}n.push(...e.files.map(Sl))}if(e.agentMentions&&e.agentMentions.length>0)for(let t of e.agentMentions){if(!t?.name)continue;let e={type:`agent`,name:t.name};t.source&&(e.source=t.source),n.push(e)}if(n.length===0)throw Error(`Message must have at least one part (text or file)`);return n},El=e=>e.replace(/\\/g,`/`),Dl=400,Ol=()=>{let e=p();return e&&e.runtime?.isDesktop&&e.files?e.files:null},q=new class{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;healthInFlight=new Map;healthCache=new Map;healthCacheGeneration=0;liveLocationsFlight=null;sessionBoundaryQueues=new Map;constructor(e=tl){let t=hl()||e;this.baseUrl=ml(t),this.client=bl({baseUrl:dl(this.baseUrl)})}getBaseUrl(){return ml(hl()||this.baseUrl)}reconnectToRuntimeBaseUrl(){let e=ml(hl()||tl);e!==this.baseUrl&&(this.baseUrl=e,this.client=bl({baseUrl:dl(this.baseUrl)}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear(),this.clearHealthCache(),this.liveLocationsFlight=null)}getSdkClient(){return this.client}getScopedSdkClient(e){return this.getScopedApiClient(e)}async checkLocationReleaseUse(e,t){let n=this.normalizeCandidatePath(e),r=await this.listLiveLocationDirectories();if(!r)throw Error(`Live Location inventory unavailable`);if(r&&n&&!r.has(n))return`free`;let i=this.getScopedSdkClient(e),a={location:{directory:e}},[o,s]=await Promise.all([i.shell.list(a,{signal:t}),i.form.list(a,{signal:t})]);return o.data.some(e=>e.status===`running`)||s.data.length>0?`busy`:`free`}listLiveLocationDirectories(){let e=Date.now();if(this.liveLocationsFlight&&this.liveLocationsFlight.expiresAt>e)return this.liveLocationsFlight.promise;let t=this.client.debug.location.list().then(e=>{if(!Array.isArray(e))return null;let t=new Set;for(let n of e){let e=this.normalizeCandidatePath(n?.directory??null);e&&t.add(e)}return t}).catch(()=>null);return this.liveLocationsFlight={promise:t,expiresAt:e+ol},t}async resolveBlockingRequestDirectories(e){let t=new Set;for(let n of e??[]){let e=this.normalizeCandidatePath(n??null);e&&t.add(e)}if(t.size===0)return[];let n=await this.listLiveLocationDirectories();if(!n)throw Error(`Live Location inventory unavailable`);return Array.from(t).filter(e=>n.has(e))}async releaseLocation(e,t){await this.getScopedSdkClient(e).debug.location.evict({location:{directory:e}},{signal:t})}getScopedApiClient(e){let t=(this.normalizeCandidatePath(e)??e)||``,n=this.scopedClients.get(t);if(n)return n;let r=bl({baseUrl:dl(this.baseUrl)});return this.scopedClients.set(t,r),r}normalizeCandidatePath(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return(n.length>1?n.replace(/\/+$/,``):n)||null}deriveHomeDirectory(e){let t=e.match(/^([A-Za-z]:)(?:\/|$)/);if(t){let n=t[1],r=e.slice(n.length+ +(e.charAt(n.length)===`/`)).split(`/`).filter(Boolean);return r.length>=2?{homeDirectory:`${n}/${r[0]}/${r[1]}`,username:r[1]}:r.length===1?{homeDirectory:`${n}/${r[0]}`,username:r[0]}:{homeDirectory:n,username:void 0}}let n=e.startsWith(`/`),r=e.split(`/`).filter(Boolean);return r.length>=2&&(r[0]===`Users`||r[0]===`home`)?{homeDirectory:`${n?`/`:``}${r[0]}/${r[1]}`,username:r[1]}:n?r.length===0?{homeDirectory:`/`,username:void 0}:{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:r.length>0?{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:{homeDirectory:`/`,username:void 0}}setDirectory(e){let t=this.normalizeCandidatePath(e)??e;this.currentDirectory!==t&&R(`opencodeClient:setDirectory`,{previous:this.currentDirectory??null,next:t??null}),this.currentDirectory=t}getDirectory(){return this.currentDirectory}runSessionBoundary(e,t){let n=e.trim();if(!n)return t();let r=this.sessionBoundaryQueues.get(n)??Promise.resolve(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s=()=>t().then(i,a),c=r.then(s,s);return this.sessionBoundaryQueues.set(n,c.then(()=>void 0,()=>void 0)),o}assertCapturedRuntime(e,t,n){if(s()!==e||c()!==t){let e=Error(`${n}: runtime switched`);throw e.name=`RuntimeGenerationMismatchError`,e}}async switchSessionModel(e,t,n){let r=s(),i=c(),a=`id`in t&&typeof t.id==`string`&&t.id?t.id:t.modelID,o=t.providerID;if(!e||!a||!o)throw Error(`switchSessionModel requires sessionID, model.id, and providerID`);let l=typeof t.variant==`string`&&t.variant.trim()?t.variant.trim():void 0,u={id:a,providerID:o,...l?{variant:l}:{}},d=this.normalizeCandidatePath(n)??this.currentDirectory??``,f=this.getScopedSdkClient(d);this.assertCapturedRuntime(r,i,`session model switch`),await f.session.switchModel({sessionID:e,model:u}),this.assertCapturedRuntime(r,i,`session model switch`),uo(e,d||n,{model:u})}async switchSessionAgent(e,t,n){let r=s(),i=c(),a=typeof t==`string`?t.trim():``;if(!e||!a)throw Error(`switchSessionAgent requires sessionID and agent`);let o=this.normalizeCandidatePath(n)??this.currentDirectory??``,l=this.getScopedSdkClient(o);this.assertCapturedRuntime(r,i,`session agent switch`),await l.session.switchAgent({sessionID:e,agent:a}),this.assertCapturedRuntime(r,i,`session agent switch`),uo(e,o||n,{agent:a})}async generateSessionAside(e){let t=typeof e.sessionId==`string`?e.sessionId.trim():``;if(!t)throw Error(`generateSessionAside requires sessionId`);let n=typeof e.prompt==`string`?e.prompt:``,r=this.normalizeCandidatePath(e.directory)??this.currentDirectory??``,i=await this.getScopedSdkClient(r).session.generate({sessionID:t,prompt:n},e.signal?{signal:e.signal}:void 0);if(!i||typeof i.text!=`string`)throw Error(`session.generate returned invalid payload`);return{text:i.text}}async applySendSelection(e,t,n){t.model&&await this.switchSessionModel(e,t.model,n),t.agent&&await this.switchSessionAgent(e,t.agent,n)}async withDirectory(e,t){let n=async()=>{if(e==null)return t();let n=this.currentDirectory,r=this.normalizeCandidatePath(e)??e;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory===r&&(this.currentDirectory=n)}},r=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=r.then(()=>void 0,()=>void 0),r}getApiClient(){return this.client}async getSystemInfo(){let e=new Set,t=t=>{let n=this.normalizeCandidatePath(t);n&&e.add(n)};try{let e=await this.client.location.get(K(this.currentDirectory));e&&(t(e.directory),t(e.project?.directory),t(e.project?.canonical))}catch{}if(!e.size)try{let e=await this.client.location.get(K(this.currentDirectory));t(e?.project?.directory),t(e?.project?.canonical)}catch{}if(!e.size)try{(await this.listSessions()).forEach(e=>t(e.directory))}catch{}if(t(this.currentDirectory),typeof window<`u`)try{t(ae(`lastDirectory`)),t(ae(`homeDirectory`))}catch{}if(!e.size&&typeof process<`u`&&typeof process.cwd==`function`&&t(process.cwd()),!e.size)return{homeDirectory:`/`,username:void 0};let[n]=Array.from(e);return this.deriveHomeDirectory(n)}async probeDirectory(e){let t=this.normalizeCandidatePath(e);if(!t)return!1;try{let e=await this.client.location.get({location:{directory:t}}),n=typeof e?.directory==`string`?e.directory:null;return!!(n&&n.trim().length>0)}catch{return!1}}async listSessions(){let e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data.map(v):[]}async searchSessionsByTitle(e){let t=e.search.trim(),n=await this.client.session.list({search:t||void 0,parentID:null,limit:e.limit??30,order:`desc`},e.signal?{signal:e.signal}:void 0);if(!Array.isArray(n?.data))throw Error(`session.list search returned no data`);return n.data.map(v)}async createSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;if(e?.metadata,e?.parentID){let t=await this.client.session.fork({sessionID:e.parentID});return e.title?(await this.client.session.update({sessionID:t.id,title:e.title}),v(await this.client.session.get({sessionID:t.id}))):v(t)}return v(await this.client.session.create({...n?{location:{directory:n}}:{},title:e?.title}))}async getSession(e,t){return v(await this.client.session.get({sessionID:e}))}async deleteSession(e,t){return await this.client.session.remove({sessionID:e}),!0}async deleteSessionMessage(e,t,n){throw G(`session.deleteMessage`)}async updateSession(e,t,n){let r=t.title!==void 0,i=t.metadata!==void 0,a=t.time!==void 0&&Object.prototype.hasOwnProperty.call(t.time,`archived`);if(!r&&!i&&!a)throw G(`session.update`);let o=this.normalizeCandidatePath(n)??this.currentDirectory,l=s(),d=c(),f=()=>{if(s()!==l||c()!==d){let e=Error(`session.update discarded: runtime switched`);throw e.name=`RuntimeGenerationMismatchError`,e}},p=[],m=null,h=null,g=e=>{if(p.length===0)throw e;let t=cl(e),n=Error(`session.update partial failure after ${p.join(`,`)}: ${t}`);throw n.name=`SessionUpdatePartialFailureError`,n.cause=e,n.completed=[...p],n};try{if(r&&(await this.client.session.update({sessionID:e,title:t.title}),f(),p.push(`title`),m=v(await this.client.session.get({sessionID:e})),f()),i){let n={patch:t.metadata};o&&(n.directory=o);let r=await u(`/api/yuri/sessions/${encodeURIComponent(e)}/metadata`,{method:`PUT`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(n)});if(f(),!r.ok){let e=Error(`session.metadata update failed (${r.status})`);throw e.status=r.status,e}let i=await r.json().catch(()=>null);f(),h=typeof i==`object`&&i&&!Array.isArray(i)&&`metadata`in i&&i.metadata!==null&&typeof i.metadata==`object`&&!Array.isArray(i.metadata)?i.metadata:null,p.push(`metadata`)}if(a){let n=t.time?.archived,r;if(n==null)r=0;else if(typeof n==`number`&&Number.isFinite(n))r=n>0?Math.trunc(n):0;else throw Error(`archivedAt must be a finite number or null`);let i={archivedAt:r};o&&(i.directory=o);let a=await u(`/api/yuri/sessions/${encodeURIComponent(e)}/archive`,{method:`PUT`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(i)});if(f(),!a.ok){let e=Error(`session.archive update failed (${a.status})`);throw e.status=a.status,e}let s=await a.json().catch(()=>null);f();let c=typeof s==`object`&&s&&!Array.isArray(s)&&`session`in s?s.session:null;if(!c||typeof c!=`object`||Array.isArray(c))throw Error(`session.archive update failed: empty response`);m=v(c),p.push(`archive`)}return m||(m=await this.getSession(e,n),f()),h&&!a?{...m,metadata:h}:m}catch(e){return g(e)}}async getSessionMessages(e,t){return(await $e({sessionID:e,directory:this.currentDirectory??``,...typeof t==`number`?{limit:t}:{}})).records}async getSessionDiff(e,t){let n=this.normalizeCandidatePath(e.directory)??this.currentDirectory,r=typeof e.messageID==`string`&&e.messageID.trim().length>0?e.messageID.trim():void 0,i=new URLSearchParams;n&&i.set(`directory`,n),r&&i.set(`messageID`,r);let a=i.toString(),o=await u(`/api/session/${encodeURIComponent(e.sessionID)}/diff${a?`?${a}`:``}`,{method:`GET`,headers:{Accept:`application/json`},signal:t?.signal});if(!o.ok){let e=Error(`session.diff failed (${o.status})`);throw e.status=o.status,e}let s=await o.json().catch(()=>null),c=typeof s==`object`&&s&&Array.isArray(s.data)?s.data:null;if(!c)throw Error(`session.diff failed: empty response`);return c}async getSessionTodos(e){throw G(`session.todo`)}shouldNormalizeToTextPlain(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`text/`)&&t!==`text/plain`?!0:[`application/json`,`application/xml`,`application/javascript`,`application/typescript`,`application/x-yaml`,`application/yaml`,`application/toml`,`application/x-sh`,`application/x-shellscript`,`application/octet-stream`,`image/svg+xml`].includes(t)}isHeicMime(e){if(!e)return!1;let t=e.toLowerCase();return t===`image/heic`||t===`image/heif`}async convertHeicToJpeg(t){try{let n=ds(t.url,t.mime);if(!n)return t;let r=await vo(n)??await(await he(async()=>{let{default:t}=await import(`./vendor-heic2any-DgJnLT1Y.js`).then(t=>e(t.t(),1));return{default:t}},__vite__mapDeps([0,1]))).default({blob:n,toType:`image/jpeg`,quality:.9}),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)}),a=t.filename;return a&&=a.replace(/\.heic$/i,`.jpg`).replace(/\.heif$/i,`.jpg`),{mime:`image/jpeg`,filename:a,url:i}}catch(e){return console.warn(`Failed to convert HEIC to JPEG:`,e),t}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let t=e.url;if(e.url.startsWith(`data:`)){let n=e.url.indexOf(`,`);if(n!==-1){let r=e.url.substring(5,n),i=e.url.substring(n);t=`data:${r.replace(/^[^;,]+/,`text/plain`)}${i}`}}return{mime:`text/plain`,filename:e.filename,url:t}}async toNormalizedFilePartInput(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c(),i=Cl(e)?await this.normalizeFilePart(e):e;this.assertCapturedRuntime(n,r,`prompt attachment normalize`);let a=i.url,o;if(fs(a)){let e=a.startsWith(`blob:`)?await fetch(a).then(e=>e.blob()):ds(a,i.mime);if(!e)throw Error(`Failed to materialize attachment bytes for ${i.filename??`file`}`);this.assertCapturedRuntime(n,r,`prompt attachment upload`);let t=await ps({body:e,mime:i.mime,filename:i.filename});this.assertCapturedRuntime(n,r,`prompt attachment upload`),a=t.url,o=t.size}if(Cl(i)&&o===void 0&&a.toLowerCase().startsWith(`file://`)){let e=os(a),t=p()?.files;if(t?.statFile)o=(await t.statFile(e)).size;else{let t=await u(`/api/fs/stat`,{query:{path:e}});if(!t.ok)throw Error(`Failed to inspect prompt attachment`);o=(await t.json()).size}this.assertCapturedRuntime(n,r,`prompt attachment stat`)}return{...e.id?{id:e.id}:{},type:`file`,mime:i.mime,filename:i.filename,url:a,...Cl(i)&&(o===void 0||!Number.isSafeInteger(o)||o<0||o>xl)?{referenceOnly:!0}:{}}}async buildMessageParts(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c();return Tl(e,e=>this.toNormalizedFilePartInput(e,{generation:n,runtimeKey:r}))}async sendMessage(e){let t=s(),n=c(),r=()=>{this.assertCapturedRuntime(t,n,`session prompt discarded`)};r();let i=e.messageId??ue(`msg`),a=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,o=Js(a??``),l=await this.buildMessageParts({text:e.text,prefaceText:e.prefaceText,prefaceTextSynthetic:e.prefaceTextSynthetic,files:e.files,additionalParts:e.additionalParts,agentMentions:e.agentMentions},{generation:t,runtimeKey:n});r(),W(o)||this.assertCapturedRuntime(t,n,`session prompt discarded`),e.format&&(e.id,e.providerID,e.modelID,e.agent,e.variant,this.baseUrl,e.format.type),el(e.providerID);let u=l.flatMap(e=>e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(`
|
|
5
5
|
`)||e.text,d=l.flatMap(e=>e.type!==`file`||typeof e.url!=`string`?[]:[{uri:e.url,...e.filename?{name:e.filename}:{}}]),f=l.flatMap(e=>e.type===`agent`&&typeof e.name==`string`?[{name:e.name}]:[]),p=xe(l.flatMap(e=>e.type===`text`&&!e.synthetic?[e.text]:[]).join(`
|
|
6
|
-
`));try{return await this.runSessionBoundary(e.id,async()=>{r();let t=e.delivery===`queue`?`queue`:`steer`;t!==`queue`&&(await this.applySendSelection(e.id,{model:e.switchModel,agent:e.switchAgent},a),r());let n={sessionID:e.id,directory:o.directory,messageID:i,text:u,delivery:t,commit:o,...d.length>0?{files:d}:{},...f.length>0?{agents:f}:{},...p.length>0?{skills:p}:{},...e.agent||e.variant||e.format||e.providerID?{metadata:{...e.agent?{agent:e.agent}:{},...e.variant?{variant:e.variant}:{},model:{providerID:e.providerID,modelID:e.modelID},...e.format?{format:e.format}:{}}}:{}},s=async()=>{r();let e=await
|
|
7
|
-
`);if(e.providerID,e.modelID,e.agent,e.variant,t!==s()||n!==c())throw Error(`Runtime changed while preparing command`);return await r.session.command({sessionID:e.id,name:e.command,text:l,...e.delivery?{delivery:e.delivery}:{},...o.length>0?{files:o}:{}}),i}async abortSession(e){return await cc({sessionID:e,directory:this.currentDirectory}),!0}async shellSession(e){return e.directory,await this.client.session.shell({sessionID:e.sessionId,command:e.command,...e.messageId?{id:e.messageId}:{}}),{info:{id:e.messageId??``,sessionID:e.sessionId,role:`assistant`,time:{created:Date.now()},clientRole:`shell`,agent:e.agent,modelID:e.model.modelID,providerID:e.model.providerID},parts:[]}}async revertSession(e,t,n,r){let i=await Cc({sessionID:e,directory:this.normalizeCandidatePath(r)??this.currentDirectory,messageID:t,files:!0});return{id:e,time:{created:0,updated:Date.now()},revert:i}}async summarizeSession(e,t,n,r){return await vt({sessionID:e,directory:this.normalizeCandidatePath(r)??this.currentDirectory??``}),!0}async unrevertSession(e,t){return await wc({sessionID:e,directory:this.normalizeCandidatePath(t)??this.currentDirectory}),{id:e,time:{created:0,updated:Date.now()}}}async forkSession(e,t,n){this.normalizeCandidatePath(n)??this.currentDirectory;let r=await this.client.session.fork({sessionID:e,...t?{before:t}:{}});return r.id,v(r)}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e,t){return null}async getSessionActive(e){try{let t=await this.client.session.active(e?{signal:e}:void 0),n=t&&typeof t==`object`&&`data`in t&&t.data!==void 0?t.data:t;if(!n||typeof n!=`object`||Array.isArray(n))return{state:`unknown`};let r={};for(let[e,t]of Object.entries(n)){if(typeof e!=`string`||e.length===0||!t||typeof t!=`object`||t.type!==`running`)return{state:`unknown`};r[e]={type:`running`}}return{state:`supported`,membership:r}}catch(e){return dl(ul(e))?{state:`unsupported`}:{state:`unknown`}}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{let e=await u(`/api/session-activity`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json().catch(()=>null);return!t||typeof t!=`object`?null:t}catch{return null}}async listToolIds(e){throw G(`tool.ids`)}async replyToPermission(e,t,n){let r=this.normalizeCandidatePath(n?.directory??null)??this.currentDirectory;if(!n?.sessionID)throw G(`permission.reply (sessionID required)`);return await jc({sessionID:n.sessionID,requestID:e,reply:t,...n.message?{message:n.message}:{},directory:r}),!0}async createPermission(e,t,n,r){try{let i=await this.client.permission.create({sessionID:e,action:t,resources:n,...r?.id?{id:r.id}:{},...r?.save?{save:r.save}:{},...r?.metadata?{metadata:r.metadata}:{},...r?.source?{source:r.source}:{},...r?.agent?{agent:r.agent}:{}});return!i||typeof i.id!=`string`?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(e,t){try{let n=await this.client.permission.get({sessionID:e,requestID:t});return n===void 0?{state:`unknown`}:{state:`ok`,permission:n}}catch(e){return ee(e)||ul(e)===404?{state:`resolved`}:{state:`unknown`}}}async listPendingPermissions(e){let t=async e=>{let t=await this.client.permission.request.list(K(e));if(!t||!Array.isArray(t.data))throw Error(`permission.list failed: ${ll(t)}`);return t.data.flatMap(e=>{let t=pl(e);return t?[t]:[]})},n=e?.directories===void 0?[null]:await this.resolveBlockingRequestDirectories(e.directories),r=await Promise.all(n.map(t)),i=[],a=new Set;for(let e of r)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(a.has(e)||(a.add(e),i.push(t)))}return i}async replyToQuestion(e,t,n,r){let i=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];if(!r)throw G(`session.form.reply (sessionID required)`);let a=this.client,o=await a.session.form.get({sessionID:r,formID:e});return await a.session.form.reply({sessionID:r,formID:e,answer:Vc(i,o.fields)}),!0}async rejectQuestion(e,t){if(!t)throw G(`session.form.cancel (sessionID required)`);return await this.client.session.form.cancel({sessionID:t,formID:e}),!0}async listPendingQuestions(e){let t=async e=>{let t=await this.client.form.list(K(e));if(!t||!Array.isArray(t.data))throw Error(`form.list failed: ${ll(t)}`);return t.data.flatMap(e=>Lc(e.metadata)?[Bc({id:e.id,sessionID:e.sessionID,title:e.title,fields:e.fields,...e.metadata?{metadata:e.metadata}:{}})]:[])},n=e?.directories===void 0?[null]:await this.resolveBlockingRequestDirectories(e.directories),r=await Promise.all(n.map(t)),i=[],a=new Set;for(let e of r)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(a.has(e)||(a.add(e),i.push(t)))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}clearHealthCache(){this.healthCacheGeneration+=1,this.healthInFlight.clear(),this.healthCache.clear()}async getConfig(e){let t=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,n=t??``,r=this.configCache.get(n);if(r&&r.expiresAt>Date.now())return R(`opencodeClient.getConfig:cacheHit`,{directory:t??null}),r.config;let i=this.configInFlight.get(n);if(i)return R(`opencodeClient.getConfig:deduped`,{directory:t??null}),i;let a=this.configCacheGeneration,o=(async()=>{R(`opencodeClient.getConfig:start`,{directory:t??null});let e=typeof performance<`u`?performance.now():Date.now(),r=await this.client.config.get(K(t));if(!Array.isArray(r))throw Error(`Failed to get config`);let i=Se(r),o=typeof performance<`u`?performance.now():Date.now();return R(`opencodeClient.getConfig:end`,{directory:t??null,durationMs:Math.round(o-e)}),a===this.configCacheGeneration&&this.configCache.set(n,{config:i,expiresAt:Date.now()+rl}),i})();this.configInFlight.set(n,o);try{return await o}finally{this.configInFlight.get(n)===o&&this.configInFlight.delete(n)}}async updateConfig(e){throw G(`config.update`)}async updateConfigPartial(e){let t=e(await this.getConfig());return await this.updateConfig(t)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(e){let t=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,n=t??``,r=this.configProvidersInFlight.get(n);if(r)return r;let i=(async()=>{let e=await this.client.provider.list(K(t));if(!e||!Array.isArray(e.data))throw Error(`config.providers failed: ${ll(e)}`);let n={};try{let e=await this.client.model.default(K(t));e?.data&&(n[e.data.providerID]=e.data.modelID)}catch{}return{providers:e.data,default:n}})();this.configProvidersInFlight.set(n,i);try{return await i}finally{this.configProvidersInFlight.delete(n)}}async getApp(){return{version:`0.0.3`,config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(e,t){let n=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,r=n??``;if(!t){let e=this.listAgentsInFlight.get(r);if(e)return e}let i=(async()=>{let e=vl(cl),r=yl(t?[t,e.signal]:[e.signal]);try{let e=K(n),t=await this.client.agent.list(e,{signal:r.signal});if(!t||!Array.isArray(t.data))throw Error(`app.agents failed: ${ll(t)}`);return t.data.map(e=>_e(e))}finally{e.cleanup(),r.cleanup()}})();if(t)return i;this.listAgentsInFlight.set(r,i);try{return await i}finally{this.listAgentsInFlight.delete(r)}}async readFile(e){try{let t=await this.client.file.read({path:e,...K(this.currentDirectory)});return new TextDecoder().decode(t)}catch{return`// Content of ${e}\n// This would be loaded from the server`}}async listFiles(e){try{let t=e||this.currentDirectory||`/`,n=(await this.client.file.list({path:t,...K(this.currentDirectory)})).data;return Array.isArray(n)?n:[]}catch{return[]}}async listCommands(){let e=await this.client.command.list(K(this.currentDirectory)),t=e.data;if(!Array.isArray(t))throw Error(`command.list failed: ${ll(e)}`);return t.map(e=>({name:e.name,description:e.description,agent:void 0,model:void 0,source:void 0}))}async listCommandsWithDetails(){let e=await this.client.command.list(K(this.currentDirectory)),t=e.data;if(!Array.isArray(t))throw Error(`command.list failed: ${ll(e)}`);return t.map(e=>({name:e.name,description:e.description,agent:void 0,model:void 0,source:void 0,template:``}))}async listSkillsWithDetails(){try{let e=(await this.client.skill.list(K(this.currentDirectory))).data;if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=typeof n.id==`string`?n.id:``,r=typeof n.path==`string`?n.path:``;if(!e||!r)continue;let i={name:e,location:r};typeof n.description==`string`&&(i.description=n.description),typeof n.content==`string`&&(i.content=n.content),t.push(i)}return t}catch{return[]}}async getCommandDetails(e){try{let t=await this.client.command.list(K(this.currentDirectory));if(t.data){let n=t.data.find(t=>t.name===e);if(n)return{name:n.name,template:``,description:n.description,agent:void 0,model:void 0}}return null}catch{return null}}async checkHealth(){let e=c(),t=this.healthCache.get(e);if(t&&t.expiresAt>Date.now())return t.healthy;let n=this.healthInFlight.get(e);if(n)return n;let r=this.healthCacheGeneration,i=(async()=>{let t=!1;try{let e=`/api/opencode/health`;R(`opencodeClient.checkHealth:url`,{baseUrl:this.baseUrl,healthUrl:e});let n=vl(il),r=await u(e,{signal:n.signal}).finally(n.cleanup);if(R(`opencodeClient.checkHealth:response`,{status:r.status}),r.ok){let e=await r.json();R(`opencodeClient.checkHealth:result`,{healthy:e?.healthy}),t=e?.healthy===!0}}catch{t=!1}return r!==this.healthCacheGeneration||e!==c()?!1:(this.healthCache.set(e,{healthy:t,expiresAt:Date.now()+(t?al:ol)}),t)})();this.healthInFlight.set(e,i);try{return await i}finally{this.healthInFlight.get(e)===i&&this.healthInFlight.delete(e)}}async createDirectory(e,t){let n=kl();if(n?.createDirectory)try{return await n.createDirectory(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(t||`Failed to create directory`)}let r={path:e,...t?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},i=await u(`/api/fs/mkdir`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:`Failed to create directory`}));throw Error(e.error||`Failed to create directory`)}return await i.json()}async cloneRepository(e){let t=await u(`/api/fs/clone`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to clone repository`}));throw Error(e.error||`Failed to clone repository`)}return await t.json()}async listLocalDirectory(e,t){let n=`${typeof e==`string`?Dl(e.trim()):``}|${t?.respectGitignore?`1`:`0`}`,r=Date.now(),i=this.listDirectoryCache.get(n);if(i&&i.expiresAt>r)return i.entries;let a=this.listDirectoryInFlight.get(n);if(a)return a;let o=(async()=>{let r=kl();if(r)try{let i=await r.listDirectory(e||``,t);if(!i||!Array.isArray(i.entries))return[];let a=i.entries.map(e=>({name:e.name,path:Dl(e.path),isDirectory:!!e.isDirectory,isFile:!e.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:a,expiresAt:Date.now()+Ol}),a}catch(e){throw console.error(`Failed to list directory contents:`,e),e}try{let r=new URLSearchParams;e&&e.trim().length>0&&r.set(`path`,e),t?.respectGitignore&&r.set(`respectGitignore`,`true`);let i=r.toString(),a=await u(`/api/fs/list${i?`?${i}`:``}`);if(!a.ok){let e=await a.json().catch(()=>({})),t=typeof e.error==`string`?e.error:`Failed to list directory`;throw Error(t)}let o=await a.json();if(!o||!Array.isArray(o.entries))return[];let s=o.entries;return this.listDirectoryCache.set(n,{entries:s,expiresAt:Date.now()+Ol}),s}catch(e){throw console.error(`Failed to list directory contents:`,e),e}})().finally(()=>{this.listDirectoryInFlight.get(n)===o&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,o),o}async searchFiles(e,t){let n=typeof t?.directory==`string`&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,r=n?Dl(n):null;t?.signal?.throwIfAborted();try{let i=await this.client.file.find({query:e,...K(n),limit:typeof t?.limit==`number`&&Number.isFinite(t.limit)?t.limit:void 0,type:t?.type},{signal:t?.signal});return t?.signal?.throwIfAborted(),(Array.isArray(i?.data)?i.data:[]).map(e=>{let t=Dl(e.path),n=t.split(`/`).filter(Boolean).pop()||t;return{name:n,path:Dl(r?`${r}/${t}`:t),relativePath:t,extension:n.includes(`.`)?n.split(`.`).pop()?.toLowerCase():void 0,isDirectory:e.type===`directory`}})}catch(e){throw t?.signal?.aborted||console.error(`Failed to search files:`,e),e}}async getFilesystemHome(){let e=c();if(!e||e===`local`){let e=await d();if(e)return e}try{let e=await u(`/api/fs/home`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok){let t=await e.json().catch(()=>({})),n=typeof t.error==`string`&&t.error.length>0?t.error:`Failed to resolve home directory`;throw Error(n)}let t=await e.json();return t&&typeof t.home==`string`&&t.home.length>0?t.home:null}catch(e){return console.warn(`Failed to resolve filesystem home directory:`,e),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!=`string`||!e.trim())return console.warn(`[OpencodeClient] setOpenCodeWorkingDirectory: invalid path`,e),null;try{let t=await u(`/api/opencode/directory`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})}),n=await t.json().catch(()=>null);if(!t.ok){let e=n??{},t=typeof e.error==`string`&&e.error.length>0?e.error:`Failed to update OpenCode working directory`;throw Error(t)}return n&&typeof n==`object`?n:{success:!0,restarted:!1,path:e}}catch(e){throw console.warn(`Failed to update OpenCode working directory:`,e),e}}},Al=3e4,jl=40,Ml=60,Nl=(e,t,n,r,i,a)=>{let o=e.trim(),s=t.trim().toLowerCase();return JSON.stringify([o,s,n,r,i,a])},Pl=(e,t)=>{try{let n=JSON.parse(e);return Array.isArray(n)&&n[0]===t}catch{return!1}},Fl=m()(h((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,i=Ml,a){if(!n||n.trim().length===0)return[];let o=n.trim(),s=typeof r==`string`?r.trim():``,c=!!a?.includeHidden,l=a?.respectGitignore??!0,u=a?.type===`directory`?`directory`:`file`,d=Nl(o,s,i,c,l,u),f=Date.now(),p=t().cache[d];if(p&&f-p.timestamp<Al)return p.files;let m=t().inFlight[d];if(m)return m;let h=q.searchFiles(s,{directory:o,limit:i,includeHidden:c,respectGitignore:l,dirs:u!==`file`,type:u}).then(t=>(e(e=>{if(e.inFlight[d]!==h)return e;let n={...e.cache,[d]:{files:t,timestamp:Date.now()}},r=e.cacheKeys.filter(e=>e!==d);for(r.push(d);r.length>jl;){let e=r.shift();e&&delete n[e]}return{cache:n,cacheKeys:r}}),t)).finally(()=>{e(e=>{if(e.inFlight[d]!==h)return e;let t={...e.inFlight};return delete t[d],{inFlight:t}})});return e(e=>({inFlight:{...e.inFlight,[d]:h}})),h},invalidateDirectory(t){if(!t||t.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}let n=t.trim();e(e=>{let t={...e.cache},r=e.cacheKeys.filter(e=>!Pl(e,n)||(delete t[e],!1)),i=Object.entries(e.inFlight).filter(([e])=>!Pl(e,n));return{cache:t,cacheKeys:r,inFlight:Object.fromEntries(i)}})}}),{name:`file-search-store`})),Il=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`yuri_stream_debug`)===`1`}catch{return!1}},Ll=`yuri_stream_perf`,Rl=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(Ll)===`1`}catch{return!1}},zl=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),Bl=()=>{if(!Rl()||typeof window>`u`)return null;if(!window.__yuriStreamPerfState){let e=Date.now();window.__yuriStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__yuriStreamPerfState},Vl=e=>Array.from(e.entries()).map(([e,t])=>({metric:e,count:t.count,avg:t.count>0?Number((t.total/t.count).toFixed(3)):0,max:Number(t.max.toFixed(3)),total:Number(t.total.toFixed(3)),last:Number(t.last.toFixed(3))})).sort((e,t)=>t.total-e.total||t.count-e.count),Hl=(e,t)=>{let n=Bl();if(!n)return;let r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},Ul=e=>{if(!(typeof window>`u`))try{if(e){window.localStorage.setItem(Ll,`1`),window.__yuriStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Ll),delete window.__yuriStreamPerfState,delete window.__yuriVsCodeStreamPerfState}catch{}},Wl=()=>{typeof window>`u`||(Rl()&&(window.__yuriStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__yuriVsCodeStreamPerfState&&(window.__yuriVsCodeStreamPerfState={...window.__yuriVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Gl=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__yuriStreamPerfState;return!Rl()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:Vl(e.counters)}},Kl=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__yuriVsCodeStreamPerfState;if(!Rl()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let t=typeof e.startedAt==`number`?e.startedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:typeof e.lastUpdatedAt==`number`?e.lastUpdatedAt:null,durationMs:t?Math.max(0,Date.now()-t):0,entries:Vl(e.counters)}},ql=(e,t=1)=>{Hl(e,t)},Jl=(e,t)=>{Hl(e,t)},Yl=(e,t)=>{if(!Rl())return t();let n=zl();try{return t()}finally{Hl(e,zl()-n)}},J=null,Xl=0,Y=re(),Zl=ae(`lastDirectory`,{storage:Y}),Ql=typeof Zl==`string`&&Zl.length>0,$l=e=>{try{Fl.getState().invalidateDirectory(e)}catch(e){console.warn(`Failed to invalidate file search cache:`,e)}},eu=e=>{let t=e.trim();if(!t)return t;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return n.length>1?n.replace(/\/+$/,``):n},tu=(e,t)=>{let n=e.trim();return n.startsWith(`~`)?n===`~`?t||n:(n.startsWith(`~/`)||n.startsWith(`~\\`))&&t?`${t}${n.slice(1)}`:n:n},nu=(e,t)=>eu(tu(e,t)),ru=()=>{let e=ae(`homeDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=eu(e);return t.length>0?t:null},iu=()=>{let e=ae(`lastDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=eu(e);return t.length>0?t:null},au=()=>{if(typeof process>`u`)return null;let e={},t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t==`string`&&t.trim().length>0){let e=eu(t);return e.length>0?e:null}let n=process?.cwd?.();if(typeof n==`string`&&n.trim().length>0){let e=eu(n);return e.length>0?e:null}return null},ou=()=>{if(typeof window<`u`){if(J)return J;let e=typeof window.__YURI_HOME__==`string`&&window.__YURI_HOME__.length>0?window.__YURI_HOME__:null;if(e&&e.length>0)return J=e,ie(`homeDirectory`,e,{storage:Y}),e;let t=ru();if(t&&!f())return J=t,t}return au()||`/`},su=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`);if(n.length>1){let e=n.replace(/\/+$/,``);if(e&&e.length>0)return e===`/`?null:e}return n===`/`||n.length===0?null:n},cu=e=>(J=e,typeof window<`u`&&ie(`homeDirectory`,e,{storage:Y}),ce({homeDirectory:e}),e),lu=async()=>{let e=e=>{let t=su(e);return t?cu(t):null};try{let t=e(await q.getFilesystemHome());if(t)return t}catch(e){console.warn(`Failed to obtain filesystem home directory:`,e)}try{let t=e((await q.getSystemInfo())?.homeDirectory);if(t)return t}catch(e){console.warn(`Failed to get home directory from system info:`,e)}try{let t=e(await d());if(t)return t}catch(e){console.warn(`Failed to obtain desktop-integrated home directory:`,e)}let t=ou();return e(t)||t},uu=(()=>{if(!f())return null;let e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!=`string`||e.trim().length===0)return null;let t=eu(e);return t.length>0?t:null})()||ou(),du=(()=>{let e=iu();return e&&!f()?nu(e,uu):uu})();du&&q.setDirectory(du);var fu=!!(uu&&uu!==`/`),pu=m()(h((e,t)=>({currentDirectory:du,directoryHistory:[du],historyIndex:0,homeDirectory:uu,hasPersistedDirectory:Ql,isHomeReady:fu,isSwitchingDirectory:!1,setDirectory:(n,r)=>{let i=nu(n,J||t().homeDirectory||ae(`homeDirectory`,{storage:Y}));Il(),ge(t().currentDirectory,i)&&(q.setDirectory(i),$l(),e(e=>{let t=[...e.directoryHistory.slice(0,e.historyIndex+1),i];return ie(`lastDirectory`,i,{storage:Y}),ce({lastDirectory:i}),{currentDirectory:i,directoryHistory:t,historyIndex:t.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}}))},goBack:()=>{let n=t();if(n.historyIndex>0){let t=n.historyIndex-1,r=n.directoryHistory[t];q.setDirectory(r),$l(),ie(`lastDirectory`,r,{storage:Y}),ce({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{let n=t();if(n.historyIndex<n.directoryHistory.length-1){let t=n.historyIndex+1,r=n.directoryHistory[t];q.setDirectory(r),$l(),ie(`lastDirectory`,r,{storage:Y}),ce({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{let{currentDirectory:e,setDirectory:n}=t();if(e===(J||t().homeDirectory||ou())||e===`/`)return;let r=e.endsWith(`/`)?e.slice(0,-1):e,i=r.lastIndexOf(`/`);n(i===-1?J||ou():i===0?`/`:r.substring(0,i))},goHome:async()=>{let e=J||t().homeDirectory||await lu();t().setDirectory(e)},synchronizeHomeDirectory:n=>{let r=t(),i=n;J=i;let a=r.homeDirectory!==i,o=ae(`lastDirectory`,{storage:Y}),s=typeof o==`string`&&o.length>0,c=!s&&(r.currentDirectory===`/`||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!a&&!c){r.isHomeReady||e({isHomeReady:!0});return}let l=typeof i==`string`&&i!==``&&i!==`/`,u=r.currentDirectory?nu(r.currentDirectory,i):r.currentDirectory,d=r.directoryHistory.map(e=>nu(e,i)),f=d.some((e,t)=>e!==r.directoryHistory[t]),p=!!(u&&u!==r.currentDirectory),m={homeDirectory:i,hasPersistedDirectory:s,isHomeReady:l};if(c?(m.currentDirectory=i,m.directoryHistory=[i],m.historyIndex=0,m.isSwitchingDirectory=!1):(p||f)&&(m.currentDirectory=u,m.directoryHistory=d,m.historyIndex=Math.min(r.historyIndex,d.length-1),m.isSwitchingDirectory=!1),e(()=>m),(c||p)&&l){let e=c?i:u;q.setDirectory(e),$l(),ie(`lastDirectory`,e,{storage:Y}),ce({lastDirectory:e})}ce({homeDirectory:i})}}),{name:`directory-store`}));typeof window<`u`&&(lu().then(e=>{pu.getState().synchronizeHomeDirectory(e)}),i(e=>{J=null;let t=++Xl;if(l(e)){let e=ru(),t=iu(),n=e||`/`,r=t||n;J=e,pu.setState({currentDirectory:r,directoryHistory:[r],historyIndex:0,homeDirectory:n,hasPersistedDirectory:!!t,isHomeReady:!!(e&&e!==`/`),isSwitchingDirectory:!1}),r&&(q.setDirectory(r),$l())}lu().then(e=>{t===Xl&&pu.getState().synchronizeHomeDirectory(e)})}));var mu=(e,i)=>{let a=t();return a?a.openWebSocket(r(e),i):n(i?new WebSocket(e,i):new WebSocket(e))},X=`/api/git`,hu=1200,gu=5e3,_u=2,vu=5e3,yu=`${X}/worktrees/queue-activation`,bu=`message_queue_activation_pending`,xu=`worktree_lifecycle_busy`,Su=`worktree_activation_stale`,Cu=5e3,wu=3e4,Tu=[0,500,1e3,2e3,4e3,8e3,14e3],Eu=new Map,Du=new Map,Ou=new Map,ku=new Map,Au=new Map,ju=new Map,Mu=new Map,Nu=new Map,Pu=new Map,Fu=new Map,Iu=new Map,Lu=new Set,Ru=0,zu=[],Bu=()=>Ru<_u?(Ru+=1,Promise.resolve()):new Promise(e=>{zu.push(e)}),Vu=()=>{let e=zu.shift();if(e){e();return}Ru=Math.max(0,Ru-1)},Hu=async e=>{await Bu();try{return await e()}finally{Vu()}},Uu=Symbol.for(`yuri.git.discoveryGated`),Wu=e=>(Object.defineProperty(e,Uu,{value:!0,configurable:!0}),e),Gu=e=>typeof e==`function`&&e[Uu]===!0,Z=e=>e.trim(),Ku=(e,t)=>t===`light`?`${Z(e)}::light`:Z(e),qu=e=>Ou.get(Z(e))??0,Q=e=>{let t=Z(e);Ou.set(t,qu(e)+1);for(let e of Array.from(ku.keys()))(e===t||e.startsWith(`${t}::`))&&ku.delete(e);for(let e of Array.from(Eu.keys()))(e===t||e.startsWith(`${t}::`))&&Eu.delete(e);for(let e of Array.from(Du.keys()))(e===t||e.startsWith(`${t}::`))&&Du.delete(e)},Ju=e=>Iu.get(Z(e))??0,Yu=e=>{let t=Z(e);t&&(Iu.set(t,Ju(e)+1),Pu.delete(t),Fu.delete(t))};function $(e,t,n){let r={...n};return t&&(r.directory=t),a().api(e,r)}var Xu=(e,t,n)=>{let r=Z(e);if(!r)return;let i=Date.now()+vu;Au.set(r,{value:t,expiresAt:i});let a=typeof n==`string`&&n?n:e;Mu.set(r,{value:{root:a},expiresAt:i})};async function Zu(e){let t=Array.from(new Set(e.map(e=>Z(e)).filter(Boolean))),n=new Map;if(t.length===0)return n;let r=Date.now(),i=[];for(let e of t){let t=Au.get(e),a=Mu.get(e);if(t&&t.expiresAt>r&&a&&a.expiresAt>r){n.set(e,{isGitRepository:t.value,primaryRoot:a.value.root});continue}i.push(e)}if(i.length===0)return n;let o=e=>{for(let t of e){let e=typeof t.directory==`string`?Z(t.directory):``;if(!e)continue;let r=!!t.isGitRepository,i=typeof t.primaryRoot==`string`&&t.primaryRoot?t.primaryRoot:null;Xu(e,r,i),n.set(e,{isGitRepository:r,primaryRoot:i})}},s=async e=>{await Promise.all(e.map(async e=>{try{let[t,r]=await Promise.all([Qu(e),ed(e).then(e=>e.root).catch(()=>e)]);Xu(e,t,t?r:null),n.set(e,{isGitRepository:t,primaryRoot:t?r:null})}catch{Xu(e,!1,null),n.set(e,{isGitRepository:!1,primaryRoot:null})}}))};try{await Hu(async()=>{let e=new URLSearchParams;for(let t of i)e.append(`directories`,t);let t=a().api(`${X}/discover`),n=e.toString(),r=n?t.includes(`?`)?`${t}&${n}`:`${t}?${n}`:t,s=await u(r);if(s.status===501||!s.ok)throw Error(`Batch git discover unavailable: ${s.status} ${s.statusText}`);let c=await s.json().catch(()=>null),l=Array.isArray(c)?c:[];if(l.length===0&&i.length>0)throw Error(`Batch git discover returned empty payload`);o(l)})}catch{}let c=i.filter(e=>!n.has(e));return c.length>0&&await s(c),n}async function Qu(e){let t=Z(e),n=Date.now(),r=Au.get(t);if(r&&r.expiresAt>n)return r.value;let i=ju.get(t);if(i)return i;let a=(async()=>{let n=await u($(`${X}/check`,e));if(!n.ok)throw Error(`Failed to check git repository: ${n.statusText}`);let r=!!(await n.json()).isGitRepository;return Au.set(t,{value:r,expiresAt:Date.now()+gu}),r})();ju.set(t,a);try{return await a}finally{ju.get(t)===a&&ju.delete(t)}}async function $u(e,t){let n=t?.mode,r=Ku(e,n),i=Date.now(),a=Eu.get(r);if(a&&a.expiresAt>i)return a.value;let s=Du.get(r);if(s)return s;let c=(async()=>{let t=qu(e),i=o(),a=ku.get(r),s=a&&a.transport===i&&a.cacheVersion===t?a:null,c=await u($(`${X}/status`,e,{...n?{mode:n}:{},...s?{since:s.revision}:{}}));if(!c.ok)throw Error(`Failed to get git status: ${c.statusText}`);let l=await c.json(),d;if(`unchanged`in l&&l.unchanged===!0){if(!s||l.revision!==s.revision)throw Error(`Failed to get git status: unexpected unchanged response`);d=s.value}else{let{revision:n,...a}=l;d=a,typeof n==`string`&&qu(e)===t&&ku.set(r,{revision:n,value:d,transport:i,cacheVersion:t})}return qu(e)===t&&Eu.set(r,{value:d,expiresAt:Date.now()+hu}),d})();Du.set(r,c);try{return await c}finally{Du.get(r)===c&&Du.delete(r)}}async function ed(e){let t=Z(e),n=Date.now(),r=Mu.get(t);if(r&&r.expiresAt>n)return r.value;let i=Nu.get(t);if(i)return i;let a=Hu(async()=>{let n=await u($(`${X}/primary-root`,e));if(!n.ok)throw Error(`Failed to resolve git primary root: ${n.statusText}`);let r=await n.json().catch(()=>({})),i={root:typeof r.root==`string`&&r.root?r.root:e};return Mu.set(t,{value:i,expiresAt:Date.now()+vu}),i});Nu.set(t,a);try{return await a}finally{Nu.get(t)===a&&Nu.delete(t)}}async function td(e){let t=await u($(`${X}/toplevel`,e));if(!t.ok)throw Error(`Failed to resolve git toplevel: ${t.statusText}`);let n=await t.json().catch(()=>({}));return{root:typeof n.root==`string`&&n.root?n.root:e}}async function nd(e,t){let{path:n,staged:r,contextLines:i}=t;if(!n)throw Error(`path is required to fetch git diff`);let a=await u($(`${X}/diff`,e,{path:n,staged:r?`true`:void 0,context:i}));if(!a.ok)throw Error(`Failed to get git diff: ${a.statusText}`);return a.json()}async function rd(e,t){let{path:n,staged:r}=t;if(!n)throw Error(`path is required to fetch git file diff`);let i=await u($(`${X}/file-diff`,e,{path:n,staged:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get git file diff: ${i.statusText}`);return i.json()}async function id(e,t,n){if(!t)throw Error(`path is required to revert git changes`);let r=await u($(`${X}/revert`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to revert git changes`)}Q(e)}async function ad(e,t){await od(e,[t])}async function od(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to stage git changes`);let r=await u($(`${X}/stage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to stage git changes`)}Q(e)}async function sd(e,t){await cd(e,[t])}async function cd(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to unstage git changes`);let r=await u($(`${X}/unstage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to unstage git changes`)}Q(e)}async function ld(e,t,n){await fd(e,t,n,`stage`)}async function ud(e,t,n){await fd(e,t,n,`unstage`)}async function dd(e,t,n){await fd(e,t,n,`discard`)}async function fd(e,t,n,r){if(!t)throw Error(`path is required to apply a git hunk`);if(typeof n!=`string`||!n.trim())throw Error(`patch is required to apply a git hunk`);let i=await u($(`${X}/apply-hunk`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,patch:n,action:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to apply git hunk`)}Q(e)}async function pd(e){if(!e)return!1;let t=await u($(`${X}/worktree-type`,e));if(!t.ok)throw Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function md(e,t){let n=await u($(`${X}/branches`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get branches: ${n.statusText}`);return n.json()}async function hd(e,t){if(!t?.branch)throw Error(`branch is required to delete a branch`);let n=await u($(`${X}/branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete branch`)}return n.json()}async function gd(e,t){if(!t?.branch)throw Error(`branch is required to delete remote branch`);let n=await u($(`${X}/remote-branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete remote branch`)}return n.json()}async function _d(e,t){let n=t?.remote?.trim();if(!n)throw Error(`remote is required to remove a remote`);let r=await u($(`${X}/remotes`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({remote:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to remove remote`)}return r.json()}async function vd(e,t,n){if(!Array.isArray(t)||t.length===0)throw Error(`No files provided to generate commit message`);let r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);let i=await u($(`${X}/commit-message`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));console.error(`[git-generation][browser] http error`,{status:i.status,statusText:i.statusText,error:e});let t=typeof e?.traceId==`string`&&e.traceId?` (traceId: ${e.traceId})`:``;throw Error(`${e.error||`Failed to generate commit message`}${t}`)}let a=await i.json();if(!a?.message||typeof a.message!=`object`)throw Error(`Malformed commit generation response`);return{message:{subject:typeof a.message.subject==`string`&&a.message.subject.trim().length>0?a.message.subject.trim():``,highlights:Array.isArray(a.message.highlights)?a.message.highlights.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim()):[]}}}async function yd(e,t){let{base:n,head:r,context:i,zenModel:a,providerId:o,modelId:s}=t;if(!n||!r)throw Error(`base and head are required`);let c={base:n,head:r};i?.trim()&&(c.context=i.trim()),a&&(c.zenModel=a),o&&(c.providerId=o),s&&(c.modelId=s);let l=await u($(`${X}/pr-description`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c)});if(!l.ok){let e=await l.json().catch(()=>({error:l.statusText}));throw Error(e.error||`Failed to generate PR description`)}let d=await l.json().catch(()=>null),f=typeof d?.title==`string`?d.title:``,p=typeof d?.body==`string`?d.body:``;if(!f&&!p)throw Error(`Malformed PR description response`);return{title:f,body:p}}async function bd(e){let t=Z(e),n=Date.now(),r=Pu.get(t);if(r&&r.expiresAt>n)return r.value;let i=Fu.get(t);if(i)return i;let a=Ju(e),o=Hu(async()=>{let n=await u($(`${X}/worktrees`,e));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to list worktrees`)}let r=await n.json();return a===Ju(e)&&Pu.set(t,{value:r,expiresAt:Date.now()+vu}),r});Fu.set(t,o);try{return await o}finally{Fu.get(t)===o&&Fu.delete(t)}}Wu(bd);async function xd(e,t){let n=await u($(`${X}/worktrees/validate`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to validate worktree`)}return n.json()}async function Sd(e){let t=await u($(`${X}/worktrees/bootstrap-status`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to get worktree bootstrap status`)}return t.json()}async function Cd(e,t){let n=await u($(`${X}/worktrees/preview`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to preview worktree`)}return n.json()}var wd=e=>typeof e==`string`&&e.length>0,Td=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(!wd(t.name)||!wd(t.path))return null;let n={head:typeof t.head==`string`?t.head:``,name:t.name,branch:typeof t.branch==`string`?t.branch:``,path:t.path};return t.directoryCreated===!0&&(n.directoryCreated=!0),t.bootstrapStatus&&typeof t.bootstrapStatus==`object`&&(n.bootstrapStatus=t.bootstrapStatus),n},Ed=(e,t,n)=>{if(e!==503||!t||typeof t!=`object`)return null;let r=t;if(r.code!==bu)return null;let i=Td(r.worktree);if(!i)return null;let a=r.repair;if(!a||typeof a!=`object`)return null;let o=a;if(o.method!==`POST`||o.path!==yu)return null;let s=o.body;if(!s||typeof s!=`object`)return null;let c=s;return c.projectDirectory!==n||c.directory!==i.path?null:i},Dd=(e,t,n,r)=>`${e}\u0000${t}\u0000${n}\u0000${r}`,Od=e=>new Promise(t=>{setTimeout(t,e)}),kd=async e=>{if(e.status===409){let t=await e.json().catch(()=>null);return t?.code===xu||t?.code===Su}return e.status===503&&(await e.json().catch(()=>null))?.code===bu},Ad=e=>e===400||e===401||e===403||e===501,jd=(e,t)=>{let n=o(),r=s(),i=Dd(n,r,e,t);if(Lu.has(i))return;Lu.add(i);let a=()=>o()===n&&s()===r;(async()=>{let n=Date.now(),r=0;for(;Date.now()-n<wu;){if(!a())return;let i=Tu[Math.min(r,Tu.length-1)]??0;if(i>0){let e=wu-(Date.now()-n);if(e<=0||(await Od(Math.min(i,e)),!a()))return}let o=new AbortController,s=setTimeout(()=>o.abort(),Cu);try{let n=await u($(yu,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectDirectory:e,directory:t}),signal:o.signal});if(n.ok||Ad(n.status))return;if(await kd(n)){r+=1;continue}return}catch{r+=1}finally{clearTimeout(s)}}})().catch(()=>{}).finally(()=>{Lu.delete(i)})};async function Md(e,t){let n=await u($(`${X}/worktrees`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})}),r=await n.json().catch(()=>null);if(n.ok){let t=Td(r);if(t)return Yu(e),t;if(r&&typeof r==`object`)return Yu(e),r;throw Error(`Failed to create worktree`)}let i=Ed(n.status,r,e);if(i)return Yu(e),jd(e,i.path),i;let a=r&&typeof r==`object`?r:{error:n.statusText};throw Error(a.error||`Failed to create worktree`)}async function Nd(e,t){let n=await u($(`${X}/worktrees`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete worktree`)}let r=await n.json();return Yu(e),r}async function Pd(e,t,n={}){let r=await u($(`${X}/commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create commit`)}let i=await r.json();return Q(e),i}async function Fd(e,t={}){let n=await u($(`${X}/push`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to push`)}let r=await n.json();return Q(e),r}async function Id(e,t={}){let n=await u($(`${X}/pull`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to pull`)}let r=await n.json();return Q(e),r}async function Ld(e,t={}){let n=await u($(`${X}/fetch`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to fetch`)}let r=await n.json();return Q(e),r}async function Rd(e){let t=await u($(`${X}/stashes`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to list stashes`)}return t.json()}async function zd(e,t){let n=await u($(`${X}/stashes/file-counts`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({refs:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to count stash files`)}return n.json()}async function Bd(e,t={}){let n=await u($(`${X}/stash`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to stash changes`)}return n.json()}var Vd=async(e,t,n)=>{let r=await u($(`${X}/${t}`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to ${t}`)}return r.json()},Hd=(e,t)=>Vd(e,`stash/apply`,t),Ud=(e,t)=>Vd(e,`stash/pop`,t),Wd=(e,t)=>Vd(e,`stash/drop`,t);async function Gd(e,t){let n=await u($(`${X}/checkout`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({branch:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout branch`)}return n.json()}async function Kd(e,t,n){let r=await u($(`${X}/branches`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create branch`)}return r.json()}async function qd(e,t,n){let r=await u($(`${X}/branches/rename`,e),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to rename branch`)}return r.json()}async function Jd(e,t={}){let n=await u($(`${X}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?`true`:void 0}));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(`Failed to get git log: ${e.error||n.statusText}`)}return n.json()}async function Yd(e,t){let n=await u($(`${X}/commit-files`,e,{hash:t}));if(!n.ok)throw Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function Xd(e,t,n,r){let i=await u($(`${X}/commit-file-diff`,e,{hash:t,path:n,binary:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function Zd(){let e=await u($(`${X}/identities`,void 0));if(!e.ok)throw Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Qd(e){let t=await u($(`${X}/identities`,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to create git identity`)}return t.json()}async function $d(e,t){let n=await u($(`${X}/identities/${e}`,void 0),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to update git identity`)}return n.json()}async function ef(e){let t=await u($(`${X}/identities/${e}`,void 0),{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to delete git identity`)}}async function tf(e){if(!e)return null;let t=await u($(`${X}/current-identity`,e));if(!t.ok)throw Error(`Failed to get current git identity: ${t.statusText}`);let n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function nf(e){if(!e)return!1;let t=await u($(`${X}/has-local-identity`,e));if(!t.ok)throw Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function rf(){let e=await u($(`${X}/global-identity`,void 0));if(!e.ok)throw Error(`Failed to get global git identity: ${e.statusText}`);let t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function af(e,t){let n=await u($(`${X}/set-identity`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profileId:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to set git identity`)}return n.json()}async function of(){let e=await u($(`${X}/discover-credentials`,void 0));if(!e.ok)throw Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function sf(e,t){let n=await u($(`${X}/remotes`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get remotes: ${n.statusText}`);return n.json()}async function cf(e,t){let n=await u($(`${X}/rebase`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to rebase`)}return n.json()}async function lf(e){let t=await u($(`${X}/rebase/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort rebase`)}return t.json()}async function uf(e,t){let n=await u($(`${X}/merge`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to merge`)}return n.json()}async function df(e,t){let n=await u($(`${X}/checkout-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout commit`)}return n.json()}async function ff(e,t){let n=await u($(`${X}/cherry-pick`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to cherry-pick`)}return n.json()}async function pf(e,t){let n=await u($(`${X}/revert-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to revert commit`)}return n.json()}async function mf(e,t,n,r){let i=await u($(`${X}/reset-to-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t,mode:n,force:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to reset`)}return i.json()}async function hf(e){let t=await u($(`${X}/merge/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort merge`)}return t.json()}async function gf(e){let t=await u($(`${X}/rebase/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue rebase`)}return t.json()}async function _f(e){let t=await u($(`${X}/merge/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue merge`)}return t.json()}async function vf(e,t){return await Bd(e,{message:t?.message}),{success:!0}}async function yf(e){return await Ud(e,{ref:`stash@{0}`}),{success:!0}}async function bf(e){let t=await u($(`${X}/conflict-details`,e));if(!t.ok)throw Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function xf(e,t){let n=await u(`${X}/validate-directory`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function Sf(e){let t=await u(`${X}/canonicalize-worktree-state`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e})});if(!t.ok)throw Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}export{mf as $,Ca as $n,Rn as $r,xs as $t,nd as A,De as Ai,wo as An,Ni as Ar,q as At,Fd as B,Qa as Bn,Ur as Br,gc as Bt,vd as C,Ve as Ci,Jo as Cn,Wi as Cr,Wl as Ct,bf as D,je as Di,Vo as Dn,Bi as Dr,Yl as Dt,Yd as E,et as Ei,Zo as En,Fi as Er,ql as Et,Sd as F,ve as Fi,Ja as Fn,zr as Fr,Ic as Ft,Rd as G,ma as Gn,wr as Gr,ec as Gt,Yu as H,to as Hn,kr as Hr,Tc as Ht,rf as I,ye as Ii,qa as In,Hr as Ir,Bc as It,Ud as J,Ra as Jn,mr as Jr,lc as Jt,bd as K,pa as Kn,Cr as Kr,ac as Kt,sf as L,_e as Li,Ya as Ln,Kr as Lr,Pc as Lt,Zd as M,Se as Mi,Za as Mn,gi as Mr,Vc as Mt,Jd as N,v as Ni,eo as Nn,_i as Nr,Lc as Nt,tf as O,Te as Oi,So as On,Ai as Or,Jl as Ot,$u as P,xe as Pi,$a as Pn,Ir as Pr,Nc as Pt,qd as Q,_a as Qn,Fn as Qr,rc as Qt,Ld as R,be as Ri,no as Rn,Mr as Rr,Mc as Rt,Wd as S,He as Si,Ko as Sn,Hi as Sr,Kl as St,Xd as T,Ze as Ti,Bo as Tn,Pi as Tr,Il as Tt,Gu as U,Ga as Un,Sr as Ur,Cc as Ut,nf as V,Ka as Vn,Br as Vr,wc as Vt,pd as W,Xa as Wn,xr as Wr,Sc as Wt,cf as X,la as Xn,Nn as Xr,cc as Xt,Cd as Y,ua as Yn,Pn as Yr,tc as Yt,_d as Z,Ta as Zn,Sn as Zr,ic as Zt,ef as _,pt as _i,qo as _n,Ri as _r,xf as _t,Qu as a,bn as ai,Rs as an,Ia as ar,af as at,of as b,$e as bi,Ro as bn,ji as br,pu as bt,ff as c,En as ci,Is as cn,na as cr,ld as ct,zd as d,hn as di,V as dn,qi as dr,yf as dt,kn as ei,B as en,Pa as er,ed as et,Kd as f,rn as fi,R as fn,Ki as fr,sd as ft,hd as g,zt as gi,ns as gn,zi as gr,xd as gt,Md as h,tn as hi,rs as hn,Mi as hr,$d as ht,Sf as i,xn as ii,Ts as in,ka as ir,dd as it,rd as j,Ee as ji,uo as jn,wi as jr,Fc as jt,md as k,we as ki,xo as kn,N as kr,Fl as kt,_f as l,Cn as li,ys as ln,ta as lr,vf as lt,Qd as m,Ht as mi,_s as mn,Li as mr,ud as mt,lf as n,Ln as ni,Ps as nn,Da as nr,pf as nt,Gd as o,yn as oi,Ms as on,ja as or,ad as ot,Pd as p,un as pi,vs as pn,Gi as pr,cd as pt,uf as q,Ea as qn,br as qr,sc as qt,Hd as r,In as ri,As as rn,ya as rr,id as rt,df as s,Tn as si,Ns as sn,fa as sr,od as st,hf as t,wn as ti,Fs as tn,ha as tr,td as tt,gf as u,pn as ui,Ls as un,Yi as ur,Bd as ut,Nd as v,_t as vi,Io as vn,Ui as vr,Hu as vt,yd as w,Pe as wi,Yo as wn,Vi as wr,Ul as wt,Zu as x,Fe as xi,Go as xn,Ii as xr,Gl as xt,gd as y,dt as yi,Lo as yn,M as yr,mu as yt,Id as z,ro as zn,Nr as zr,jc as zt};
|
|
6
|
+
`));try{return await this.runSessionBoundary(e.id,async()=>{r();let t=e.delivery===`queue`?`queue`:`steer`;t!==`queue`&&(await this.applySendSelection(e.id,{model:e.switchModel,agent:e.switchAgent},a),r());let n={sessionID:e.id,directory:o.directory,messageID:i,text:u,delivery:t,commit:o,...d.length>0?{files:d}:{},...f.length>0?{agents:f}:{},...p.length>0?{skills:p}:{},...e.agent||e.variant||e.format||e.providerID?{metadata:{...e.agent?{agent:e.agent}:{},...e.variant?{variant:e.variant}:{},model:{providerID:e.providerID,modelID:e.modelID},...e.format?{format:e.format}:{}}}:{}},s=async()=>{r();let e=await Xs(n);return r(),e.id};try{let t=await s();return Xc(e.providerID),t}catch(t){if(r(),Zs(t)||t?.name===`RuntimeGenerationMismatchError`)throw t;let n=await Qs({sessionID:e.id,directory:o.directory,inputID:i,commit:o});if(r(),n.status===`pending`||n.status===`promoted`)return Xc(e.providerID),i;try{let t=await s();return Xc(e.providerID),t}catch(t){if(r(),Zs(t)||t?.name===`RuntimeGenerationMismatchError`)throw t;let n=await Qs({sessionID:e.id,directory:o.directory,inputID:i,commit:o});if(r(),n.status===`pending`||n.status===`promoted`)return Xc(e.providerID),i;throw t}}})}catch(t){throw Zc(e.providerID,t.status),t}}async sendCommand(e){let t=s(),n=c(),r=e.directory?this.getScopedSdkClient(e.directory):this.client,i=e.messageId??ue(`msg`),a=e.arguments?.trim()||e.files?.length?await this.buildMessageParts({text:e.arguments??``,files:e.files}):[],o=a.flatMap(e=>e.type===`file`?[{uri:e.url,...e.filename?{name:e.filename}:{}}]:[]),l=a.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
|
|
7
|
+
`);if(e.providerID,e.modelID,e.agent,e.variant,t!==s()||n!==c())throw Error(`Runtime changed while preparing command`);return await r.session.command({sessionID:e.id,name:e.command,text:l,...e.delivery?{delivery:e.delivery}:{},...o.length>0?{files:o}:{}}),i}async abortSession(e){return await sc({sessionID:e,directory:this.currentDirectory}),!0}async shellSession(e){return e.directory,await this.client.session.shell({sessionID:e.sessionId,command:e.command,...e.messageId?{id:e.messageId}:{}}),{info:{id:e.messageId??``,sessionID:e.sessionId,role:`assistant`,time:{created:Date.now()},clientRole:`shell`,agent:e.agent,modelID:e.model.modelID,providerID:e.model.providerID},parts:[]}}async revertSession(e,t,n,r){let i=await Sc({sessionID:e,directory:this.normalizeCandidatePath(r)??this.currentDirectory,messageID:t,files:!0});return{id:e,time:{created:0,updated:Date.now()},revert:i}}async summarizeSession(e,t,n,r){return await vt({sessionID:e,directory:this.normalizeCandidatePath(r)??this.currentDirectory??``}),!0}async unrevertSession(e,t){return await Cc({sessionID:e,directory:this.normalizeCandidatePath(t)??this.currentDirectory}),{id:e,time:{created:0,updated:Date.now()}}}async forkSession(e,t,n){this.normalizeCandidatePath(n)??this.currentDirectory;let r=await this.client.session.fork({sessionID:e,...t?{before:t}:{}});return r.id,v(r)}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e,t){return null}async getSessionActive(e){try{let t=await this.client.session.active(e?{signal:e}:void 0),n=t&&typeof t==`object`&&`data`in t&&t.data!==void 0?t.data:t;if(!n||typeof n!=`object`||Array.isArray(n))return{state:`unknown`};let r={};for(let[e,t]of Object.entries(n)){if(typeof e!=`string`||e.length===0||!t||typeof t!=`object`||t.type!==`running`)return{state:`unknown`};r[e]={type:`running`}}return{state:`supported`,membership:r}}catch(e){return ul(ll(e))?{state:`unsupported`}:{state:`unknown`}}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{let e=await u(`/api/session-activity`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json().catch(()=>null);return!t||typeof t!=`object`?null:t}catch{return null}}async listToolIds(e){throw G(`tool.ids`)}async replyToPermission(e,t,n){let r=this.normalizeCandidatePath(n?.directory??null)??this.currentDirectory;if(!n?.sessionID)throw G(`permission.reply (sessionID required)`);return await Ac({sessionID:n.sessionID,requestID:e,reply:t,...n.message?{message:n.message}:{},directory:r}),!0}async createPermission(e,t,n,r){try{let i=await this.client.permission.create({sessionID:e,action:t,resources:n,...r?.id?{id:r.id}:{},...r?.save?{save:r.save}:{},...r?.metadata?{metadata:r.metadata}:{},...r?.source?{source:r.source}:{},...r?.agent?{agent:r.agent}:{}});return!i||typeof i.id!=`string`?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(e,t){try{let n=await this.client.permission.get({sessionID:e,requestID:t});return n===void 0?{state:`unknown`}:{state:`ok`,permission:n}}catch(e){return ee(e)||ll(e)===404?{state:`resolved`}:{state:`unknown`}}}async listPendingPermissions(e){let t=async e=>{let t=await this.client.permission.request.list(K(e));if(!t||!Array.isArray(t.data))throw Error(`permission.list failed: ${cl(t)}`);return t.data.flatMap(e=>{let t=fl(e);return t?[t]:[]})},n=e?.directories===void 0?[null]:await this.resolveBlockingRequestDirectories(e.directories),r=await Promise.all(n.map(t)),i=[],a=new Set;for(let e of r)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(a.has(e)||(a.add(e),i.push(t)))}return i}async replyToQuestion(e,t,n,r){let i=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];if(!r)throw G(`session.form.reply (sessionID required)`);let a=this.client,o=await a.session.form.get({sessionID:r,formID:e});return await a.session.form.reply({sessionID:r,formID:e,answer:Bc(i,o.fields)}),!0}async rejectQuestion(e,t){if(!t)throw G(`session.form.cancel (sessionID required)`);return await this.client.session.form.cancel({sessionID:t,formID:e}),!0}async listPendingQuestions(e){let t=async e=>{let t=await this.client.form.list(K(e));if(!t||!Array.isArray(t.data))throw Error(`form.list failed: ${cl(t)}`);return t.data.flatMap(e=>Ic(e.metadata)?[zc({id:e.id,sessionID:e.sessionID,title:e.title,fields:e.fields,...e.metadata?{metadata:e.metadata}:{}})]:[])},n=e?.directories===void 0?[null]:await this.resolveBlockingRequestDirectories(e.directories),r=await Promise.all(n.map(t)),i=[],a=new Set;for(let e of r)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(a.has(e)||(a.add(e),i.push(t)))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}clearHealthCache(){this.healthCacheGeneration+=1,this.healthInFlight.clear(),this.healthCache.clear()}async getConfig(e){let t=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,n=t??``,r=this.configCache.get(n);if(r&&r.expiresAt>Date.now())return R(`opencodeClient.getConfig:cacheHit`,{directory:t??null}),r.config;let i=this.configInFlight.get(n);if(i)return R(`opencodeClient.getConfig:deduped`,{directory:t??null}),i;let a=this.configCacheGeneration,o=(async()=>{R(`opencodeClient.getConfig:start`,{directory:t??null});let e=typeof performance<`u`?performance.now():Date.now(),r=await this.client.config.get(K(t));if(!Array.isArray(r))throw Error(`Failed to get config`);let i=Se(r),o=typeof performance<`u`?performance.now():Date.now();return R(`opencodeClient.getConfig:end`,{directory:t??null,durationMs:Math.round(o-e)}),a===this.configCacheGeneration&&this.configCache.set(n,{config:i,expiresAt:Date.now()+nl}),i})();this.configInFlight.set(n,o);try{return await o}finally{this.configInFlight.get(n)===o&&this.configInFlight.delete(n)}}async updateConfig(e){throw G(`config.update`)}async updateConfigPartial(e){let t=e(await this.getConfig());return await this.updateConfig(t)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(e){let t=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,n=t??``,r=this.configProvidersInFlight.get(n);if(r)return r;let i=(async()=>{let e=await this.client.provider.list(K(t));if(!e||!Array.isArray(e.data))throw Error(`config.providers failed: ${cl(e)}`);let n={};try{let e=await this.client.model.default(K(t));e?.data&&(n[e.data.providerID]=e.data.modelID)}catch{}return{providers:e.data,default:n}})();this.configProvidersInFlight.set(n,i);try{return await i}finally{this.configProvidersInFlight.delete(n)}}async getApp(){return{version:`0.0.3`,config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(e,t){let n=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,r=n??``;if(!t){let e=this.listAgentsInFlight.get(r);if(e)return e}let i=(async()=>{let e=_l(sl),r=vl(t?[t,e.signal]:[e.signal]);try{let e=K(n),t=await this.client.agent.list(e,{signal:r.signal});if(!t||!Array.isArray(t.data))throw Error(`app.agents failed: ${cl(t)}`);return t.data.map(e=>_e(e))}finally{e.cleanup(),r.cleanup()}})();if(t)return i;this.listAgentsInFlight.set(r,i);try{return await i}finally{this.listAgentsInFlight.delete(r)}}async readFile(e){try{let t=await this.client.file.read({path:e,...K(this.currentDirectory)});return new TextDecoder().decode(t)}catch{return`// Content of ${e}\n// This would be loaded from the server`}}async listFiles(e){try{let t=e||this.currentDirectory||`/`,n=(await this.client.file.list({path:t,...K(this.currentDirectory)})).data;return Array.isArray(n)?n:[]}catch{return[]}}async listCommands(){let e=await this.client.command.list(K(this.currentDirectory)),t=e.data;if(!Array.isArray(t))throw Error(`command.list failed: ${cl(e)}`);return t.map(e=>({name:e.name,description:e.description,agent:void 0,model:void 0,source:void 0}))}async listCommandsWithDetails(){let e=await this.client.command.list(K(this.currentDirectory)),t=e.data;if(!Array.isArray(t))throw Error(`command.list failed: ${cl(e)}`);return t.map(e=>({name:e.name,description:e.description,agent:void 0,model:void 0,source:void 0,template:``}))}async listSkillsWithDetails(){try{let e=(await this.client.skill.list(K(this.currentDirectory))).data;if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=typeof n.id==`string`?n.id:``,r=typeof n.path==`string`?n.path:``;if(!e||!r)continue;let i={name:e,location:r};typeof n.description==`string`&&(i.description=n.description),typeof n.content==`string`&&(i.content=n.content),t.push(i)}return t}catch{return[]}}async getCommandDetails(e){try{let t=await this.client.command.list(K(this.currentDirectory));if(t.data){let n=t.data.find(t=>t.name===e);if(n)return{name:n.name,template:``,description:n.description,agent:void 0,model:void 0}}return null}catch{return null}}async checkHealth(){let e=c(),t=this.healthCache.get(e);if(t&&t.expiresAt>Date.now())return t.healthy;let n=this.healthInFlight.get(e);if(n)return n;let r=this.healthCacheGeneration,i=(async()=>{let t=!1;try{let e=`/api/opencode/health`;R(`opencodeClient.checkHealth:url`,{baseUrl:this.baseUrl,healthUrl:e});let n=_l(rl),r=await u(e,{signal:n.signal}).finally(n.cleanup);if(R(`opencodeClient.checkHealth:response`,{status:r.status}),r.ok){let e=await r.json();R(`opencodeClient.checkHealth:result`,{healthy:e?.healthy}),t=e?.healthy===!0}}catch{t=!1}return r!==this.healthCacheGeneration||e!==c()?!1:(this.healthCache.set(e,{healthy:t,expiresAt:Date.now()+(t?il:al)}),t)})();this.healthInFlight.set(e,i);try{return await i}finally{this.healthInFlight.get(e)===i&&this.healthInFlight.delete(e)}}async createDirectory(e,t){let n=Ol();if(n?.createDirectory)try{return await n.createDirectory(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(t||`Failed to create directory`)}let r={path:e,...t?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},i=await u(`/api/fs/mkdir`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:`Failed to create directory`}));throw Error(e.error||`Failed to create directory`)}return await i.json()}async cloneRepository(e){let t=await u(`/api/fs/clone`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to clone repository`}));throw Error(e.error||`Failed to clone repository`)}return await t.json()}async listLocalDirectory(e,t){let n=`${typeof e==`string`?El(e.trim()):``}|${t?.respectGitignore?`1`:`0`}`,r=Date.now(),i=this.listDirectoryCache.get(n);if(i&&i.expiresAt>r)return i.entries;let a=this.listDirectoryInFlight.get(n);if(a)return a;let o=(async()=>{let r=Ol();if(r)try{let i=await r.listDirectory(e||``,t);if(!i||!Array.isArray(i.entries))return[];let a=i.entries.map(e=>({name:e.name,path:El(e.path),isDirectory:!!e.isDirectory,isFile:!e.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:a,expiresAt:Date.now()+Dl}),a}catch(e){throw console.error(`Failed to list directory contents:`,e),e}try{let r=new URLSearchParams;e&&e.trim().length>0&&r.set(`path`,e),t?.respectGitignore&&r.set(`respectGitignore`,`true`);let i=r.toString(),a=await u(`/api/fs/list${i?`?${i}`:``}`);if(!a.ok){let e=await a.json().catch(()=>({})),t=typeof e.error==`string`?e.error:`Failed to list directory`;throw Error(t)}let o=await a.json();if(!o||!Array.isArray(o.entries))return[];let s=o.entries;return this.listDirectoryCache.set(n,{entries:s,expiresAt:Date.now()+Dl}),s}catch(e){throw console.error(`Failed to list directory contents:`,e),e}})().finally(()=>{this.listDirectoryInFlight.get(n)===o&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,o),o}async searchFiles(e,t){let n=typeof t?.directory==`string`&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,r=n?El(n):null;t?.signal?.throwIfAborted();try{let i=await this.client.file.find({query:e,...K(n),limit:typeof t?.limit==`number`&&Number.isFinite(t.limit)?t.limit:void 0,type:t?.type},{signal:t?.signal});return t?.signal?.throwIfAborted(),(Array.isArray(i?.data)?i.data:[]).map(e=>{let t=El(e.path),n=t.split(`/`).filter(Boolean).pop()||t;return{name:n,path:El(r?`${r}/${t}`:t),relativePath:t,extension:n.includes(`.`)?n.split(`.`).pop()?.toLowerCase():void 0,isDirectory:e.type===`directory`}})}catch(e){throw t?.signal?.aborted||console.error(`Failed to search files:`,e),e}}async getFilesystemHome(){let e=c();if(!e||e===`local`){let e=await d();if(e)return e}try{let e=await u(`/api/fs/home`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok){let t=await e.json().catch(()=>({})),n=typeof t.error==`string`&&t.error.length>0?t.error:`Failed to resolve home directory`;throw Error(n)}let t=await e.json();return t&&typeof t.home==`string`&&t.home.length>0?t.home:null}catch(e){return console.warn(`Failed to resolve filesystem home directory:`,e),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!=`string`||!e.trim())return console.warn(`[OpencodeClient] setOpenCodeWorkingDirectory: invalid path`,e),null;try{let t=await u(`/api/opencode/directory`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})}),n=await t.json().catch(()=>null);if(!t.ok){let e=n??{},t=typeof e.error==`string`&&e.error.length>0?e.error:`Failed to update OpenCode working directory`;throw Error(t)}return n&&typeof n==`object`?n:{success:!0,restarted:!1,path:e}}catch(e){throw console.warn(`Failed to update OpenCode working directory:`,e),e}}},kl=3e4,Al=40,jl=60,Ml=(e,t,n,r,i,a)=>{let o=e.trim(),s=t.trim().toLowerCase();return JSON.stringify([o,s,n,r,i,a])},Nl=(e,t)=>{try{let n=JSON.parse(e);return Array.isArray(n)&&n[0]===t}catch{return!1}},Pl=m()(h((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,i=jl,a){if(!n||n.trim().length===0)return[];let o=n.trim(),s=typeof r==`string`?r.trim():``,c=!!a?.includeHidden,l=a?.respectGitignore??!0,u=a?.type===`directory`?`directory`:`file`,d=Ml(o,s,i,c,l,u),f=Date.now(),p=t().cache[d];if(p&&f-p.timestamp<kl)return p.files;let m=t().inFlight[d];if(m)return m;let h=q.searchFiles(s,{directory:o,limit:i,includeHidden:c,respectGitignore:l,dirs:u!==`file`,type:u}).then(t=>(e(e=>{if(e.inFlight[d]!==h)return e;let n={...e.cache,[d]:{files:t,timestamp:Date.now()}},r=e.cacheKeys.filter(e=>e!==d);for(r.push(d);r.length>Al;){let e=r.shift();e&&delete n[e]}return{cache:n,cacheKeys:r}}),t)).finally(()=>{e(e=>{if(e.inFlight[d]!==h)return e;let t={...e.inFlight};return delete t[d],{inFlight:t}})});return e(e=>({inFlight:{...e.inFlight,[d]:h}})),h},invalidateDirectory(t){if(!t||t.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}let n=t.trim();e(e=>{let t={...e.cache},r=e.cacheKeys.filter(e=>!Nl(e,n)||(delete t[e],!1)),i=Object.entries(e.inFlight).filter(([e])=>!Nl(e,n));return{cache:t,cacheKeys:r,inFlight:Object.fromEntries(i)}})}}),{name:`file-search-store`})),Fl=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`yuri_stream_debug`)===`1`}catch{return!1}},Il=`yuri_stream_perf`,Ll=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(Il)===`1`}catch{return!1}},Rl=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),zl=()=>{if(!Ll()||typeof window>`u`)return null;if(!window.__yuriStreamPerfState){let e=Date.now();window.__yuriStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__yuriStreamPerfState},Bl=e=>Array.from(e.entries()).map(([e,t])=>({metric:e,count:t.count,avg:t.count>0?Number((t.total/t.count).toFixed(3)):0,max:Number(t.max.toFixed(3)),total:Number(t.total.toFixed(3)),last:Number(t.last.toFixed(3))})).sort((e,t)=>t.total-e.total||t.count-e.count),Vl=(e,t)=>{let n=zl();if(!n)return;let r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},Hl=e=>{if(!(typeof window>`u`))try{if(e){window.localStorage.setItem(Il,`1`),window.__yuriStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Il),delete window.__yuriStreamPerfState,delete window.__yuriVsCodeStreamPerfState}catch{}},Ul=()=>{typeof window>`u`||(Ll()&&(window.__yuriStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__yuriVsCodeStreamPerfState&&(window.__yuriVsCodeStreamPerfState={...window.__yuriVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Wl=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__yuriStreamPerfState;return!Ll()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:Bl(e.counters)}},Gl=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__yuriVsCodeStreamPerfState;if(!Ll()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let t=typeof e.startedAt==`number`?e.startedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:typeof e.lastUpdatedAt==`number`?e.lastUpdatedAt:null,durationMs:t?Math.max(0,Date.now()-t):0,entries:Bl(e.counters)}},Kl=(e,t=1)=>{Vl(e,t)},ql=(e,t)=>{Vl(e,t)},Jl=(e,t)=>{if(!Ll())return t();let n=Rl();try{return t()}finally{Vl(e,Rl()-n)}},J=null,Yl=0,Y=re(),Xl=ae(`lastDirectory`,{storage:Y}),Zl=typeof Xl==`string`&&Xl.length>0,Ql=e=>{try{Pl.getState().invalidateDirectory(e)}catch(e){console.warn(`Failed to invalidate file search cache:`,e)}},$l=e=>{let t=e.trim();if(!t)return t;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return n.length>1?n.replace(/\/+$/,``):n},eu=(e,t)=>{let n=e.trim();return n.startsWith(`~`)?n===`~`?t||n:(n.startsWith(`~/`)||n.startsWith(`~\\`))&&t?`${t}${n.slice(1)}`:n:n},tu=(e,t)=>$l(eu(e,t)),nu=()=>{let e=ae(`homeDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=$l(e);return t.length>0?t:null},ru=()=>{let e=ae(`lastDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=$l(e);return t.length>0?t:null},iu=()=>{if(typeof process>`u`)return null;let e={},t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t==`string`&&t.trim().length>0){let e=$l(t);return e.length>0?e:null}let n=process?.cwd?.();if(typeof n==`string`&&n.trim().length>0){let e=$l(n);return e.length>0?e:null}return null},au=()=>{if(typeof window<`u`){if(J)return J;let e=typeof window.__YURI_HOME__==`string`&&window.__YURI_HOME__.length>0?window.__YURI_HOME__:null;if(e&&e.length>0)return J=e,ie(`homeDirectory`,e,{storage:Y}),e;let t=nu();if(t&&!f())return J=t,t}return iu()||`/`},ou=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`);if(n.length>1){let e=n.replace(/\/+$/,``);if(e&&e.length>0)return e===`/`?null:e}return n===`/`||n.length===0?null:n},su=e=>(J=e,typeof window<`u`&&ie(`homeDirectory`,e,{storage:Y}),ce({homeDirectory:e}),e),cu=async()=>{let e=e=>{let t=ou(e);return t?su(t):null};try{let t=e(await q.getFilesystemHome());if(t)return t}catch(e){console.warn(`Failed to obtain filesystem home directory:`,e)}try{let t=e((await q.getSystemInfo())?.homeDirectory);if(t)return t}catch(e){console.warn(`Failed to get home directory from system info:`,e)}try{let t=e(await d());if(t)return t}catch(e){console.warn(`Failed to obtain desktop-integrated home directory:`,e)}let t=au();return e(t)||t},lu=(()=>{if(!f())return null;let e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!=`string`||e.trim().length===0)return null;let t=$l(e);return t.length>0?t:null})()||au(),uu=(()=>{let e=ru();return e&&!f()?tu(e,lu):lu})();uu&&q.setDirectory(uu);var du=!!(lu&&lu!==`/`),fu=m()(h((e,t)=>({currentDirectory:uu,directoryHistory:[uu],historyIndex:0,homeDirectory:lu,hasPersistedDirectory:Zl,isHomeReady:du,isSwitchingDirectory:!1,setDirectory:(n,r)=>{let i=tu(n,J||t().homeDirectory||ae(`homeDirectory`,{storage:Y}));Fl(),ge(t().currentDirectory,i)&&(q.setDirectory(i),Ql(),e(e=>{let t=[...e.directoryHistory.slice(0,e.historyIndex+1),i];return ie(`lastDirectory`,i,{storage:Y}),ce({lastDirectory:i}),{currentDirectory:i,directoryHistory:t,historyIndex:t.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}}))},goBack:()=>{let n=t();if(n.historyIndex>0){let t=n.historyIndex-1,r=n.directoryHistory[t];q.setDirectory(r),Ql(),ie(`lastDirectory`,r,{storage:Y}),ce({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{let n=t();if(n.historyIndex<n.directoryHistory.length-1){let t=n.historyIndex+1,r=n.directoryHistory[t];q.setDirectory(r),Ql(),ie(`lastDirectory`,r,{storage:Y}),ce({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{let{currentDirectory:e,setDirectory:n}=t();if(e===(J||t().homeDirectory||au())||e===`/`)return;let r=e.endsWith(`/`)?e.slice(0,-1):e,i=r.lastIndexOf(`/`);n(i===-1?J||au():i===0?`/`:r.substring(0,i))},goHome:async()=>{let e=J||t().homeDirectory||await cu();t().setDirectory(e)},synchronizeHomeDirectory:n=>{let r=t(),i=n;J=i;let a=r.homeDirectory!==i,o=ae(`lastDirectory`,{storage:Y}),s=typeof o==`string`&&o.length>0,c=!s&&(r.currentDirectory===`/`||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!a&&!c){r.isHomeReady||e({isHomeReady:!0});return}let l=typeof i==`string`&&i!==``&&i!==`/`,u=r.currentDirectory?tu(r.currentDirectory,i):r.currentDirectory,d=r.directoryHistory.map(e=>tu(e,i)),f=d.some((e,t)=>e!==r.directoryHistory[t]),p=!!(u&&u!==r.currentDirectory),m={homeDirectory:i,hasPersistedDirectory:s,isHomeReady:l};if(c?(m.currentDirectory=i,m.directoryHistory=[i],m.historyIndex=0,m.isSwitchingDirectory=!1):(p||f)&&(m.currentDirectory=u,m.directoryHistory=d,m.historyIndex=Math.min(r.historyIndex,d.length-1),m.isSwitchingDirectory=!1),e(()=>m),(c||p)&&l){let e=c?i:u;q.setDirectory(e),Ql(),ie(`lastDirectory`,e,{storage:Y}),ce({lastDirectory:e})}ce({homeDirectory:i})}}),{name:`directory-store`}));typeof window<`u`&&(cu().then(e=>{fu.getState().synchronizeHomeDirectory(e)}),i(e=>{J=null;let t=++Yl;if(l(e)){let e=nu(),t=ru(),n=e||`/`,r=t||n;J=e,fu.setState({currentDirectory:r,directoryHistory:[r],historyIndex:0,homeDirectory:n,hasPersistedDirectory:!!t,isHomeReady:!!(e&&e!==`/`),isSwitchingDirectory:!1}),r&&(q.setDirectory(r),Ql())}cu().then(e=>{t===Yl&&fu.getState().synchronizeHomeDirectory(e)})}));var pu=(e,i)=>{let a=t();return a?a.openWebSocket(r(e),i):n(i?new WebSocket(e,i):new WebSocket(e))},X=`/api/git`,mu=1200,hu=5e3,gu=2,_u=5e3,vu=`${X}/worktrees/queue-activation`,yu=`message_queue_activation_pending`,bu=`worktree_lifecycle_busy`,xu=`worktree_activation_stale`,Su=5e3,Cu=3e4,wu=[0,500,1e3,2e3,4e3,8e3,14e3],Tu=new Map,Eu=new Map,Du=new Map,Ou=new Map,ku=new Map,Au=new Map,ju=new Map,Mu=new Map,Nu=new Map,Pu=new Map,Fu=new Map,Iu=new Set,Lu=0,Ru=[],zu=()=>Lu<gu?(Lu+=1,Promise.resolve()):new Promise(e=>{Ru.push(e)}),Bu=()=>{let e=Ru.shift();if(e){e();return}Lu=Math.max(0,Lu-1)},Vu=async e=>{await zu();try{return await e()}finally{Bu()}},Hu=Symbol.for(`yuri.git.discoveryGated`),Uu=e=>(Object.defineProperty(e,Hu,{value:!0,configurable:!0}),e),Wu=e=>typeof e==`function`&&e[Hu]===!0,Z=e=>e.trim(),Gu=(e,t)=>t===`light`?`${Z(e)}::light`:Z(e),Ku=e=>Du.get(Z(e))??0,Q=e=>{let t=Z(e);Du.set(t,Ku(e)+1);for(let e of Array.from(Ou.keys()))(e===t||e.startsWith(`${t}::`))&&Ou.delete(e);for(let e of Array.from(Tu.keys()))(e===t||e.startsWith(`${t}::`))&&Tu.delete(e);for(let e of Array.from(Eu.keys()))(e===t||e.startsWith(`${t}::`))&&Eu.delete(e)},qu=e=>Fu.get(Z(e))??0,Ju=e=>{let t=Z(e);t&&(Fu.set(t,qu(e)+1),Nu.delete(t),Pu.delete(t))};function $(e,t,n){let r={...n};return t&&(r.directory=t),a().api(e,r)}var Yu=(e,t,n)=>{let r=Z(e);if(!r)return;let i=Date.now()+_u;ku.set(r,{value:t,expiresAt:i});let a=typeof n==`string`&&n?n:e;ju.set(r,{value:{root:a},expiresAt:i})};async function Xu(e){let t=Array.from(new Set(e.map(e=>Z(e)).filter(Boolean))),n=new Map;if(t.length===0)return n;let r=Date.now(),i=[];for(let e of t){let t=ku.get(e),a=ju.get(e);if(t&&t.expiresAt>r&&a&&a.expiresAt>r){n.set(e,{isGitRepository:t.value,primaryRoot:a.value.root});continue}i.push(e)}if(i.length===0)return n;let o=e=>{for(let t of e){let e=typeof t.directory==`string`?Z(t.directory):``;if(!e)continue;let r=!!t.isGitRepository,i=typeof t.primaryRoot==`string`&&t.primaryRoot?t.primaryRoot:null;Yu(e,r,i),n.set(e,{isGitRepository:r,primaryRoot:i})}},s=async e=>{await Promise.all(e.map(async e=>{try{let[t,r]=await Promise.all([Zu(e),$u(e).then(e=>e.root).catch(()=>e)]);Yu(e,t,t?r:null),n.set(e,{isGitRepository:t,primaryRoot:t?r:null})}catch{Yu(e,!1,null),n.set(e,{isGitRepository:!1,primaryRoot:null})}}))};try{await Vu(async()=>{let e=new URLSearchParams;for(let t of i)e.append(`directories`,t);let t=a().api(`${X}/discover`),n=e.toString(),r=n?t.includes(`?`)?`${t}&${n}`:`${t}?${n}`:t,s=await u(r);if(s.status===501||!s.ok)throw Error(`Batch git discover unavailable: ${s.status} ${s.statusText}`);let c=await s.json().catch(()=>null),l=Array.isArray(c)?c:[];if(l.length===0&&i.length>0)throw Error(`Batch git discover returned empty payload`);o(l)})}catch{}let c=i.filter(e=>!n.has(e));return c.length>0&&await s(c),n}async function Zu(e){let t=Z(e),n=Date.now(),r=ku.get(t);if(r&&r.expiresAt>n)return r.value;let i=Au.get(t);if(i)return i;let a=(async()=>{let n=await u($(`${X}/check`,e));if(!n.ok)throw Error(`Failed to check git repository: ${n.statusText}`);let r=!!(await n.json()).isGitRepository;return ku.set(t,{value:r,expiresAt:Date.now()+hu}),r})();Au.set(t,a);try{return await a}finally{Au.get(t)===a&&Au.delete(t)}}async function Qu(e,t){let n=t?.mode,r=Gu(e,n),i=Date.now(),a=Tu.get(r);if(a&&a.expiresAt>i)return a.value;let s=Eu.get(r);if(s)return s;let c=(async()=>{let t=Ku(e),i=o(),a=Ou.get(r),s=a&&a.transport===i&&a.cacheVersion===t?a:null,c=await u($(`${X}/status`,e,{...n?{mode:n}:{},...s?{since:s.revision}:{}}));if(!c.ok)throw Error(`Failed to get git status: ${c.statusText}`);let l=await c.json(),d;if(`unchanged`in l&&l.unchanged===!0){if(!s||l.revision!==s.revision)throw Error(`Failed to get git status: unexpected unchanged response`);d=s.value}else{let{revision:n,...a}=l;d=a,typeof n==`string`&&Ku(e)===t&&Ou.set(r,{revision:n,value:d,transport:i,cacheVersion:t})}return Ku(e)===t&&Tu.set(r,{value:d,expiresAt:Date.now()+mu}),d})();Eu.set(r,c);try{return await c}finally{Eu.get(r)===c&&Eu.delete(r)}}async function $u(e){let t=Z(e),n=Date.now(),r=ju.get(t);if(r&&r.expiresAt>n)return r.value;let i=Mu.get(t);if(i)return i;let a=Vu(async()=>{let n=await u($(`${X}/primary-root`,e));if(!n.ok)throw Error(`Failed to resolve git primary root: ${n.statusText}`);let r=await n.json().catch(()=>({})),i={root:typeof r.root==`string`&&r.root?r.root:e};return ju.set(t,{value:i,expiresAt:Date.now()+_u}),i});Mu.set(t,a);try{return await a}finally{Mu.get(t)===a&&Mu.delete(t)}}async function ed(e){let t=await u($(`${X}/toplevel`,e));if(!t.ok)throw Error(`Failed to resolve git toplevel: ${t.statusText}`);let n=await t.json().catch(()=>({}));return{root:typeof n.root==`string`&&n.root?n.root:e}}async function td(e,t){let{path:n,staged:r,contextLines:i}=t;if(!n)throw Error(`path is required to fetch git diff`);let a=await u($(`${X}/diff`,e,{path:n,staged:r?`true`:void 0,context:i}));if(!a.ok)throw Error(`Failed to get git diff: ${a.statusText}`);return a.json()}async function nd(e,t){let{path:n,staged:r}=t;if(!n)throw Error(`path is required to fetch git file diff`);let i=await u($(`${X}/file-diff`,e,{path:n,staged:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get git file diff: ${i.statusText}`);return i.json()}async function rd(e,t,n){if(!t)throw Error(`path is required to revert git changes`);let r=await u($(`${X}/revert`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to revert git changes`)}Q(e)}async function id(e,t){await ad(e,[t])}async function ad(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to stage git changes`);let r=await u($(`${X}/stage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to stage git changes`)}Q(e)}async function od(e,t){await sd(e,[t])}async function sd(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to unstage git changes`);let r=await u($(`${X}/unstage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to unstage git changes`)}Q(e)}async function cd(e,t,n){await dd(e,t,n,`stage`)}async function ld(e,t,n){await dd(e,t,n,`unstage`)}async function ud(e,t,n){await dd(e,t,n,`discard`)}async function dd(e,t,n,r){if(!t)throw Error(`path is required to apply a git hunk`);if(typeof n!=`string`||!n.trim())throw Error(`patch is required to apply a git hunk`);let i=await u($(`${X}/apply-hunk`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,patch:n,action:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to apply git hunk`)}Q(e)}async function fd(e){if(!e)return!1;let t=await u($(`${X}/worktree-type`,e));if(!t.ok)throw Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function pd(e,t){let n=await u($(`${X}/branches`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get branches: ${n.statusText}`);return n.json()}async function md(e,t){if(!t?.branch)throw Error(`branch is required to delete a branch`);let n=await u($(`${X}/branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete branch`)}return n.json()}async function hd(e,t){if(!t?.branch)throw Error(`branch is required to delete remote branch`);let n=await u($(`${X}/remote-branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete remote branch`)}return n.json()}async function gd(e,t){let n=t?.remote?.trim();if(!n)throw Error(`remote is required to remove a remote`);let r=await u($(`${X}/remotes`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({remote:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to remove remote`)}return r.json()}async function _d(e,t,n){if(!Array.isArray(t)||t.length===0)throw Error(`No files provided to generate commit message`);let r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);let i=await u($(`${X}/commit-message`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));console.error(`[git-generation][browser] http error`,{status:i.status,statusText:i.statusText,error:e});let t=typeof e?.traceId==`string`&&e.traceId?` (traceId: ${e.traceId})`:``;throw Error(`${e.error||`Failed to generate commit message`}${t}`)}let a=await i.json();if(!a?.message||typeof a.message!=`object`)throw Error(`Malformed commit generation response`);return{message:{subject:typeof a.message.subject==`string`&&a.message.subject.trim().length>0?a.message.subject.trim():``,highlights:Array.isArray(a.message.highlights)?a.message.highlights.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim()):[]}}}async function vd(e,t){let{base:n,head:r,context:i,zenModel:a,providerId:o,modelId:s}=t;if(!n||!r)throw Error(`base and head are required`);let c={base:n,head:r};i?.trim()&&(c.context=i.trim()),a&&(c.zenModel=a),o&&(c.providerId=o),s&&(c.modelId=s);let l=await u($(`${X}/pr-description`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c)});if(!l.ok){let e=await l.json().catch(()=>({error:l.statusText}));throw Error(e.error||`Failed to generate PR description`)}let d=await l.json().catch(()=>null),f=typeof d?.title==`string`?d.title:``,p=typeof d?.body==`string`?d.body:``;if(!f&&!p)throw Error(`Malformed PR description response`);return{title:f,body:p}}async function yd(e){let t=Z(e),n=Date.now(),r=Nu.get(t);if(r&&r.expiresAt>n)return r.value;let i=Pu.get(t);if(i)return i;let a=qu(e),o=Vu(async()=>{let n=await u($(`${X}/worktrees`,e));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to list worktrees`)}let r=await n.json();return a===qu(e)&&Nu.set(t,{value:r,expiresAt:Date.now()+_u}),r});Pu.set(t,o);try{return await o}finally{Pu.get(t)===o&&Pu.delete(t)}}Uu(yd);async function bd(e,t){let n=await u($(`${X}/worktrees/validate`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to validate worktree`)}return n.json()}async function xd(e){let t=await u($(`${X}/worktrees/bootstrap-status`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to get worktree bootstrap status`)}return t.json()}async function Sd(e,t){let n=await u($(`${X}/worktrees/preview`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to preview worktree`)}return n.json()}var Cd=e=>typeof e==`string`&&e.length>0,wd=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(!Cd(t.name)||!Cd(t.path))return null;let n={head:typeof t.head==`string`?t.head:``,name:t.name,branch:typeof t.branch==`string`?t.branch:``,path:t.path};return t.directoryCreated===!0&&(n.directoryCreated=!0),t.bootstrapStatus&&typeof t.bootstrapStatus==`object`&&(n.bootstrapStatus=t.bootstrapStatus),n},Td=(e,t,n)=>{if(e!==503||!t||typeof t!=`object`)return null;let r=t;if(r.code!==yu)return null;let i=wd(r.worktree);if(!i)return null;let a=r.repair;if(!a||typeof a!=`object`)return null;let o=a;if(o.method!==`POST`||o.path!==vu)return null;let s=o.body;if(!s||typeof s!=`object`)return null;let c=s;return c.projectDirectory!==n||c.directory!==i.path?null:i},Ed=(e,t,n,r)=>`${e}\u0000${t}\u0000${n}\u0000${r}`,Dd=e=>new Promise(t=>{setTimeout(t,e)}),Od=async e=>{if(e.status===409){let t=await e.json().catch(()=>null);return t?.code===bu||t?.code===xu}return e.status===503&&(await e.json().catch(()=>null))?.code===yu},kd=e=>e===400||e===401||e===403||e===501,Ad=(e,t)=>{let n=o(),r=s(),i=Ed(n,r,e,t);if(Iu.has(i))return;Iu.add(i);let a=()=>o()===n&&s()===r;(async()=>{let n=Date.now(),r=0;for(;Date.now()-n<Cu;){if(!a())return;let i=wu[Math.min(r,wu.length-1)]??0;if(i>0){let e=Cu-(Date.now()-n);if(e<=0||(await Dd(Math.min(i,e)),!a()))return}let o=new AbortController,s=setTimeout(()=>o.abort(),Su);try{let n=await u($(vu,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectDirectory:e,directory:t}),signal:o.signal});if(n.ok||kd(n.status))return;if(await Od(n)){r+=1;continue}return}catch{r+=1}finally{clearTimeout(s)}}})().catch(()=>{}).finally(()=>{Iu.delete(i)})};async function jd(e,t){let n=await u($(`${X}/worktrees`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})}),r=await n.json().catch(()=>null);if(n.ok){let t=wd(r);if(t)return Ju(e),t;if(r&&typeof r==`object`)return Ju(e),r;throw Error(`Failed to create worktree`)}let i=Td(n.status,r,e);if(i)return Ju(e),Ad(e,i.path),i;let a=r&&typeof r==`object`?r:{error:n.statusText};throw Error(a.error||`Failed to create worktree`)}async function Md(e,t){let n=await u($(`${X}/worktrees`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete worktree`)}let r=await n.json();return Ju(e),r}async function Nd(e,t,n={}){let r=await u($(`${X}/commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create commit`)}let i=await r.json();return Q(e),i}async function Pd(e,t={}){let n=await u($(`${X}/push`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to push`)}let r=await n.json();return Q(e),r}async function Fd(e,t={}){let n=await u($(`${X}/pull`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to pull`)}let r=await n.json();return Q(e),r}async function Id(e,t={}){let n=await u($(`${X}/fetch`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to fetch`)}let r=await n.json();return Q(e),r}async function Ld(e){let t=await u($(`${X}/stashes`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to list stashes`)}return t.json()}async function Rd(e,t){let n=await u($(`${X}/stashes/file-counts`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({refs:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to count stash files`)}return n.json()}async function zd(e,t={}){let n=await u($(`${X}/stash`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to stash changes`)}return n.json()}var Bd=async(e,t,n)=>{let r=await u($(`${X}/${t}`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to ${t}`)}return r.json()},Vd=(e,t)=>Bd(e,`stash/apply`,t),Hd=(e,t)=>Bd(e,`stash/pop`,t),Ud=(e,t)=>Bd(e,`stash/drop`,t);async function Wd(e,t){let n=await u($(`${X}/checkout`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({branch:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout branch`)}return n.json()}async function Gd(e,t,n){let r=await u($(`${X}/branches`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create branch`)}return r.json()}async function Kd(e,t,n){let r=await u($(`${X}/branches/rename`,e),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to rename branch`)}return r.json()}async function qd(e,t={}){let n=await u($(`${X}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?`true`:void 0}));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(`Failed to get git log: ${e.error||n.statusText}`)}return n.json()}async function Jd(e,t){let n=await u($(`${X}/commit-files`,e,{hash:t}));if(!n.ok)throw Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function Yd(e,t,n,r){let i=await u($(`${X}/commit-file-diff`,e,{hash:t,path:n,binary:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function Xd(){let e=await u($(`${X}/identities`,void 0));if(!e.ok)throw Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Zd(e){let t=await u($(`${X}/identities`,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to create git identity`)}return t.json()}async function Qd(e,t){let n=await u($(`${X}/identities/${e}`,void 0),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to update git identity`)}return n.json()}async function $d(e){let t=await u($(`${X}/identities/${e}`,void 0),{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to delete git identity`)}}async function ef(e){if(!e)return null;let t=await u($(`${X}/current-identity`,e));if(!t.ok)throw Error(`Failed to get current git identity: ${t.statusText}`);let n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function tf(e){if(!e)return!1;let t=await u($(`${X}/has-local-identity`,e));if(!t.ok)throw Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function nf(){let e=await u($(`${X}/global-identity`,void 0));if(!e.ok)throw Error(`Failed to get global git identity: ${e.statusText}`);let t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function rf(e,t){let n=await u($(`${X}/set-identity`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profileId:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to set git identity`)}return n.json()}async function af(){let e=await u($(`${X}/discover-credentials`,void 0));if(!e.ok)throw Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function of(e,t){let n=await u($(`${X}/remotes`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get remotes: ${n.statusText}`);return n.json()}async function sf(e,t){let n=await u($(`${X}/rebase`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to rebase`)}return n.json()}async function cf(e){let t=await u($(`${X}/rebase/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort rebase`)}return t.json()}async function lf(e,t){let n=await u($(`${X}/merge`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to merge`)}return n.json()}async function uf(e,t){let n=await u($(`${X}/checkout-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout commit`)}return n.json()}async function df(e,t){let n=await u($(`${X}/cherry-pick`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to cherry-pick`)}return n.json()}async function ff(e,t){let n=await u($(`${X}/revert-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to revert commit`)}return n.json()}async function pf(e,t,n,r){let i=await u($(`${X}/reset-to-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t,mode:n,force:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to reset`)}return i.json()}async function mf(e){let t=await u($(`${X}/merge/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort merge`)}return t.json()}async function hf(e){let t=await u($(`${X}/rebase/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue rebase`)}return t.json()}async function gf(e){let t=await u($(`${X}/merge/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue merge`)}return t.json()}async function _f(e,t){return await zd(e,{message:t?.message}),{success:!0}}async function vf(e){return await Hd(e,{ref:`stash@{0}`}),{success:!0}}async function yf(e){let t=await u($(`${X}/conflict-details`,e));if(!t.ok)throw Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function bf(e,t){let n=await u(`${X}/validate-directory`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function xf(e){let t=await u(`${X}/canonicalize-worktree-state`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e})});if(!t.ok)throw Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}export{pf as $,Sa as $n,Rn as $r,bs as $t,td as A,De as Ai,Co as An,Ni as Ar,q as At,Pd as B,Za as Bn,Ur as Br,hc as Bt,_d as C,Ve as Ci,qo as Cn,Wi as Cr,Ul as Ct,yf as D,je as Di,Bo as Dn,Bi as Dr,Jl as Dt,Jd as E,et as Ei,Xo as En,Fi as Er,Kl as Et,xd as F,ve as Fi,qa as Fn,zr as Fr,Fc as Ft,Ld as G,ma as Gn,wr as Gr,$s as Gt,Ju as H,eo as Hn,kr as Hr,wc as Ht,nf as I,ye as Ii,Ka as In,Hr as Ir,zc as It,Hd as J,La as Jn,mr as Jr,cc as Jt,yd as K,pa as Kn,Cr as Kr,ic as Kt,of as L,_e as Li,Ja as Ln,Kr as Lr,Nc as Lt,Xd as M,Se as Mi,Xa as Mn,gi as Mr,Bc as Mt,qd as N,v as Ni,$a as Nn,_i as Nr,Ic as Nt,ef as O,Te as Oi,xo as On,Ai as Or,ql as Ot,Qu as P,xe as Pi,Qa as Pn,Ir as Pr,Mc as Pt,Kd as Q,_a as Qn,Fn as Qr,nc as Qt,Id as R,be as Ri,to as Rn,Mr as Rr,jc as Rt,Ud as S,He as Si,Go as Sn,Hi as Sr,Gl as St,Yd as T,Ze as Ti,zo as Tn,Pi as Tr,Fl as Tt,Wu as U,Wa as Un,Sr as Ur,Sc as Ut,tf as V,Ga as Vn,Br as Vr,Cc as Vt,fd as W,Ya as Wn,xr as Wr,xc as Wt,sf as X,la as Xn,Nn as Xr,sc as Xt,Sd as Y,ua as Yn,Pn as Yr,ec as Yt,gd as Z,wa as Zn,Sn as Zr,rc as Zt,$d as _,pt as _i,Ko as _n,Ri as _r,bf as _t,Zu as a,bn as ai,Ls as an,Fa as ar,rf as at,af as b,$e as bi,Lo as bn,ji as br,fu as bt,df as c,En as ci,Fs as cn,na as cr,cd as ct,Rd as d,hn as di,V as dn,qi as dr,vf as dt,kn as ei,B as en,Na as er,$u as et,Gd as f,rn as fi,R as fn,Ki as fr,od as ft,md as g,zt as gi,ts as gn,zi as gr,bd as gt,jd as h,tn as hi,ns as hn,Mi as hr,Qd as ht,xf as i,xn as ii,ws as in,Oa as ir,ud as it,nd as j,Ee as ji,lo as jn,wi as jr,Pc as jt,pd as k,we as ki,bo as kn,N as kr,Pl as kt,gf as l,Cn as li,vs as ln,ta as lr,_f as lt,Zd as m,Ht as mi,gs as mn,Li as mr,ld as mt,cf as n,Ln as ni,Ns as nn,Ea as nr,ff as nt,Wd as o,yn as oi,js as on,Aa as or,id as ot,Nd as p,un as pi,_s as pn,Gi as pr,sd as pt,lf as q,Ta as qn,br as qr,oc as qt,Vd as r,In as ri,ks as rn,ba as rr,rd as rt,uf as s,Tn as si,Ms as sn,fa as sr,ad as st,mf as t,wn as ti,Ps as tn,ga as tr,ed as tt,hf as u,pn as ui,Is as un,Yi as ur,zd as ut,Md as v,_t as vi,Fo as vn,Ui as vr,Vu as vt,vd as w,Pe as wi,Jo as wn,Vi as wr,Hl as wt,Xu as x,Fe as xi,Wo as xn,Ii as xr,Wl as xt,hd as y,dt as yi,Io as yn,M as yr,pu as yt,Fd as z,no as zn,Nr as zr,Ac as zt};
|