@openchamber/web 2.6.1 → 2.6.2-canary.20261104.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/assets/{AboutDialog-D-IujH5P.js → AboutDialog-BLUUIZML.js} +1 -1
  2. package/dist/assets/{AboutLogo-Bghz4cno.js → AboutLogo-DiHHd_5t.js} +1 -1
  3. package/dist/assets/{ArchiveView-SQdNDg7X.js → ArchiveView-CwhPe3Y_.js} +1 -1
  4. package/dist/assets/{ChangeRequestDiffUnavailable-uZ8LXZIU.js → ChangeRequestDiffUnavailable-3YgjMJtr.js} +1 -1
  5. package/dist/assets/{ChangedPathLabel-BZHIGJ_0.js → ChangedPathLabel-B6Ig547I.js} +1 -1
  6. package/dist/assets/{CommandPalette-DjCVXkJM.js → CommandPalette-BChv7Yci.js} +1 -1
  7. package/dist/assets/{DiffView-CIlNcbDh.js → DiffView-pFcLbagS.js} +1 -1
  8. package/dist/assets/{FilesView-VMk-uSwN.js → FilesView-Bod-r3C6.js} +1 -1
  9. package/dist/assets/{GitView-BIg-1tUn.js → GitView-C4xsLAUw.js} +1 -1
  10. package/dist/assets/{GuestSurfacePane-BUmmCfBg.js → GuestSurfacePane-BTyjXjRj.js} +1 -1
  11. package/dist/assets/{HelpDialog-DlCrl3jK.js → HelpDialog-jRlVnJ_e.js} +1 -1
  12. package/dist/assets/{IntegrationsCatalogView-tZTRIaCg.js → IntegrationsCatalogView-CjJ3sWIM.js} +1 -1
  13. package/dist/assets/{JsonTreeView-D5DVoS6l.js → JsonTreeView-C7EScp5B.js} +1 -1
  14. package/dist/assets/{MarkdownDiffPreview-DoMO0ER1.js → MarkdownDiffPreview-cPqaSgaj.js} +1 -1
  15. package/dist/assets/{MarkdownRendererImpl-D1KCox5d.js → MarkdownRendererImpl-BcJ1sqsU.js} +3 -3
  16. package/dist/assets/{MemoryDebugPanel-X5DD6Cjd.js → MemoryDebugPanel-D0N9KDmI.js} +1 -1
  17. package/dist/assets/{NoteEditor-_UWC0M0H.js → NoteEditor-DxvVLbA7.js} +1 -1
  18. package/dist/assets/{OnboardingScreen-DBSPDpEj.js → OnboardingScreen-CMeQdpeM.js} +1 -1
  19. package/dist/assets/{OpenCodeStatusDialog-e8gdYqEY.js → OpenCodeStatusDialog-BAv0K4eb.js} +1 -1
  20. package/dist/assets/{OverviewView-Cf5_Harr.js → OverviewView-DyDBexdg.js} +1 -1
  21. package/dist/assets/{PatchDiff-DIWEk4tG.js → PatchDiff-CvabHkAC.js} +1 -1
  22. package/dist/assets/{PlanView-CV7_x4Hj.js → PlanView-DPpR2O_F.js} +1 -1
  23. package/dist/assets/{ProjectActionsDialog-B90g1jby.js → ProjectActionsDialog-B96GmKCc.js} +1 -1
  24. package/dist/assets/{ReplyUiBlock-D2m0ZgRL.js → ReplyUiBlock-BuiEYmcz.js} +1 -1
  25. package/dist/assets/{ReviewCards-D--SZYNA.js → ReviewCards-B219SHVL.js} +1 -1
  26. package/dist/assets/{RunOverview-CGv4KD-i.js → RunOverview-6n10wBYl.js} +1 -1
  27. package/dist/assets/{ScheduledTasksDialog-XjiWbQnf.js → ScheduledTasksDialog-CTkrlYii.js} +1 -1
  28. package/dist/assets/{SettingsView-Cz-oULIY.js → SettingsView-CenZZQat.js} +1 -1
  29. package/dist/assets/{SettingsWindow-BHUNfQBn.js → SettingsWindow-HEw9_GIT.js} +1 -1
  30. package/dist/assets/{SidebarSectionsManager-C1YsRka1.js → SidebarSectionsManager-CEl8jV_W.js} +1 -1
  31. package/dist/assets/{SourceBoardView-Cc3LeYUo.js → SourceBoardView-CJZ3s1XD.js} +1 -1
  32. package/dist/assets/{SpaceAccessDialog-f_DzFvFs.js → SpaceAccessDialog-Ngob2qn9.js} +1 -1
  33. package/dist/assets/{SpaceApplyDialog-CddUu8PS.js → SpaceApplyDialog-BxjDC_0D.js} +1 -1
  34. package/dist/assets/{SpaceRow-DnnOnMYM.js → SpaceRow-CckOV1g8.js} +1 -1
  35. package/dist/assets/{SpaceSetupOutput-BzQQtLdO.js → SpaceSetupOutput-lGqiVX-3.js} +1 -1
  36. package/dist/assets/{SpacesView-BZhH9crf.js → SpacesView-CP5k-k3v.js} +1 -1
  37. package/dist/assets/{SubmoduleDiffSummary-D6Wu1QuT.js → SubmoduleDiffSummary-Cdi9S4gX.js} +1 -1
  38. package/dist/assets/{ToolOutputDialog-BkmKHRdh.js → ToolOutputDialog-08mv6_M5.js} +1 -1
  39. package/dist/assets/{ToolPartDiffPreview-BurYz6UW.js → ToolPartDiffPreview-DRL47sfe.js} +1 -1
  40. package/dist/assets/{UiBlock-Bwx-T68z.js → UiBlock-C47vwIuG.js} +1 -1
  41. package/dist/assets/{UsageStatsView-WPrhgORf.js → UsageStatsView-DCpTVWz3.js} +1 -1
  42. package/dist/assets/{WalkthroughView-BMD1xSij.js → WalkthroughView-DeaBPhAn.js} +1 -1
  43. package/dist/assets/{WorktreesView-BFut-2yK.js → WorktreesView-B1YD_EPW.js} +1 -1
  44. package/dist/assets/{appThemeRegistry-Dk6CF03D.js → appThemeRegistry-hfPZ6say.js} +1 -1
  45. package/dist/assets/{ar-CuYBgoCL.js → ar-BrwaPZTB.js} +1 -1
  46. package/dist/assets/{codeHighlight-BYbxdxkk.js → codeHighlight-CXtTq4co.js} +1 -1
  47. package/dist/assets/{computeVirtualFileMetrics-COD-bZRh.js → computeVirtualFileMetrics-vVCRMHlo.js} +2 -2
  48. package/dist/assets/{contextFileOpenGuard-D_Eh6QOM.js → contextFileOpenGuard-BrUXbAMg.js} +1 -1
  49. package/dist/assets/{date-time-KFcfG8FZ.js → date-time-t6mCSZMr.js} +1 -1
  50. package/dist/assets/{de-Jo819vpe.js → de-DM_yQ7AG.js} +1 -1
  51. package/dist/assets/{es-CV0MRSsN.js → es-DMJlwy06.js} +1 -1
  52. package/dist/assets/{fileContentPoller-dM2aYiRt.js → fileContentPoller-B_D2WQHm.js} +1 -1
  53. package/dist/assets/{flexokiTheme-BL4fG_5M.js → flexokiTheme-DJhpTHWO.js} +1 -1
  54. package/dist/assets/{fr-CdmUjdKh.js → fr-BKEy-Z_2.js} +1 -1
  55. package/dist/assets/{he-B0Jv5rnl.js → he-BnqH_lWh.js} +1 -1
  56. package/dist/assets/{highlights-Cz6HBqYD.js → highlights-hXz5ezHu.js} +1 -1
  57. package/dist/assets/{index-BaQtYnl3.js → index-D6cItOu7.js} +1 -1
  58. package/dist/assets/{initializeSharedPreferences-CiaDh0AM.js → initializeSharedPreferences-BKG_0s4E.js} +1 -1
  59. package/dist/assets/{install-T6u73Zz0.js → install-csQoiut9.js} +1 -1
  60. package/dist/assets/{isDiffPlainText-B8tZAZQ4.js → isDiffPlainText-OMACajs1.js} +1 -1
  61. package/dist/assets/{isFilePlainText-CgNXAeJu.js → isFilePlainText-Z9Wi1AQY.js} +1 -1
  62. package/dist/assets/{ja-BGc1V8I_.js → ja-lqTz_4gG.js} +1 -1
  63. package/dist/assets/{katex.min-BM3LOlr3.js → katex.min-B7gF3rmE.js} +4 -4
  64. package/dist/assets/{ko-CadSaTs-.js → ko-DXd5Gg_L.js} +1 -1
  65. package/dist/assets/{main-b_PAxB6R.js → main-D0VV0_-r.js} +4 -4
  66. package/dist/assets/{main-BX74Pq6m.js → main-DC2rz5Pv.js} +2 -2
  67. package/dist/assets/{miniChat-CzVxcGLZ.js → miniChat-C6te7Cha.js} +2 -2
  68. package/dist/assets/{mobile-DfBoGVRE.js → mobile-h7Y89upC.js} +2 -2
  69. package/dist/assets/{nl-Ds8N-7nU.js → nl-X6CZmwET.js} +1 -1
  70. package/dist/assets/{pageTitle-DcFkBvgW.js → pageTitle-CAd4Kwsy.js} +1 -1
  71. package/dist/assets/{parseDiffFromFile-DEaa1di6.js → parseDiffFromFile-BuLpViZg.js} +1 -1
  72. package/dist/assets/{pierreDiffTint-CS5FWjsh.js → pierreDiffTint-Bda-Leur.js} +1 -1
  73. package/dist/assets/{pl-BAAqSvOD.js → pl-CmAyO7EH.js} +1 -1
  74. package/dist/assets/{pt-BR-CxTCCQt5.js → pt-BR-QNheuCzR.js} +1 -1
  75. package/dist/assets/{relocateRestoredSession-C8x_kYRX.js → relocateRestoredSession-hOOmUC2p.js} +2 -2
  76. package/dist/assets/{renderElectronMiniChatApp-Bwgx8afa.js → renderElectronMiniChatApp-Dg-2lMCR.js} +2 -2
  77. package/dist/assets/{renderMarkdownForExport-DzVoMkQY.js → renderMarkdownForExport-Dy3HSiOK.js} +1 -1
  78. package/dist/assets/{renderMobileApp-0o5iW3gX.js → renderMobileApp-BhpguGxm.js} +3 -3
  79. package/dist/assets/{resolveLanguages-O4KbMEYv.js → resolveLanguages-BF-kRWyQ.js} +1 -1
  80. package/dist/assets/{runtimeEndpointReset-IJE1o-nk.js → runtimeEndpointReset-DUwSilpj.js} +8 -8
  81. package/dist/assets/{scheduledTasksApi-Bt4F6fco.js → scheduledTasksApi-jkEn2fUL.js} +1 -1
  82. package/dist/assets/{shiki-DfHQjW4b.js → shiki-D0FPzA_f.js} +1 -1
  83. package/dist/assets/{space-apply-BWMKP1l4.js → space-apply-De-hlG-f.js} +1 -1
  84. package/dist/assets/{space-close-B5_k2AhX.js → space-close-BQzjlZ-w.js} +1 -1
  85. package/dist/assets/{spaceNetwork-Bww_OVgL.js → spaceNetwork-CVVlgvhL.js} +1 -1
  86. package/dist/assets/{stream-tokenizer-B87hBGmH.js → stream-tokenizer-w3w2i3zK.js} +1 -1
  87. package/dist/assets/{textMateThemeFromAppTheme-BA68BaAw.js → textMateThemeFromAppTheme-B38k_gpV.js} +1 -1
  88. package/dist/assets/{tr-vj7L-0nl.js → tr-4WQrywE1.js} +1 -1
  89. package/dist/assets/{uk-DYlYVGgJ.js → uk-Dos-a0OZ.js} +1 -1
  90. package/dist/assets/{useAppFontEffects-UKWR--vP.js → useAppFontEffects-6HvTeJY2.js} +15 -15
  91. package/dist/assets/{useBranchPullRequestRequest-DJNOWuS3.js → useBranchPullRequestRequest-B8yYsqiw.js} +1 -1
  92. package/dist/assets/{useCallableModelProviders-BVbgbn_M.js → useCallableModelProviders-BLdr2CgV.js} +1 -1
  93. package/dist/assets/{useDiffFindSurface-zju_sQ6_.js → useDiffFindSurface-BVO1E6le.js} +1 -1
  94. package/dist/assets/{useGitCleanLine-DA-nRAvz.js → useGitCleanLine-DEZFq7uh.js} +1 -1
  95. package/dist/assets/{useInlineCommentController-DgJBL64V.js → useInlineCommentController-BiX7K5jy.js} +1 -1
  96. package/dist/assets/{useMarkdownLocalAssets-DFwvtvsy.js → useMarkdownLocalAssets-DM7b941V.js} +1 -1
  97. package/dist/assets/{useRootScrollLock-ywfMiLmM.js → useRootScrollLock-BrNPOsn7.js} +2 -2
  98. package/dist/assets/{useWalkthroughReview-DeioHUwn.js → useWalkthroughReview-kBvgTX6M.js} +1 -1
  99. package/dist/assets/{useWholeFileComment-3Adypnae.js → useWholeFileComment-DrynMs0_.js} +1 -1
  100. package/dist/assets/{useWorktreeArchiveActions-D57vyZ1C.js → useWorktreeArchiveActions-CewTlnGF.js} +1 -1
  101. package/dist/assets/{vendor-codemirror-language-data-CVww3XgZ.js → vendor-codemirror-language-data-BJfFTbvV.js} +2 -2
  102. package/dist/assets/{zh-CN-CNdkQtjY.js → zh-CN-C4Ip1vNN.js} +1 -1
  103. package/dist/assets/{zh-TW-njZbI3nO.js → zh-TW-BmwR7rb1.js} +1 -1
  104. package/dist/index.html +2 -2
  105. package/dist/mini-chat.html +2 -2
  106. package/dist/mobile.html +2 -2
  107. package/package.json +3 -3
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CRnROUpT.js","assets/vendor-react--VO_rL_p.js","assets/vendor-scheduler-7OC5HNn7.js","assets/zh-CN-CNdkQtjY.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-zustand-C9tWdk0j.js","assets/vendor-zod-Csf1sqWl.js","assets/vendor-opencode-client-CqFY51gT.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/vendor-streamdown-BbSYZ3NF.js","assets/vendor-markdown-BTUqNk6W.js","assets/vendor-mdast-util-from-markdown-CZHjOE75.js","assets/vendor-micromark-util-decode-numeric-character-reference-CNs1qBpV.js","assets/vendor-micromark-util-decode-string-fHsnqYdj.js","assets/vendor-decode-named-character-reference-C3-224fz.js","assets/vendor-micromark-util-normalize-identifier-C9ANKk3v.js","assets/vendor-micromark-AWM-NZXP.js","assets/vendor-micromark-util-combine-extensions-d8XJZrgA.js","assets/vendor-micromark-util-chunked-DrRIdSP-.js","assets/vendor-micromark-factory-space-PzSHLgmq.js","assets/vendor-micromark-util-character-CW3Cu1MS.js","assets/vendor-micromark-core-commonmark-kzTLNXAm.js","assets/vendor-micromark-util-classify-character-tcLuZZwM.js","assets/vendor-micromark-util-resolve-all-PQCKh0dx.js","assets/vendor-micromark-util-subtokenize-BF1Jf29a.js","assets/vendor-micromark-factory-destination-Sj0xfi0V.js","assets/vendor-micromark-factory-label-amyP0HdC.js","assets/vendor-micromark-factory-title-khnLkZK6.js","assets/vendor-micromark-factory-whitespace-eIB00uTl.js","assets/vendor-micromark-util-html-tag-name-DbKNfynz.js","assets/vendor-unist-util-stringify-position-Ch_qCilz.js","assets/vendor-mdast-util-to-string-C_aolqmU.js","assets/vendor-unist-util-visit-DhPeCsfG.js","assets/vendor-unist-util-visit-parents-DlviEg7Z.js","assets/vendor-unist-util-is-BPZGFiMU.js","assets/vendor-hast-util-raw-DvvLJg15.js","assets/vendor-ungap-structured-clone--gfxRhYI.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-parse5-DwmzEj2o.js","assets/vendor-entities-wUUgTZDW.js","assets/vendor-web-namespaces-bsVAaBS1.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-unist-util-position-60F3QETU.js","assets/vendor-hast-util-from-parse5-Ba3T6RJI.js","assets/vendor-devlop-0Dp3JUBc.js","assets/vendor-property-information-Boo8Xpef.js","assets/vendor-hastscript-BrPNioaz.js","assets/vendor-comma-separated-tokens-CRUGqg4f.js","assets/vendor-space-separated-tokens-D7QSIrTI.js","assets/vendor-hast-util-parse-selector-TXfch5wI.js","assets/vendor-vfile-location-LfEFwJ2h.js","assets/vendor-hast-util-to-parse5-BoysVIPW.js","assets/vendor-hast-util-sanitize-2aGO5ay8.js","assets/vendor-micromark-extension-gfm-CsfPlnlB.js","assets/vendor-micromark-extension-gfm-autolink-literal-BYug7onl.js","assets/vendor-micromark-extension-gfm-footnote-OFl1FCH2.js","assets/vendor-micromark-extension-gfm-strikethrough-CyFiuwBf.js","assets/vendor-micromark-extension-gfm-table-dgw4LfUw.js","assets/vendor-micromark-extension-gfm-task-list-item-Dnadzr9U.js","assets/vendor-mdast-util-gfm-CroMDYLM.js","assets/vendor-mdast-util-gfm-autolink-literal-CTruMtvI.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-mdast-util-find-and-replace-DB9iC-bx.js","assets/vendor-escape-string-regexp-BaJN9MlJ.js","assets/vendor-mdast-util-gfm-footnote-C-csI7OF.js","assets/vendor-mdast-util-gfm-strikethrough-BcskTdio.js","assets/vendor-mdast-util-gfm-table-DhPwQIyj.js","assets/vendor-markdown-table-DvhhVmnL.js","assets/vendor-mdast-util-to-markdown-Cl3qaiyc.js","assets/vendor-longest-streak-CtXnX3Xp.js","assets/vendor-mdast-util-phrasing-4oVbNLC3.js","assets/vendor-mdast-util-gfm-task-list-item-DMU5mK_M.js","assets/vendor-mdast-util-to-hast-CWnLaQSO.js","assets/vendor-micromark-util-sanitize-uri-BbwQ7CLk.js","assets/vendor-trim-lines-D8znQY54.js","assets/vendor-micromark-extension-cjk-friendly-BzZDGrF5.js","assets/vendor-micromark-extension-cjk-friendly-util-D5lVNoxW.js","assets/vendor-get-east-asian-width-CPhS2cOv.js","assets/vendor-micromark-util-symbol-JJPacVTp.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-BZ3pe_qd.js","assets/vendor-micromark-extension-cjk-friendly-gfm-strikethrough-CqW-Ep4M.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-BdPDQFO7.js","assets/vendor-hast-util-from-html-isomorphic-B0Kn01s9.js","assets/vendor-hast-util-from-dom-DeNf9aYW.js","assets/vendor-katex-DBqql0K7.js","assets/vendor-hast-util-to-text-0GXLnBvt.js","assets/vendor-hast-util-is-element-CuOmiqQi.js","assets/vendor-unist-util-find-after-CMaZmLxc.js","assets/vendor-micromark-extension-math-BRFoDziv.js","assets/vendor-mdast-util-math-wB-IJCL0.js","assets/vendor-remend-r8cP_t-e.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-marked-DN3zOnEe.js","assets/vendor-hast-util-to-jsx-runtime-Bq6JeJCx.js","assets/vendor-style-to-js-CI2G4dgu.js","assets/vendor-style-to-object-BAv4SQXc.js","assets/vendor-inline-style-parser-BlqBsVO4.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-estree-util-is-identifier-name-BgBfM8ME.js","assets/vendor-vfile-message-DqhD22jI.js","assets/vendor-unified-1CQKw2_w.js","assets/vendor-bail-FqpXQuLt.js","assets/vendor-extend-B94qxKr5.js","assets/vendor-is-plain-obj-C1gvLhAf.js","assets/vendor-trough-B_b8ryxu.js","assets/vendor-vfile-BCWrK60u.js","assets/vendor-html-url-attributes-D46m5wfe.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/fr-CdmUjdKh.js","assets/nl-Ds8N-7nU.js","assets/zh-TW-njZbI3nO.js","assets/es-CV0MRSsN.js","assets/pt-BR-CxTCCQt5.js","assets/uk-DYlYVGgJ.js","assets/ko-CadSaTs-.js","assets/pl-BAAqSvOD.js","assets/de-Jo819vpe.js","assets/ja-BGc1V8I_.js","assets/tr-vj7L-0nl.js","assets/ar-CuYBgoCL.js","assets/he-B0Jv5rnl.js","assets/vendor-capacitor-app-BrDJj9I_.js"])))=>i.map(i=>d[i]);
2
- import{_ as Ee}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as yt,d as oa,p as Pi,a as ek}from"./vendor-zustand-C9tWdk0j.js";import{o as p,s as g,n as v,l as y,e as z,d as x,h as we,_ as R,u as J,a as bt,f as Y,j as zo,i as tk,k as xo,p as oi,q as Fu,v as Mi}from"./vendor-zod-Csf1sqWl.js";import{e as Nu,C as ng}from"./vendor-opencode-client-CqFY51gT.js";import{f as Ft,R as Kn,r as sk}from"./vendor-react--VO_rL_p.js";import{F as Mu}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as nk}from"./vendor-streamdown-BbSYZ3NF.js";import{u as ak}from"./vendor-unified-1CQKw2_w.js";import{c as ik}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as ok}from"./vendor-capacitor-core-B4EWRrHz.js";const Ua=1,rk=p({type:y("relay-retire"),code:v().int(),reason:g().catch("")}),ck=e=>{try{const t=rk.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},lk="openchamber-relay-v1",Eu=1,Lu=12,Wa=1+Lu,ri=64*1024,ci=5,To=128,qu=0,Vu=1,Zn=4,dk=1+Zn,Rc=ri-ci-dk,gk="x-openchamber-tunnel-accept-encoding",pk="x-openchamber-tunnel-content-encoding",se={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},uk=new Set(Object.values(se)),mk=e=>uk.has(e),Bs={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},rs=globalThis.crypto.subtle,Uu={name:"ECDH",namedCurve:"P-256"},Wu=16,zr=32,hk=16,jc=4,Hu=8;class Os extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const fk=()=>rs.generateKey(Uu,!0,["deriveBits"]),bk=async e=>{const t=await rs.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},kk=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Os("invalid ECDH public key JWK");try{return await rs.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Uu,!0,[])}catch{throw new Os("invalid ECDH public key JWK")}},yk=()=>{const e=new Uint8Array(Wu);return globalThis.crypto.getRandomValues(e),e},wk=async(e,t,s)=>{if(s.length!==Wu)throw new Os("invalid handshake nonce length");const n=await rs.deriveBits({name:"ECDH",public:t},e,256),a=await rs.importKey("raw",n,"HKDF",!1,["deriveBits"]),i=new Uint8Array(await rs.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(lk)},a,zr*2*8)),o=(r,c)=>rs.importKey("raw",r,{name:"AES-GCM"},!1,c);return{clientToHost:await o(i.slice(0,zr),["encrypt","decrypt"]),hostToClient:await o(i.slice(zr),["encrypt","decrypt"])}},vk=(e,t,s)=>{for(let n=Hu-1;n>=0;n-=1)e[t+n]=Number(s&0xffn),s>>=8n},Ck=(e,t)=>{let s=0n;for(let n=0;n<Hu;n+=1)s=s<<8n|BigInt(e[t+n]);return s},Sk=e=>{const t=new Uint8Array(jc);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(n){if(n.length>ri)throw new Os("plaintext frame exceeds maximum size");s+=1n;const a=new Uint8Array(Lu);a.set(t,0),vk(a,jc,s);const i=new Uint8Array(await rs.encrypt({name:"AES-GCM",iv:a},e,n)),o=new Uint8Array(Wa+i.length);return o[0]=Eu,o.set(a,1),o.set(i,Wa),o}}},Pk=e=>{let t=0n;return{async decrypt(s){if(s.length<Wa+hk)throw new Os("encrypted frame too short");if(s[0]!==Eu)throw new Os("unsupported encrypted frame version");const n=s.slice(1,Wa),a=Ck(n,jc);if(a<=t)throw new Os("frame counter regression");let i;try{i=await rs.decrypt({name:"AES-GCM",iv:n},e,s.slice(Wa))}catch{throw new Os("frame decryption failed")}return t=a,new Uint8Array(i)}}},Ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ak=e=>{let t="";for(let s=0;s<e.length;s+=3){const n=e[s],a=s+1<e.length?e[s+1]:void 0,i=s+2<e.length?e[s+2]:void 0;t+=Ei[n>>2],t+=Ei[(n&3)<<4|(a??0)>>4],a!==void 0&&(t+=Ei[(a&15)<<2|(i??0)>>6]),i!==void 0&&(t+=Ei[i&63])}return t},ag=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const s=t;if(s.v!==Ua)return null;const n=s.batch===!0,a=s.flowControl===!0;return s.t==="ready"?{t:"ready",v:Ua,batch:n,flowControl:a}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:Ua,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:n,flowControl:a}:null},zk=e=>({type:"fail",closeCode:Bs.ChannelFailure,reason:e}),xk=async(e,t={})=>{const s=t.batch!==!1,n=await kk(e),a=await fk(),i=yk(),o={t:"hello",v:Ua,clientPubJwk:await bk(a.publicKey),nonce:Ak(i)};s&&(o.batch=!0),t.flowControl!==!1&&(o.flowControl=!0);let r=!1;return{helloText:JSON.stringify(o),get established(){return r},async handleText(c){if(r)return ag(c)?.t==="ready"?{type:"ignore"}:zk("plaintext frame on established channel");const l=ag(c);if(l?.t!=="ready")return{type:"ignore"};const d=await wk(a.privateKey,n,i);return r=!0,{type:"established",batch:s&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:Sk(d.clientToHost),decryptor:Pk(d.hostToClient)}}}}},Gu=4294967295,Tk=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class Le extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const At=(e,t,s,n=!1)=>{if(!Number.isInteger(t)||t<0||t>Gu)throw new Le("invalid stream id");if(s.length>Rc)throw new Le("tunnel payload exceeds maximum size");const a=new Uint8Array(ci+s.length);return a[0]=n?e|To:e,a[1]=t>>>24&255,a[2]=t>>>16&255,a[3]=t>>>8&255,a[4]=t&255,a.set(s,ci),a},Ik=e=>{if(e.length<ci)throw new Le("tunnel frame too short");const t=e[0],s=(t&To)!==0,n=t&~To;if(!mk(n))throw new Le(`unknown tunnel frame type ${n}`);const a=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:n,streamId:a,payload:e.slice(ci),hasMoreFragments:s}},Rk=new TextEncoder,jk=new TextDecoder,Li=e=>Rk.encode(JSON.stringify(e)),qi=(e,t)=>{let s;try{s=JSON.parse(jk.decode(e))}catch{throw new Le("malformed JSON tunnel payload")}if(!t(s))throw new Le("unexpected JSON tunnel payload shape");return s},_u=(e,t=Rc)=>{if(t<=0||t>Rc)throw new Le("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},ig=(e,t,s)=>{const n=_u(s);return n.map((a,i)=>At(e,t,a,i<n.length-1))},Ok=(e=16*1024*1024)=>{const t=new Map;return{push(s){const n=`${s.streamId}:${s.frameType}`,a=t.get(n);if(!s.hasMoreFragments&&!a)return s.payload;const i=a?.chunks??[],o=(a?.totalBytes??0)+s.payload.length;if(o>e)throw t.delete(n),new Le("fragmented message exceeds maximum size");if(i.push(s.payload),s.hasMoreFragments)return t.set(n,{chunks:i,totalBytes:o}),null;t.delete(n);const r=new Uint8Array(o);let c=0;for(const l of i)r.set(l,c),c+=l.length;return r},dropStream(s){for(const n of t.keys())n.startsWith(`${s}:`)&&t.delete(n)}}},Dk=e=>{if(e.length===0)throw new Le("cannot encode an empty frame batch");if(e.length===1){const a=e[0],i=new Uint8Array(1+a.length);if(i[0]=qu,i.set(a,1),i.length>ri)throw new Le("frame batch exceeds maximum plaintext size");return i}let t=1;for(const a of e)t+=Zn+a.length;if(t>ri)throw new Le("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=Vu;let n=1;for(const a of e)s[n]=a.length>>>24&255,s[n+1]=a.length>>>16&255,s[n+2]=a.length>>>8&255,s[n+3]=a.length&255,n+=Zn,s.set(a,n),n+=a.length;return s},Bk=e=>{if(e.length<1)throw new Le("empty batch plaintext");const t=e[0];if(t===qu)return[e.slice(1)];if(t!==Vu)throw new Le(`unknown batch container tag ${t}`);const s=[];let n=1;for(;n<e.length;){if(n+Zn>e.length)throw new Le("truncated batch frame length");const a=(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0;if(n+=Zn,n+a>e.length)throw new Le("truncated batch frame body");s.push(e.slice(n,n+a)),n+=a}if(s.length===0)throw new Le("empty frame batch");return s},Fk=new Set([se.HttpBody,se.WsText,se.WsBinary]),Ku=150,Nk=24*1024,Mk=32,Ek=e=>{const t=e.windowMs??Ku,s=e.maxBatchBytes??Nk,n=e.maxBatchFrames??Mk,a=e.now??(()=>Date.now()),i=e.setTimer??((k,w)=>setTimeout(k,w)),o=e.clearTimer??(k=>clearTimeout(k));let r=[],c=0,l=null,d=0,u=!1;const m=()=>{l!==null&&(o(l),l=null)},f=()=>{if(m(),r.length===0)return;const k=r;r=[],c=0,d=a(),e.sendBatch(Dk(k))};return{enqueue:k=>{if(u)return;const w=k[0]&~To;if(!Fk.has(w)){r.push(k),f();return}const T=a();if(r.length===0&&T-d>=t){r.push(k),f();return}const S=Zn+k.length;if(r.length>0&&1+c+S>ri&&f(),r.push(k),c+=S,c>=s||r.length>=n){f();return}l===null&&(l=i(f,t))},flush:f,dispose(){u=!0,m(),r=[],c=0}}},Lk=()=>{let e=1;return{next(){if(e>Gu)throw new Le("stream id space exhausted");const t=e;return e+=2,t}}},$o=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qk=e=>$o(e)&&Object.values(e).every(t=>typeof t=="string"),Vk=e=>$o(e)&&typeof e.status=="number"&&qk(e.headers),og=e=>$o(e)&&typeof e.reason=="string",Uk=e=>$o(e)&&typeof e.code=="number"&&typeof e.reason=="string",Zu=/^[a-z][a-z\d+.-]*:\/\//i,Hl="http://tunnel.invalid",Wk=e=>{try{const t=Zu.test(e)?new URL(e):new URL(e,Hl);return`${t.pathname}${t.search}`}catch{return e}},Vi=e=>({async*[Symbol.asyncIterator](){yield e}}),Hk=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:n}=await t.read();if(s)return;n&&(yield n)}}finally{t.releaseLock()}}}),Gk=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},_k=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Hk(e)};if(typeof e=="string")return{body:Vi(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Vi(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Vi(Gk(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,n=new Uint8Array(await t.arrayBuffer());return{body:Vi(n),contentType:s}},Kk=async(e,t)=>{let s;const n=new Headers;let a="GET",i=null,o;e instanceof Request?(s=e.url,a=e.method,e.headers.forEach((u,m)=>n.set(m,u)),o=e.signal,i=e.body):s=e.toString(),t&&(t.method&&(a=t.method),t.headers&&new Headers(t.headers).forEach((u,m)=>n.set(m,u)),t.body!==void 0&&(i=t.body),t.signal&&(o=t.signal));const r=Zu.test(s)?new URL(s):new URL(s,Hl),{body:c,contentType:l}=await _k(i);l&&!n.has("content-type")&&n.set("content-type",l);const d={};return n.forEach((u,m)=>{d[m]=u}),{method:a.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:d,body:c,signal:o}},Ju="__openchamberAmbiguousTransport",$u=new WeakSet,Zk=e=>($u.add(e),e),Jk=e=>$u.has(e),Oc=e=>(Object.defineProperty(e,Ju,{value:!0,enumerable:!1,configurable:!0}),e),$k=e=>!e||typeof e!="object"?!1:e[Ju]===!0,Qk=["local","remote",null],Yk=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Qu(e){if(!e||typeof e!="object")return{valid:!1};const t=e,s=t.localAvailable===!1?{localAvailable:!1}:{},n=t.target,a=t.status;if(n!==null&&(typeof n!="string"||!Qk.includes(n)))return{valid:!1};if(typeof a!="string"||!Yk.includes(a))return{valid:!1};if(n==="remote"||n==="local"){if(a==="ok"&&n==="local"){const i={target:"local",status:"ok",...s},o=g().min(1).safeParse(t.sshStartupFallbackHostId);return o.success&&(i.sshStartupFallbackHostId=o.data),{valid:!0,outcome:i}}if(a==="ok"&&n==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(a==="unreachable")return n==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(a==="incompatible"||a==="wrong-service")return n!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:a,hostId:t.hostId,url:t.url,...s}};if(a==="missing")return n!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(n===null){if(a==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...s}};if(a==="missing")return{valid:!1}}return{valid:!1}}function WN(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...s};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...s}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...s};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...s};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...s};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...s};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...s};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...s}}return null}function HN(e){return!e.isDesktopShell||e.bootOutcomeKnown}function GN(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function Yu(){if(Xk()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=Qu(t);return s.valid?s.outcome:null}function Xk(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Qu(e).valid?"valid":"malformed"}const Io=/^[a-z][a-z\d+.-]*:\/\//i,ey=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Ro=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),ty=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Ro(e)},sy=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Ro(e)},ny=()=>Object.keys(la()).length>0,ay=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Dc=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,a]of s)a!=null&&e.searchParams.set(n,String(a))},iy=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Dc({searchParams:s},t);const n=s.toString();return n?e.includes("?")?`${e}&${n}`:`${e}?${n}`:e},rg=(e,t,s)=>{if(Io.test(t)){const o=new URL(t);return Dc(o,s),o.toString()}const n=ey(t);if(!e)return iy(n,s);const a=new URL(e),i=new URL(`${a.origin}${a.pathname.replace(/\/+$/,"")}${n}`);return Dc(i,s),i.toString()},Ui=(e,t=Hy())=>{if(!t)return e;const s=Io.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),Io.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},Xu=(e,t)=>{const s=Io.test(e)?new URL(e):new URL(e,ay(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},cg=(e,t,s)=>{if(!ny())return null;const n=sy();if(!n)return null;try{const a=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${n}/`);a.searchParams.set("url",t);const i=Gy(n);return i&&a.searchParams.set("oc_url_token",i),e==="ws"?(a.protocol=a.protocol==="https:"?"wss:":"ws:",Xu(a.toString(),s)):a.toString()}catch{return null}},Gl=(e={})=>{const t=Ro(e.apiBaseUrl),s=Ro(e.realtimeBaseUrl),n=()=>t||ty(),a=()=>s||n(),i=(r,c)=>rg(n(),r,c),o=(r,c)=>rg(a(),r,c);return{api:i,authenticatedAsset:(r,c)=>Ui(i(r,c)),assetWithUrlToken:(r,c,l)=>Ui(i(r,l),c),auth:i,health:r=>i("/health",r),rawFile:(r,c)=>i("/api/fs/raw",{path:r,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(r,c)=>{const l=Ui(o(r,c));return cg("sse",l,e)||l},websocket:(r,c)=>{const l=Xu(Ui(o(r,c)),e);return cg("ws",l,e)||l}}};let jo=Gl();const ls=()=>jo,oy=e=>{jo=e},em=e=>(jo=Gl(e),jo),Bc="openchamber:runtime-endpoint-changed",Fc="openchamber:runtime-endpoint-will-change";let Jn="",li="",Nc=0,Mc=null;const xr=(e,t,s)=>{try{e[t]=s}catch{}},_l=e=>{try{const t=new URL(e);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,"")||"/",`url:${t.toString().replace(/\/+$/,"")}`}catch{return`url:${e.trim().replace(/\/+$/,"")||"default"}`}},ry="mobile-disconnected",cy="url:default",Ec=e=>e===""||e===cy||e===ry,tm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},sm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},nm=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ps=()=>Jn||tm(),ly=()=>{if(Mc!==null)return Mc;const e=ps();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let Tr="",lg=null,dg,gg;const pg=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(li)return li;const e=pg("__OPENCHAMBER_API_BASE_URL__"),t=pg("__OPENCHAMBER_LOCAL_ORIGIN__");if(lg===Jn&&dg===e&&gg===t)return Tr;const s=ps();return Tr=nm(s,sm())?"local":_l(s),lg=Jn,dg=e,gg=t,Tr},am=()=>{const e=Nc,t=D();return()=>e===Nc&&t===D()},dy=(e={})=>{if(Jn||li)return;const t=e.apiBaseUrl?.trim()||tm(),s=globalThis.window?.location?.origin??"",n=/^https?:\/\//.test(s)?s:"";if(!t&&!n)return;const a=sm(),i=a&&(!t||nm(t,a));Jn=t,li=e.runtimeKey?.trim()||(i?"local":_l(t||n))},Lc=e=>{const t=e.apiBaseUrl.trim(),s=ps(),n=D(),a=e.runtimeKey?.trim()||_l(t),i=e.sshForwarded??(t===s&&a===n&&ly()),o={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:a,previousRuntimeKey:n};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fc,{detail:o})),Jn=t,li=a,a!==n&&(Nc+=1),Mc=i,typeof window<"u"){const r=window;xr(r,"__OPENCHAMBER_API_BASE_URL__",t),xr(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),xr(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}em({apiBaseUrl:t,realtimeBaseUrl:t}),wm(e.requestHeaders||null),ym(e.clientToken||null),e.relay?My(e.relay):Ey(),tr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bc,{detail:o}))},Qo=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Fc,t),()=>window.removeEventListener(Fc,t)},Yo=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Bc,t),()=>window.removeEventListener(Bc,t)};let qc=null;const _N=e=>{qc=e},ra=()=>qc||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Kl=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,di=()=>{const e=Kl();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():!1},im=(e=Kl())=>!!e,gy=e=>e==="stable"||e==="canary",py=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,KN=e=>{const t=py.exec(e??"");if(!t)return null;const[,s,n,a,i,o]=t;return{release:s,builtOn:new Date(Date.UTC(Number(n),Number(a)-1,Number(i))),build:o?Number(o):null}},uy=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),ZN=(e,t,s)=>{const n=uy(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${n} #${e.build}`:n},om=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,us=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,un=()=>om()?.runtime==="electron",rm=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},my="right",JN=()=>{if(!un())return!1;const e=rm();return e==="linux"?om()?.nativeFrame!==!0:e==="win32"},$N=e=>e==="left"?"left":my,QN=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Qe=()=>typeof us()?.invoke=="function",ct=()=>un()&&Qe(),hy=()=>{const e=us()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>g().parse(await t()),writeText:async n=>{y(!0).parse(await s(n))}}}},fy=()=>{if(us()?.pickThemeFile)return{async pick(){const e=us()?.pickThemeFile;return e?{status:"picked",file:p({name:g(),size:v().nonnegative(),text:g()}).nullable().parse(await e())}:{status:"unsupported"}}}},ee=async(e,t)=>{const s=us();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},YN=e=>{rm()!=="darwin"||!ct()||ee("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},XN=()=>({apiBaseUrl:ps(),clientToken:Yl(),runtimeKey:D()}),eM=async()=>{if(!Ye()||!Ce())return!1;const e=ps();try{const t=z().safeParse(await ee("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===ps()}catch{return!1}},tM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},sM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},cm=e=>gy(e?.channel)?e.channel:null,nM=async()=>{if(!ct()||!Ce())return null;try{return cm(await ee("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},aM=async e=>{if(!ct()||!Ce())return null;try{return cm(await ee("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},iM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},oM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},rM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_mini_chat_global_shortcut");return!e||typeof e.supported!="boolean"||e.combo!==null&&typeof e.combo!="string"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get Mini Chat global shortcut status",e),null}},cM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_mini_chat_global_shortcut",{combo:e});return!t||typeof t.supported!="boolean"||t.combo!==null&&typeof t.combo!="string"||typeof t.active!="boolean"||t.error!==void 0&&t.error!=="unsupported-combo"?null:t}catch(t){return console.warn("Failed to set Mini Chat global shortcut",t),null}},by=p({supported:z(),enabled:z(),combo:g().nullable(),storedCombo:g().nullable(),active:z(),heightFraction:v(),error:y("unsupported-combo").optional()}),Xo=async(e,t,s)=>{if(!ct()||!Ce())return null;try{const n=by.safeParse(await ee(e,t));return n.success?n.data:null}catch(n){return console.warn(s,n),null}},lM=()=>Xo("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),dM=e=>Xo("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),gM=e=>Xo("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),pM=e=>Xo("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),uM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},mM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},ug=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},Ir=e=>{const t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith("/")?t:`${t}/`)}catch{return null}}},ky=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Sa=e=>{const t=ky(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ce=()=>{if(typeof window>"u"||!Ye())return!1;if(D()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Ir(e),s=Ir(ps());if(!s&&t&&Yu()?.target==="local")return!0;if(t&&s){if(t.origin===s.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&o===r&&Sa(t.hostname)&&Sa(s.hostname)}const n=Ir(window.location.origin);if(t&&n){if(t.origin===n.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&o===r&&Sa(t.hostname)&&Sa(n.hostname)}const a=ug(e),i=ug(window.location.origin)||window.location.origin;return a&&i&&a===i?!0:!!(n&&Sa(n.hostname))},Ye=()=>typeof window>"u"?!1:un(),hM=async()=>{if(!Ye())return null;const e=p({visible:z()}).safeParse(await ee("desktop_get_current_window_state"));return e.success?e.data.visible:null},fM=async()=>{if(!Ye())return!1;try{return!!await ee("desktop_focus_window")}catch{return!1}},bM=(e,t,s=null)=>!t||t===D()||!ct()?!1:(ee("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(a=>{console.warn("[desktop] failed to open host session",a)}),!0),lm=()=>Ye()&&Qe()&&Ce(),yy=x(p({sessionId:g().min(1),messageId:g().min(1).optional(),runtimeKey:g().min(1).optional(),requireKnownSession:z().optional()})),kM=async()=>{if(!Ye()||!Ce())return[];try{const e=yy.safeParse(await ee("desktop_take_pending_session_links"));return e.success?e.data.map(t=>({sessionId:t.sessionId,messageId:t.messageId??null,runtimeKey:t.runtimeKey??null,requireKnownSession:t.requireKnownSession===!0})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},wy=x(we("type",[p({type:y("pairing"),link:g().min(1)}),p({type:y("host"),hostId:g().min(1)})])),yM=async()=>{if(!Ye())return[];try{const e=wy.safeParse(await ee("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},vy=g().min(1),wM=e=>{if(!lm())return null;try{const t=vy.safeParse(us()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},vM=async()=>{if(!Ye())return!1;try{return await ee("desktop_start_window_drag"),!0}catch{return!1}},je=()=>im()?!0:ra()?.runtime?.isVSCode===!0,CM=()=>{const t=ra()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!je()},SM=(e,t=Ye())=>e==="web"&&!t,dm=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},PM=async e=>{if(lm())try{const t=await us()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},Cy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),AM=async e=>{if(Qe()&&Ce())try{const t=await us()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!Cy(t))return{success:!1,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:!0,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},zM=async e=>({success:!0}),xM=async e=>({success:!0}),TM=async()=>Qe()?await ee("desktop_check_for_updates"):null,IM=async e=>{if(!Qe())return!1;const t=us();let s=null,n=0,a;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",i=>{const o=i?.payload;if(!o||typeof o!="object")return;const r=o,c=typeof r.event=="string"?r.event:null,l=r.data&&typeof r.data=="object"?r.data:null;if(c==="Started"){n=0,a=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:n,total:a});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(n=d),typeof u=="number"&&(a=u),e({downloaded:n,total:a});return}c==="Finished"&&e({downloaded:n,total:a})})),await ee("desktop_download_and_install_update"),!0}catch(i){throw i instanceof Error?i:new Error(String(i))}finally{if(s)try{const i=s();i instanceof Promise&&await i}catch{}}},RM=async()=>Qe()?(await ee("desktop_restart"),!0):!1,jM=async()=>{if(!Qe())return!1;try{return await ee("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},OM=async()=>{if(!Qe()||!Ce())return null;try{const e=await ee("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},Sy=async(e,t)=>{if(!Qe()||!Ce())return!1;const s=e?.trim();if(!s)return!1;try{return await ee("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(n){return console.warn("Failed to open path",n),!1}},DM=async e=>{if(!Qe()||!Ce())return!1;const t=e?.trim();if(!t)return!1;try{return await ee("desktop_reveal_path",{path:t}),!0}catch{return Sy(t)}},BM=async(e,t)=>{if(!Qe()||!Ce())return null;const s=e?.trim();if(!s)return null;try{const n=await ee("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof n=="string"&&n.trim().length>0?n:null}catch(n){return console.warn("Failed to save markdown file",n),null}},FM=async(e,t,s)=>{if(!Qe()||!Ce())return!1;const n=e?.trim(),a=t?.trim(),i=s?.trim();if(!n||!a||!i)return!1;try{return await ee("desktop_open_in_app",{projectPath:n,appId:a,appName:i}),!0}catch(o){return console.warn("Failed to open project in app",o),!1}},NM=async(e,t,s)=>{if(!Qe()||!Ce())return!1;const n=e?.trim(),a=t?.trim(),i=s?.trim();if(!n||!a||!i)return!1;try{return await ee("desktop_open_file_in_app",{filePath:n,appId:a,appName:i}),!0}catch(o){return console.warn("Failed to open file in app",o),!1}},MM=async(e,t)=>{if(!Qe()||!Ce())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];if(s.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const n=await ee("desktop_get_installed_apps",{apps:s,force:t===!0?!0:void 0});if(!n||typeof n!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const a=n;return a.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(a.apps)?{apps:a.apps.filter(o=>o&&typeof o=="object").map(o=>{const r=o;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(o=>o.name.length>0),success:!0,hasCache:a.hasCache===!0,isCacheStale:a.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(n){return console.warn("Failed to fetch installed apps",n),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},EM=()=>navigator.platform.toLowerCase().startsWith("linux"),mn=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",LM=()=>typeof window>"u"||!mn()?!1:gm()==="ios"&&Py(),Py=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},gm=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return je()?"vscode":Ye()?"desktop":"web"},Ay="2.6.1",Wi=new Uint8Array(0),zy=typeof DecompressionStream=="function",xy=e=>e.pipeThrough(new TransformStream({transform(t,s){s.enqueue(t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t))}})).pipeThrough(new DecompressionStream("gzip")),pm=e=>ArrayBuffer.isView(e)?e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e,Ty=new TextEncoder,Iy=new TextDecoder,Ct=e=>e instanceof Error?e:new Error(String(e)),Hi=()=>new DOMException("The operation was aborted.","AbortError"),Ry=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(pm(s))},close(s,n){e.close(s,n)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>t.onmessage?.({data:s.data}),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),e.onerror=()=>t.onerror?.(),t},jy=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(s){s&&(e.binaryType=s)},onopen:null,onmessage:null,onerror:null,onclose:null,send(s){e.send(pm(s))},close(s,n){e.close(s,n)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const n=s.data;(typeof n=="string"||n instanceof ArrayBuffer)&&t.onmessage?.({data:n})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},Oy=e=>e?.state==="error"&&e.closeCode===Bs.LimitExceeded,mg=0,Rr=1,hg=2,fg=3,Dy=new Set([Bs.AuthFailed,Bs.DuplicateClient,Bs.LimitExceeded]),By={[Bs.AuthFailed]:"relay authentication failed",[Bs.DuplicateClient]:"relay connection replaced by another client",[Bs.LimitExceeded]:"relay connection limit reached"},jr=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Zl=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,n=e.pingIntervalMs??3e4,a=e.pingTimeoutMs??15e3,i=e.batchWindowMs??Ku,o=e.batch!==!1,r=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(M=>Ry(new WebSocket(M)));let u=!1,m=null,f={state:"idle"};const b=new Set;let k=null,w=null,T=null,S=0,E=0,H=null,Z=[],N=!1;const ce=M=>{if(!(f.state===M.state&&f.lastError===M.lastError&&f.terminal===M.terminal&&f.closeCode===M.closeCode)){f=M;for(const le of b)try{le(f)}catch{}}},$=M=>{const le=Z;Z=[];for(const U of le)U.reject(M)},lt=M=>{const le=Z;Z=[];for(const U of le)U.resolve(M)},Xe=(M,le)=>{M.dead=!0;const U=Array.from(M.streams.values());M.streams.clear();for(const _ of U)try{_.fail(le)}catch{}},ka=()=>{H!==null&&(clearTimeout(H),H=null)},ya=()=>{if(!u){if(H!==null){if(jr())return;ka(),wt(),yn();return}jr()||Ls()}},Ls=()=>{u||m===null||(wt(),m=null,yn())},G=()=>{typeof document<"u"&&document.visibilityState==="visible"&&ya()},nt=()=>{N||typeof window>"u"||(N=!0,window.addEventListener("online",ya),typeof document<"u"&&document.addEventListener("visibilitychange",G))},wt=()=>{!N||typeof window>"u"||(N=!1,window.removeEventListener("online",ya),typeof document<"u"&&document.removeEventListener("visibilitychange",G))},wa=()=>{if(u||H!==null)return;const M=Math.max(0,E-1),le=r*2**Math.min(M,10),U=jr()?l:c,_=Math.min(U,le);nt(),H=setTimeout(()=>{H=null,wt(),yn()},_)},Cr=()=>{const M=new URL(e.relayUrl);return M.searchParams.set("v",String(Ua)),M.searchParams.set("role","client"),M.searchParams.set("serverId",e.serverId),M.searchParams.set("appId","openchamber"),M.searchParams.set("appVersion",Ay),M.searchParams.set("platform",gm()),e.grant&&M.searchParams.set("grant",e.grant),M.toString()},yn=async()=>{if(u)return;ka(),S+=1;const M=S;ce({state:E>0?"reconnecting":"connecting",lastError:f.lastError});let le;try{le=await xk(e.hostEncPubJwk,{batch:o,flowControl:e.flowControl})}catch(pe){if(M!==S||u)return;sg(M,Ct(pe),!0);return}if(M!==S||u)return;let U;try{U=d(Cr())}catch(pe){sg(M,Ct(pe));return}w=U;let _=!1,Q=null,ge=null,at=null,Fe=null,te=Promise.resolve(),ne=null,Te=null,Xt=!1,Oe=!1,De=0,Ne=0,Me=null,es=null,ve=Date.now();const bs=()=>{Me!==null&&(clearTimeout(Me),Me=null),Q!==null&&(clearInterval(Q),Q=null),ge!==null&&(clearTimeout(ge),ge=null),at!==null&&(clearInterval(at),at=null),Fe!==null&&(clearTimeout(Fe),Fe=null),es!==null&&(es.dispose(),es=null)};T=bs;function ue(pe,Se=!1,me=null){if(!(_||M!==S)){_=!0,me!==null&&(m=pe),bs(),ne&&(k=null,Xe(ne,new Error(`relay tunnel reset: ${pe.message}`))),$(pe);try{U.close()}catch{}if(w===U&&(w=null),!u){if(E+=1,me!==null){nt(),ce({state:"error",lastError:pe.message,terminal:!0,closeCode:me});return}ce({state:Se?"error":"reconnecting",lastError:pe.message}),wa()}}}const va=()=>{try{U.send(le.helloText)}catch{}},qs=(pe,Se,me)=>{Te=pe,Xt=Se,Oe=me,Q!==null&&(clearInterval(Q),Q=null),ge!==null&&(clearTimeout(ge),ge=null);const it=new Map,Ve=Lk(),vt=Ok();let Vs=Promise.resolve();const ks=Ca=>{Vs=Vs.then(async()=>{if(Us.dead)return;const Xb=await pe.encryptor.encrypt(Ca);Us.dead||U.send(Xb)}).catch(()=>{ue(new Error("relay encrypt/send failed"))})},Ar=Se?Ek({windowMs:i,sendBatch:ks}):null;es=Ar;const Us={streams:it,assembler:vt,nextStreamId:()=>Ve.next(),dead:!1,send(Ca){Us.dead||(Ar?Ar.enqueue(Ca):ks(Ca))}};ne=Us,k=Us,E=0,ve=Date.now(),ce({state:"connected"}),lt(Us),at=setInterval(()=>{Date.now()-ve<n||(Us.send(At(se.Ping,0,Wi)),Fe===null&&(Fe=setTimeout(()=>{Fe=null,ue(new Error("relay keepalive timeout"))},a)))},n)},Ni=()=>{Me!==null&&clearTimeout(Me),Me=null,!(!ne||ne.dead||De===Ne)&&(Ne=De,ne.send(At(se.DeliveryAck,0,Tk(De))))},Pr=(pe,Se)=>{let me;try{me=Ik(Se)}catch(vt){ue(Ct(vt));return}if(me.frameType===se.DeliveryAck){ue(new Error("unexpected downstream delivery acknowledgement"));return}if(Oe&&me.streamId!==0&&(De+=Se.length,Me===null&&(Me=setTimeout(Ni,10))),ve=Date.now(),Fe!==null&&(clearTimeout(Fe),Fe=null),me.frameType===se.Ping){pe.send(At(se.Pong,me.streamId,Wi));return}if(me.frameType===se.Pong)return;let it=me.payload;if(me.frameType===se.WsText||me.frameType===se.WsBinary){let vt;try{vt=pe.assembler.push(me)}catch(Vs){ue(Ct(Vs));return}if(vt===null)return;it=vt}else if(me.hasMoreFragments){ue(new Error("unexpected fragmented tunnel frame"));return}const Ve=pe.streams.get(me.streamId);Ve&&Ve.handleFrame(me.frameType,it)};U.onopen=()=>{_||M!==S||(va(),Q=setInterval(va,t))};const wn=pe=>{const Se=Dy.has(pe);ue(new Error(By[pe]??`relay socket closed (code ${pe})`),Se,Se?pe:null)};U.onmessage=pe=>{if(_||M!==S)return;const Se=pe.data;if(typeof Se=="string"){const it=ck(Se);if(it){wn(it.code);return}te=te.then(async()=>{if(_||M!==S)return;const Ve=await le.handleText(Se);if(Ve.type==="established"){if(Te)return;qs(Ve.channel,Ve.batch,Ve.flowControl)}else Ve.type==="fail"&&ue(new Error(`relay handshake failed: ${Ve.reason}`))}).catch(Ve=>{ue(Ct(Ve))});return}const me=Se instanceof ArrayBuffer?new Uint8Array(Se):Se instanceof Uint8Array?Se:null;me&&(te=te.then(async()=>{if(_||M!==S)return;const it=ne,Ve=Te;if(!it||!Ve){ue(new Error("encrypted frame before handshake completed"));return}let vt;try{vt=await Ve.decryptor.decrypt(me)}catch(ks){ue(Ct(ks));return}let Vs;try{Vs=Xt?Bk(vt):[vt]}catch(ks){ue(Ct(ks));return}for(const ks of Vs){if(_||M!==S||it.dead)return;Pr(it,ks)}Oe&&De-Ne>=16*1024&&Ni()}).catch(it=>{ue(Ct(it))}))},U.onclose=pe=>wn(pe.code),U.onerror=()=>{},ge=setTimeout(()=>{ge=null,ue(new Error("relay handshake timeout"),!0)},s);function sg(pe,Se,me=!1){pe!==S||u||($(Se),E+=1,ce({state:me?"error":"reconnecting",lastError:Se.message}),wa())}},Yt=M=>u?Promise.reject(new Error("relay tunnel closed")):M?.aborted?Promise.reject(Hi()):m?Promise.reject(m):k&&!k.dead?Promise.resolve(k):new Promise((le,U)=>{let _=null;const Q={resolve(ge){_&&M&&M.removeEventListener("abort",_),le(ge)},reject(ge){_&&M&&M.removeEventListener("abort",_),U(ge)}};M&&(_=()=>{Z=Z.filter(ge=>ge!==Q),U(Hi())},M.addEventListener("abort",_,{once:!0})),Z.push(Q)}),Sr=async(M,le)=>{const U=await Kk(M,le),_=U.signal;if(_?.aborted)throw Hi();const Q=await Yt(_),ge=Q.nextStreamId();return await new Promise((at,Fe)=>{let te=!1,ne=!1,Te=null,Xt=null;const Oe=()=>{Q.streams.delete(ge),Q.assembler.dropStream(ge),Xt&&_&&_.removeEventListener("abort",Xt)},De=ve=>{if(!ne){if(ne=!0,Oe(),!te){Fe(ve);return}try{Te?.error(ve)}catch{}}},Ne=ve=>{Q.dead||Q.send(At(se.StreamAbort,ge,Li({reason:ve})))},Me=ve=>Oc(new Error(ve));Xt=()=>{Ne("aborted"),De(Hi())},Q.streams.set(ge,{handleFrame(ve,bs){if(ve===se.HttpResponse){if(te||ne)return;let ue;try{ue=qi(bs,Vk)}catch(wn){Ne("malformed response head"),De(Me(Ct(wn).message));return}const va=ue.status===204||ue.status===205||ue.status===304;let qs=null;va||(qs=new ReadableStream({start(wn){Te=wn},cancel(){ne||(ne=!0,Oe(),Ne("response body cancelled"))}})),te=!0;const{[pk]:Ni,...Pr}=ue.headers;qs&&Ni==="gzip"&&(qs=xy(qs)),at(new Response(qs,{status:ue.status,headers:Pr})),va&&(ne=!0,Oe());return}if(ve===se.HttpBody){if(!te||ne)return;try{Te?.enqueue(bs)}catch{}return}if(ve===se.StreamEnd){if(ne)return;if(!te){De(Me("tunnel stream ended before response head"));return}ne=!0,Oe();try{Te?.close()}catch{}return}if(ve===se.StreamAbort){let ue="stream aborted by host";try{ue=qi(bs,og).reason}catch{}De(Me(ue))}},fail(ve){De(Me(ve.message))}}),_&&_.addEventListener("abort",Xt,{once:!0});const es={method:U.method,path:U.path,query:U.query,headers:zy?{...U.headers,[gk]:"gzip"}:U.headers,hasBody:U.body!==null};Q.send(At(se.HttpRequest,ge,Li(es))),(async()=>{try{let ve=!1;if(U.body)for await(const bs of U.body){if(ne||Q.dead)return;for(const ue of _u(bs))Q.send(At(se.HttpBody,ge,ue)),ve=!0}!ne&&!Q.dead&&(U.body&&!ve&&Q.send(At(se.HttpBody,ge,Wi)),Q.send(At(se.StreamEnd,ge,Wi)))}catch(ve){Ne("request body failed"),De(Me(Ct(ve).message))}})()})},$b=M=>{const le=M.indexOf("?");return le===-1?{path:M,query:""}:{path:M.slice(0,le),query:M.slice(le+1)}},Qb=(M,le)=>{let U=mg,_=null,Q=0,ge=!1;const at={get readyState(){return U},onopen:null,onmessage:null,onerror:null,onclose:null,send(te){if(U!==Rr||!_||_.dead)throw new Error("relay tunnel socket is not open");if(typeof te=="string"){for(const Te of ig(se.WsText,Q,Ty.encode(te)))_.send(Te);return}const ne=te instanceof ArrayBuffer?new Uint8Array(te.slice(0)):(()=>{const Te=new Uint8Array(te.byteLength);return Te.set(new Uint8Array(te.buffer,te.byteOffset,te.byteLength)),Te})();for(const Te of ig(se.WsBinary,Q,ne))_.send(Te)},close(te=1e3,ne=""){U===fg||U===hg||(U===Rr&&_&&!_.dead&&(U=hg,_.send(At(se.WsClose,Q,Li({code:te,reason:ne})))),Fe(te,ne))}},Fe=(te,ne,Te=!1)=>{if(!ge){if(ge=!0,_&&(_.streams.delete(Q),_.assembler.dropStream(Q)),U=fg,Te)try{at.onerror?.()}catch{}try{at.onclose?.({code:te,reason:ne})}catch{}}};return(async()=>{let te;try{te=await Yt()}catch(Oe){Fe(1006,Ct(Oe).message,!0);return}if(ge)return;_=te,Q=te.nextStreamId(),te.streams.set(Q,{handleFrame(Oe,De){if(Oe===se.WsOpened){if(U===mg){U=Rr;try{at.onopen?.()}catch{}}return}if(Oe===se.WsText){try{at.onmessage?.({data:Iy.decode(De)})}catch{}return}if(Oe===se.WsBinary){const Ne=new ArrayBuffer(De.byteLength);new Uint8Array(Ne).set(De);try{at.onmessage?.({data:Ne})}catch{}return}if(Oe===se.WsClose){let Ne=1e3,Me="";try{const es=qi(De,Uk);Ne=es.code,Me=es.reason}catch{}Fe(Ne,Me);return}if(Oe===se.StreamAbort){let Ne="stream aborted";try{Ne=qi(De,og).reason}catch{}Fe(1006,Ne,!0)}},fail(Oe){Fe(1012,Oe.message,!0)}});const{path:ne,query:Te}=$b(M),Xt=le&&le.length>0?{path:ne,query:Te,protocols:le}:{path:ne,query:Te};te.send(At(se.WsOpen,Q,Li(Xt)))})(),at},Yb=()=>{if(u)return;u=!0,S+=1,ka(),wt(),T?.(),T=null;const M=k;k=null;const le=new Error("relay tunnel closed");M&&Xe(M,le),$(le);try{w?.close()}catch{}w=null,ce({state:"idle"})};return yn(),{fetch:Sr,openWebSocket:Qb,getStatus:()=>f,subscribeStatus(M){return b.add(M),()=>{b.delete(M)}},retry:Ls,close:Yb}};let Jt=null,_t=null;const Vc=new Set;let Or=null;const Jl=e=>{Or?.(),Or=null,Jt=e,e&&(Or=e.subscribeStatus(t=>{for(const s of Vc)s(t)}))},qM=e=>(Vc.add(e),()=>{Vc.delete(e)}),Fy=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),ca=()=>Jt,VM=()=>!Jt||!_t?null:{relayUrl:_t.relayUrl,serverId:_t.serverId,hostEncPubJwk:{..._t.hostEncPubJwk}},Ny=()=>Jt!==null,My=e=>{if(Jt&&_t&&Fy(_t,e))return Jt;Jt?.close(),_t=e;const t=Zl(e);return Jl(t),t},UM=(e,t)=>{if(Jt===t){_t=e;return}Jt?.close(),_t=e,Jl(t)},Ey=()=>{Jt?.close(),Jl(null),_t=null};let um=()=>null,mm="",Oo={},$n="",gi=0,Ys=null,qn="",pi=0,dn="",Xs=null,As="",uo=0,mo=0;const $l=1e4,Ly=e=>e.toLowerCase()==="authorization",hm=e=>{const t={};for(const[s,n]of Object.entries(e||{})){const a=s.trim(),i=n.trim();a&&i&&!Ly(a)&&(t[a]=i)}return t},qy=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?!1:s.every(([n,a])=>t[n]===a)},er=e=>typeof e!="string"?"":e.trim(),Vy=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return er(e)},Uy=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},fm=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():Uy();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},Ql=e=>{try{return new URL(e).origin}catch{return""}},bm=()=>{qn="",pi=0,dn="",Xs=null,As="",uo+=1},Ai=()=>{$n="",gi=0,bm()},km=()=>{mo+=1,Ys=null,Ai(),Xl()},ym=e=>{const t=er(e);mm=t,km(),um=()=>t?{type:"bearer",token:t}:null},wm=e=>{const t=hm(e);qy(Oo,t)||(Oo=t,km())},la=()=>{if(Object.keys(Oo).length>0)return Oo;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?hm(e):{}},Yl=()=>mm||Vy(),Wy=(e,t)=>{const s=er(e);if(!s||typeof t!="number"||!Number.isFinite(t)){Ai();return}$n=s,gi=t},vm=()=>!$n||gi<=Date.now()+$l?(Ai(),""):$n,Cm=e=>{const t=Ql(e);return!t||dn!==t?"":!qn||pi<=Date.now()+$l?(qn="",pi=0,dn="",""):qn},Hy=()=>{const e=vm();return!e&&(Yl()||typeof window<"u")&&tr().catch(()=>{}),e},Gy=e=>{const t=e?Cm(e):"";return!t&&e&&typeof window<"u"&&zm(e).catch(()=>{}),t},Sm=async()=>{const e=await um(),t=e?.type==="bearer"?er(e.token):Yl();return t?{type:"bearer",token:t}:null},_y=p({token:g(),expiresAt:v(),expiresIn:v().optional()}),Pm=async(e,t)=>{const s=await Sm(),n=new Headers;for(const[u,m]of Object.entries(la()))n.set(u,m);s?.type==="bearer"&&n.set("Authorization",`Bearer ${s.token}`);const a=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",i=ca(),o=i?await i.fetch(a,{method:"POST",headers:n}):await fetch(fm(e,a),{method:"POST",headers:n,credentials:"include"});if(!o.ok)throw new Error(`Failed to mint runtime URL auth token (${o.status})`);const r=_y.safeParse(await o.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:c,expiresAt:l,expiresIn:d}=r.data;return{token:c.trim(),expiresAt:d===void 0?l:Date.now()+d}},WM=async e=>{const t=await Pm(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Am=e=>{if(Ys)return Ys;const t=mo,n=(async()=>{let a;try{a=await Pm(e)}catch(i){throw t===mo&&Ai(),i}if(t!==mo)throw new Error("Runtime URL auth token response is stale");if(Wy(a.token,a.expiresAt),!$n)throw new Error("Runtime URL auth token response was invalid");return $n})().finally(()=>{Ys===n&&(Ys=null)});return Ys=n,Ys},Ky=e=>{const t=Ql(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Xs&&As===t)return Xs;const s=uo,a=(async()=>{const i=await fetch(fm(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!i.ok)throw s===uo&&t===As&&(qn="",pi=0,dn=""),new Error(`Failed to mint local runtime URL auth token (${i.status})`);const o=await i.json().catch(()=>null),r=typeof o?.token=="string"?o.token.trim():"",c=typeof o?.expiresAt=="number"?o.expiresAt:0;if(!r||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(s!==uo||t!==As)throw new Error("Local runtime URL auth token response is stale");return qn=r,pi=c,dn=t,r})().finally(()=>{Xs===a&&(Xs=null,As="")});return Xs=a,As=t,Xs},tr=async e=>{const t=vm();return t||Am(e)},zm=async e=>{const t=Ql(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=Cm(t);return s||((dn&&dn!==t||As&&As!==t)&&bm(),Ky(t))};let Bn=0,Ha=null,Zy=null;const Jy=5e3,xm=()=>{Ha!==null&&(clearTimeout(Ha),Ha=null)},Xl=()=>{if(xm(),Bn<=0||typeof window>"u")return;const e=gi-$l-Jy,t=gi>0?Math.max(0,e-Date.now()):0;Ha=setTimeout(()=>{Ha=null,!(Bn<=0)&&Am(Zy).catch(()=>{}).finally(()=>{Xl()})},t)},HM=e=>{Bn+=1,Xl();let t=!1;return()=>{t||(t=!0,Bn=Math.max(0,Bn-1),Bn===0&&xm())}},Tm=async e=>{const t=new Headers(e);for(const[n,a]of Object.entries(la()))t.has(n)||t.set(n,a);if(t.has("Authorization"))return t;const s=await Sm();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},Qn=yt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),GM=e=>new Promise(t=>{if(e.aborted||Qn.getState().state==="ok"){t();return}const s=()=>{n(),e.removeEventListener("abort",s),t()},n=Qn.subscribe(a=>{a.state==="ok"&&s()});e.addEventListener("abort",s,{once:!0})}),$y=15e3,Qy=5*6e4;let Uc=0,Dr=!1;const Yy=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),Xy=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!Yy(t)},Im=async()=>{if(!Dr){Dr=!0;try{const{runtimeFetch:e}=await Ee(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>bw);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){Qn.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:n}=Qn.getState();s==="expired"&&n()}}catch{}finally{Dr=!1}}},ew=(e,t)=>{if(t!==401||Qn.getState().state==="expired"||!Xy(e))return;const s=Date.now();s-Uc<$y||(Uc=s,Im())};let bg=!1;const _M=()=>{if(bg)return;bg=!0;let e=Date.now();const t=()=>{if(Qn.getState().state!=="ok")return;const s=Date.now();s-e<Qy||(e=s,Uc=s,Im())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},tw=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,kt=e=>{if(!e)return null;const t=tw.exec(e);return t?t[1]:null},Wc=e=>kt(e)!==null,sw=()=>im()||ra()?.runtime?.isVSCode===!0,nw=e=>!e||sw()||!Wc(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},Rm=e=>`/spaces/${e}`,gn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",aw=()=>typeof window>"u"?"":window.location.origin||"",ed=e=>{if(typeof window>"u")return!1;const t=aw();if(t&&e.origin===t)return!0;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return!1}},td=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),iw=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),ss=(e,t)=>{try{iw(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},sd=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,a]of s)a!=null&&e.searchParams.set(n,String(a))},ow=e=>{if(!e)return!1;if(e instanceof Headers)return e.has("x-opencode-directory");const t=Array.isArray(e)?e:Object.entries(e);for(const[s]of t)if(s.toLowerCase()==="x-opencode-directory")return!0;return!1},rw=(e,t,s)=>{const n=nw(s);if(n===null||ow(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const a=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...a,...Object.entries(n)]}},cw=()=>{const e=ls().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return null;const t=new URL(e);return`${t.origin}${t.pathname.replace(/\/api$/,"")}`},lw=e=>{try{const t=cw();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const n=s.pathname.replace(/\/+$/,"");return n?e.pathname!==n&&!e.pathname.startsWith(`${n}/`)?null:e.pathname.slice(n.length)||"/":e.pathname}catch{return null}},ho=e=>{const t=lw(e);return t!==null&&gn(t)},Br=e=>{if(gn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ed(t)&&gn(t.pathname)}catch{return!1}},dw=(e,t)=>{try{const s=new URL(e);if(!ed(s))return e;const n=Fs(`${s.pathname}${s.search}`,t);return!td(n)&&(s.protocol==="http:"||s.protocol==="https:")?(sd(s,t),s.toString()):s.hash?`${n}${s.hash}`:n}catch{return e}},Fs=(e,t)=>e==="/health"?ls().health(t):e.startsWith("/auth/")||e==="/auth"?ls().auth(e,t):gn(e)?ls().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?dw(e,t):e,jm=e=>{const t=e instanceof Request?e.url:e.toString();if(!td(t))return gn(t);try{return ho(new URL(t))}catch{return!1}},Om=(e,t)=>Object.keys(la()).length>0&&mn()&&jm(e)?{...t,redirect:"error"}:t,Dm=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},gw=(e,t)=>!Dm(t),Do=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const s=[];let n=!1,a=!1;for(const[i,o]of t)gw(i,o)?(s.push([i,encodeURIComponent(o)]),n=!0,i.toLowerCase()==="x-opencode-directory"&&(a=!0)):s.push([i,o]);return a&&s.push(["x-opencode-directory-encoding","uri"]),n?s:void 0},ns=async(e,t,s=!0)=>{const n=new Headers(Do(e)??e);return t&&new Headers(Do(t)??t).forEach((a,i)=>n.set(i,a)),s?Tm(n):n},pw=(e,t)=>{if(!t)return e;const s=new URL(e,Hl);return sd(s,t),`${s.pathname}${s.search}`},Bm=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!td(s))return gn(s)?pw(s,t):null;try{const n=new URL(s);return!ed(n)||!gn(n.pathname)?null:(sd(n,t),`${n.pathname}${n.search}`)}catch{return null}},uw=async(e,t,s)=>{const n=ca();if(!n)return null;const a=Bm(e,s);if(a===null)return null;const i=e instanceof Request?e.headers:void 0,o=await ns(i,t.headers,!0);return e instanceof Request?n.fetch(e,{...t,headers:o}):n.fetch(a,{...t,headers:o})},mw=(e,t)=>{if(typeof e=="string")return Fs(e,t);if(e instanceof URL)return Fs(e.toString(),t);const s=Fs(e.url,t);return s===e.url?e:new Request(s,e)},hw=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Gi=new Map,fw=(e,t,s,n)=>s||e!=="GET"||t.includes("/event")||!hw.test(t)?null:`GET ${t}\0${n.get("x-opencode-directory")??""}`,C=async(e,t={})=>{const{query:s,directory:n,...a}=t,i=e,o=rw(i,a,n),r=ca(),c=r?Bm(i,s):null;let l,d,u,m;if(r&&c!==null){const S=i instanceof Request?i.headers:void 0,E=await ns(S,o.headers,!0);l=i instanceof Request?()=>r.fetch(i,{...o,headers:E}):()=>r.fetch(c,{...o,headers:E}),m=E,d=c,u=String(o.method??(i instanceof Request?i.method:"GET")).toUpperCase()}else{const S=mw(i,s),E=S instanceof Request?S.headers:void 0,H=await ns(E,o.headers,jm(S)),Z=S instanceof Request?S.url:S instanceof URL?S.toString():String(S);ss(Z,H);const N=Om(S,{...o,headers:H});l=S instanceof Request?()=>fetch(new Request(S,N)):()=>fetch(S,N),m=H,d=Z,u=String(o.method??(S instanceof Request?S.method:"GET")).toUpperCase()}const f=l;l=()=>f().then(S=>(ew(d,S.status),S));const b=o.signal!=null||i instanceof Request,k=fw(u,d,b,m);if(!k)return l();const w=Gi.get(k);if(w)return w.then(S=>S.clone());const T=l();return Gi.set(k,T),T.then(()=>Gi.delete(k),()=>Gi.delete(k)),T.then(S=>S.clone())};let kg=!1,Fm=null;const Nm=(e,t)=>(Fm??globalThis.fetch.bind(globalThis))(e,t),Mm=()=>{if(kg||typeof window>"u")return;kg=!0;const e=window.fetch.bind(window);Fm=e;const t=(s,n)=>e(s,Om(s,n));window.fetch=async(s,n)=>{const a=await uw(s,n??{});if(a)return a;if(typeof s=="string"){if(!Br(s)){try{const r=new URL(s);if(ho(r)){const c=await ns(void 0,n?.headers);return ss(r.toString(),c),t(s,{...n,headers:c})}}catch{}return t(s,n)}const i=await ns(void 0,n?.headers),o=Fs(s);return ss(o,i),t(o,{...n,headers:i})}if(s instanceof URL){const i=s.toString();if(!Br(i)){if(ho(s)){const c=await ns(void 0,n?.headers);return ss(s.toString(),c),t(s,{...n,headers:c})}return t(s,n)}const o=await ns(void 0,n?.headers),r=Fs(i);return ss(r,o),t(r,{...n,headers:o})}if(s instanceof Request){if(!Br(s.url)){try{const c=new URL(s.url);if(ho(c)){const l=await ns(s.headers,n?.headers);return ss(c.toString(),l),t(new Request(s,{...n,headers:l}))}}catch{}return t(s,n)}const i=await ns(s.headers,n?.headers),o=Fs(s.url);ss(o,i);const r=o===s.url?s:new Request(o,s);return t(new Request(r,{...n,headers:i}))}return t(s,n)}},bw=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:ss,buildRuntimeFetchUrl:Fs,fetchBypassingRuntimeBridge:Nm,installRuntimeFetchBridge:Mm,isLatin1Safe:Dm,runtimeFetch:C,sanitizeHeadersForBrowser:Do},Symbol.toStringTag,{value:"Module"})),Vn=16384,Bo=globalThis,kw=e=>{if(Bo.Buffer)return Bo.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let n=0;n<t.length;n+=32768)s+=String.fromCharCode(...t.slice(n,n+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},Em=e=>{try{if(Bo.Buffer)return Bo.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),n=new Uint8Array(s.length);for(let a=0;a<s.length;a+=1)n[a]=s.charCodeAt(a);return new TextDecoder().decode(n)}catch{return null}},yw=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString().replace(/\/+$/g,""))}catch{return null}},ww=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="ws:"&&s.protocol!=="wss:"?null:(s.hash="",s.toString())}catch{return null}},yg=e=>typeof e=="string"&&e.length>0,vw=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!yg(t.x)||!yg(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Cw=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Sw=e=>{if(!e||typeof e!="object")return null;const t=e,s=Cw(t.priority);if(t.type==="lan"||t.type==="tunnel"){const n=yw(t.url);return n?s===void 0?{type:t.type,url:n}:{type:t.type,url:n,priority:s}:null}if(t.type==="relay"){const n=ww(t.relayUrl);if(!n)return null;const a=typeof t.serverId=="string"?t.serverId.trim():"";if(!a)return null;const i=vw(t.hostEncPubJwk);if(!i)return null;const o=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:n,serverId:a,hostEncPubJwk:i,...o?{grant:o}:{},...s===void 0?{}:{priority:s}}}return null},nd=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const s=typeof t.pairingId=="string"?t.pairingId.trim():"",n=typeof t.secret=="string"?t.secret.trim():"";if(!s||!n)return null;const a=Array.isArray(t.candidates)?t.candidates.map(Sw).filter(c=>!!c):[];if(a.length===0)return null;const i=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(i){const c=Date.parse(i);if(!Number.isFinite(c)||c<=Date.now())return null}const o=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,r=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:s,secret:n,...o?{label:o}:{},...r?{fingerprint:r}:{},...i?{expiresAt:i}:{},candidates:a}},KM=e=>({v:2,pairingId:e.pairingId.trim(),secret:e.secret.trim(),...e.label?.trim()?{label:e.label.trim()}:{},...e.fingerprint?.trim()?{fingerprint:e.fingerprint.trim()}:{},...e.expiresAt?.trim()?{expiresAt:e.expiresAt.trim()}:{},candidates:e.candidates}),ZM=e=>{const t=nd(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",kw(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},Pw=e=>{const t=e.trim();if(!t||t.length>Vn)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const n=s.searchParams.get("p")||"";if(!n||n.length>Vn)return null;const a=Em(n);return!a||a.length>Vn?null:nd(JSON.parse(a))}catch{return null}},JM=e=>{const t=e.trim();if(!t||t.length>Vn)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let n=null,a=null;for(const o of t.slice(s+1).split("&")){const r=o.indexOf("=");if(r===-1)continue;const c=o.slice(0,r),l=o.slice(r+1);c==="v"?n=l:c==="p"&&(a=l)}if(n!=="2"||!a||a.length>Vn)return null;const i=Em(a);if(!i||i.length>Vn)return null;try{return nd(JSON.parse(i))}catch{return null}},Yn=e=>typeof e=="object"&&e!==null,Aw=e=>e.trim().toLowerCase()==="authorization",zw=e=>{if(!Yn(e))return;const t={};for(const[s,n]of Object.entries(e)){const a=s.trim(),i=typeof n=="string"?n.trim():"";!a||!i||/[\r\n:]/.test(a)||/[\r\n]/.test(i)||Aw(a)||(t[a]=i)}return Object.keys(t).length>0?t:void 0},xw=e=>`relay://${e}`,Tw=e=>{if(!Yn(e))return null;const t=Ge(e,"relayUrl")||Ge(e,"relay_url"),s=Ge(e,"serverId")||Ge(e,"server_id"),n=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!Yn(n)?null:{relayUrl:t,serverId:s,hostEncPubJwk:n}},Iw=()=>{if(typeof navigator>"u")return;const e=navigator.userAgent;if(/Macintosh|Mac OS X/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux"},wg=15e3,$M=async(e,t)=>{const s=Pw(e);if(!s)throw new Error("invalid-connect-link");const n=await Bw().catch(()=>""),a={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:s.pairingId,secret:s.secret,clientLabel:s.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:Iw(),...n?{dedupeKey:`desktop:${n}`}:{}})},i=async w=>{if(!w.ok)return null;const T=await w.json().catch(()=>null);return(typeof T?.clientToken=="string"?T.clientToken.trim():"")||null};let o=null;const r=[...s.candidates].sort((w,T)=>(w.type==="relay"?1:0)-(T.type==="relay"?1:0));for(const w of r){if(w.type==="relay"){const S=Zl({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const E=await i(await S.fetch("/api/client-auth/pairing/redeem",{...a,signal:AbortSignal.timeout(wg)}));if(E){o={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:E};break}}catch{}finally{S.close()}continue}const T=qe(w.url);if(T)try{const S=await i(await fetch(`${T}/api/client-auth/pairing/redeem`,{...a,signal:AbortSignal.timeout(wg)}));if(S){o={directUrl:T,token:S};break}}catch{}}if(!o)throw new Error("pairing-redeem-failed");const c=s.candidates.find(w=>w.type==="relay"),l=o.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),d=s.candidates.filter(w=>w.type!=="relay").map(w=>qe(w.url)).find(w=>!!w),u=o.directUrl||d,m=u||(l?xw(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");const f=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&qe(w.apiUrl||w.url)===m),b=f?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),k={...f||{},id:b,label:s.label||f?.label||Lm(m),url:m,apiUrl:u,clientToken:o.token,...l?{relay:l}:{}};return{hostId:b,hosts:f?t.map(w=>w.id===b?k:w):[k,...t]}},Rw=/^(t|.*(?:token|auth|secret|api).*)$/i,qe=e=>{const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},QM=e=>{const t=qe(e);if(!t)return null;try{const s=new URL(t);if((s.pathname.replace(/\/+$/,"")||"/")==="/connect"&&s.searchParams.has("t"))return{persistedUrl:s.origin,redeemUrl:s.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},Lm=e=>{const t=qe(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const n=Array.from(new Set(Array.from(s.searchParams.keys())));for(const a of n)Rw.test(a)&&s.searchParams.set(a,"[REDACTED]");return s.toString()}catch{return t}},_i=(e,t)=>{const s=qe(e),n=qe(t);if(!s||!n)return!1;try{const a=new URL(s),i=new URL(n);if(a.origin!==i.origin||i.search&&a.search!==i.search)return!1;const o=i.pathname.length>1?i.pathname.replace(/\/+$/,""):i.pathname,r=a.pathname.length>1?a.pathname.replace(/\/+$/,""):a.pathname;return o==="/"?!0:r===o||r.startsWith(`${o}/`)}catch{return!1}},Ge=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},vg=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},jw=e=>{if(!Yn(e))return null;const t=Ge(e,"id"),s=Ge(e,"label"),n=Ge(e,"url"),a=Ge(e,"apiUrl")||Ge(e,"api_url"),i=Ge(e,"clientToken")||Ge(e,"client_token"),o=zw(e.requestHeaders),r=Tw(e.relay);if(!t||!s||!n)return null;const c={id:t,label:s,url:n,...a?{apiUrl:a}:{},...i?{clientToken:i}:{},...o?{requestHeaders:o}:{},...r?{relay:r}:{}};return e.sshForwarded===!0&&(c.sshForwarded=!0),c},Un=e=>qe(e.apiUrl||e.url)||e.apiUrl||e.url,fs=()=>Qe()?(e,t)=>ee(e,t):null,ui=async()=>{const e=fs();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Yn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const s=t.hosts,n=Array.isArray(s)?s.map(jw).filter(r=>!!r):[],a=Ge(t,"defaultHostId")||Ge(t,"default_host_id")||Ge(t,"defaultHostID"),i=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,o=Ge(t,"localOrigin")||Ge(t,"local_origin");return{hosts:n,defaultHostId:a,initialHostChoiceCompleted:i,localOrigin:o}},Ow=async e=>{const t=fs();if(!t)return;const s={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(s.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:s})},Dw=async()=>{const e=fs();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},YM=async()=>{const e=fs();return e?await e("desktop_switch_to_local").catch(()=>!1)===!0:!1},Bw=async()=>{const e=fs();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Fw=8e3,Nw=15e3,Mw=400,Ew=async(e,t,s,n)=>{const a=new AbortController,i=window.setTimeout(()=>a.abort(),s);try{return await e.fetch(t,{...n,signal:a.signal})}finally{window.clearTimeout(i)}},Cg=async(e,t,s,n)=>{for(;;){const a=s-Date.now();if(a<=0)throw new Error("relay probe deadline exceeded");try{return await Ew(e,t,Math.min(Fw,a),n)}catch(i){if(e.getStatus().state==="error"||Date.now()>=s)throw i;await new Promise(o=>window.setTimeout(o,Mw))}}},Lw=async(e,t)=>{const s=Zl({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),n=Date.now(),a=n+Nw;let i=!1;try{if(!(await Cg(s,"/health",a)).ok)return{status:"unreachable",latencyMs:0};const r=new Headers({Accept:"application/json"});for(const[d,u]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&r.set(d,u);const c=t?.clientToken?.trim();c&&r.set("Authorization",`Bearer ${c}`);const l=await Cg(s,"/auth/session",a,{headers:r});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-n)}:l.ok?(i=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-n),...i?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:Oy(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{i||s.close()}},sr=async(e,t)=>{const s=fs();if(!s)return{status:"unreachable",latencyMs:0};const n=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!Yn(n))return{status:"unreachable",latencyMs:0};const a=n.status,i=a==="ok"||a==="auth"||a==="update-recommended"||a==="incompatible"||a==="wrong-service"||a==="unreachable"?a:"unreachable",o=vg(n,"latencyMs")??vg(n,"latency_ms")??0;return{status:i,latencyMs:o}},qw=we("status",[p({status:y("started")}),p({status:y("auth")}),p({status:y("failed"),error:g().nullable()})]),XM=async e=>{const t=fs();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),n=qw.safeParse(s);return n.success?n.data:{status:"failed",error:null}},Vw=600*1e3,Uw=3e3,eE=async(e,{maxWaitMs:t=Vw,intervalMs:s=Uw,readHosts:n=ui,probe:a=sr}={})=>{const i=Date.now()+t;for(;Date.now()<i;){await new Promise(c=>setTimeout(c,Math.min(s,Math.max(0,i-Date.now()))));const o=(await n()).hosts.find(c=>c.id===e);if(!o)return"timeout";const r=await a(Un(o),{clientToken:o.clientToken,requestHeaders:o.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},tE=async(e,t)=>{const s=fs();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},sE=async e=>{const t=fs();t&&await t("desktop_new_window_for_host",{hostId:e})},Ds="local",Ww=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",Hw=(e,t)=>t?[{id:Ds,label:"Local",url:t},...e]:e,Gw=e=>e.id===Ds?"local":`host:${e.id}`,nE=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(m=>m.id===Ds)?.url||Ww(),n=ps(),a=qe(s)||s,i=qe(t)||t,o=D(),r=e.find(m=>m.relay&&Gw(m)===o);if(r)return{id:r.id,label:r.label,url:r.url};if(n&&_i(n,s))return{id:Ds,label:"Local",url:a};const c=e.find(m=>n?_i(n,Un(m)):!1);if(c)return{id:c.id,label:c.label,url:qe(Un(c))||Un(c)};if(t&&_i(t,s))return{id:Ds,label:"Local",url:a};const l=e.find(m=>t?_i(t,m.url):!1);if(l)return{id:l.id,label:l.label,url:qe(l.url)||l.url};const d=t.startsWith("openchamber-ui://");if(d&&s&&!n)return{id:Ds,label:"Local",url:a};const u=n?qe(n)||n:d?"":i;return{id:"custom",label:Lm(u||"Instance"),url:u}},Fo=new Map;let qm=0;const Ga=new Map,Wn=new Set;let Hc=0,Vm={byHostId:{},isProbing:!1};const Gc=new Set,No=()=>{Vm={byHostId:Object.fromEntries(Fo),isProbing:Hc>0};for(const e of Gc)try{e()}catch{}},aE=e=>(Gc.add(e),()=>{Gc.delete(e)}),iE=()=>Vm,Um=(e,t)=>{Fo.set(e,t),No()},oE=(e,t)=>{Ga.set(e,++qm),Wn.delete(e),Um(e,t)},rE=e=>Wn.has(e),_w=e=>{const t=new Set([Ds,...e]);let s=!1;for(const n of Array.from(Fo.keys()))t.has(n)||(Fo.delete(n),Ga.delete(n),Wn.delete(n),s=!0);s&&No()},Kw=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",Zw=async()=>un()?Dw().catch(()=>""):"",Jw=async(e,t)=>{const s=e.id===Ds?t:e.clientToken||"",n=async()=>{const o=await Lw(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:o.status,latencyMs:o.latencyMs};return o.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return n();const a=qe(un()?Un(e):e.url);if(!a)return{status:"unreachable",latencyMs:0};const i=await sr(a,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Kw(i.status)&&e.relay){const o=await n();if(o.status==="ok"||o.status==="relay-limit")return o}return{status:i.status,latencyMs:i.latencyMs}},$w=async e=>{if(!Ye())return;const t=++qm;for(const s of e)Ga.set(s.id,t),Wn.add(s.id);Hc+=1,No();try{const s=await Zw();await Promise.all(e.map(async n=>{const a=await Jw(n,s);Ga.get(n.id)===t&&(Wn.delete(n.id),Um(n.id,a))}))}finally{for(const s of e)Ga.get(s.id)===t&&Wn.delete(s.id);Hc-=1,No()}};let Sg=!1;const Qw=async()=>{if(Sg||!Ye())return;Sg=!0;const e=await ui().catch(()=>null);e&&(_w(e.hosts.map(t=>t.id)),await $w(Hw(e.hosts,e.localOrigin)))},Yw=5e3,Xw=1500;let Fr=!1;const Nr=e=>{const t=String(e??"").trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString())}catch{return null}},ev=async e=>{if(!un()||Fr)return;const t=`host:${e}`;if(D()===t){Fr=!0;try{const s=await ui().catch(()=>null),n=s?.hosts.find(b=>b.id===e);if(!s||!n?.relay)return;const a=n.apiUrl?qe(n.apiUrl):null;if(a&&a.startsWith("https://"))return;const i=await C("/api/client-auth/connection/candidates").catch(()=>null);if(!i?.ok)return;const o=await i.json().catch(()=>null);if(!o||o.serverId!==n.relay.serverId)return;const r=Array.isArray(o.candidates)?o.candidates:[],c=[];for(const b of r){if(!b||typeof b!="object")continue;const k=b;if(k.type!=="lan"||typeof k.url!="string")continue;const w=qe(k.url);w&&!c.includes(w)&&c.push(w)}if(c.length===0)return;const l=a&&c.includes(a)?a:c[0],d=Nr(l);d&&d!==Nr(a)&&await Ow({hosts:s.hosts.map(b=>b.id===e?{...b,apiUrl:l}:b),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const m=(await ui().catch(()=>null))?.hosts.find(b=>b.id===e)??null;if(!m||!d||Nr(m.apiUrl)!==d)return;const f=await sr(l,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(f.status==="unreachable"||f.status==="wrong-service"||f.status==="incompatible"||D()!==t)return;Lc({apiBaseUrl:l,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:t})}finally{Fr=!1}}},tv=e=>{typeof window>"u"||window.setTimeout(()=>{ev(e).catch(()=>{})},Yw)},Pg=async(e,t)=>{if(!un())return;const s=await ui().catch(()=>null);if(!s)return;const n=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!n)return;const a=s.hosts.find(m=>m.id===n);if(!a?.relay)return;const i=`host:${a.id}`;if(D()===i&&!t?.reconnectActive)return;const o=m=>{Lc({apiBaseUrl:m,clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,runtimeKey:i})},r=()=>{Lc({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:a.clientToken||null,runtimeKey:i,relay:a.relay??void 0}),tv(a.id)},c=a.apiUrl?qe(Un(a)):null;if(!c){r();return}const l=m=>m.status!=="unreachable"&&m.status!=="wrong-service"&&m.status!=="incompatible",d=sr(c,{clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,expectedServerId:a.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),u=await Promise.race([d,new Promise(m=>setTimeout(()=>m(null),Xw))]);if(u){if(l(u)){o(c);return}r();return}r(),d.then(m=>{l(m)&&D()===i&&o(c)})},sv=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class It extends Error{reason;status;constructor(t,s={}){super(t),this.name="FilesystemError",this.reason=s.reason??"unknown",this.status=s.status}}const nv=e=>e instanceof It||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),_a=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},av=p({message:g()}),cE=e=>{if(nv(e)&&e.reason==="not-found")return!0;const t=av.safeParse(e),n=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return n.includes("file not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")},Ws=new Map;let Mr;async function Ag(e){const t=ls().api("/api").replace(/\/api\/?$/,""),s=ca(),n=await Tm();if(D()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(i,o)=>{const r=i instanceof Request?i.url:String(i),c=r.startsWith("/")?`${t}${r}`:r,l=new Headers(i instanceof Request?i.headers:void 0);return new Headers(Do(o?.headers)??o?.headers).forEach((d,u)=>l.set(u,d)),n.forEach((d,u)=>l.set(u,d)),s?s.fetch(i,{...o,headers:l}):(ss(c,l),Nm(i instanceof Request?new Request(c,i):c,{...o,headers:l}))},baseUrl:t}}async function Wm(e){const t=!!ps()&&!ca(),s=await Ag(e);return async n=>{let a=!1;const i=async()=>{if(!a){a=!0;try{const r=D()===e;if(!t&&!r)return;await n(r?await Ag(e):s),Ws.get(e)?.delete(i),Ws.get(e)?.size===0&&Ws.delete(e),Ws.size===0&&(Mr?.(),Mr=void 0)}catch{}finally{a=!1}}},o=Ws.get(e)??new Set;o.add(i),Ws.set(e,o),Mr??=Yo(({runtimeKey:r})=>{for(const c of Ws.get(r)??[])c()}),await i()}}const Mo=()=>({active:0,waiters:[],activeSessionWaiters:[]});let zs=Mo(),on=Mo();const iv=3,zg=2;Qo(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[zs,on];zs=Mo(),on=Mo();for(const n of s){for(const a of[...n.activeSessionWaiters,...n.waiters])a(!1);n.activeSessionWaiters.length=0,n.waiters.length=0}});const xg=()=>{for(;zs.active+on.active<iv;){const e=on.active<zg&&on.waiters.length>0?on:zs.active<zg&&(zs.activeSessionWaiters.length>0||zs.waiters.length>0)?zs:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(!0)}};async function Hm(e,t,s){const n=am();if(await new Promise(i=>{s==="active-session"?e.activeSessionWaiters.push(i):e.waiters.push(i),xg()}))try{if(!n())return;const i=await t();return n()?i:void 0}finally{e.active-=1,xg()}}const ov=(e,t="normal")=>Hm(zs,e,t),lE=e=>Hm(on,e,"normal"),Gm="/api/opencode/trust",rv="opencode_trust_required",cv=p({kind:R(["plugin","package","mcp","lsp","formatter","shell","config"]),source:g(),name:g(),detail:g()}),lv=p({directory:g(),trusted:z(),fingerprint:g().nullable(),items:x(cv)}),dv=p({code:y(rv),directory:g()});let cn=null;const _c=new Set,Fa=new Map,mi=new Set;let Kc=Promise.resolve(),xs=0;const Er=()=>{for(const e of _c)e()},dE=()=>cn,gE=e=>(_c.add(e),()=>{_c.delete(e)}),pE=e=>cn?cn.settle(e):Promise.resolve("skipped");Qo(()=>{xs+=1,cn?.settle("skip"),Fa.clear(),mi.clear(),Kc=Promise.resolve()});const gv=()=>{mi.clear()},pv=async e=>{if(e.status!==403)return null;try{const t=dv.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},_m=async e=>lv.parse(await e.json()),Lr=async e=>{const t=await C(Gm,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return _m(t)},uv=async e=>{const t=await C(Gm,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({directory:e.directory,fingerprint:e.fingerprint})});if(t.status===409)return{kind:"changed",assessment:await _m(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},mv=(e,t)=>new Promise(s=>{const n=a=>{if(t!==xs){s(!1);return}cn={directory:a.directory,items:a.items,settle:async i=>{if(i==="skip")return mi.add(`${a.directory}
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CRnROUpT.js","assets/vendor-react--VO_rL_p.js","assets/vendor-scheduler-7OC5HNn7.js","assets/zh-CN-C4Ip1vNN.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-zustand-C9tWdk0j.js","assets/vendor-zod-Csf1sqWl.js","assets/vendor-opencode-client-CqFY51gT.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/vendor-streamdown-BbSYZ3NF.js","assets/vendor-markdown-BTUqNk6W.js","assets/vendor-mdast-util-from-markdown-CZHjOE75.js","assets/vendor-micromark-util-decode-numeric-character-reference-CNs1qBpV.js","assets/vendor-micromark-util-decode-string-fHsnqYdj.js","assets/vendor-decode-named-character-reference-C3-224fz.js","assets/vendor-micromark-util-normalize-identifier-C9ANKk3v.js","assets/vendor-micromark-AWM-NZXP.js","assets/vendor-micromark-util-combine-extensions-d8XJZrgA.js","assets/vendor-micromark-util-chunked-DrRIdSP-.js","assets/vendor-micromark-factory-space-PzSHLgmq.js","assets/vendor-micromark-util-character-CW3Cu1MS.js","assets/vendor-micromark-core-commonmark-kzTLNXAm.js","assets/vendor-micromark-util-classify-character-tcLuZZwM.js","assets/vendor-micromark-util-resolve-all-PQCKh0dx.js","assets/vendor-micromark-util-subtokenize-BF1Jf29a.js","assets/vendor-micromark-factory-destination-Sj0xfi0V.js","assets/vendor-micromark-factory-label-amyP0HdC.js","assets/vendor-micromark-factory-title-khnLkZK6.js","assets/vendor-micromark-factory-whitespace-eIB00uTl.js","assets/vendor-micromark-util-html-tag-name-DbKNfynz.js","assets/vendor-unist-util-stringify-position-Ch_qCilz.js","assets/vendor-mdast-util-to-string-C_aolqmU.js","assets/vendor-unist-util-visit-DhPeCsfG.js","assets/vendor-unist-util-visit-parents-DlviEg7Z.js","assets/vendor-unist-util-is-BPZGFiMU.js","assets/vendor-hast-util-raw-DvvLJg15.js","assets/vendor-ungap-structured-clone--gfxRhYI.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-parse5-DwmzEj2o.js","assets/vendor-entities-wUUgTZDW.js","assets/vendor-web-namespaces-bsVAaBS1.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-unist-util-position-60F3QETU.js","assets/vendor-hast-util-from-parse5-Ba3T6RJI.js","assets/vendor-devlop-0Dp3JUBc.js","assets/vendor-property-information-Boo8Xpef.js","assets/vendor-hastscript-BrPNioaz.js","assets/vendor-comma-separated-tokens-CRUGqg4f.js","assets/vendor-space-separated-tokens-D7QSIrTI.js","assets/vendor-hast-util-parse-selector-TXfch5wI.js","assets/vendor-vfile-location-LfEFwJ2h.js","assets/vendor-hast-util-to-parse5-BoysVIPW.js","assets/vendor-hast-util-sanitize-2aGO5ay8.js","assets/vendor-micromark-extension-gfm-CsfPlnlB.js","assets/vendor-micromark-extension-gfm-autolink-literal-BYug7onl.js","assets/vendor-micromark-extension-gfm-footnote-OFl1FCH2.js","assets/vendor-micromark-extension-gfm-strikethrough-CyFiuwBf.js","assets/vendor-micromark-extension-gfm-table-dgw4LfUw.js","assets/vendor-micromark-extension-gfm-task-list-item-Dnadzr9U.js","assets/vendor-mdast-util-gfm-CroMDYLM.js","assets/vendor-mdast-util-gfm-autolink-literal-CTruMtvI.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-mdast-util-find-and-replace-DB9iC-bx.js","assets/vendor-escape-string-regexp-BaJN9MlJ.js","assets/vendor-mdast-util-gfm-footnote-C-csI7OF.js","assets/vendor-mdast-util-gfm-strikethrough-BcskTdio.js","assets/vendor-mdast-util-gfm-table-DhPwQIyj.js","assets/vendor-markdown-table-DvhhVmnL.js","assets/vendor-mdast-util-to-markdown-Cl3qaiyc.js","assets/vendor-longest-streak-CtXnX3Xp.js","assets/vendor-mdast-util-phrasing-4oVbNLC3.js","assets/vendor-mdast-util-gfm-task-list-item-DMU5mK_M.js","assets/vendor-mdast-util-to-hast-CWnLaQSO.js","assets/vendor-micromark-util-sanitize-uri-BbwQ7CLk.js","assets/vendor-trim-lines-D8znQY54.js","assets/vendor-micromark-extension-cjk-friendly-BzZDGrF5.js","assets/vendor-micromark-extension-cjk-friendly-util-D5lVNoxW.js","assets/vendor-get-east-asian-width-CPhS2cOv.js","assets/vendor-micromark-util-symbol-JJPacVTp.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-BZ3pe_qd.js","assets/vendor-micromark-extension-cjk-friendly-gfm-strikethrough-CqW-Ep4M.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-BdPDQFO7.js","assets/vendor-hast-util-from-html-isomorphic-B0Kn01s9.js","assets/vendor-hast-util-from-dom-DeNf9aYW.js","assets/vendor-katex-DBqql0K7.js","assets/vendor-hast-util-to-text-0GXLnBvt.js","assets/vendor-hast-util-is-element-CuOmiqQi.js","assets/vendor-unist-util-find-after-CMaZmLxc.js","assets/vendor-micromark-extension-math-BRFoDziv.js","assets/vendor-mdast-util-math-wB-IJCL0.js","assets/vendor-remend-r8cP_t-e.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-marked-DN3zOnEe.js","assets/vendor-hast-util-to-jsx-runtime-Bq6JeJCx.js","assets/vendor-style-to-js-CI2G4dgu.js","assets/vendor-style-to-object-BAv4SQXc.js","assets/vendor-inline-style-parser-BlqBsVO4.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-estree-util-is-identifier-name-BgBfM8ME.js","assets/vendor-vfile-message-DqhD22jI.js","assets/vendor-unified-1CQKw2_w.js","assets/vendor-bail-FqpXQuLt.js","assets/vendor-extend-B94qxKr5.js","assets/vendor-is-plain-obj-C1gvLhAf.js","assets/vendor-trough-B_b8ryxu.js","assets/vendor-vfile-BCWrK60u.js","assets/vendor-html-url-attributes-D46m5wfe.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/fr-BKEy-Z_2.js","assets/nl-X6CZmwET.js","assets/zh-TW-BmwR7rb1.js","assets/es-DMJlwy06.js","assets/pt-BR-QNheuCzR.js","assets/uk-Dos-a0OZ.js","assets/ko-DXd5Gg_L.js","assets/pl-CmAyO7EH.js","assets/de-DM_yQ7AG.js","assets/ja-lqTz_4gG.js","assets/tr-4WQrywE1.js","assets/ar-BrwaPZTB.js","assets/he-BnqH_lWh.js","assets/vendor-capacitor-app-BrDJj9I_.js"])))=>i.map(i=>d[i]);
2
+ import{_ as Ee}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as yt,d as oa,p as Pi,a as ek}from"./vendor-zustand-C9tWdk0j.js";import{o as p,s as g,n as v,l as y,e as z,d as x,h as we,_ as R,u as J,a as bt,f as Y,j as zo,i as tk,k as xo,p as oi,q as Fu,v as Mi}from"./vendor-zod-Csf1sqWl.js";import{e as Nu,C as ng}from"./vendor-opencode-client-CqFY51gT.js";import{f as Ft,R as Kn,r as sk}from"./vendor-react--VO_rL_p.js";import{F as Mu}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as nk}from"./vendor-streamdown-BbSYZ3NF.js";import{u as ak}from"./vendor-unified-1CQKw2_w.js";import{c as ik}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as ok}from"./vendor-capacitor-core-B4EWRrHz.js";const Ua=1,rk=p({type:y("relay-retire"),code:v().int(),reason:g().catch("")}),ck=e=>{try{const t=rk.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},lk="openchamber-relay-v1",Eu=1,Lu=12,Wa=1+Lu,ri=64*1024,ci=5,To=128,qu=0,Vu=1,Zn=4,dk=1+Zn,Rc=ri-ci-dk,gk="x-openchamber-tunnel-accept-encoding",pk="x-openchamber-tunnel-content-encoding",se={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},uk=new Set(Object.values(se)),mk=e=>uk.has(e),Bs={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},rs=globalThis.crypto.subtle,Uu={name:"ECDH",namedCurve:"P-256"},Wu=16,zr=32,hk=16,jc=4,Hu=8;class Os extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const fk=()=>rs.generateKey(Uu,!0,["deriveBits"]),bk=async e=>{const t=await rs.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},kk=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Os("invalid ECDH public key JWK");try{return await rs.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Uu,!0,[])}catch{throw new Os("invalid ECDH public key JWK")}},yk=()=>{const e=new Uint8Array(Wu);return globalThis.crypto.getRandomValues(e),e},wk=async(e,t,s)=>{if(s.length!==Wu)throw new Os("invalid handshake nonce length");const n=await rs.deriveBits({name:"ECDH",public:t},e,256),a=await rs.importKey("raw",n,"HKDF",!1,["deriveBits"]),i=new Uint8Array(await rs.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(lk)},a,zr*2*8)),o=(r,c)=>rs.importKey("raw",r,{name:"AES-GCM"},!1,c);return{clientToHost:await o(i.slice(0,zr),["encrypt","decrypt"]),hostToClient:await o(i.slice(zr),["encrypt","decrypt"])}},vk=(e,t,s)=>{for(let n=Hu-1;n>=0;n-=1)e[t+n]=Number(s&0xffn),s>>=8n},Ck=(e,t)=>{let s=0n;for(let n=0;n<Hu;n+=1)s=s<<8n|BigInt(e[t+n]);return s},Sk=e=>{const t=new Uint8Array(jc);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(n){if(n.length>ri)throw new Os("plaintext frame exceeds maximum size");s+=1n;const a=new Uint8Array(Lu);a.set(t,0),vk(a,jc,s);const i=new Uint8Array(await rs.encrypt({name:"AES-GCM",iv:a},e,n)),o=new Uint8Array(Wa+i.length);return o[0]=Eu,o.set(a,1),o.set(i,Wa),o}}},Pk=e=>{let t=0n;return{async decrypt(s){if(s.length<Wa+hk)throw new Os("encrypted frame too short");if(s[0]!==Eu)throw new Os("unsupported encrypted frame version");const n=s.slice(1,Wa),a=Ck(n,jc);if(a<=t)throw new Os("frame counter regression");let i;try{i=await rs.decrypt({name:"AES-GCM",iv:n},e,s.slice(Wa))}catch{throw new Os("frame decryption failed")}return t=a,new Uint8Array(i)}}},Ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ak=e=>{let t="";for(let s=0;s<e.length;s+=3){const n=e[s],a=s+1<e.length?e[s+1]:void 0,i=s+2<e.length?e[s+2]:void 0;t+=Ei[n>>2],t+=Ei[(n&3)<<4|(a??0)>>4],a!==void 0&&(t+=Ei[(a&15)<<2|(i??0)>>6]),i!==void 0&&(t+=Ei[i&63])}return t},ag=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const s=t;if(s.v!==Ua)return null;const n=s.batch===!0,a=s.flowControl===!0;return s.t==="ready"?{t:"ready",v:Ua,batch:n,flowControl:a}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:Ua,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:n,flowControl:a}:null},zk=e=>({type:"fail",closeCode:Bs.ChannelFailure,reason:e}),xk=async(e,t={})=>{const s=t.batch!==!1,n=await kk(e),a=await fk(),i=yk(),o={t:"hello",v:Ua,clientPubJwk:await bk(a.publicKey),nonce:Ak(i)};s&&(o.batch=!0),t.flowControl!==!1&&(o.flowControl=!0);let r=!1;return{helloText:JSON.stringify(o),get established(){return r},async handleText(c){if(r)return ag(c)?.t==="ready"?{type:"ignore"}:zk("plaintext frame on established channel");const l=ag(c);if(l?.t!=="ready")return{type:"ignore"};const d=await wk(a.privateKey,n,i);return r=!0,{type:"established",batch:s&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:Sk(d.clientToHost),decryptor:Pk(d.hostToClient)}}}}},Gu=4294967295,Tk=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class Le extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const At=(e,t,s,n=!1)=>{if(!Number.isInteger(t)||t<0||t>Gu)throw new Le("invalid stream id");if(s.length>Rc)throw new Le("tunnel payload exceeds maximum size");const a=new Uint8Array(ci+s.length);return a[0]=n?e|To:e,a[1]=t>>>24&255,a[2]=t>>>16&255,a[3]=t>>>8&255,a[4]=t&255,a.set(s,ci),a},Ik=e=>{if(e.length<ci)throw new Le("tunnel frame too short");const t=e[0],s=(t&To)!==0,n=t&~To;if(!mk(n))throw new Le(`unknown tunnel frame type ${n}`);const a=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:n,streamId:a,payload:e.slice(ci),hasMoreFragments:s}},Rk=new TextEncoder,jk=new TextDecoder,Li=e=>Rk.encode(JSON.stringify(e)),qi=(e,t)=>{let s;try{s=JSON.parse(jk.decode(e))}catch{throw new Le("malformed JSON tunnel payload")}if(!t(s))throw new Le("unexpected JSON tunnel payload shape");return s},_u=(e,t=Rc)=>{if(t<=0||t>Rc)throw new Le("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},ig=(e,t,s)=>{const n=_u(s);return n.map((a,i)=>At(e,t,a,i<n.length-1))},Ok=(e=16*1024*1024)=>{const t=new Map;return{push(s){const n=`${s.streamId}:${s.frameType}`,a=t.get(n);if(!s.hasMoreFragments&&!a)return s.payload;const i=a?.chunks??[],o=(a?.totalBytes??0)+s.payload.length;if(o>e)throw t.delete(n),new Le("fragmented message exceeds maximum size");if(i.push(s.payload),s.hasMoreFragments)return t.set(n,{chunks:i,totalBytes:o}),null;t.delete(n);const r=new Uint8Array(o);let c=0;for(const l of i)r.set(l,c),c+=l.length;return r},dropStream(s){for(const n of t.keys())n.startsWith(`${s}:`)&&t.delete(n)}}},Dk=e=>{if(e.length===0)throw new Le("cannot encode an empty frame batch");if(e.length===1){const a=e[0],i=new Uint8Array(1+a.length);if(i[0]=qu,i.set(a,1),i.length>ri)throw new Le("frame batch exceeds maximum plaintext size");return i}let t=1;for(const a of e)t+=Zn+a.length;if(t>ri)throw new Le("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=Vu;let n=1;for(const a of e)s[n]=a.length>>>24&255,s[n+1]=a.length>>>16&255,s[n+2]=a.length>>>8&255,s[n+3]=a.length&255,n+=Zn,s.set(a,n),n+=a.length;return s},Bk=e=>{if(e.length<1)throw new Le("empty batch plaintext");const t=e[0];if(t===qu)return[e.slice(1)];if(t!==Vu)throw new Le(`unknown batch container tag ${t}`);const s=[];let n=1;for(;n<e.length;){if(n+Zn>e.length)throw new Le("truncated batch frame length");const a=(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0;if(n+=Zn,n+a>e.length)throw new Le("truncated batch frame body");s.push(e.slice(n,n+a)),n+=a}if(s.length===0)throw new Le("empty frame batch");return s},Fk=new Set([se.HttpBody,se.WsText,se.WsBinary]),Ku=150,Nk=24*1024,Mk=32,Ek=e=>{const t=e.windowMs??Ku,s=e.maxBatchBytes??Nk,n=e.maxBatchFrames??Mk,a=e.now??(()=>Date.now()),i=e.setTimer??((k,w)=>setTimeout(k,w)),o=e.clearTimer??(k=>clearTimeout(k));let r=[],c=0,l=null,d=0,u=!1;const m=()=>{l!==null&&(o(l),l=null)},f=()=>{if(m(),r.length===0)return;const k=r;r=[],c=0,d=a(),e.sendBatch(Dk(k))};return{enqueue:k=>{if(u)return;const w=k[0]&~To;if(!Fk.has(w)){r.push(k),f();return}const T=a();if(r.length===0&&T-d>=t){r.push(k),f();return}const S=Zn+k.length;if(r.length>0&&1+c+S>ri&&f(),r.push(k),c+=S,c>=s||r.length>=n){f();return}l===null&&(l=i(f,t))},flush:f,dispose(){u=!0,m(),r=[],c=0}}},Lk=()=>{let e=1;return{next(){if(e>Gu)throw new Le("stream id space exhausted");const t=e;return e+=2,t}}},$o=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qk=e=>$o(e)&&Object.values(e).every(t=>typeof t=="string"),Vk=e=>$o(e)&&typeof e.status=="number"&&qk(e.headers),og=e=>$o(e)&&typeof e.reason=="string",Uk=e=>$o(e)&&typeof e.code=="number"&&typeof e.reason=="string",Zu=/^[a-z][a-z\d+.-]*:\/\//i,Hl="http://tunnel.invalid",Wk=e=>{try{const t=Zu.test(e)?new URL(e):new URL(e,Hl);return`${t.pathname}${t.search}`}catch{return e}},Vi=e=>({async*[Symbol.asyncIterator](){yield e}}),Hk=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:n}=await t.read();if(s)return;n&&(yield n)}}finally{t.releaseLock()}}}),Gk=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},_k=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Hk(e)};if(typeof e=="string")return{body:Vi(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Vi(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Vi(Gk(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,n=new Uint8Array(await t.arrayBuffer());return{body:Vi(n),contentType:s}},Kk=async(e,t)=>{let s;const n=new Headers;let a="GET",i=null,o;e instanceof Request?(s=e.url,a=e.method,e.headers.forEach((u,m)=>n.set(m,u)),o=e.signal,i=e.body):s=e.toString(),t&&(t.method&&(a=t.method),t.headers&&new Headers(t.headers).forEach((u,m)=>n.set(m,u)),t.body!==void 0&&(i=t.body),t.signal&&(o=t.signal));const r=Zu.test(s)?new URL(s):new URL(s,Hl),{body:c,contentType:l}=await _k(i);l&&!n.has("content-type")&&n.set("content-type",l);const d={};return n.forEach((u,m)=>{d[m]=u}),{method:a.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:d,body:c,signal:o}},Ju="__openchamberAmbiguousTransport",$u=new WeakSet,Zk=e=>($u.add(e),e),Jk=e=>$u.has(e),Oc=e=>(Object.defineProperty(e,Ju,{value:!0,enumerable:!1,configurable:!0}),e),$k=e=>!e||typeof e!="object"?!1:e[Ju]===!0,Qk=["local","remote",null],Yk=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Qu(e){if(!e||typeof e!="object")return{valid:!1};const t=e,s=t.localAvailable===!1?{localAvailable:!1}:{},n=t.target,a=t.status;if(n!==null&&(typeof n!="string"||!Qk.includes(n)))return{valid:!1};if(typeof a!="string"||!Yk.includes(a))return{valid:!1};if(n==="remote"||n==="local"){if(a==="ok"&&n==="local"){const i={target:"local",status:"ok",...s},o=g().min(1).safeParse(t.sshStartupFallbackHostId);return o.success&&(i.sshStartupFallbackHostId=o.data),{valid:!0,outcome:i}}if(a==="ok"&&n==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(a==="unreachable")return n==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(a==="incompatible"||a==="wrong-service")return n!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:a,hostId:t.hostId,url:t.url,...s}};if(a==="missing")return n!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(n===null){if(a==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...s}};if(a==="missing")return{valid:!1}}return{valid:!1}}function WN(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...s};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...s}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...s};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...s};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...s};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...s};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...s};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...s}}return null}function HN(e){return!e.isDesktopShell||e.bootOutcomeKnown}function GN(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function Yu(){if(Xk()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=Qu(t);return s.valid?s.outcome:null}function Xk(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Qu(e).valid?"valid":"malformed"}const Io=/^[a-z][a-z\d+.-]*:\/\//i,ey=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Ro=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),ty=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Ro(e)},sy=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Ro(e)},ny=()=>Object.keys(la()).length>0,ay=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Dc=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,a]of s)a!=null&&e.searchParams.set(n,String(a))},iy=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Dc({searchParams:s},t);const n=s.toString();return n?e.includes("?")?`${e}&${n}`:`${e}?${n}`:e},rg=(e,t,s)=>{if(Io.test(t)){const o=new URL(t);return Dc(o,s),o.toString()}const n=ey(t);if(!e)return iy(n,s);const a=new URL(e),i=new URL(`${a.origin}${a.pathname.replace(/\/+$/,"")}${n}`);return Dc(i,s),i.toString()},Ui=(e,t=Hy())=>{if(!t)return e;const s=Io.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),Io.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},Xu=(e,t)=>{const s=Io.test(e)?new URL(e):new URL(e,ay(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},cg=(e,t,s)=>{if(!ny())return null;const n=sy();if(!n)return null;try{const a=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${n}/`);a.searchParams.set("url",t);const i=Gy(n);return i&&a.searchParams.set("oc_url_token",i),e==="ws"?(a.protocol=a.protocol==="https:"?"wss:":"ws:",Xu(a.toString(),s)):a.toString()}catch{return null}},Gl=(e={})=>{const t=Ro(e.apiBaseUrl),s=Ro(e.realtimeBaseUrl),n=()=>t||ty(),a=()=>s||n(),i=(r,c)=>rg(n(),r,c),o=(r,c)=>rg(a(),r,c);return{api:i,authenticatedAsset:(r,c)=>Ui(i(r,c)),assetWithUrlToken:(r,c,l)=>Ui(i(r,l),c),auth:i,health:r=>i("/health",r),rawFile:(r,c)=>i("/api/fs/raw",{path:r,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(r,c)=>{const l=Ui(o(r,c));return cg("sse",l,e)||l},websocket:(r,c)=>{const l=Xu(Ui(o(r,c)),e);return cg("ws",l,e)||l}}};let jo=Gl();const ls=()=>jo,oy=e=>{jo=e},em=e=>(jo=Gl(e),jo),Bc="openchamber:runtime-endpoint-changed",Fc="openchamber:runtime-endpoint-will-change";let Jn="",li="",Nc=0,Mc=null;const xr=(e,t,s)=>{try{e[t]=s}catch{}},_l=e=>{try{const t=new URL(e);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,"")||"/",`url:${t.toString().replace(/\/+$/,"")}`}catch{return`url:${e.trim().replace(/\/+$/,"")||"default"}`}},ry="mobile-disconnected",cy="url:default",Ec=e=>e===""||e===cy||e===ry,tm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},sm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},nm=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ps=()=>Jn||tm(),ly=()=>{if(Mc!==null)return Mc;const e=ps();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let Tr="",lg=null,dg,gg;const pg=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(li)return li;const e=pg("__OPENCHAMBER_API_BASE_URL__"),t=pg("__OPENCHAMBER_LOCAL_ORIGIN__");if(lg===Jn&&dg===e&&gg===t)return Tr;const s=ps();return Tr=nm(s,sm())?"local":_l(s),lg=Jn,dg=e,gg=t,Tr},am=()=>{const e=Nc,t=D();return()=>e===Nc&&t===D()},dy=(e={})=>{if(Jn||li)return;const t=e.apiBaseUrl?.trim()||tm(),s=globalThis.window?.location?.origin??"",n=/^https?:\/\//.test(s)?s:"";if(!t&&!n)return;const a=sm(),i=a&&(!t||nm(t,a));Jn=t,li=e.runtimeKey?.trim()||(i?"local":_l(t||n))},Lc=e=>{const t=e.apiBaseUrl.trim(),s=ps(),n=D(),a=e.runtimeKey?.trim()||_l(t),i=e.sshForwarded??(t===s&&a===n&&ly()),o={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:a,previousRuntimeKey:n};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fc,{detail:o})),Jn=t,li=a,a!==n&&(Nc+=1),Mc=i,typeof window<"u"){const r=window;xr(r,"__OPENCHAMBER_API_BASE_URL__",t),xr(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),xr(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}em({apiBaseUrl:t,realtimeBaseUrl:t}),wm(e.requestHeaders||null),ym(e.clientToken||null),e.relay?My(e.relay):Ey(),tr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bc,{detail:o}))},Qo=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Fc,t),()=>window.removeEventListener(Fc,t)},Yo=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Bc,t),()=>window.removeEventListener(Bc,t)};let qc=null;const _N=e=>{qc=e},ra=()=>qc||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Kl=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,di=()=>{const e=Kl();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():!1},im=(e=Kl())=>!!e,gy=e=>e==="stable"||e==="canary",py=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,KN=e=>{const t=py.exec(e??"");if(!t)return null;const[,s,n,a,i,o]=t;return{release:s,builtOn:new Date(Date.UTC(Number(n),Number(a)-1,Number(i))),build:o?Number(o):null}},uy=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),ZN=(e,t,s)=>{const n=uy(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${n} #${e.build}`:n},om=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,us=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,un=()=>om()?.runtime==="electron",rm=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},my="right",JN=()=>{if(!un())return!1;const e=rm();return e==="linux"?om()?.nativeFrame!==!0:e==="win32"},$N=e=>e==="left"?"left":my,QN=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Qe=()=>typeof us()?.invoke=="function",ct=()=>un()&&Qe(),hy=()=>{const e=us()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>g().parse(await t()),writeText:async n=>{y(!0).parse(await s(n))}}}},fy=()=>{if(us()?.pickThemeFile)return{async pick(){const e=us()?.pickThemeFile;return e?{status:"picked",file:p({name:g(),size:v().nonnegative(),text:g()}).nullable().parse(await e())}:{status:"unsupported"}}}},ee=async(e,t)=>{const s=us();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},YN=e=>{rm()!=="darwin"||!ct()||ee("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},XN=()=>({apiBaseUrl:ps(),clientToken:Yl(),runtimeKey:D()}),eM=async()=>{if(!Ye()||!Ce())return!1;const e=ps();try{const t=z().safeParse(await ee("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===ps()}catch{return!1}},tM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},sM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},cm=e=>gy(e?.channel)?e.channel:null,nM=async()=>{if(!ct()||!Ce())return null;try{return cm(await ee("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},aM=async e=>{if(!ct()||!Ce())return null;try{return cm(await ee("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},iM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},oM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},rM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_mini_chat_global_shortcut");return!e||typeof e.supported!="boolean"||e.combo!==null&&typeof e.combo!="string"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get Mini Chat global shortcut status",e),null}},cM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_mini_chat_global_shortcut",{combo:e});return!t||typeof t.supported!="boolean"||t.combo!==null&&typeof t.combo!="string"||typeof t.active!="boolean"||t.error!==void 0&&t.error!=="unsupported-combo"?null:t}catch(t){return console.warn("Failed to set Mini Chat global shortcut",t),null}},by=p({supported:z(),enabled:z(),combo:g().nullable(),storedCombo:g().nullable(),active:z(),heightFraction:v(),error:y("unsupported-combo").optional()}),Xo=async(e,t,s)=>{if(!ct()||!Ce())return null;try{const n=by.safeParse(await ee(e,t));return n.success?n.data:null}catch(n){return console.warn(s,n),null}},lM=()=>Xo("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),dM=e=>Xo("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),gM=e=>Xo("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),pM=e=>Xo("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),uM=async()=>{if(!ct()||!Ce())return null;try{const e=await ee("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},mM=async e=>{if(!ct()||!Ce())return null;try{const t=await ee("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},ug=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},Ir=e=>{const t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith("/")?t:`${t}/`)}catch{return null}}},ky=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Sa=e=>{const t=ky(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ce=()=>{if(typeof window>"u"||!Ye())return!1;if(D()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Ir(e),s=Ir(ps());if(!s&&t&&Yu()?.target==="local")return!0;if(t&&s){if(t.origin===s.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&o===r&&Sa(t.hostname)&&Sa(s.hostname)}const n=Ir(window.location.origin);if(t&&n){if(t.origin===n.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&o===r&&Sa(t.hostname)&&Sa(n.hostname)}const a=ug(e),i=ug(window.location.origin)||window.location.origin;return a&&i&&a===i?!0:!!(n&&Sa(n.hostname))},Ye=()=>typeof window>"u"?!1:un(),hM=async()=>{if(!Ye())return null;const e=p({visible:z()}).safeParse(await ee("desktop_get_current_window_state"));return e.success?e.data.visible:null},fM=async()=>{if(!Ye())return!1;try{return!!await ee("desktop_focus_window")}catch{return!1}},bM=(e,t,s=null)=>!t||t===D()||!ct()?!1:(ee("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(a=>{console.warn("[desktop] failed to open host session",a)}),!0),lm=()=>Ye()&&Qe()&&Ce(),yy=x(p({sessionId:g().min(1),messageId:g().min(1).optional(),runtimeKey:g().min(1).optional(),requireKnownSession:z().optional()})),kM=async()=>{if(!Ye()||!Ce())return[];try{const e=yy.safeParse(await ee("desktop_take_pending_session_links"));return e.success?e.data.map(t=>({sessionId:t.sessionId,messageId:t.messageId??null,runtimeKey:t.runtimeKey??null,requireKnownSession:t.requireKnownSession===!0})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},wy=x(we("type",[p({type:y("pairing"),link:g().min(1)}),p({type:y("host"),hostId:g().min(1)})])),yM=async()=>{if(!Ye())return[];try{const e=wy.safeParse(await ee("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},vy=g().min(1),wM=e=>{if(!lm())return null;try{const t=vy.safeParse(us()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},vM=async()=>{if(!Ye())return!1;try{return await ee("desktop_start_window_drag"),!0}catch{return!1}},je=()=>im()?!0:ra()?.runtime?.isVSCode===!0,CM=()=>{const t=ra()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!je()},SM=(e,t=Ye())=>e==="web"&&!t,dm=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},PM=async e=>{if(lm())try{const t=await us()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},Cy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),AM=async e=>{if(Qe()&&Ce())try{const t=await us()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!Cy(t))return{success:!1,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:!0,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},zM=async e=>({success:!0}),xM=async e=>({success:!0}),TM=async()=>Qe()?await ee("desktop_check_for_updates"):null,IM=async e=>{if(!Qe())return!1;const t=us();let s=null,n=0,a;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",i=>{const o=i?.payload;if(!o||typeof o!="object")return;const r=o,c=typeof r.event=="string"?r.event:null,l=r.data&&typeof r.data=="object"?r.data:null;if(c==="Started"){n=0,a=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:n,total:a});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(n=d),typeof u=="number"&&(a=u),e({downloaded:n,total:a});return}c==="Finished"&&e({downloaded:n,total:a})})),await ee("desktop_download_and_install_update"),!0}catch(i){throw i instanceof Error?i:new Error(String(i))}finally{if(s)try{const i=s();i instanceof Promise&&await i}catch{}}},RM=async()=>Qe()?(await ee("desktop_restart"),!0):!1,jM=async()=>{if(!Qe())return!1;try{return await ee("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},OM=async()=>{if(!Qe()||!Ce())return null;try{const e=await ee("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},Sy=async(e,t)=>{if(!Qe()||!Ce())return!1;const s=e?.trim();if(!s)return!1;try{return await ee("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(n){return console.warn("Failed to open path",n),!1}},DM=async e=>{if(!Qe()||!Ce())return!1;const t=e?.trim();if(!t)return!1;try{return await ee("desktop_reveal_path",{path:t}),!0}catch{return Sy(t)}},BM=async(e,t)=>{if(!Qe()||!Ce())return null;const s=e?.trim();if(!s)return null;try{const n=await ee("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof n=="string"&&n.trim().length>0?n:null}catch(n){return console.warn("Failed to save markdown file",n),null}},FM=async(e,t,s)=>{if(!Qe()||!Ce())return!1;const n=e?.trim(),a=t?.trim(),i=s?.trim();if(!n||!a||!i)return!1;try{return await ee("desktop_open_in_app",{projectPath:n,appId:a,appName:i}),!0}catch(o){return console.warn("Failed to open project in app",o),!1}},NM=async(e,t,s)=>{if(!Qe()||!Ce())return!1;const n=e?.trim(),a=t?.trim(),i=s?.trim();if(!n||!a||!i)return!1;try{return await ee("desktop_open_file_in_app",{filePath:n,appId:a,appName:i}),!0}catch(o){return console.warn("Failed to open file in app",o),!1}},MM=async(e,t)=>{if(!Qe()||!Ce())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];if(s.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const n=await ee("desktop_get_installed_apps",{apps:s,force:t===!0?!0:void 0});if(!n||typeof n!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const a=n;return a.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(a.apps)?{apps:a.apps.filter(o=>o&&typeof o=="object").map(o=>{const r=o;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(o=>o.name.length>0),success:!0,hasCache:a.hasCache===!0,isCacheStale:a.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(n){return console.warn("Failed to fetch installed apps",n),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},EM=()=>navigator.platform.toLowerCase().startsWith("linux"),mn=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",LM=()=>typeof window>"u"||!mn()?!1:gm()==="ios"&&Py(),Py=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},gm=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return je()?"vscode":Ye()?"desktop":"web"},Ay="2.6.2-canary.20261104.6",Wi=new Uint8Array(0),zy=typeof DecompressionStream=="function",xy=e=>e.pipeThrough(new TransformStream({transform(t,s){s.enqueue(t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t))}})).pipeThrough(new DecompressionStream("gzip")),pm=e=>ArrayBuffer.isView(e)?e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e,Ty=new TextEncoder,Iy=new TextDecoder,Ct=e=>e instanceof Error?e:new Error(String(e)),Hi=()=>new DOMException("The operation was aborted.","AbortError"),Ry=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(pm(s))},close(s,n){e.close(s,n)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>t.onmessage?.({data:s.data}),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),e.onerror=()=>t.onerror?.(),t},jy=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(s){s&&(e.binaryType=s)},onopen:null,onmessage:null,onerror:null,onclose:null,send(s){e.send(pm(s))},close(s,n){e.close(s,n)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const n=s.data;(typeof n=="string"||n instanceof ArrayBuffer)&&t.onmessage?.({data:n})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},Oy=e=>e?.state==="error"&&e.closeCode===Bs.LimitExceeded,mg=0,Rr=1,hg=2,fg=3,Dy=new Set([Bs.AuthFailed,Bs.DuplicateClient,Bs.LimitExceeded]),By={[Bs.AuthFailed]:"relay authentication failed",[Bs.DuplicateClient]:"relay connection replaced by another client",[Bs.LimitExceeded]:"relay connection limit reached"},jr=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Zl=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,n=e.pingIntervalMs??3e4,a=e.pingTimeoutMs??15e3,i=e.batchWindowMs??Ku,o=e.batch!==!1,r=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(M=>Ry(new WebSocket(M)));let u=!1,m=null,f={state:"idle"};const b=new Set;let k=null,w=null,T=null,S=0,E=0,H=null,Z=[],N=!1;const ce=M=>{if(!(f.state===M.state&&f.lastError===M.lastError&&f.terminal===M.terminal&&f.closeCode===M.closeCode)){f=M;for(const le of b)try{le(f)}catch{}}},$=M=>{const le=Z;Z=[];for(const U of le)U.reject(M)},lt=M=>{const le=Z;Z=[];for(const U of le)U.resolve(M)},Xe=(M,le)=>{M.dead=!0;const U=Array.from(M.streams.values());M.streams.clear();for(const _ of U)try{_.fail(le)}catch{}},ka=()=>{H!==null&&(clearTimeout(H),H=null)},ya=()=>{if(!u){if(H!==null){if(jr())return;ka(),wt(),yn();return}jr()||Ls()}},Ls=()=>{u||m===null||(wt(),m=null,yn())},G=()=>{typeof document<"u"&&document.visibilityState==="visible"&&ya()},nt=()=>{N||typeof window>"u"||(N=!0,window.addEventListener("online",ya),typeof document<"u"&&document.addEventListener("visibilitychange",G))},wt=()=>{!N||typeof window>"u"||(N=!1,window.removeEventListener("online",ya),typeof document<"u"&&document.removeEventListener("visibilitychange",G))},wa=()=>{if(u||H!==null)return;const M=Math.max(0,E-1),le=r*2**Math.min(M,10),U=jr()?l:c,_=Math.min(U,le);nt(),H=setTimeout(()=>{H=null,wt(),yn()},_)},Cr=()=>{const M=new URL(e.relayUrl);return M.searchParams.set("v",String(Ua)),M.searchParams.set("role","client"),M.searchParams.set("serverId",e.serverId),M.searchParams.set("appId","openchamber"),M.searchParams.set("appVersion",Ay),M.searchParams.set("platform",gm()),e.grant&&M.searchParams.set("grant",e.grant),M.toString()},yn=async()=>{if(u)return;ka(),S+=1;const M=S;ce({state:E>0?"reconnecting":"connecting",lastError:f.lastError});let le;try{le=await xk(e.hostEncPubJwk,{batch:o,flowControl:e.flowControl})}catch(pe){if(M!==S||u)return;sg(M,Ct(pe),!0);return}if(M!==S||u)return;let U;try{U=d(Cr())}catch(pe){sg(M,Ct(pe));return}w=U;let _=!1,Q=null,ge=null,at=null,Fe=null,te=Promise.resolve(),ne=null,Te=null,Xt=!1,Oe=!1,De=0,Ne=0,Me=null,es=null,ve=Date.now();const bs=()=>{Me!==null&&(clearTimeout(Me),Me=null),Q!==null&&(clearInterval(Q),Q=null),ge!==null&&(clearTimeout(ge),ge=null),at!==null&&(clearInterval(at),at=null),Fe!==null&&(clearTimeout(Fe),Fe=null),es!==null&&(es.dispose(),es=null)};T=bs;function ue(pe,Se=!1,me=null){if(!(_||M!==S)){_=!0,me!==null&&(m=pe),bs(),ne&&(k=null,Xe(ne,new Error(`relay tunnel reset: ${pe.message}`))),$(pe);try{U.close()}catch{}if(w===U&&(w=null),!u){if(E+=1,me!==null){nt(),ce({state:"error",lastError:pe.message,terminal:!0,closeCode:me});return}ce({state:Se?"error":"reconnecting",lastError:pe.message}),wa()}}}const va=()=>{try{U.send(le.helloText)}catch{}},qs=(pe,Se,me)=>{Te=pe,Xt=Se,Oe=me,Q!==null&&(clearInterval(Q),Q=null),ge!==null&&(clearTimeout(ge),ge=null);const it=new Map,Ve=Lk(),vt=Ok();let Vs=Promise.resolve();const ks=Ca=>{Vs=Vs.then(async()=>{if(Us.dead)return;const Xb=await pe.encryptor.encrypt(Ca);Us.dead||U.send(Xb)}).catch(()=>{ue(new Error("relay encrypt/send failed"))})},Ar=Se?Ek({windowMs:i,sendBatch:ks}):null;es=Ar;const Us={streams:it,assembler:vt,nextStreamId:()=>Ve.next(),dead:!1,send(Ca){Us.dead||(Ar?Ar.enqueue(Ca):ks(Ca))}};ne=Us,k=Us,E=0,ve=Date.now(),ce({state:"connected"}),lt(Us),at=setInterval(()=>{Date.now()-ve<n||(Us.send(At(se.Ping,0,Wi)),Fe===null&&(Fe=setTimeout(()=>{Fe=null,ue(new Error("relay keepalive timeout"))},a)))},n)},Ni=()=>{Me!==null&&clearTimeout(Me),Me=null,!(!ne||ne.dead||De===Ne)&&(Ne=De,ne.send(At(se.DeliveryAck,0,Tk(De))))},Pr=(pe,Se)=>{let me;try{me=Ik(Se)}catch(vt){ue(Ct(vt));return}if(me.frameType===se.DeliveryAck){ue(new Error("unexpected downstream delivery acknowledgement"));return}if(Oe&&me.streamId!==0&&(De+=Se.length,Me===null&&(Me=setTimeout(Ni,10))),ve=Date.now(),Fe!==null&&(clearTimeout(Fe),Fe=null),me.frameType===se.Ping){pe.send(At(se.Pong,me.streamId,Wi));return}if(me.frameType===se.Pong)return;let it=me.payload;if(me.frameType===se.WsText||me.frameType===se.WsBinary){let vt;try{vt=pe.assembler.push(me)}catch(Vs){ue(Ct(Vs));return}if(vt===null)return;it=vt}else if(me.hasMoreFragments){ue(new Error("unexpected fragmented tunnel frame"));return}const Ve=pe.streams.get(me.streamId);Ve&&Ve.handleFrame(me.frameType,it)};U.onopen=()=>{_||M!==S||(va(),Q=setInterval(va,t))};const wn=pe=>{const Se=Dy.has(pe);ue(new Error(By[pe]??`relay socket closed (code ${pe})`),Se,Se?pe:null)};U.onmessage=pe=>{if(_||M!==S)return;const Se=pe.data;if(typeof Se=="string"){const it=ck(Se);if(it){wn(it.code);return}te=te.then(async()=>{if(_||M!==S)return;const Ve=await le.handleText(Se);if(Ve.type==="established"){if(Te)return;qs(Ve.channel,Ve.batch,Ve.flowControl)}else Ve.type==="fail"&&ue(new Error(`relay handshake failed: ${Ve.reason}`))}).catch(Ve=>{ue(Ct(Ve))});return}const me=Se instanceof ArrayBuffer?new Uint8Array(Se):Se instanceof Uint8Array?Se:null;me&&(te=te.then(async()=>{if(_||M!==S)return;const it=ne,Ve=Te;if(!it||!Ve){ue(new Error("encrypted frame before handshake completed"));return}let vt;try{vt=await Ve.decryptor.decrypt(me)}catch(ks){ue(Ct(ks));return}let Vs;try{Vs=Xt?Bk(vt):[vt]}catch(ks){ue(Ct(ks));return}for(const ks of Vs){if(_||M!==S||it.dead)return;Pr(it,ks)}Oe&&De-Ne>=16*1024&&Ni()}).catch(it=>{ue(Ct(it))}))},U.onclose=pe=>wn(pe.code),U.onerror=()=>{},ge=setTimeout(()=>{ge=null,ue(new Error("relay handshake timeout"),!0)},s);function sg(pe,Se,me=!1){pe!==S||u||($(Se),E+=1,ce({state:me?"error":"reconnecting",lastError:Se.message}),wa())}},Yt=M=>u?Promise.reject(new Error("relay tunnel closed")):M?.aborted?Promise.reject(Hi()):m?Promise.reject(m):k&&!k.dead?Promise.resolve(k):new Promise((le,U)=>{let _=null;const Q={resolve(ge){_&&M&&M.removeEventListener("abort",_),le(ge)},reject(ge){_&&M&&M.removeEventListener("abort",_),U(ge)}};M&&(_=()=>{Z=Z.filter(ge=>ge!==Q),U(Hi())},M.addEventListener("abort",_,{once:!0})),Z.push(Q)}),Sr=async(M,le)=>{const U=await Kk(M,le),_=U.signal;if(_?.aborted)throw Hi();const Q=await Yt(_),ge=Q.nextStreamId();return await new Promise((at,Fe)=>{let te=!1,ne=!1,Te=null,Xt=null;const Oe=()=>{Q.streams.delete(ge),Q.assembler.dropStream(ge),Xt&&_&&_.removeEventListener("abort",Xt)},De=ve=>{if(!ne){if(ne=!0,Oe(),!te){Fe(ve);return}try{Te?.error(ve)}catch{}}},Ne=ve=>{Q.dead||Q.send(At(se.StreamAbort,ge,Li({reason:ve})))},Me=ve=>Oc(new Error(ve));Xt=()=>{Ne("aborted"),De(Hi())},Q.streams.set(ge,{handleFrame(ve,bs){if(ve===se.HttpResponse){if(te||ne)return;let ue;try{ue=qi(bs,Vk)}catch(wn){Ne("malformed response head"),De(Me(Ct(wn).message));return}const va=ue.status===204||ue.status===205||ue.status===304;let qs=null;va||(qs=new ReadableStream({start(wn){Te=wn},cancel(){ne||(ne=!0,Oe(),Ne("response body cancelled"))}})),te=!0;const{[pk]:Ni,...Pr}=ue.headers;qs&&Ni==="gzip"&&(qs=xy(qs)),at(new Response(qs,{status:ue.status,headers:Pr})),va&&(ne=!0,Oe());return}if(ve===se.HttpBody){if(!te||ne)return;try{Te?.enqueue(bs)}catch{}return}if(ve===se.StreamEnd){if(ne)return;if(!te){De(Me("tunnel stream ended before response head"));return}ne=!0,Oe();try{Te?.close()}catch{}return}if(ve===se.StreamAbort){let ue="stream aborted by host";try{ue=qi(bs,og).reason}catch{}De(Me(ue))}},fail(ve){De(Me(ve.message))}}),_&&_.addEventListener("abort",Xt,{once:!0});const es={method:U.method,path:U.path,query:U.query,headers:zy?{...U.headers,[gk]:"gzip"}:U.headers,hasBody:U.body!==null};Q.send(At(se.HttpRequest,ge,Li(es))),(async()=>{try{let ve=!1;if(U.body)for await(const bs of U.body){if(ne||Q.dead)return;for(const ue of _u(bs))Q.send(At(se.HttpBody,ge,ue)),ve=!0}!ne&&!Q.dead&&(U.body&&!ve&&Q.send(At(se.HttpBody,ge,Wi)),Q.send(At(se.StreamEnd,ge,Wi)))}catch(ve){Ne("request body failed"),De(Me(Ct(ve).message))}})()})},$b=M=>{const le=M.indexOf("?");return le===-1?{path:M,query:""}:{path:M.slice(0,le),query:M.slice(le+1)}},Qb=(M,le)=>{let U=mg,_=null,Q=0,ge=!1;const at={get readyState(){return U},onopen:null,onmessage:null,onerror:null,onclose:null,send(te){if(U!==Rr||!_||_.dead)throw new Error("relay tunnel socket is not open");if(typeof te=="string"){for(const Te of ig(se.WsText,Q,Ty.encode(te)))_.send(Te);return}const ne=te instanceof ArrayBuffer?new Uint8Array(te.slice(0)):(()=>{const Te=new Uint8Array(te.byteLength);return Te.set(new Uint8Array(te.buffer,te.byteOffset,te.byteLength)),Te})();for(const Te of ig(se.WsBinary,Q,ne))_.send(Te)},close(te=1e3,ne=""){U===fg||U===hg||(U===Rr&&_&&!_.dead&&(U=hg,_.send(At(se.WsClose,Q,Li({code:te,reason:ne})))),Fe(te,ne))}},Fe=(te,ne,Te=!1)=>{if(!ge){if(ge=!0,_&&(_.streams.delete(Q),_.assembler.dropStream(Q)),U=fg,Te)try{at.onerror?.()}catch{}try{at.onclose?.({code:te,reason:ne})}catch{}}};return(async()=>{let te;try{te=await Yt()}catch(Oe){Fe(1006,Ct(Oe).message,!0);return}if(ge)return;_=te,Q=te.nextStreamId(),te.streams.set(Q,{handleFrame(Oe,De){if(Oe===se.WsOpened){if(U===mg){U=Rr;try{at.onopen?.()}catch{}}return}if(Oe===se.WsText){try{at.onmessage?.({data:Iy.decode(De)})}catch{}return}if(Oe===se.WsBinary){const Ne=new ArrayBuffer(De.byteLength);new Uint8Array(Ne).set(De);try{at.onmessage?.({data:Ne})}catch{}return}if(Oe===se.WsClose){let Ne=1e3,Me="";try{const es=qi(De,Uk);Ne=es.code,Me=es.reason}catch{}Fe(Ne,Me);return}if(Oe===se.StreamAbort){let Ne="stream aborted";try{Ne=qi(De,og).reason}catch{}Fe(1006,Ne,!0)}},fail(Oe){Fe(1012,Oe.message,!0)}});const{path:ne,query:Te}=$b(M),Xt=le&&le.length>0?{path:ne,query:Te,protocols:le}:{path:ne,query:Te};te.send(At(se.WsOpen,Q,Li(Xt)))})(),at},Yb=()=>{if(u)return;u=!0,S+=1,ka(),wt(),T?.(),T=null;const M=k;k=null;const le=new Error("relay tunnel closed");M&&Xe(M,le),$(le);try{w?.close()}catch{}w=null,ce({state:"idle"})};return yn(),{fetch:Sr,openWebSocket:Qb,getStatus:()=>f,subscribeStatus(M){return b.add(M),()=>{b.delete(M)}},retry:Ls,close:Yb}};let Jt=null,_t=null;const Vc=new Set;let Or=null;const Jl=e=>{Or?.(),Or=null,Jt=e,e&&(Or=e.subscribeStatus(t=>{for(const s of Vc)s(t)}))},qM=e=>(Vc.add(e),()=>{Vc.delete(e)}),Fy=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),ca=()=>Jt,VM=()=>!Jt||!_t?null:{relayUrl:_t.relayUrl,serverId:_t.serverId,hostEncPubJwk:{..._t.hostEncPubJwk}},Ny=()=>Jt!==null,My=e=>{if(Jt&&_t&&Fy(_t,e))return Jt;Jt?.close(),_t=e;const t=Zl(e);return Jl(t),t},UM=(e,t)=>{if(Jt===t){_t=e;return}Jt?.close(),_t=e,Jl(t)},Ey=()=>{Jt?.close(),Jl(null),_t=null};let um=()=>null,mm="",Oo={},$n="",gi=0,Ys=null,qn="",pi=0,dn="",Xs=null,As="",uo=0,mo=0;const $l=1e4,Ly=e=>e.toLowerCase()==="authorization",hm=e=>{const t={};for(const[s,n]of Object.entries(e||{})){const a=s.trim(),i=n.trim();a&&i&&!Ly(a)&&(t[a]=i)}return t},qy=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?!1:s.every(([n,a])=>t[n]===a)},er=e=>typeof e!="string"?"":e.trim(),Vy=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return er(e)},Uy=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},fm=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():Uy();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},Ql=e=>{try{return new URL(e).origin}catch{return""}},bm=()=>{qn="",pi=0,dn="",Xs=null,As="",uo+=1},Ai=()=>{$n="",gi=0,bm()},km=()=>{mo+=1,Ys=null,Ai(),Xl()},ym=e=>{const t=er(e);mm=t,km(),um=()=>t?{type:"bearer",token:t}:null},wm=e=>{const t=hm(e);qy(Oo,t)||(Oo=t,km())},la=()=>{if(Object.keys(Oo).length>0)return Oo;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?hm(e):{}},Yl=()=>mm||Vy(),Wy=(e,t)=>{const s=er(e);if(!s||typeof t!="number"||!Number.isFinite(t)){Ai();return}$n=s,gi=t},vm=()=>!$n||gi<=Date.now()+$l?(Ai(),""):$n,Cm=e=>{const t=Ql(e);return!t||dn!==t?"":!qn||pi<=Date.now()+$l?(qn="",pi=0,dn="",""):qn},Hy=()=>{const e=vm();return!e&&(Yl()||typeof window<"u")&&tr().catch(()=>{}),e},Gy=e=>{const t=e?Cm(e):"";return!t&&e&&typeof window<"u"&&zm(e).catch(()=>{}),t},Sm=async()=>{const e=await um(),t=e?.type==="bearer"?er(e.token):Yl();return t?{type:"bearer",token:t}:null},_y=p({token:g(),expiresAt:v(),expiresIn:v().optional()}),Pm=async(e,t)=>{const s=await Sm(),n=new Headers;for(const[u,m]of Object.entries(la()))n.set(u,m);s?.type==="bearer"&&n.set("Authorization",`Bearer ${s.token}`);const a=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",i=ca(),o=i?await i.fetch(a,{method:"POST",headers:n}):await fetch(fm(e,a),{method:"POST",headers:n,credentials:"include"});if(!o.ok)throw new Error(`Failed to mint runtime URL auth token (${o.status})`);const r=_y.safeParse(await o.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:c,expiresAt:l,expiresIn:d}=r.data;return{token:c.trim(),expiresAt:d===void 0?l:Date.now()+d}},WM=async e=>{const t=await Pm(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Am=e=>{if(Ys)return Ys;const t=mo,n=(async()=>{let a;try{a=await Pm(e)}catch(i){throw t===mo&&Ai(),i}if(t!==mo)throw new Error("Runtime URL auth token response is stale");if(Wy(a.token,a.expiresAt),!$n)throw new Error("Runtime URL auth token response was invalid");return $n})().finally(()=>{Ys===n&&(Ys=null)});return Ys=n,Ys},Ky=e=>{const t=Ql(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Xs&&As===t)return Xs;const s=uo,a=(async()=>{const i=await fetch(fm(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!i.ok)throw s===uo&&t===As&&(qn="",pi=0,dn=""),new Error(`Failed to mint local runtime URL auth token (${i.status})`);const o=await i.json().catch(()=>null),r=typeof o?.token=="string"?o.token.trim():"",c=typeof o?.expiresAt=="number"?o.expiresAt:0;if(!r||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(s!==uo||t!==As)throw new Error("Local runtime URL auth token response is stale");return qn=r,pi=c,dn=t,r})().finally(()=>{Xs===a&&(Xs=null,As="")});return Xs=a,As=t,Xs},tr=async e=>{const t=vm();return t||Am(e)},zm=async e=>{const t=Ql(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=Cm(t);return s||((dn&&dn!==t||As&&As!==t)&&bm(),Ky(t))};let Bn=0,Ha=null,Zy=null;const Jy=5e3,xm=()=>{Ha!==null&&(clearTimeout(Ha),Ha=null)},Xl=()=>{if(xm(),Bn<=0||typeof window>"u")return;const e=gi-$l-Jy,t=gi>0?Math.max(0,e-Date.now()):0;Ha=setTimeout(()=>{Ha=null,!(Bn<=0)&&Am(Zy).catch(()=>{}).finally(()=>{Xl()})},t)},HM=e=>{Bn+=1,Xl();let t=!1;return()=>{t||(t=!0,Bn=Math.max(0,Bn-1),Bn===0&&xm())}},Tm=async e=>{const t=new Headers(e);for(const[n,a]of Object.entries(la()))t.has(n)||t.set(n,a);if(t.has("Authorization"))return t;const s=await Sm();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},Qn=yt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),GM=e=>new Promise(t=>{if(e.aborted||Qn.getState().state==="ok"){t();return}const s=()=>{n(),e.removeEventListener("abort",s),t()},n=Qn.subscribe(a=>{a.state==="ok"&&s()});e.addEventListener("abort",s,{once:!0})}),$y=15e3,Qy=5*6e4;let Uc=0,Dr=!1;const Yy=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),Xy=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!Yy(t)},Im=async()=>{if(!Dr){Dr=!0;try{const{runtimeFetch:e}=await Ee(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>bw);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){Qn.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:n}=Qn.getState();s==="expired"&&n()}}catch{}finally{Dr=!1}}},ew=(e,t)=>{if(t!==401||Qn.getState().state==="expired"||!Xy(e))return;const s=Date.now();s-Uc<$y||(Uc=s,Im())};let bg=!1;const _M=()=>{if(bg)return;bg=!0;let e=Date.now();const t=()=>{if(Qn.getState().state!=="ok")return;const s=Date.now();s-e<Qy||(e=s,Uc=s,Im())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},tw=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,kt=e=>{if(!e)return null;const t=tw.exec(e);return t?t[1]:null},Wc=e=>kt(e)!==null,sw=()=>im()||ra()?.runtime?.isVSCode===!0,nw=e=>!e||sw()||!Wc(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},Rm=e=>`/spaces/${e}`,gn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",aw=()=>typeof window>"u"?"":window.location.origin||"",ed=e=>{if(typeof window>"u")return!1;const t=aw();if(t&&e.origin===t)return!0;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return!1}},td=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),iw=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),ss=(e,t)=>{try{iw(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},sd=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,a]of s)a!=null&&e.searchParams.set(n,String(a))},ow=e=>{if(!e)return!1;if(e instanceof Headers)return e.has("x-opencode-directory");const t=Array.isArray(e)?e:Object.entries(e);for(const[s]of t)if(s.toLowerCase()==="x-opencode-directory")return!0;return!1},rw=(e,t,s)=>{const n=nw(s);if(n===null||ow(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const a=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...a,...Object.entries(n)]}},cw=()=>{const e=ls().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return null;const t=new URL(e);return`${t.origin}${t.pathname.replace(/\/api$/,"")}`},lw=e=>{try{const t=cw();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const n=s.pathname.replace(/\/+$/,"");return n?e.pathname!==n&&!e.pathname.startsWith(`${n}/`)?null:e.pathname.slice(n.length)||"/":e.pathname}catch{return null}},ho=e=>{const t=lw(e);return t!==null&&gn(t)},Br=e=>{if(gn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ed(t)&&gn(t.pathname)}catch{return!1}},dw=(e,t)=>{try{const s=new URL(e);if(!ed(s))return e;const n=Fs(`${s.pathname}${s.search}`,t);return!td(n)&&(s.protocol==="http:"||s.protocol==="https:")?(sd(s,t),s.toString()):s.hash?`${n}${s.hash}`:n}catch{return e}},Fs=(e,t)=>e==="/health"?ls().health(t):e.startsWith("/auth/")||e==="/auth"?ls().auth(e,t):gn(e)?ls().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?dw(e,t):e,jm=e=>{const t=e instanceof Request?e.url:e.toString();if(!td(t))return gn(t);try{return ho(new URL(t))}catch{return!1}},Om=(e,t)=>Object.keys(la()).length>0&&mn()&&jm(e)?{...t,redirect:"error"}:t,Dm=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},gw=(e,t)=>!Dm(t),Do=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const s=[];let n=!1,a=!1;for(const[i,o]of t)gw(i,o)?(s.push([i,encodeURIComponent(o)]),n=!0,i.toLowerCase()==="x-opencode-directory"&&(a=!0)):s.push([i,o]);return a&&s.push(["x-opencode-directory-encoding","uri"]),n?s:void 0},ns=async(e,t,s=!0)=>{const n=new Headers(Do(e)??e);return t&&new Headers(Do(t)??t).forEach((a,i)=>n.set(i,a)),s?Tm(n):n},pw=(e,t)=>{if(!t)return e;const s=new URL(e,Hl);return sd(s,t),`${s.pathname}${s.search}`},Bm=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!td(s))return gn(s)?pw(s,t):null;try{const n=new URL(s);return!ed(n)||!gn(n.pathname)?null:(sd(n,t),`${n.pathname}${n.search}`)}catch{return null}},uw=async(e,t,s)=>{const n=ca();if(!n)return null;const a=Bm(e,s);if(a===null)return null;const i=e instanceof Request?e.headers:void 0,o=await ns(i,t.headers,!0);return e instanceof Request?n.fetch(e,{...t,headers:o}):n.fetch(a,{...t,headers:o})},mw=(e,t)=>{if(typeof e=="string")return Fs(e,t);if(e instanceof URL)return Fs(e.toString(),t);const s=Fs(e.url,t);return s===e.url?e:new Request(s,e)},hw=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Gi=new Map,fw=(e,t,s,n)=>s||e!=="GET"||t.includes("/event")||!hw.test(t)?null:`GET ${t}\0${n.get("x-opencode-directory")??""}`,C=async(e,t={})=>{const{query:s,directory:n,...a}=t,i=e,o=rw(i,a,n),r=ca(),c=r?Bm(i,s):null;let l,d,u,m;if(r&&c!==null){const S=i instanceof Request?i.headers:void 0,E=await ns(S,o.headers,!0);l=i instanceof Request?()=>r.fetch(i,{...o,headers:E}):()=>r.fetch(c,{...o,headers:E}),m=E,d=c,u=String(o.method??(i instanceof Request?i.method:"GET")).toUpperCase()}else{const S=mw(i,s),E=S instanceof Request?S.headers:void 0,H=await ns(E,o.headers,jm(S)),Z=S instanceof Request?S.url:S instanceof URL?S.toString():String(S);ss(Z,H);const N=Om(S,{...o,headers:H});l=S instanceof Request?()=>fetch(new Request(S,N)):()=>fetch(S,N),m=H,d=Z,u=String(o.method??(S instanceof Request?S.method:"GET")).toUpperCase()}const f=l;l=()=>f().then(S=>(ew(d,S.status),S));const b=o.signal!=null||i instanceof Request,k=fw(u,d,b,m);if(!k)return l();const w=Gi.get(k);if(w)return w.then(S=>S.clone());const T=l();return Gi.set(k,T),T.then(()=>Gi.delete(k),()=>Gi.delete(k)),T.then(S=>S.clone())};let kg=!1,Fm=null;const Nm=(e,t)=>(Fm??globalThis.fetch.bind(globalThis))(e,t),Mm=()=>{if(kg||typeof window>"u")return;kg=!0;const e=window.fetch.bind(window);Fm=e;const t=(s,n)=>e(s,Om(s,n));window.fetch=async(s,n)=>{const a=await uw(s,n??{});if(a)return a;if(typeof s=="string"){if(!Br(s)){try{const r=new URL(s);if(ho(r)){const c=await ns(void 0,n?.headers);return ss(r.toString(),c),t(s,{...n,headers:c})}}catch{}return t(s,n)}const i=await ns(void 0,n?.headers),o=Fs(s);return ss(o,i),t(o,{...n,headers:i})}if(s instanceof URL){const i=s.toString();if(!Br(i)){if(ho(s)){const c=await ns(void 0,n?.headers);return ss(s.toString(),c),t(s,{...n,headers:c})}return t(s,n)}const o=await ns(void 0,n?.headers),r=Fs(i);return ss(r,o),t(r,{...n,headers:o})}if(s instanceof Request){if(!Br(s.url)){try{const c=new URL(s.url);if(ho(c)){const l=await ns(s.headers,n?.headers);return ss(c.toString(),l),t(new Request(s,{...n,headers:l}))}}catch{}return t(s,n)}const i=await ns(s.headers,n?.headers),o=Fs(s.url);ss(o,i);const r=o===s.url?s:new Request(o,s);return t(new Request(r,{...n,headers:i}))}return t(s,n)}},bw=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:ss,buildRuntimeFetchUrl:Fs,fetchBypassingRuntimeBridge:Nm,installRuntimeFetchBridge:Mm,isLatin1Safe:Dm,runtimeFetch:C,sanitizeHeadersForBrowser:Do},Symbol.toStringTag,{value:"Module"})),Vn=16384,Bo=globalThis,kw=e=>{if(Bo.Buffer)return Bo.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let n=0;n<t.length;n+=32768)s+=String.fromCharCode(...t.slice(n,n+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},Em=e=>{try{if(Bo.Buffer)return Bo.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),n=new Uint8Array(s.length);for(let a=0;a<s.length;a+=1)n[a]=s.charCodeAt(a);return new TextDecoder().decode(n)}catch{return null}},yw=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString().replace(/\/+$/g,""))}catch{return null}},ww=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="ws:"&&s.protocol!=="wss:"?null:(s.hash="",s.toString())}catch{return null}},yg=e=>typeof e=="string"&&e.length>0,vw=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!yg(t.x)||!yg(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Cw=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Sw=e=>{if(!e||typeof e!="object")return null;const t=e,s=Cw(t.priority);if(t.type==="lan"||t.type==="tunnel"){const n=yw(t.url);return n?s===void 0?{type:t.type,url:n}:{type:t.type,url:n,priority:s}:null}if(t.type==="relay"){const n=ww(t.relayUrl);if(!n)return null;const a=typeof t.serverId=="string"?t.serverId.trim():"";if(!a)return null;const i=vw(t.hostEncPubJwk);if(!i)return null;const o=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:n,serverId:a,hostEncPubJwk:i,...o?{grant:o}:{},...s===void 0?{}:{priority:s}}}return null},nd=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const s=typeof t.pairingId=="string"?t.pairingId.trim():"",n=typeof t.secret=="string"?t.secret.trim():"";if(!s||!n)return null;const a=Array.isArray(t.candidates)?t.candidates.map(Sw).filter(c=>!!c):[];if(a.length===0)return null;const i=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(i){const c=Date.parse(i);if(!Number.isFinite(c)||c<=Date.now())return null}const o=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,r=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:s,secret:n,...o?{label:o}:{},...r?{fingerprint:r}:{},...i?{expiresAt:i}:{},candidates:a}},KM=e=>({v:2,pairingId:e.pairingId.trim(),secret:e.secret.trim(),...e.label?.trim()?{label:e.label.trim()}:{},...e.fingerprint?.trim()?{fingerprint:e.fingerprint.trim()}:{},...e.expiresAt?.trim()?{expiresAt:e.expiresAt.trim()}:{},candidates:e.candidates}),ZM=e=>{const t=nd(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",kw(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},Pw=e=>{const t=e.trim();if(!t||t.length>Vn)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const n=s.searchParams.get("p")||"";if(!n||n.length>Vn)return null;const a=Em(n);return!a||a.length>Vn?null:nd(JSON.parse(a))}catch{return null}},JM=e=>{const t=e.trim();if(!t||t.length>Vn)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let n=null,a=null;for(const o of t.slice(s+1).split("&")){const r=o.indexOf("=");if(r===-1)continue;const c=o.slice(0,r),l=o.slice(r+1);c==="v"?n=l:c==="p"&&(a=l)}if(n!=="2"||!a||a.length>Vn)return null;const i=Em(a);if(!i||i.length>Vn)return null;try{return nd(JSON.parse(i))}catch{return null}},Yn=e=>typeof e=="object"&&e!==null,Aw=e=>e.trim().toLowerCase()==="authorization",zw=e=>{if(!Yn(e))return;const t={};for(const[s,n]of Object.entries(e)){const a=s.trim(),i=typeof n=="string"?n.trim():"";!a||!i||/[\r\n:]/.test(a)||/[\r\n]/.test(i)||Aw(a)||(t[a]=i)}return Object.keys(t).length>0?t:void 0},xw=e=>`relay://${e}`,Tw=e=>{if(!Yn(e))return null;const t=Ge(e,"relayUrl")||Ge(e,"relay_url"),s=Ge(e,"serverId")||Ge(e,"server_id"),n=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!Yn(n)?null:{relayUrl:t,serverId:s,hostEncPubJwk:n}},Iw=()=>{if(typeof navigator>"u")return;const e=navigator.userAgent;if(/Macintosh|Mac OS X/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux"},wg=15e3,$M=async(e,t)=>{const s=Pw(e);if(!s)throw new Error("invalid-connect-link");const n=await Bw().catch(()=>""),a={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:s.pairingId,secret:s.secret,clientLabel:s.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:Iw(),...n?{dedupeKey:`desktop:${n}`}:{}})},i=async w=>{if(!w.ok)return null;const T=await w.json().catch(()=>null);return(typeof T?.clientToken=="string"?T.clientToken.trim():"")||null};let o=null;const r=[...s.candidates].sort((w,T)=>(w.type==="relay"?1:0)-(T.type==="relay"?1:0));for(const w of r){if(w.type==="relay"){const S=Zl({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const E=await i(await S.fetch("/api/client-auth/pairing/redeem",{...a,signal:AbortSignal.timeout(wg)}));if(E){o={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:E};break}}catch{}finally{S.close()}continue}const T=qe(w.url);if(T)try{const S=await i(await fetch(`${T}/api/client-auth/pairing/redeem`,{...a,signal:AbortSignal.timeout(wg)}));if(S){o={directUrl:T,token:S};break}}catch{}}if(!o)throw new Error("pairing-redeem-failed");const c=s.candidates.find(w=>w.type==="relay"),l=o.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),d=s.candidates.filter(w=>w.type!=="relay").map(w=>qe(w.url)).find(w=>!!w),u=o.directUrl||d,m=u||(l?xw(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");const f=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&qe(w.apiUrl||w.url)===m),b=f?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),k={...f||{},id:b,label:s.label||f?.label||Lm(m),url:m,apiUrl:u,clientToken:o.token,...l?{relay:l}:{}};return{hostId:b,hosts:f?t.map(w=>w.id===b?k:w):[k,...t]}},Rw=/^(t|.*(?:token|auth|secret|api).*)$/i,qe=e=>{const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},QM=e=>{const t=qe(e);if(!t)return null;try{const s=new URL(t);if((s.pathname.replace(/\/+$/,"")||"/")==="/connect"&&s.searchParams.has("t"))return{persistedUrl:s.origin,redeemUrl:s.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},Lm=e=>{const t=qe(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const n=Array.from(new Set(Array.from(s.searchParams.keys())));for(const a of n)Rw.test(a)&&s.searchParams.set(a,"[REDACTED]");return s.toString()}catch{return t}},_i=(e,t)=>{const s=qe(e),n=qe(t);if(!s||!n)return!1;try{const a=new URL(s),i=new URL(n);if(a.origin!==i.origin||i.search&&a.search!==i.search)return!1;const o=i.pathname.length>1?i.pathname.replace(/\/+$/,""):i.pathname,r=a.pathname.length>1?a.pathname.replace(/\/+$/,""):a.pathname;return o==="/"?!0:r===o||r.startsWith(`${o}/`)}catch{return!1}},Ge=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},vg=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},jw=e=>{if(!Yn(e))return null;const t=Ge(e,"id"),s=Ge(e,"label"),n=Ge(e,"url"),a=Ge(e,"apiUrl")||Ge(e,"api_url"),i=Ge(e,"clientToken")||Ge(e,"client_token"),o=zw(e.requestHeaders),r=Tw(e.relay);if(!t||!s||!n)return null;const c={id:t,label:s,url:n,...a?{apiUrl:a}:{},...i?{clientToken:i}:{},...o?{requestHeaders:o}:{},...r?{relay:r}:{}};return e.sshForwarded===!0&&(c.sshForwarded=!0),c},Un=e=>qe(e.apiUrl||e.url)||e.apiUrl||e.url,fs=()=>Qe()?(e,t)=>ee(e,t):null,ui=async()=>{const e=fs();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Yn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const s=t.hosts,n=Array.isArray(s)?s.map(jw).filter(r=>!!r):[],a=Ge(t,"defaultHostId")||Ge(t,"default_host_id")||Ge(t,"defaultHostID"),i=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,o=Ge(t,"localOrigin")||Ge(t,"local_origin");return{hosts:n,defaultHostId:a,initialHostChoiceCompleted:i,localOrigin:o}},Ow=async e=>{const t=fs();if(!t)return;const s={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(s.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:s})},Dw=async()=>{const e=fs();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},YM=async()=>{const e=fs();return e?await e("desktop_switch_to_local").catch(()=>!1)===!0:!1},Bw=async()=>{const e=fs();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Fw=8e3,Nw=15e3,Mw=400,Ew=async(e,t,s,n)=>{const a=new AbortController,i=window.setTimeout(()=>a.abort(),s);try{return await e.fetch(t,{...n,signal:a.signal})}finally{window.clearTimeout(i)}},Cg=async(e,t,s,n)=>{for(;;){const a=s-Date.now();if(a<=0)throw new Error("relay probe deadline exceeded");try{return await Ew(e,t,Math.min(Fw,a),n)}catch(i){if(e.getStatus().state==="error"||Date.now()>=s)throw i;await new Promise(o=>window.setTimeout(o,Mw))}}},Lw=async(e,t)=>{const s=Zl({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),n=Date.now(),a=n+Nw;let i=!1;try{if(!(await Cg(s,"/health",a)).ok)return{status:"unreachable",latencyMs:0};const r=new Headers({Accept:"application/json"});for(const[d,u]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&r.set(d,u);const c=t?.clientToken?.trim();c&&r.set("Authorization",`Bearer ${c}`);const l=await Cg(s,"/auth/session",a,{headers:r});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-n)}:l.ok?(i=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-n),...i?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:Oy(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{i||s.close()}},sr=async(e,t)=>{const s=fs();if(!s)return{status:"unreachable",latencyMs:0};const n=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!Yn(n))return{status:"unreachable",latencyMs:0};const a=n.status,i=a==="ok"||a==="auth"||a==="update-recommended"||a==="incompatible"||a==="wrong-service"||a==="unreachable"?a:"unreachable",o=vg(n,"latencyMs")??vg(n,"latency_ms")??0;return{status:i,latencyMs:o}},qw=we("status",[p({status:y("started")}),p({status:y("auth")}),p({status:y("failed"),error:g().nullable()})]),XM=async e=>{const t=fs();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),n=qw.safeParse(s);return n.success?n.data:{status:"failed",error:null}},Vw=600*1e3,Uw=3e3,eE=async(e,{maxWaitMs:t=Vw,intervalMs:s=Uw,readHosts:n=ui,probe:a=sr}={})=>{const i=Date.now()+t;for(;Date.now()<i;){await new Promise(c=>setTimeout(c,Math.min(s,Math.max(0,i-Date.now()))));const o=(await n()).hosts.find(c=>c.id===e);if(!o)return"timeout";const r=await a(Un(o),{clientToken:o.clientToken,requestHeaders:o.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},tE=async(e,t)=>{const s=fs();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},sE=async e=>{const t=fs();t&&await t("desktop_new_window_for_host",{hostId:e})},Ds="local",Ww=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",Hw=(e,t)=>t?[{id:Ds,label:"Local",url:t},...e]:e,Gw=e=>e.id===Ds?"local":`host:${e.id}`,nE=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(m=>m.id===Ds)?.url||Ww(),n=ps(),a=qe(s)||s,i=qe(t)||t,o=D(),r=e.find(m=>m.relay&&Gw(m)===o);if(r)return{id:r.id,label:r.label,url:r.url};if(n&&_i(n,s))return{id:Ds,label:"Local",url:a};const c=e.find(m=>n?_i(n,Un(m)):!1);if(c)return{id:c.id,label:c.label,url:qe(Un(c))||Un(c)};if(t&&_i(t,s))return{id:Ds,label:"Local",url:a};const l=e.find(m=>t?_i(t,m.url):!1);if(l)return{id:l.id,label:l.label,url:qe(l.url)||l.url};const d=t.startsWith("openchamber-ui://");if(d&&s&&!n)return{id:Ds,label:"Local",url:a};const u=n?qe(n)||n:d?"":i;return{id:"custom",label:Lm(u||"Instance"),url:u}},Fo=new Map;let qm=0;const Ga=new Map,Wn=new Set;let Hc=0,Vm={byHostId:{},isProbing:!1};const Gc=new Set,No=()=>{Vm={byHostId:Object.fromEntries(Fo),isProbing:Hc>0};for(const e of Gc)try{e()}catch{}},aE=e=>(Gc.add(e),()=>{Gc.delete(e)}),iE=()=>Vm,Um=(e,t)=>{Fo.set(e,t),No()},oE=(e,t)=>{Ga.set(e,++qm),Wn.delete(e),Um(e,t)},rE=e=>Wn.has(e),_w=e=>{const t=new Set([Ds,...e]);let s=!1;for(const n of Array.from(Fo.keys()))t.has(n)||(Fo.delete(n),Ga.delete(n),Wn.delete(n),s=!0);s&&No()},Kw=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",Zw=async()=>un()?Dw().catch(()=>""):"",Jw=async(e,t)=>{const s=e.id===Ds?t:e.clientToken||"",n=async()=>{const o=await Lw(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:o.status,latencyMs:o.latencyMs};return o.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return n();const a=qe(un()?Un(e):e.url);if(!a)return{status:"unreachable",latencyMs:0};const i=await sr(a,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Kw(i.status)&&e.relay){const o=await n();if(o.status==="ok"||o.status==="relay-limit")return o}return{status:i.status,latencyMs:i.latencyMs}},$w=async e=>{if(!Ye())return;const t=++qm;for(const s of e)Ga.set(s.id,t),Wn.add(s.id);Hc+=1,No();try{const s=await Zw();await Promise.all(e.map(async n=>{const a=await Jw(n,s);Ga.get(n.id)===t&&(Wn.delete(n.id),Um(n.id,a))}))}finally{for(const s of e)Ga.get(s.id)===t&&Wn.delete(s.id);Hc-=1,No()}};let Sg=!1;const Qw=async()=>{if(Sg||!Ye())return;Sg=!0;const e=await ui().catch(()=>null);e&&(_w(e.hosts.map(t=>t.id)),await $w(Hw(e.hosts,e.localOrigin)))},Yw=5e3,Xw=1500;let Fr=!1;const Nr=e=>{const t=String(e??"").trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString())}catch{return null}},ev=async e=>{if(!un()||Fr)return;const t=`host:${e}`;if(D()===t){Fr=!0;try{const s=await ui().catch(()=>null),n=s?.hosts.find(b=>b.id===e);if(!s||!n?.relay)return;const a=n.apiUrl?qe(n.apiUrl):null;if(a&&a.startsWith("https://"))return;const i=await C("/api/client-auth/connection/candidates").catch(()=>null);if(!i?.ok)return;const o=await i.json().catch(()=>null);if(!o||o.serverId!==n.relay.serverId)return;const r=Array.isArray(o.candidates)?o.candidates:[],c=[];for(const b of r){if(!b||typeof b!="object")continue;const k=b;if(k.type!=="lan"||typeof k.url!="string")continue;const w=qe(k.url);w&&!c.includes(w)&&c.push(w)}if(c.length===0)return;const l=a&&c.includes(a)?a:c[0],d=Nr(l);d&&d!==Nr(a)&&await Ow({hosts:s.hosts.map(b=>b.id===e?{...b,apiUrl:l}:b),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const m=(await ui().catch(()=>null))?.hosts.find(b=>b.id===e)??null;if(!m||!d||Nr(m.apiUrl)!==d)return;const f=await sr(l,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(f.status==="unreachable"||f.status==="wrong-service"||f.status==="incompatible"||D()!==t)return;Lc({apiBaseUrl:l,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:t})}finally{Fr=!1}}},tv=e=>{typeof window>"u"||window.setTimeout(()=>{ev(e).catch(()=>{})},Yw)},Pg=async(e,t)=>{if(!un())return;const s=await ui().catch(()=>null);if(!s)return;const n=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!n)return;const a=s.hosts.find(m=>m.id===n);if(!a?.relay)return;const i=`host:${a.id}`;if(D()===i&&!t?.reconnectActive)return;const o=m=>{Lc({apiBaseUrl:m,clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,runtimeKey:i})},r=()=>{Lc({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:a.clientToken||null,runtimeKey:i,relay:a.relay??void 0}),tv(a.id)},c=a.apiUrl?qe(Un(a)):null;if(!c){r();return}const l=m=>m.status!=="unreachable"&&m.status!=="wrong-service"&&m.status!=="incompatible",d=sr(c,{clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,expectedServerId:a.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),u=await Promise.race([d,new Promise(m=>setTimeout(()=>m(null),Xw))]);if(u){if(l(u)){o(c);return}r();return}r(),d.then(m=>{l(m)&&D()===i&&o(c)})},sv=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class It extends Error{reason;status;constructor(t,s={}){super(t),this.name="FilesystemError",this.reason=s.reason??"unknown",this.status=s.status}}const nv=e=>e instanceof It||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),_a=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},av=p({message:g()}),cE=e=>{if(nv(e)&&e.reason==="not-found")return!0;const t=av.safeParse(e),n=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return n.includes("file not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")},Ws=new Map;let Mr;async function Ag(e){const t=ls().api("/api").replace(/\/api\/?$/,""),s=ca(),n=await Tm();if(D()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(i,o)=>{const r=i instanceof Request?i.url:String(i),c=r.startsWith("/")?`${t}${r}`:r,l=new Headers(i instanceof Request?i.headers:void 0);return new Headers(Do(o?.headers)??o?.headers).forEach((d,u)=>l.set(u,d)),n.forEach((d,u)=>l.set(u,d)),s?s.fetch(i,{...o,headers:l}):(ss(c,l),Nm(i instanceof Request?new Request(c,i):c,{...o,headers:l}))},baseUrl:t}}async function Wm(e){const t=!!ps()&&!ca(),s=await Ag(e);return async n=>{let a=!1;const i=async()=>{if(!a){a=!0;try{const r=D()===e;if(!t&&!r)return;await n(r?await Ag(e):s),Ws.get(e)?.delete(i),Ws.get(e)?.size===0&&Ws.delete(e),Ws.size===0&&(Mr?.(),Mr=void 0)}catch{}finally{a=!1}}},o=Ws.get(e)??new Set;o.add(i),Ws.set(e,o),Mr??=Yo(({runtimeKey:r})=>{for(const c of Ws.get(r)??[])c()}),await i()}}const Mo=()=>({active:0,waiters:[],activeSessionWaiters:[]});let zs=Mo(),on=Mo();const iv=3,zg=2;Qo(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[zs,on];zs=Mo(),on=Mo();for(const n of s){for(const a of[...n.activeSessionWaiters,...n.waiters])a(!1);n.activeSessionWaiters.length=0,n.waiters.length=0}});const xg=()=>{for(;zs.active+on.active<iv;){const e=on.active<zg&&on.waiters.length>0?on:zs.active<zg&&(zs.activeSessionWaiters.length>0||zs.waiters.length>0)?zs:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(!0)}};async function Hm(e,t,s){const n=am();if(await new Promise(i=>{s==="active-session"?e.activeSessionWaiters.push(i):e.waiters.push(i),xg()}))try{if(!n())return;const i=await t();return n()?i:void 0}finally{e.active-=1,xg()}}const ov=(e,t="normal")=>Hm(zs,e,t),lE=e=>Hm(on,e,"normal"),Gm="/api/opencode/trust",rv="opencode_trust_required",cv=p({kind:R(["plugin","package","mcp","lsp","formatter","shell","config"]),source:g(),name:g(),detail:g()}),lv=p({directory:g(),trusted:z(),fingerprint:g().nullable(),items:x(cv)}),dv=p({code:y(rv),directory:g()});let cn=null;const _c=new Set,Fa=new Map,mi=new Set;let Kc=Promise.resolve(),xs=0;const Er=()=>{for(const e of _c)e()},dE=()=>cn,gE=e=>(_c.add(e),()=>{_c.delete(e)}),pE=e=>cn?cn.settle(e):Promise.resolve("skipped");Qo(()=>{xs+=1,cn?.settle("skip"),Fa.clear(),mi.clear(),Kc=Promise.resolve()});const gv=()=>{mi.clear()},pv=async e=>{if(e.status!==403)return null;try{const t=dv.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},_m=async e=>lv.parse(await e.json()),Lr=async e=>{const t=await C(Gm,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return _m(t)},uv=async e=>{const t=await C(Gm,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({directory:e.directory,fingerprint:e.fingerprint})});if(t.status===409)return{kind:"changed",assessment:await _m(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},mv=(e,t)=>new Promise(s=>{const n=a=>{if(t!==xs){s(!1);return}cn={directory:a.directory,items:a.items,settle:async i=>{if(i==="skip")return mi.add(`${a.directory}
3
3
  ${a.fingerprint}`),cn=null,Er(),s(!1),"skipped";let o;try{o=await uv(a)}catch(r){return console.warn("[opencode-trust] Failed to save the answer:",r),"failed"}return t!==xs?"skipped":o.kind==="changed"?(n(o.assessment),"changed"):(cn=null,Er(),s(!0),"saved")}},Er()};n(e)}),hv=(e,{deliberate:t,background:s=!1,throwOnError:n=!1})=>{const a=c=>n?c:c.catch(l=>(console.warn("[opencode-trust] Could not check the folder:",l),!1)),i=Fa.get(e);if(i)return a(i);const o=xs,r=(async()=>{const c=await(s?ov(()=>o===xs?Lr(e):Promise.resolve(null)):Lr(e));if(!c||o!==xs)return!1;if(c.trusted)return!0;if(!t&&mi.has(`${c.directory}
4
4
  ${c.fingerprint}`))return!1;const l=Kc.then(async()=>{if(o!==xs)return!1;const d=await Lr(e);return o!==xs?!1:d.trusted?!0:!t&&mi.has(`${d.directory}
5
5
  ${d.fingerprint}`)?!1:mv(d,o)});return Kc=l.catch(()=>{}),l})().finally(()=>{Fa.get(e)===r&&Fa.delete(e)});return Fa.set(e,r),a(r)},fv=/\/api\/(?:session|(?:experimental\/)?session\/[^/]+\/(?:prompt|command|shell|skill|move))$/,bv=(e,t)=>e==="POST"&&fv.test(t.replace(/\/+$/,"")),oe="/api/openchamber/spaces",da=g().regex(/^[0-9a-f]{12}$/),ad=p({title:g().min(1).max(120),by:R(["user","agent"])}),hn=p({code:g(),message:g()}),Ka=p({count:v().int().min(0),paths:x(g())}),kv=p({path:g().optional(),other:g().nullable().optional(),branch:g().optional(),stillThere:Ka.optional(),ignoredInTheWay:Ka.optional(),filteredInTheWay:Ka.optional(),tooLarge:x(g()).optional(),failed:v().int().min(0).optional()});class qr extends Error{code;status;details;constructor(t,s,n,a={}){super(s),this.name="SpacesRequestError",this.code=t,this.status=n,this.details=a}}const yv=p({id:da,name:g(),state:g()}),wv=we("enabled",[p({enabled:y(!1)}),p({enabled:y(!0),spaces:x(yv).nullable(),failure:hn.optional()})]),vv=p({id:da,name:g(),code:g(),message:g()}),Cv=p({enabled:z(),stopped:x(p({id:da,name:g()})),stillRunning:x(vv),unknown:hn.optional()}),Km=p({mode:R(["allowlist","open"]),domains:x(g())}),Zm=we("kind",[p({kind:y("model"),id:g(),provider:g(),upstream:g(),source:we("kind",[p({kind:y("typed")}),p({kind:y("env"),name:g()})]),url:g()}),p({kind:y("login"),id:g(),provider:g(),method:g(),url:g()}),p({kind:y("custom"),id:g(),provider:g(),url:g()}),p({kind:y("domain"),id:g(),upstream:g(),url:g()})]),uE=(e,t)=>e.find(s=>(s.kind==="model"||s.kind==="login"||s.kind==="custom")&&s.provider===t),Sv=["checking_place","creating","downloading_image","preparing_tools","setting_network","bringing_code","giving_access","ready"],Pv=R(Sv),Jm=we("state",[p({state:y("queued"),total:v().int().min(1)}),p({state:y("running"),index:v().int().min(0),total:v().int().min(1),command:g()}),p({state:y("done"),total:v().int().min(1)}),p({state:y("failed"),index:v().int().min(0),total:v().int().min(1),command:g(),exitCode:v().int().nullable(),timedOut:z(),startedAt:g().nullable().default(null),finishedAt:g().nullable().default(null)}),p({state:y("interrupted"),total:v().int().min(1)})]),fn=p({id:da,name:g(),taskTitle:ad.nullish(),placeId:g(),machine:g().nullable().default(null),projectDirectory:g().nullable(),directory:g().nullable(),projectFolder:p({path:g().nullable(),found:z().nullable()}).default({path:null,found:null}),state:R(["preparing","running","exited","missing","failed","unreachable"]),stoppedIdle:z().default(!1),step:J([Pv,y("failed")]).nullable(),failure:hn.nullable(),network:Km.nullable(),grants:x(Zm),access:R(["granted","needs_access","unknown"]).nullable(),needsAccess:x(g()),accessFailures:x(p({provider:g(),code:g(),message:g()})).default([]),damage:R(["repairable","gatekeeper_gone"]).nullable().default(null),setup:Jm.nullable().default(null)}),$m=["install_all","install_cli","start_colima","start_desktop"],Av=[...$m,"get_brew","linux_install","linux_start","permission","windows_install","windows_start"],id=p({action:R($m),running:z(),failure:hn.extend({output:g().default("")}).nullable()}),Tg=p({remedy:R(Av).nullable().catch(null),job:id.nullable(),memory:p({bytes:v().min(0),engine:R(["colima","docker_desktop","other"]).catch("other"),low:z()}).nullable()}).nullable().default(null),Qm=J([p({id:g(),machine:g().nullable().default(null),available:y(!0),hostIsolation:z(),version:g().default(""),setup:Tg}),p({id:g(),machine:g().nullable().default(null),available:y(!1),code:g(),message:g(),setup:Tg})]),mE="docker-ssh",zv=p({provider:g(),method:g(),expires:g().nullable(),state:R(["usable","expired","unsupported"])}),xv=p({id:g(),name:g(),package:g(),baseURL:g().nullable(),loopback:z(),models:x(g()),hasKey:z(),supported:z()}),Tv=p({code:g(),message:g(),details:kv.nullable().optional().catch(null)}),re=async(e,t,s={})=>{const n=await C(e,{...s,headers:s.body===void 0?s.headers:{"Content-Type":"application/json",...s.headers}}),a=await n.json().catch(()=>null);if(!n.ok){const o=Tv.safeParse(a);throw o.success?new qr(o.data.code,o.data.message,n.status,o.data.details??{}):new qr("space_request_failed",`The server answered ${n.status}.`,n.status)}const i=t.safeParse(a);if(!i.success)throw new qr("space_answer_malformed","The server answered in a shape this version does not know.",n.status);return i.data},Iv=e=>e.enabled?e.spaces!==null?{enabled:!0,spaces:e.spaces}:{enabled:!0,spaces:null,failure:e.failure??{code:"space_journey_failed",message:""}}:{enabled:!1},hE=async e=>Iv(await re(`${oe}/switch`,wv,{signal:e})),fE=e=>re(`${oe}/switch`,Cv,{method:"PUT",body:JSON.stringify({enabled:e})}),bE=async e=>(await re(`${oe}/places`,p({places:x(Qm)}),{signal:e})).places,kE=async e=>(await re(`${oe}/machine`,p({place:Qm.nullable()}),{method:"PUT",body:JSON.stringify({machine:e})})).place,od=p({imageBytes:v().min(0).nullable(),imagePulling:z().default(!1),imageFailure:hn.nullable().default(null),toolsBytes:v().min(0),spacesBytes:v().min(0),bytesBySpace:bt(g(),v().min(0)).default({}),freeBytes:v().min(0),freesImage:z()}),Rv=p({freedBytes:v().min(0),kept:x(p({kind:g(),reason:R(["in_use","failed"])})),disk:od}),yE=(e,t)=>re(`${oe}/places/${encodeURIComponent(e)}/disk`,od,{signal:t}),wE=e=>re(`${oe}/places/${encodeURIComponent(e)}/clean-up`,Rv,{method:"POST"}),vE=async e=>(await re(`${oe}/places/local/setup`,p({job:id.nullable()}),{signal:e})).job,CE=async e=>(await re(`${oe}/places/local/setup`,p({job:id.nullable()}),{method:"POST",body:JSON.stringify({action:e})})).job,SE=e=>re(`${oe}/places/${encodeURIComponent(e)}/image`,od,{method:"POST"}),jv=async e=>(await re(oe,p({spaces:x(fn)}),{signal:e})).spaces,PE=e=>re(oe,fn,{method:"POST",body:JSON.stringify(e)}),AE=async e=>(await re(`${oe}/logins`,p({logins:x(zv)}),{signal:e})).logins,Ov=async(e,t)=>(await re(`${oe}/custom-providers?directory=${encodeURIComponent(e)}`,p({providers:x(xv)}),{signal:t})).providers,zE=async(e,t)=>(await re(`${oe}/${e}/grants`,p({grant:Zm}),{method:"POST",body:JSON.stringify(t)})).grant,xE=async(e,t)=>(await re(`${oe}/${e}/network/domains`,p({network:Km}),{method:"POST",body:JSON.stringify({domain:t})})).network,Dv=p({at:g(),listener:g(),host:g(),port:v(),decision:g()}),Bv=p({records:x(Dv),dropped:v(),since:g()}),TE=(e,t)=>re(`${oe}/${e}/journal`,Bv,{signal:t}),Fv=p({saved:v().int().min(0)}),Ym=p({id:da,removed:z(),failures:x(hn),chats:Fv.nullable().default(null)}),IE=e=>re(`${oe}/${e}/start`,fn,{method:"POST"}),RE=async(e,t)=>{await re(`${oe}/${e}/task-title`,p({applied:z(),taskTitle:ad.nullable()}),{method:"PUT",body:JSON.stringify({title:t})})},jE=e=>re(`${oe}/${e}/stop`,fn,{method:"POST"}),OE=e=>re(`${oe}/${e}/restart`,fn,{method:"POST"}),DE=e=>re(`${oe}/${e}/restart-opencode`,fn,{method:"POST"}),Nv=1,Mv=168,Xm=p({enabled:z(),hours:v().int().min(Nv).max(Mv)}),BE=e=>re(`${oe}/idle-stop`,Xm,{signal:e}),FE=e=>re(`${oe}/idle-stop`,Xm,{method:"PUT",body:JSON.stringify(e)}),NE=(e,t)=>re(`${oe}/${e}/setup`,fn,{method:"POST",body:JSON.stringify({commands:t})}),Ev=p({setup:Jm.nullable(),output:g().nullable()}),ME=(e,t)=>re(`${oe}/${e}/setup`,Ev,{signal:t}),EE=(e,{deleteUnsavedChats:t=!1}={})=>re(`${oe}/${e}${t?"?unsavedChats=delete":""}`,Ym,{method:"DELETE"}),Lv=p({spaceId:da,name:g(),directory:g()}),LE=async e=>(await re(`${oe}/archives`,p({archives:x(Lv)}),{signal:e})).archives,qv=p({changedPaths:v().int().min(0),changedBytes:v().min(0),nestedRepositories:Ka,unmerged:Ka,changesRoute:R(["open","closed"]),lastApplied:g().nullable(),newPaths:v().int().min(0).nullable(),newPathsUndecided:z().default(!1)}),Vv=J([p({status:y("applied"),branch:g()}),p({status:y("applied"),appliedPaths:v().int().min(0)}),p({status:y("nothing_to_apply")})]),Uv=p({applied:Vv,removal:Ym.nullable(),kept:hn.nullable().default(null)}),qE=(e,t)=>re(`${oe}/${e}/apply`,qv,{signal:t}),VE=(e,t)=>re(`${oe}/${e}/apply`,Uv,{method:"POST",body:JSON.stringify(t)}),eh=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,Ig=/^(?:\/\/\?\/)?[A-Za-z]:$/u,Wv=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/UNC\/[^/]+\/[^/]+)$/iu,ze=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const s=t.replace(/\\/g,"/").replace(/^([a-z]):/,(a,i)=>i.toUpperCase()+":");return s==="/"?"/":eh.test(s)?s.replace(/\/+$/u,"/"):(s.length>1?s.replace(/\/+$/,""):s)||null},Hv=e=>{if(e==="/"||eh.test(e)||Ig.test(e)||Wv.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const s=e.slice(0,t);return Ig.test(s)?`${s}/`:s},Gv=e=>ze(e)??"",_v=p({id:g().regex(/^[0-9a-f]{12}$/),name:g().default(""),taskTitle:ad.nullish(),state:R(["complete","partial","stale","unknown"]),projectDirectory:g().nullable().default(null),directory:g().nullable().default(null)}),Zc=new Map,vn=new Map,Kv=(e,t)=>t.step==="failed"?{...e,state:"failed",failure:t.failure}:{...e,state:t.step==="ready"?"running":"preparing",step:t.step==="ready"?null:t.step,failure:null},Rg=(e,t,s)=>{const n=e.get(t);if(!n||n.state===s)return e;const a=new Map(e);return a.set(t,{...n,state:s}),a},$e=yt((e,t)=>({spaces:Zc,journey:null,progressRevision:0,applyJourney:(s,n)=>e(a=>{const i=new Map(s.map(o=>[o.id,o]));for(const[o,r]of vn){const c=a.journey?.get(o);r>n&&c&&i.set(o,c)}return{journey:i}}),addJourneyEntry:s=>e(n=>{const a=n.progressRevision+1;vn.set(s.id,a);const i=new Map(n.journey??[]);return i.set(s.id,s),{journey:i,progressRevision:a}}),noteTaskTitle:(s,n)=>{const a=t(),i=a.journey?.get(s),o=a.spaces.get(s),r=a.progressRevision+1;vn.set(s,r);const c=i?new Map(a.journey).set(s,{...i,taskTitle:n}):a.journey,l=o?new Map(a.spaces).set(s,{...o,taskTitle:n}):a.spaces;return e({journey:c,spaces:l,progressRevision:r}),!!i},noteGrantGiven:(s,n)=>e(a=>{const i=a.journey?.get(s);if(!i)return a;const o=a.progressRevision+1;vn.set(s,o);const r=new Map(a.journey);return r.set(s,{...i,grants:[...i.grants.filter(c=>c.id!==n.id),n],needsAccess:i.needsAccess.filter(c=>c!==n.id),accessFailures:n.kind==="domain"?i.accessFailures:i.accessFailures.filter(c=>c.provider!==n.provider)}),{journey:r,progressRevision:o}}),customProviders:new Map,noteCustomProviders:(s,n)=>e(a=>{const i=new Map(a.customProviders);return i.set(s,n),{customProviders:i}}),accessDialog:null,openAccessDialog:(s,n=null)=>e({accessDialog:{spaceId:s,providerId:n}}),closeAccessDialog:()=>e({accessDialog:null}),actions:new Map,noteAction:(s,n)=>e(a=>{const i=new Map(a.actions);return n?i.set(s,n):i.delete(s),{actions:i}}),applyDialog:null,openApplyDialog:s=>e({applyDialog:s}),closeApplyDialog:()=>e({applyDialog:null}),deleteDialog:null,deleteUnsaved:null,openDeleteDialog:(s,n=null)=>e({deleteDialog:s,deleteUnsaved:n}),closeDeleteDialog:()=>e({deleteDialog:null,deleteUnsaved:null}),archivedNotice:null,noteChatsArchived:s=>e({archivedNotice:s}),setupOutputDialog:null,openSetupOutputDialog:s=>e({setupOutputDialog:s}),closeSetupOutputDialog:()=>e({setupOutputDialog:null}),actionsSheet:null,openActionsSheet:s=>e({actionsSheet:s}),closeActionsSheet:()=>e({actionsSheet:null}),noteProgress:s=>{const n=t().progressRevision+1;vn.set(s.spaceId,n);const a=t().journey?.get(s.spaceId);if(!a)return e({progressRevision:n}),!1;const i=new Map(t().journey);return i.set(s.spaceId,Kv(a,s)),e({journey:i,progressRevision:n}),!0},applyMarks:s=>e(n=>{const a=new Map(s.map(i=>[i.id,i]));return a.size===0&&n.spaces.size===0?n:{spaces:a}}),noteStream:(s,n)=>e(a=>n==="connected"?a:{spaces:Rg(a.spaces,s,"stale")}),noteReachable:s=>e(n=>({spaces:Rg(n.spaces,s,"complete")})),resetForRuntimeSwitch:()=>{vn.clear(),Xn+=1,e({spaces:Zc,journey:null,progressRevision:0,customProviders:new Map,accessDialog:null,actions:new Map,applyDialog:null,deleteDialog:null,deleteUnsaved:null,archivedNotice:null,setupOutputDialog:null,actionsSheet:null})},forgetForSwitchOff:()=>t().resetForRuntimeSwitch()}));let Xn=0;const UE=()=>Xn,Zv=async()=>{const e=Xn,t=$e.getState().progressRevision,s=await jv();if(e===Xn){$e.getState().applyJourney(s,t);for(const n of new Set(s.flatMap(a=>a.projectDirectory?[a.projectDirectory]:[])))$e.getState().customProviders.has(n)||Jv(n)}},Vr=new Map,Jv=e=>{const t=Vr.get(e);if(t)return t;const s=Xn,n=Ov(e).then(a=>{s===Xn&&$e.getState().noteCustomProviders(e,a)}).catch(()=>{}).finally(()=>{Vr.delete(e)});return Vr.set(e,n),n},$v=e=>$e.getState().spaces.get(e)??null,th=e=>e?.state==="exited"||e?.state==="missing"||e?.state==="unreachable",Qv=e=>th($e.getState().journey?.get(e)),sh=e=>e?.state==="failed"||e?.state==="missing"||e?.state==="unreachable",WE=e=>{const t=Ft.c(2);let s;return t[0]!==e?(s=n=>e!=null&&sh(n.journey?.get(e)),t[0]=e,t[1]=s):s=t[1],$e(s)},HE=e=>{const t=kt(e);return t!==null&&sh($e.getState().journey?.get(t))},nh=(e,t)=>{const s=kt(t);return s===null?null:e.spaces.get(s)?.projectDirectory??e.journey?.get(s)?.projectDirectory??null},GE=e=>nh($e.getState(),e),_E=e=>{const t=Ft.c(2);let s;return t[0]!==e?(s=n=>nh(n,e),t[0]=e,t[1]=s):s=t[1],$e(s)},KE=e=>{const t=kt(e);return t!==null&&Qv(t)},Yv=e=>new Set([...e.spaces.keys(),...e.journey?.keys()??[]]),ZE=e=>{const t=kt(e);return t===null||Yv($e.getState()).has(t)},JE=(e,t)=>Array.from(e).filter(s=>!t.has(s)),$E=e=>{const t=Ft.c(4);let s;t[0]!==e?(s=kt(e),t[0]=e,t[1]=s):s=t[1];const n=s;let a;return t[2]!==n?(a=i=>n!==null&&th(i.journey?.get(n)),t[2]=n,t[3]=a):a=t[3],$e(a)},Xv=(e,t)=>{const s=Array.from(e.values(),n=>{const a=t?.get(n.id);return a?{...n,taskTitle:a.taskTitle??null}:n});for(const n of t?.values()??[])e.has(n.id)||n.projectDirectory===null||n.directory===null||s.push({id:n.id,name:n.name,taskTitle:n.taskTitle??null,state:"complete",projectDirectory:n.projectDirectory,directory:n.directory});return s},QE=e=>{const t=Ft.c(7),s=e===void 0?!0:e;let n;t[0]!==s?(n=c=>s?c.spaces:Zc,t[0]=s,t[1]=n):n=t[1];const a=$e(n);let i;t[2]!==s?(i=c=>s?c.journey:null,t[2]=s,t[3]=i):i=t[3];const o=$e(i);let r;return t[4]!==o||t[5]!==a?(r=Xv(a,o),t[4]=o,t[5]=a,t[6]=r):r=t[6],r},YE=(e,t)=>{const s=ze(t);return Array.from(e.values()).filter(n=>s!==null&&ze(n.projectDirectory)===s)},XE=e=>Array.from(e.values()).filter(t=>t.projectDirectory===null),eL=()=>{const e=Ft.c(5),t=$e(eC),[s,n]=Kn.useState(null);let a,i;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>{let r=!0;return Zv().then(()=>{r&&n(null)},c=>{r&&n(c)}),()=>{r=!1}},i=[],e[0]=a,e[1]=i):(a=e[0],i=e[1]),Kn.useEffect(a,i);let o;return e[2]!==s||e[3]!==t?(o={journey:t,error:s},e[2]=s,e[3]=t,e[4]=o):o=e[4],o};function eC(e){return e.journey}const jg=500,ah=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("OPENCHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},tL=()=>ah(),Tt=(e,t)=>{if(!ah())return;const s=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=s,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(s-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>jg&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-jg)},tC=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(n=>n.name==="ModelControls:ready"),s=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,s).filter(n=>n.name.includes("checkConnection")||n.name.includes("checkHealth")||n.name.includes("initializeApp")||n.name.includes("initApp")||n.name.includes("loadProviders")||n.name.includes("loadAgents")||n.name.includes("config.defaults")||n.name.includes("modelsMetadata")||n.name.includes("ModelControls")||n.name.includes("activateDirectory")||n.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=tC);const sL=async(e,t,s)=>{const n=typeof performance<"u"?performance.now():Date.now();Tt(`${e}:start`,s);try{const a=await t(),i=typeof performance<"u"?performance.now():Date.now();return Tt(`${e}:end`,{durationMs:Math.round(i-n)}),a}catch(a){const i=typeof performance<"u"?performance.now():Date.now();throw Tt(`${e}:error`,{durationMs:Math.round(i-n),error:a instanceof Error?a.message:String(a)}),a}},sC=3,nC=3e4,aC=32e3,iC=3600*1e3,oC=600*1e3,rC=200,cC=new Set([429,502,503,504]),is=new Map,rd=e=>JSON.stringify([D(),e]);function lC(){const e=Date.now();for(const[t,s]of is){const n=Math.max(s.lastErrorAt,s.circuitOpenAt);e-n>iC&&is.delete(t)}}typeof setInterval<"u"&&setInterval(lC,oC).unref?.();function dC(e){const t=rd(e);let s=is.get(t);if(!s)for(s={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:nC},is.set(t,s);is.size>rC;){const n=is.keys().next().value;if(!n)break;is.delete(n)}return s}function gC(e){e&&is.delete(rd(e))}function pC(e,t){if(!e)return;const s=dC(e);s.consecutiveErrors+=1,s.lastErrorAt=Date.now(),uC(t)&&s.consecutiveErrors>=sC&&(s.circuitOpen=!0,s.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${s.consecutiveErrors} consecutive errors`))}function uC(e){return e!==void 0&&cC.has(e)}function mC(e){const t=is.get(rd(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,aC*4),!1):!0:!1}function hC(e){if(!(!e||!mC(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}function Ur({providerID:e,id:t,variant:s}){return s?{providerID:e,id:t,variant:s}:{providerID:e,id:t}}function nL(e,t){return e.providerID===t.providerID&&e.id===t.id&&(e.variant??"default")===(t.variant??"default")}function aL(e,t){if(!(!e||!t))return e.find(s=>s.id===t)??e.find(s=>s.modelID===t)}function X(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const Hn={text:(e,t)=>`${e}:text:${t}`,reasoning:(e,t)=>`${e}:reasoning:${t}`,tool:e=>e,userText:e=>`${e}:text:0`,userFile:(e,t)=>`${e}:file:${t}`,userAgent:(e,t)=>`${e}:agent:${t}`},iL=e=>e==="completed"||e==="error",ih=e=>e.role==="user"||e.role==="assistant",oL=e=>e==="user"||e==="assistant",rL=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s&&ih(s))return s}},cL=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s?.info&&ih(s.info))return s}},lL=e=>e?.role==="assistant"&&e.time.completed===void 0,L={edit:"edit",execute:"execute",glob:"glob",grep:"grep",patch:"patch",question:"question",read:"read",shell:"shell",skill:"skill",subagent:"subagent",webfetch:"webfetch",websearch:"websearch",write:"write",sessionRename:"session_rename",sessionMove:"session_move",models:"models"};function Nt(e){const t=e?.trim().toLowerCase();if(!t)return"";const s=t.replace(/:\d+$/,"");if(!s.includes("."))return s;const n=s.split(".").filter(Boolean);return n[n.length-1]??s}const Es=e=>t=>Nt(t)===e,fC=Es(L.shell),dL=Es(L.execute),cd=Es(L.subagent),gL=Es(L.question),pL=Es(L.skill),uL=Es(L.edit),mL=Es(L.write),hL=Es(L.patch),bC=new Set([L.read,L.skill]),kC=e=>bC.has(Nt(e)),yC=new Set([L.edit,L.write,L.patch]),wC=new Set([L.read,L.grep,L.glob,L.skill]),vC=new Set([L.webfetch,L.websearch]),fL=e=>yC.has(Nt(e)),bL=e=>{const t=Nt(e);return t===L.edit||t===L.patch},kL=e=>wC.has(Nt(e)),yL=e=>vC.has(Nt(e)),wL=e=>Nt(e)===L.websearch,q=g().trim().min(1).optional().catch(void 0),Og=v().int().nonnegative().optional().catch(void 0),Jc=J([z(),R(["true","false"]).transform(e=>e==="true")]).optional().catch(void 0),CC=p({path:q,filePath:q,file_path:q,command:q,description:q,agent:q,name:q,id:q,title:q,directory:q,search:q,provider:q,patchText:q,pattern:q,query:q,url:q,code:q,questions:x(Y()).optional().catch(void 0),action:q,parameters:p({title:q,name:q,prompt:q,path:q,url:q,query:q,text:q,selector:q,taskId:q,link:p({identifier:q,title:q}).optional().catch(void 0)}).optional().catch(void 0)}).catch({}),SC=p({file:q,patch:q,additions:Og,deletions:Og,status:R(["added","deleted","modified"]).optional().catch(void 0)}),PC=p({tool:q,status:q,input:Y().optional().catch(void 0)}),ga=p({files:x(SC.nullable().catch(null)).optional().catch(void 0),sessionID:q,sessionId:q,shellID:q,status:q,name:q,toolCalls:x(PC.nullable().catch(null)).optional().catch(void 0),truncated:z().optional().catch(void 0),outputPath:q}).catch({}),pa=e=>CC.parse(e??{}),Dg=p({html:g().optional().catch(void 0),ui:g().optional().catch(void 0),title:q,awaitAnswer:Jc}),AC=Dg.extend({parameters:Dg.optional().catch(void 0)}).catch({}),zC=J([p({answered:y(!0),summary:g(),data:zo().catch(null)}),p({answered:y(!1),reason:g().optional().catch(void 0)})]),xC=p({openchamber:p({ok:z().optional().catch(void 0),answer:zC.optional().catch(void 0)}).optional().catch(void 0)}).catch({});function TC(e){const t=pa(e);return t.path??t.filePath??t.file_path}function $c(e){return(ga.parse(e??{}).files??[]).filter(s=>s!==null&&s.file!==void 0)}const Bg=160;function vL(e){const t=ga.parse(e??{});return t.shellID||t.status==="running"&&(t.sessionID||t.sessionId)?!0:(t.toolCalls??[]).some(s=>s?.status==="running"&&(fC(s.tool)||cd(s.tool)))}function IC(e){const t=ga.parse(e??{}).toolCalls??[],s=[];for(const n of t){if(!n?.tool)continue;const a={tool:n.tool};n.status&&(a.status=n.status);const i=jC(n.input);i&&i!=="{}"&&i!=="null"&&(a.input=i.length>Bg?`${i.slice(0,Bg)}…`:i),s.push(a)}return s}const RC=p({toolCalls:x(p({tool:q,input:zo().optional().catch(void 0)}).nullable().catch(null)).optional().catch(void 0)}).catch({});function CL(e){const t=RC.parse(e??{}).toolCalls??[];for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n?.tool)return{tool:n.tool,input:n.input}}}function jC(e){if(e!=null)try{return JSON.stringify(e)}catch{return}}function SL(e){const t=ga.parse(e??{});return t.truncated?t.outputPath?{outputPath:t.outputPath}:{}:null}function PL(e){return pa(e).code}const OC=e=>e===oh,DC={amp:"&",lt:"<",gt:">",quot:'"',"#39":"'",apos:"'",nbsp:" "},BC=120,Fg=(e,t)=>(t.exec(e)?.[1]??"").replace(/<[^>]*>/g," ").replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g,(s,n)=>DC[n]).replace(/\s+/g," ").trim(),FC=e=>(Fg(e,/<title\b[^>]*>([\s\S]*?)<\/title>/i)||Fg(e,/<h[1-3]\b[^>]*>([\s\S]*?)<\/h[1-3]>/i)).slice(0,BC).trim();function NC(e,t){if(!OC(e))return null;const s=AC.parse(t.input??{}),n=s.parameters?.html??s.html??"",a=s.parameters?.ui??s.ui,i=a?.trim()?{html:"",ui:a}:n.trim()?{html:n}:null;if(!i)return null;const o=(s.parameters?.title??s.title)?.trim()||FC(n);if((s.parameters?.awaitAnswer??s.awaitAnswer)===!0){if(t.status==="running")return{...i,title:o,ask:{kind:"waiting"}};if(t.status==="error")return{...i,title:o,ask:{kind:"unanswered"}}}if(t.status!=="completed")return null;const r=xC.parse(t.metadata??{}).openchamber;if(r?.ok!==!0)return null;const c=r.answer;if(c?.answered===!0)return{...i,title:o,ask:{kind:"answered",summary:c.summary,data:c.data}};if(c?.answered===!1){const l=c.reason==="chat-sent-earlier"?"chat-sent-earlier":c.reason==="ui-not-drawn"?"not-drawn":"answered-in-chat";return{...i,title:o,ask:{kind:l}}}return{...i,title:o,ask:{kind:"show"}}}const Ng=p({label:q,reason:q,placeholder:q}),MC=Ng.extend({parameters:Ng.optional().catch(void 0)}).catch({}),EC=p({openchamber:p({ok:z().optional().catch(void 0),answer:J([p({status:R(["saved","declined"])}).transform(({status:e})=>e),p({answered:y(!1)}).transform(()=>"not-given")]).optional().catch(void 0)}).optional().catch(void 0)}).catch({});function LC(e,t){if(e!==dd)return null;const s=MC.parse(t.input??{}),n=s.parameters?.label??s.label,a=s.parameters?.reason??s.reason;if(!n||!a)return null;const i={label:n,reason:a,placeholder:s.parameters?.placeholder??s.placeholder};if(t.status==="running")return{...i,state:"waiting"};if(t.status==="error")return{...i,state:"not-given"};if(t.status!=="completed")return null;const o=EC.parse(t.metadata??{}).openchamber;return o?.ok!==!0||!o.answer?null:{...i,state:o.answer}}function AL(e){return pa(e).agent}function zL(e){return pa(e).description}function qC(e){const t=ga.parse(e??{});return t.sessionID??t.sessionId}const ld=100,VC=4,UC=120,oh="openchamber_render",dd="openchamber_secret",rh="openchamber_workflow",ch="openchamber_image",lh=new Set(["openchamber","openchamber_schedule","openchamber_web","openchamber_memory","openchamber_knowledge","openchamber_notify",oh,ch,dd,rh]),WC=p({ok:y(!0),action:y("workflow.run"),data:p({runId:g().min(1)})});function HC(e,t){if(e!==rh||t.status!=="completed")return null;let s;try{s=JSON.parse(t.output)}catch{return null}const n=WC.safeParse(s);return n.success?n.data.data.runId:null}const GC=p({ok:y(!0),action:y("image.generate"),data:p({images:x(p({path:g().min(1)})).min(1)})});function _C(e,t){if(e!==ch||t.status!=="completed")return[];let s;try{s=JSON.parse(t.output)}catch{return[]}const n=GC.safeParse(s);return n.success?n.data.data.images.map(a=>a.path):[]}const xL=(e,t)=>NC(e,t)!==null||HC(e,t)!==null||_C(e,t).length>0||LC(e,t)!==null,KC=p({action:q,awaitAnswer:Jc,parameters:p({awaitAnswer:Jc}).optional().catch(void 0)}).catch({}),ZC=new Set(["session_rename","session_move","worktree_create","worktree_list","worktree_remove","models","list_mcp_resources","read_mcp_resource"]),Mg="opencode_";function TL(e){const t=e?.trim().toLowerCase()??"",s=t.startsWith(Mg)?t.slice(Mg.length):Nt(t);return ZC.has(s)?s:void 0}function IL(e,t){const s=e?.trim()??"";let n;for(const a of t){const i=`${a.replace(/[^a-zA-Z0-9_-]/g,"_")}_`;s.length>i.length&&s.startsWith(i)&&a.length>(n?.length??0)&&(n=a)}return n}function RL(e,t){const s=Nt(e);if(!lh.has(s))return null;const n=KC.parse(t??{}),a=s===dd||(n.parameters?.awaitAnswer??n.awaitAnswer)===!0;return{tool:s,action:n.action,awaitsAnswer:a}}function JC(e){const t=e.parameters,s=t?.link,a=(s?[s.identifier,s.title].filter(Boolean).join(" "):void 0)||t?.title||t?.name||t?.path||t?.url||t?.query||t?.text||t?.selector||t?.prompt?.split(`
@@ -29,7 +29,7 @@ A new session could conflict with them. You may want to commit them first or use
29
29
 
30
30
  Skip creates the worktree without running them. You can run them yourself after reading the code.`,"session.newWorktree.toast.worktreeCreated":"Worktree created","session.newWorktree.toast.worktreeCreatedDescription":"{target} - bootstrapping in background","session.newWorktree.toast.fetchSourceFailed":"Couldn't fetch from remote — created from local state","session.newWorktree.toast.fetchSourceAccess":"Couldn't fetch: this repository's access needs attention in Configure repository. Created from local state.","session.newWorktree.toast.startFolderMissing":'This worktree has no "{folder}" folder, so OpenCode started at the worktree root.',"session.newWorktree.toast.startFolderUnverified":`Couldn't check the "{folder}" folder, so OpenCode started at the worktree root.`,"session.newWorktree.toast.startFolderUnknown":"Couldn't tell which folder of the repository this project opens, so OpenCode started at the worktree root.","session.newWorktree.toast.branchBackup":"{branch} now matches the remote. Its previous commits are kept in {backup}.","session.githubIntegration.tabs.pullRequests":"Pull Requests","session.githubIntegration.validation.branchAlreadyCheckedOut":"Branch is already checked out in a worktree","session.githubIntegration.validation.failed":"Validation failed","chat.fileAttachment.toast.attachFailed":"Failed to attach file","chat.fileAttachment.toast.tooLarge":"{name} is too large to attach (over {size}). Mention it with @ if it is in the project.","chat.fileAttachment.toast.overSendLimit":"{name} is too large to attach (over {size}).","chat.fileAttachment.toast.someFilesSkipped":`Some files were skipped:
31
31
  {summary}`,"chat.fileAttachment.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.fileAttachment.fileFallback":"file","chat.fileAttachment.skippedFallback":"skipped","chat.fileAttachment.actions.attachAria":"Attach files","chat.fileAttachment.actions.attach":"Attach files","chat.fileAttachment.actions.removeNamed":"Remove {name}","chat.fileAttachment.actions.removeImage":"Remove image","chat.fileAttachment.activeEditor.addFile":"Add file:{name} to context","chat.fileAttachment.activeEditor.pinSelection":"Pin selection to context","chat.fileAttachment.activeEditor.remove":"Remove from context","chat.fileAttachment.openInDiagram":"Open in diagram view","chat.changedFiles.title":"Changed files","chat.changedFiles.actions.openFileTitle":"Open {path}","chat.changedFiles.actions.otherFiles":"Other changed files ({count})","chat.changedFiles.actions.showFewer":"Show fewer files","chat.emptyState.opencodeUnreachable":"OpenCode is not reachable","chat.emptyState.startNewChat":"Start a new chat","chat.emptyState.draftTitle":"What are we working on?","chat.emptyState.draftTitleWithProject":"What are we working on in {project}?","chat.draftPresets.explore.label":"Explore the codebase","chat.draftPresets.catchup.label":"Catch me up","chat.draftPresets.weigh.label":"Weigh my options","chat.draftPresets.plan.label":"Start feature planning","chat.draftPresets.craftGoal.label":"Craft a Goal","chat.draftPresets.scheduleTask.label":"Schedule a Task","chat.draftPresets.debug.label":"Debug an issue","chat.draftPresets.review.label":"Review my changes","chat.draftStarters.add":"Add a starter","chat.draftStarters.searchPlaceholder":"Search commands and skills…","chat.draftStarters.empty":"Nothing to add","chat.draftStarters.sectionBuiltIn":"Built-in","chat.draftStarters.sectionCommands":"Commands","chat.draftStarters.sectionSkills":"Skills","chat.draftStarters.remove":"Remove","chat.draftStarters.sharedTitle":"Pinned in the repository config; change it there","chat.draftStarters.share":"Move to repository config","chat.draftStarters.makePersonal":"Move to my settings","chat.scrollToBottom.aria":"Scroll to bottom","chat.promptNavigator.aria":"Prompt navigation","chat.promptNavigator.currentPrompt":"Current prompt","chat.promptNavigator.loadMore":"Load more prompts","chat.timeline.relative.justNow":"just now","chat.timeline.relative.minutesAgo":"{count}m ago","chat.timeline.relative.hoursAgo":"{count}h ago","chat.timeline.relative.daysAgo":"{count}d ago","chat.timeline.title":"Conversation Timeline","chat.timeline.description":"Navigate to any point in the conversation or fork a new session","chat.timeline.searchPlaceholder":"Search messages...","chat.timeline.empty.search":"No messages found","chat.timeline.empty.session":"No messages in this session yet","chat.timeline.noTextContent":"[No text content]","chat.timeline.actions.title":"Actions","chat.timeline.actions.revertFromHere":"Revert from here","chat.timeline.actions.forkFromHere":"Fork from here","chat.timeline.actions.previousTurn":"Previous turn","chat.timeline.actions.latest":"Latest","chat.timeline.help.clickMessage":"Click on a message to scroll to it in the conversation","chat.timeline.help.undoToPoint":"Undo to this point (message text will populate input)","chat.timeline.help.createSessionFromHere":"Create a new session starting from here","chat.statusRow.todo.status.inProgress":"In progress","chat.statusRow.todo.status.pending":"Pending","chat.statusRow.todo.status.completed":"Completed","chat.statusRow.todo.status.cancelled":"Cancelled","chat.statusRow.todo.priority.high":"High priority","chat.statusRow.todo.priority.medium":"Medium priority","chat.statusRow.todo.priority.low":"Low priority","chat.statusRow.actions.stopGeneratingAria":"Stop generating","chat.statusRow.tasksTitle":"Tasks","chat.statusRow.modelStatus":"{model} is {status}","chat.statusRow.summary.activeLeft":"{active} active · {left} left","chat.revertIndicator.redo":"Redo","chat.revertIndicator.redoAria":"Redo — restore reverted messages","chat.revertPopover.title":"Reverted","chat.revertPopover.noTextContent":"No text content","chat.revertPopover.forkFromHere":"Fork from here","chat.revertPopover.forkFromMessage":"Fork from this message","chat.revertPopover.restoreAll":"Restore all","chat.revertPopover.restore":"Restore","chat.revertPopover.revert":"Revert","chat.revert.toast.undo":"Reverted to {preview}","chat.revert.toast.redo":"Redone","chat.revert.toast.restored":"Restored all messages","chat.toast.opencodeRestartInterrupted.title":"Chat interrupted","chat.toast.opencodeRestartInterrupted.description":"OpenCode restarted while a response was still running. Send a message to continue.","chat.toast.opencodeRestartInterrupted.autoResumeDescription":"OpenCode restarted while a response was still running. The chat will resume automatically; send a message if it does not.","chat.toast.opencodeRestartInterrupted.openSession":"Open session","chat.errorBoundary.title":"Chat Error","chat.errorBoundary.description":"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.","chat.errorBoundary.sessionLabel":"Session","chat.errorBoundary.detailsSummary":"Error details","chat.errorBoundary.resetAction":"Reset Chat","chat.errorBoundary.persistentHint":"If the problem persists, try refreshing the page.","chat.autocomplete.tabs.commands":"Commands","chat.autocomplete.tabs.agents":"Agents","chat.autocomplete.tabs.files":"Files","chat.autocomplete.keyboardHint":"↑↓ navigate • Enter select • Esc close","chat.commandAutocomplete.command.initDescription":"Create/update AGENTS.md file","chat.commandAutocomplete.command.undoDescription":"Undo the last message","chat.commandAutocomplete.command.redoDescription":"Redo previously undone messages","chat.commandAutocomplete.command.timelineDescription":"Open the conversation timeline","chat.commandAutocomplete.command.compactDescription":"Compress session history using AI to reduce context size","chat.commandAutocomplete.command.summaryDescription":"Non-destructive session summary. Optional topic hint after the command.","chat.commandAutocomplete.command.workspaceReviewDescription":"Review the workspace diff for intent, correctness, and adequacy, graded by severity.","chat.commandAutocomplete.command.handoffReviewDescription":"Create or reuse a separate review session from a generated handoff.","chat.commandAutocomplete.command.featurePlanDescription":"Start a guided, back-and-forth planning session for a new feature.","chat.commandAutocomplete.command.craftGoalDescription":"Turn an idea or task into a clear, verifiable Goal.","chat.commandAutocomplete.command.scheduleTaskDescription":"Define a scheduled task through a guided dialogue.","chat.chatInput.toast.craftGoalFailed":"Failed to start Goal crafting","chat.chatInput.toast.scheduleTaskFailed":"Failed to start scheduled task setup","chat.commandAutocomplete.command.catchUpDescription":"Re-establish context: what you were doing and where to pick up.","chat.commandAutocomplete.command.debugDescription":"Guided root-cause investigation for a bug before proposing a fix.","chat.commandAutocomplete.command.weighDescription":"Weigh 2-3 approaches with trade-offs and a recommendation before you commit.","chat.commandAutocomplete.command.exploreDescription":"Get oriented in this codebase: a high-level tour of the architecture and main parts.","chat.commandAutocomplete.command.btwDescription":"Ask a side question in a temporary child session without derailing this chat.","chat.commandAutocomplete.command.forkDescription":"Fork this chat from the last finished reply and continue there; text after /fork is sent to the fork.","chat.commandAutocomplete.empty":"No commands found","chat.agentMentionAutocomplete.badge.system":"system","chat.agentMentionAutocomplete.empty":"No agents found","chat.fileMentionAutocomplete.searchMoreAgents":"Type to search more agents","chat.fileMentionAutocomplete.empty":"No matches found","chat.queuedMessage.attachments":"+{count} file(s)","chat.queuedMessage.empty":"(empty)","chat.queuedMessage.title":"Queued messages","chat.queuedMessage.edit":"edit","chat.queuedMessage.send":"send","chat.queuedMessage.removeAria":"Remove from queue","chat.queuedMessage.goal":"Starts a goal when sent","chat.queuedMessage.sendsAsAgent":"Sends as {agent}.","chat.queuedMessage.reorderAria":"Drag to reorder","chat.queuedMessage.toast.queueFailed":"Couldn't queue the message. It's back in the composer.","chat.queuedMessage.toast.takeFailed":"Couldn't load the queued message. Please try again.","chat.container.returnToParent.aria":"Return to parent session","chat.container.returnToParent.titleNamed":"Return to: {title}","chat.container.returnToParent.title":"Return to parent session","chat.container.returnToParent.label":"Parent","chat.container.readOnlySubagentPromptBanner":"Subagent sessions cannot be prompted.","chat.btw.destroyAria":"Destroy this btw session","chat.btw.titleFallback":"btw session","chat.btw.mainComposerPlaceholder":"Ask in this btw session…","chat.btw.loading":"Starting btw session…","chat.btw.toast.emptyArgument":"Type a question after /btw","chat.btw.toast.createFailed":"Failed to start the btw session","chat.btw.toast.destroyFailed":"Failed to destroy the btw session. It will remain in the sidebar.","chat.btw.working":"Working…","chat.btw.collapseAria":"Collapse the btw panel","chat.btw.draftHint":"Ask your question","chat.btw.cancelAria":"Cancel this BTW question","chat.btw.expandAria":"Expand the btw panel","chat.btw.promoteAria":"Keep as a separate session","chat.btw.toast.promoteFailed":"Failed to keep the btw session","chat.container.sessionLoadError.title":"Session could not be loaded","chat.container.sessionLoadError.description":"The conversation could not be fetched — the server may be offline or unreachable. Nothing is lost; retry once it is back.","chat.container.sessionLoadError.authDescription":"Your session expired, so the server refused the request. Log in and the conversation will load.","chat.container.sessionLoadError.retry":"Try again","sessions.sidebar.group.empty.loadingSessions":"Loading sessions…","sessions.sidebar.group.empty.loadFailed":"Could not refresh sessions.","sessions.sidebar.group.empty.initializationFailed":"Could not initialize workspace.","sessions.search.submitHint":"Press Enter to search","sessions.sidebar.group.empty.retry":"Try again","sessions.sidebar.group.empty.permissionDenied":"Folder access is required.","sessions.sidebar.group.empty.grantAccess":"Grant access","chat.unifiedControls.title":"Controls","chat.unifiedControls.model.title":"Model","chat.unifiedControls.model.noRecent":"No recent models","chat.unifiedControls.model.moreAria":"More models","chat.unifiedControls.effort.title":"Effort","chat.unifiedControls.effort.moreAria":"More effort options","chat.questionCard.summaryTab":"Summary","chat.questionCard.noAnswer":"(no answer)","chat.questionCard.inputNeeded":"Input needed","chat.questionCard.fromSubagent":"From subagent","chat.questionCard.questionFallback":"Question {index}","chat.questionCard.selectMultiple":"Select multiple","chat.questionCard.recommended":"recommended","chat.questionCard.other":"Other…","chat.questionCard.yourAnswer":"Your answer","chat.questionCard.submit":"Submit","chat.questionCard.next":"Next","chat.questionCard.dismiss":"Dismiss","chat.questionCard.copyMarkdown":"Copy as Markdown","chat.questionCard.copyJson":"Copy as JSON","chat.questionCard.copiedMarkdown":"Question copied as Markdown","chat.questionCard.copiedJson":"Question copied as JSON","chat.questionCard.copyFailed":"Failed to copy question","chat.questionCard.submitFailed":"Failed to send response","chat.questionCard.dismissFailed":"Failed to dismiss question","chat.questionCard.noLongerPending":"This question is no longer waiting for a response.","chat.questionCard.tryAgain":"Please try again in a moment.","chat.textSelection.toast.noProject":"No project found for this session","chat.textSelection.toast.addToNotesFailed":"Failed to add to notes","chat.textSelection.toast.addToNotesSuccess":"Added selected text to notes","chat.textSelection.toast.addToNotesSummaryFailed":"Could not summarize selection, added selected text to notes","chat.textSelection.actions.addToInput":"Quote","chat.textSelection.actions.read":"Read","chat.textSelection.actions.stopReading":"Stop","chat.textSelection.actions.comment":"Comment","chat.textSelection.actions.askOpenChamber":"By the way…","chat.textSelection.title.askOpenChamber":"Open a BTW draft with the selection","chat.textSelection.title.commentOnSelection":"Comment on selection","chat.textSelection.comment.placeholder":"Add an optional comment...","chat.textSelection.comment.attach":"Attach","chat.textSelection.comment.save":"Save comment","chat.textSelection.comment.attachFailed":"Could not attach the comment. Shorten it or remove other attached context, then try again.","chat.textSelection.actions.addToNotes":"Add to notes","chat.textSelection.title.addToCurrentChat":"Add to current chat","chat.textSelection.title.saveInsightToNotes":"Save selected text to notes","chat.messageBody.actions.revertAria":"Revert to this message","chat.messageBody.actions.revert":"Revert from here","chat.messageBody.actions.forkAria":"Fork from this message","chat.messageBody.actions.fork":"Fork from here","chat.messageBody.actions.copyMessageAria":"Copy message text","chat.messageBody.actions.copyMessage":"Copy message","chat.messageBody.actions.copyLink":"Copy link","chat.messageBody.toast.linkCopied":"Link copied","chat.messageBody.toast.linkCopyFailed":"Could not copy the link","chat.messageLink.notFound":"The linked message is not in this session","chat.messageBody.actions.pinContext":"Pin into context (survives compaction)","chat.messageBody.actions.unpinContext":"Unpin from context (will not survive compaction)","chat.messageBody.actions.contextPinFailed":"Could not update the context pin","chat.messageBody.actions.copyAnswer":"Copy answer","chat.messageBody.actions.moreActions":"More actions","chat.messageBody.toast.copied":"Copied to clipboard","chat.messageBody.actions.savingImage":"Saving image...","chat.messageBody.actions.saveAsImage":"Save as image","chat.messageBody.actions.saveAsPlan":"Save as plan","chat.messageBody.actions.startNewSession":"Start new session from this answer","chat.messageBody.actions.startNewMultiRun":"Start new multi-run from this answer","chat.messageBody.actions.branchMenu":"Continue from this answer","chat.messageBody.footer.reasoningTooltip":"Reasoning: {effort}","chat.messageBody.forkDialog.instructions.label":"Instructions","chat.messageBody.forkDialog.instructions.placeholder":"Add instructions for the new session…","chat.messageBody.forkDialog.createWorktree":"Create worktree","chat.generatedResult.actions.copy":"Copy","chat.generatedResult.actions.copied":"Copied","chat.generatedResult.commit.title":"Generated commit message","chat.generatedResult.commit.highlights":"Highlights","chat.generatedResult.pullRequest.title":"Generated pull request","chat.generatedResult.mergeRequest.title":"Generated merge request","chat.generatedResult.pullRequest.titleLabel":"Title","chat.generatedResult.pullRequest.bodyLabel":"Body","chat.messageBody.tts.stopSpeaking":"Stop speaking","chat.messageBody.tts.readAloud":"Read aloud","chat.messageBody.tts.readAloudWithProvider":"Read aloud ({provider} voice)","planView.tts.readAloud":"Read plan aloud","planView.tts.stopSpeaking":"Stop speaking","filesView.tts.readAloud":"Read file aloud","filesView.tts.stopSpeaking":"Stop speaking","chat.messageBody.toast.noProject":"No project found for this session","chat.messageBody.toast.savePlanFailed":"Failed to save plan","chat.messageBody.toast.planSaved":"Plan saved","chat.messageBody.toast.imageSaved":"Image saved","chat.messageBody.toast.generateImageFailed":"Failed to generate image","chat.chatInput.actions.commands":"Commands","chat.chatInput.actions.attachFiles":"Attach files","chat.chatInput.actions.addAttachment":"Add attachment","chat.chatInput.actions.modelAgentSettings":"Model and agent settings","chat.chatInput.actions.sendMessageAria":"Send message","chat.chatInput.actions.queueMessageAria":"Queue message","chat.chatInput.actions.stopGeneratingAria":"Stop generating","chat.chatInput.linked.byAuthor":"by {author}","chat.chatInput.linked.issue.openInBrowserAria":"Open issue in browser","chat.chatInput.linked.issue.removeAria":"Remove linked issue","chat.chatInput.linked.pr.openInBrowserAria":"Open pull request in browser","chat.chatInput.linked.mr.openInBrowserAria":"Open merge request in browser","chat.chatInput.linked.pr.removeAria":"Remove linked pull request","chat.chatInput.linked.mr.removeAria":"Remove linked merge request","chat.chatInput.placeholder.shell":"Enter shell command...","chat.chatInput.placeholder.chat":"Plan, build, or ask. @ to mention, $ for skills, / for commands","chat.chatInput.placeholder.chatCompact":"Plan, build, or ask","chat.chatInput.placeholder.selectSession":"Select or create a session to start chatting","chat.dictation.start":"Start dictation","chat.dictation.overlayAria":"Dictation","chat.dictation.downloadingModel":"Downloading speech model...","chat.dictation.downloadingModelProgress":"Downloading speech model... {percent}%","chat.dictation.listening":"Listening...","chat.dictation.processing":"Transcribing...","chat.dictation.failed":"Transcription failed","chat.dictation.cancel":"Discard dictation","chat.dictation.insert":"Insert transcript","chat.dictation.insertAndSend":"Insert and send","chat.dictation.retry":"Retry transcription","chat.dictation.discard":"Discard recording","chat.snippetAutocomplete.action.addNew":"Add new snippet","chat.snippetAutocomplete.empty":"No snippets found","chat.snippetAutocomplete.footer":"↑↓ navigate • Enter select • Esc close","chat.chatInput.toast.compactFailed":"Failed to compact session","chat.chatInput.toast.forkFailed":"Couldn't fork the session","chat.chatInput.toast.forkNothingToFork":"Nothing to fork yet: no reply has finished in this session","chat.chatInput.toast.forkSendFailed":"Forked, but the message wasn't sent. It's back in the composer.","chat.chatInput.toast.summaryFailed":"Failed to generate summary","chat.messageBody.actions.sendReviewFeedback":"Send review feedback to implementing agent","chat.messageBody.actions.sendImplementationResponse":"Send implementation response to reviewing agent","chat.chatInput.toast.reviewFailed":"Failed to review changes","chat.chatInput.toast.planFeatureFailed":"Failed to start feature planning","chat.chatInput.toast.catchUpFailed":"Failed to catch up","chat.chatInput.toast.debugFailed":"Failed to start debugging","chat.chatInput.toast.weighFailed":"Failed to weigh options","chat.chatInput.toast.exploreFailed":"Failed to start the tour","chat.chatInput.toast.attachmentsTooLarge":"Attachments are too large to send. Please try reducing the number or size of images.","chat.chatInput.toast.sendAttachmentsFailed":"Failed to send attachments. Try fewer files or smaller images.","chat.chatInput.toast.messageSendFailed":"Message failed to send. Attachments restored.","chat.chatInput.toast.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent and send again.`,"chat.chatInput.toast.noModelSelected":"Select a provider and model before sending.","chat.chatInput.toast.clipboardAttachFailed":"Failed to attach image from clipboard","chat.chatInput.toast.clipboardTextAttachFailed":"Failed to attach pasted text as a file","chat.chatInput.largeTextPaste.title":"Large text detected","chat.chatInput.largeTextPaste.attach":"Attach as file","chat.chatInput.largeTextPaste.inline":"Paste inline","chat.chatInput.toast.addedFileMentions":"Added {count} file mention(s)","chat.chatInput.toast.attachFileFailed":"Failed to attach file","chat.chatInput.toast.attachNamedFailed":"Failed to attach {name}","chat.chatInput.toast.unsupportedAttachmentModalities":"{model} does not support {modalities} input required by {files}. You can still send the message, but these attachments may be ignored.","chat.chatInput.toast.imagesSaving":"Saving {files}…","chat.chatInput.toast.imagesSavedForTextModel":"{model} can't read images. Saved {files} to {folder}.","chat.chatInput.toast.imageSaveFailed":"Couldn't save {files}. Attached instead.","chat.chatInput.toast.imagesSaved":"Saved {files} to {folder}.","chat.chatInput.toast.imageCopySaveFailed":"Couldn't save {files}.","chat.chatInput.toast.someFilesSkipped":`Some files were skipped:
32
- {summary}`,"chat.chatInput.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.chatInput.toast.openSessionFirst":"Open a session first","chat.chatInput.toast.dictationKeptForOriginalSession":"Dictation saved as a draft in the session where you started it","chat.chatInput.toast.togglePermissionAutoAcceptFailed":"Failed to toggle permission auto-accept","chat.chatInput.reviewComments":"Review comments:","chat.chatInput.reviewCommentsRemove":"Remove review comments","chat.chatInput.previewAnnotations":"Preview annotations:","chat.chatInput.previewContext":"Preview context:","chat.chatInput.previewContextRemove":"Remove preview context","chat.chatInput.projectRoot":"Project root","chat.chatInput.branch":"Branch","chat.chatInput.draftPicker.projectTitle":"Project","chat.chatInput.draftPicker.searchProjects":"Search projects...","chat.chatInput.draftPicker.searchBranches":"Search branches...","chat.chatInput.draftPicker.noProjectsFound":"No projects found.","chat.chatInput.worktrees":"Worktrees","chat.chatInput.worktreeQuick":"Quick worktree","chat.chatInput.worktreeCustom":"New worktree…","chat.chatInput.drop.insertMention":"Drop to insert as mention","chat.chatInput.drop.attachFiles":"Drop files here to attach","chat.chatInput.fileFallback":"file","chat.toolOutputDialog.image.previousAria":"Previous image","chat.toolOutputDialog.image.nextAria":"Next image","chat.toolOutputDialog.image.closeAria":"Close image preview","chat.toolOutputDialog.mermaid.missingSource":"Missing Mermaid source URL.","chat.toolOutputDialog.mermaid.loadFailed":"Unable to load Mermaid diagram.","chat.toolOutputDialog.mermaid.dataUrlMalformed":"The Mermaid data URL is malformed.","chat.toolOutputDialog.mermaid.invalidLocalPath":"The local Mermaid file path is invalid.","chat.toolOutputDialog.mermaid.readFileFailedWithStatus":"Unable to read Mermaid file. Status: {status}.","chat.toolOutputDialog.mermaid.unsupportedUrlProtocol":"The Mermaid URL protocol is unsupported.","chat.toolOutputDialog.mermaid.loadFailedWithStatus":"Unable to load Mermaid diagram. Status: {status}.","chat.toolOutputDialog.mermaid.closeAria":"Close diagram preview","chat.toolOutputDialog.mermaid.loading":"Loading diagram...","chat.toolOutputDialog.mermaid.renderFailed":"Unable to render Mermaid diagram.","chat.toolOutputDialog.mermaid.retry":"Retry","chat.toolOutputDialog.commandCompleted":"Command completed successfully","chat.toolOutputDialog.noOutputProduced":"No output was produced","chat.statusRow.background.action":"Move to background — the agent stops waiting and continues","chat.statusRow.background.failed":"Couldn't move the work to the background","chat.toolPart.background.label":"in background","chat.toolPart.background.stop":"Stop command","chat.toolPart.background.stopLabel":"Stop","chat.toolPart.background.stopFailed":"Couldn't stop the command","chat.toolPart.background.stoppedLabel":"stopped","chat.toolPart.background.stoppedNotice":"Stopped by you. The agent was told this was your stop, not a failure.","chat.toolPart.subagent.stop":"Stop subagent","chat.toolPart.subagent.stopFailed":"Couldn't stop the subagent","chat.toolPart.lspErrors":"LSP errors","chat.toolPart.moreErrors":"+{count} more errors","chat.toolPart.moreRows":"+{count} more rows","chat.toolPart.error":"Error:","chat.toolPart.awaitingResponse":"Awaiting response...","chat.toolPart.noOutputProduced":"No output produced","chat.toolPart.questionsAsked":"Questions asked: {count}","chat.toolPart.filesCount":"Files: {count}","chat.toolPart.moreToolCalls":"+{count} more","chat.toolPart.scriptCalls":"Tool calls","chat.toolPart.outputTruncated":"Output was truncated","chat.toolPart.content.loading":"Loading the result…","chat.toolPart.content.loadFailed":"Couldn't load the result.","chat.toolPart.content.retry":"Retry","chat.toolPart.output":"Output","chat.toolPart.showRawJson":"Show raw JSON","chat.toolPart.showFormattedJson":"Show formatted JSON","chat.toolPart.showNavigableJson":"Show navigable JSON","chat.toolPart.openFile":"Open file","chat.toolPart.openImageExpanded":"Open","chat.toolPart.openFileAtFirstChange":"Open file at first change","chat.toolPart.openFileDiff":"Open file diff","chat.toolPart.copyOutput":"Copy output","chat.toolPart.copiedOutput":"Copied output","chat.toolPart.copyOutputFailed":"Failed to copy output","chat.toolPart.openSubtask":"Open {type} subtask","chat.todo.total":"Total","chat.todo.inProgress":"In Progress","chat.todo.pending":"Pending","chat.todo.completed":"Completed","chat.todo.cancelled":"Cancelled","chat.permissionCard.workingDirectory":"Working Directory:","chat.permissionCard.timeout":"Timeout:","chat.permissionCard.request":"Request:","chat.permissionCard.headers":"Headers:","chat.permissionCard.body":"Body:","chat.permissionCard.action":"Action:","chat.permissionCard.patterns":"Patterns:","chat.permissionToast.sessionFallback":"Session","chat.permissionToast.permissionFallback":"Permission details unavailable","chat.permissionToast.labels.session":"Session:","chat.permissionToast.labels.permission":"Permission:","chat.permissionToast.actions.once":"Once","chat.permissionToast.actions.always":"Always","chat.permissionToast.actions.deny":"Deny","chat.permissionToast.actions.approveOnceAria":"Approve once","chat.permissionToast.actions.approveOnceAriaWithSession":"Approve once for {session}","chat.permissionToast.actions.approveAlwaysAria":"Approve always","chat.permissionToast.actions.approveAlwaysAriaWithSession":"Approve always for {session}","chat.permissionToast.actions.denyAria":"Deny permission","chat.permissionToast.actions.denyAriaWithSession":"Deny permission for {session}","chat.permissionRequest.required":"Permission required:","chat.permissionRequest.actions.once":"Once","chat.permissionRequest.actions.always":"Always","chat.permissionRequest.actions.reject":"Reject","chat.modelControls.provider":"Provider","chat.modelControls.capability.toolCalling":"Tool calling","chat.modelControls.capability.reasoning":"Reasoning","chat.modelControls.modality.text":"Text","chat.modelControls.modality.image":"Image","chat.modelControls.modality.video":"Video","chat.modelControls.modality.audio":"Audio","chat.modelControls.modality.pdf":"PDF","chat.modelControls.capabilities":"Capabilities","chat.modelControls.modalities":"Modalities","chat.modelControls.input":"Input","chat.modelControls.output":"Output","chat.modelControls.limits":"Limits","chat.modelControls.context":"Context","chat.modelControls.metadata":"Metadata","chat.modelControls.knowledge":"Knowledge","chat.modelControls.release":"Release","chat.modelControls.mode":"Mode","chat.modelControls.model":"Model","chat.modelControls.temperature":"Temperature","chat.modelControls.topP":"Top P","chat.modelControls.permissions":"Permissions","chat.modelControls.edit":"Edit","chat.modelControls.bash":"Bash","chat.modelControls.webFetch":"WebFetch","chat.modelControls.customPrompt":"Custom Prompt","chat.modelControls.selectModel":"Select model","chat.modelControls.thinking":"Thinking","chat.modelControls.inheritedVariantTooltip":"Thinking: {variant}, this model's default","chat.modelControls.rememberedVariantTooltip":"Thinking: {variant}, last used with this model","chat.modelControls.default":"Default","chat.modelControls.selectAgent":"Select agent","chat.modelControls.costPerMillion":"Cost ($/1M tokens)","chat.modelControls.metadataUnavailable":"Model metadata unavailable.","chat.modelControls.addNewProvider":"Add new provider","chat.modelControls.noAgentSelected":"No agent selected.","chat.modelControls.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent.`,"chat.modelControls.searchModels":"Search models","chat.modelControls.modelListAria":"Models","chat.modelControls.searchAgents":"Search agents","chat.modelControls.noModelsFound":"No models found","chat.modelControls.favorites":"Favorites","chat.modelControls.agentsSection":"Agents","chat.modelControls.favoriteAgentsCycleHint":"{shortcut} to cycle","chat.modelControls.favoriteAgentsTapHint":"Tap the agent to cycle","chat.modelControls.noAgentsFound":"No agents found","chat.modelControls.recent":"Recent","chat.modelControls.addToFavorites":"Add to favorites","chat.modelControls.removeFromFavorites":"Remove from favorites","chat.modelControls.useModel":"Use model","chat.modelControls.favoriteAria":"Favorite","chat.modelControls.unfavoriteAria":"Unfavorite","chat.modelControls.collapseProvider":"Collapse provider","chat.modelControls.expandProvider":"Expand provider","chat.modelControls.keyboardHint":"↑↓ navigate{thinking} • Enter select • Esc close","chat.modelControls.keyboardHintNavigate":"↑↓ navigate","chat.modelControls.keyboardHintSwitchAgent":"{shortcut} switch agent","chat.modelControls.keyboardHintSwitchThinking":"{shortcut} switch","chat.modelControls.keyboardHintThinking":"←→ thinking","chat.modelControls.reorderProviderTitle":"Drag to reorder provider","chat.modelControls.permissionLabel.custom":"Custom","chat.modelControls.permissionLabel.allow":"Allow","chat.modelControls.permissionLabel.deny":"Deny","chat.modelControls.permissionLabel.ask":"Ask","chat.modelControls.modeValue.primary":"Primary","chat.modelControls.modeValue.subagent":"Subagent","chat.modelControls.modeValue.all":"All","chat.modelControls.modeValue.none":"—","chat.reasoningTrace.thinking":"Thinking","chat.reasoningTrace.expandAria":"Expand reasoning trace","chat.reasoningTrace.collapseAria":"Collapse reasoning trace","chat.reasoningTrace.thought":"Thought","chat.messageBody.subtask.title":"Delegated task","chat.messageBody.subtask.hidePrompt":"Hide prompt","chat.messageBody.subtask.showPrompt":"Show prompt","chat.messageBody.subtask.openSession":"Open subtask session","chat.messageBody.shellCommand.copied":"Copied","chat.messageBody.shellCommand.copyOutput":"Copy output","commandPalette.title":"Command Palette","commandPalette.description":"Search files, sessions, and commands.","commandPalette.input.placeholder":"Search files, sessions, commands...","commandPalette.empty.noResults":"No results found.","commandPalette.empty.searchingFiles":"Searching files...","commandPalette.item.newSession":"New Session","commandPalette.item.newMiniChat":"New Mini Chat Window","commandPalette.item.quickWorktree":"Quick Worktree","commandPalette.item.newWorktreeDialog":"New Worktree…","commandPalette.item.addProject":"Add Project","commandPalette.item.showSessionSwitcher":"Show Session Switcher","commandPalette.item.toggleSidebar":"Toggle Sidebar","commandPalette.item.showContextUsage":"Show Context Usage","commandPalette.item.toggleTerminal":"Toggle Terminal","commandPalette.item.cycleTheme":"Cycle theme","commandPalette.item.showOpenCodeStatus":"Show diagnostic timeline","commandPalette.item.restartOpenCode":"Restart OpenCode","commandPalette.item.toggleMemoryDebug":"Toggle memory debug panel","commandPalette.item.pinSession":"Pin or unpin session","commandPalette.item.copySessionId":"Copy session ID","commandPalette.item.openMultiRun":"Run in parallel","commandPalette.item.openArchive":"Open archived sessions","commandPalette.item.openNotes":"Open notes surface","commandPalette.item.openTodos":"Open todos surface","commandPalette.item.openSettings":"Open Settings...","commandPalette.session.untitled":"Untitled Session","commandPalette.item.reloadUi":"Reload UI","commandPalette.group.openFiles":"Open files","commandPalette.group.commands":"Commands","commandPalette.group.settings":"Settings","chat.search.placeholder":"Search this conversation","chat.search.position":"{current} of {total}","chat.search.noResults":"No results","chat.search.searching":"Searching…","chat.search.tooShort":"3+ characters","chat.search.error":"Couldn't search","chat.search.unavailable":"Not available here","chat.search.previous":"Previous match","chat.search.next":"Next match","chat.search.close":"Close search","commandPalette.group.sessions":"Sessions","commandPalette.group.messages":"Messages","commandPalette.messages.showAll":"Show all message results","commandPalette.messages.placeholder":"Search messages…","commandPalette.messages.back":"Back","commandPalette.messages.filter.scopeLabel":"Where","commandPalette.messages.filter.allProjects":"All projects","commandPalette.messages.filter.thisProject":"This project","commandPalette.messages.filter.authorLabel":"Written by","commandPalette.messages.filter.anyone":"Anyone","commandPalette.messages.filter.you":"You","commandPalette.messages.filter.agent":"Agent","commandPalette.messages.filter.reasoning":"Thinking","commandPalette.messages.inReasoning":"Thinking","commandPalette.messages.tooShort":"Type at least 3 characters to search messages","commandPalette.messages.searching":"Searching messages…","commandPalette.messages.error":"Couldn't search messages","commandPalette.messages.unavailable":"Message search is not available on this server","commandPalette.messages.empty":"No messages found","commandPalette.messages.indexing":"Still indexing older conversations: {done} of {total}.","commandPalette.messages.loadMore":"Load more","commandPalette.messages.byYou":"Your message","commandPalette.messages.byAgent":"Agent reply","commandPalette.group.files":"Files","commandPalette.group.projects":"Projects","commandPalette.footer.navigate":"to navigate","commandPalette.footer.open":"to open","commandPalette.footer.close":"to close","openCodeStatusDialog.title":"Diagnostic timeline","openCodeStatusDialog.description":"Local events in time order. Private log text and remote sources are excluded.","openCodeStatusDialog.actions.download":"Download log","openCodeStatusDialog.toast.collectFailed":"Failed to collect diagnostics","openCodeStatusDialog.actions.copy":"Copy","openCodeStatusDialog.empty.noData":"No data.","openCodeStatusDialog.toast.copiedTitle":"Copied","openCodeStatusDialog.toast.copiedDescription":"Diagnostic log copied to clipboard","openCodeStatusDialog.toast.copyFailed":"Failed to copy diagnostic log","saveProjectPlanDialog.title":"Save Project Plan","saveProjectPlanDialog.description":"Save this plan into your project as a Markdown file.","saveProjectPlanDialog.field.title":"Title","saveProjectPlanDialog.field.titlePlaceholder":"Plan title","saveProjectPlanDialog.field.contentPreview":"Content preview","saveProjectPlanDialog.actions.cancel":"Cancel","saveProjectPlanDialog.actions.save":"Save","saveProjectPlanDialog.actions.saving":"Saving...","branchPickerDialog.title":"Branch Picker","branchPickerDialog.description.localBranchesForProject":"Local branches for {project}","branchPickerDialog.description.selectProject":"Select a project to view branches","branchPickerDialog.search.placeholder":"Search branches...","branchPickerDialog.search.renameBranchPlaceholder":"Rename branch","branchPickerDialog.state.noProjectSelected":"No project selected","branchPickerDialog.state.loadingBranches":"Loading branches...","branchPickerDialog.state.noMatchingBranches":"No matching branches","branchPickerDialog.state.noBranchesFound":"No branches found","branchPickerDialog.badge.head":"HEAD","branchPickerDialog.badge.worktree":"worktree","branchPickerDialog.actions.createWorktreeAria":"Create worktree from branch","branchPickerDialog.actions.renameAria":"Rename branch","branchPickerDialog.actions.deleteAria":"Delete branch","branchPickerDialog.actions.deleteWorktreeAria":"Remove worktree","branchPickerDialog.actions.confirmRenameAria":"Confirm rename","branchPickerDialog.actions.cancelRenameAria":"Cancel rename","branchPickerDialog.actions.confirmDeleteAria":"Confirm delete branch","branchPickerDialog.actions.cancelDeleteAria":"Cancel delete branch","branchPickerDialog.actions.deletePrompt":"Delete","branchPickerDialog.actions.forceDeletePrompt":"Force Delete","branchPickerDialog.tooltip.createWorktree":"Create worktree","branchPickerDialog.tooltip.worktreeAlreadyExists":"Worktree already exists","branchPickerDialog.tooltip.rename":"Rename branch","branchPickerDialog.tooltip.renameDisabledForRoot":"Cannot rename root branch","branchPickerDialog.tooltip.delete":"Delete branch","branchPickerDialog.tooltip.deleteCurrentBranch":"Cannot delete current branch","branchPickerDialog.tooltip.deleteDisabledForRoot":"Cannot delete root branch","branchPickerDialog.tooltip.deleteWorktree":"Remove worktree","branchPickerDialog.tooltip.deleteWorktreeRootProtected":"Cannot remove root worktree","branchPickerDialog.toast.branchRenamed":"Branch renamed","branchPickerDialog.toast.failedToRenameBranch":"Failed to rename branch","branchPickerDialog.toast.branchDeleted":"Branch deleted","branchPickerDialog.toast.branchNotMerged":"Branch is not fully merged","branchPickerDialog.toast.confirmAgainToForceDelete":"Confirm again to force delete","branchPickerDialog.toast.failedToDeleteBranch":"Failed to delete branch","branchPickerDialog.toast.worktreeCreated":"Worktree created","branchPickerDialog.toast.failedToCreateWorktree":"Failed to create worktree","branchPickerDialog.error.failedToLoad":"Failed to load branches","branchPickerDialog.error.renameRejected":"Rename was rejected","branchPickerDialog.error.renameFailed":"Failed to rename branch","branchPickerDialog.error.deleteRejected":"Delete was rejected","branchPickerDialog.error.deleteFailed":"Failed to delete branch","branchPickerDialog.error.createWorktreeFailed":"Failed to create worktree","projectEditDialog.title":"Edit project","projectEditDialog.field.name":"Name","projectEditDialog.field.namePlaceholder":"Project name","projectEditDialog.field.color":"Color","projectEditDialog.field.icon":"Icon","projectEditDialog.field.preview":"Preview","projectEditDialog.field.iconBackground":"Icon Background","projectEditDialog.field.iconBackgroundAria":"Project icon background color","projectEditDialog.option.none":"None","projectEditDialog.actions.uploadIcon":"Upload Icon","projectEditDialog.actions.uploading":"Uploading...","projectEditDialog.actions.discoverFavicon":"Discover Favicon","projectEditDialog.actions.discovering":"Discovering...","projectEditDialog.actions.removeProjectIcon":"Remove Project Icon","projectEditDialog.actions.removing":"Removing...","projectEditDialog.actions.undoRemove":"Undo Remove","projectEditDialog.actions.clear":"Clear","projectEditDialog.actions.cancel":"Cancel","projectEditDialog.actions.save":"Save","projectEditDialog.toast.failedToUploadIcon":"Failed to upload project icon","projectEditDialog.toast.iconUpdated":"Project icon updated","projectEditDialog.toast.failedToRemoveIcon":"Failed to remove project icon","projectEditDialog.toast.iconRemoved":"Project icon removed","projectEditDialog.toast.failedToDiscoverIcon":"Failed to discover project icon","projectEditDialog.toast.customIconAlreadySet":"Custom icon already set for this project","projectEditDialog.toast.iconDiscovered":"Project icon discovered","openInApp.actions.open":"Open","openInApp.actions.openInAria":"Open in {app}","openInApp.actions.copyPath":"Copy Path","openInApp.actions.refreshApps":"Refresh Apps","openInApp.toast.pathCopied":"Path copied to clipboard","projectActions.actions.addActionAria":"Add action","projectActions.actions.addAction":"Add action","projectActions.actions.addNewAction":"Add new action","projectActions.actions.autoDiscover":"Auto-discover dev server","projectActions.menu.sharedBadge":"repo","projects.sharedTrust.title":"Run the commands stored in this repository?","projects.sharedTrust.description":"{path} in this repository defines commands that run on this machine. Trust them once, and OpenChamber asks again only when they change.","projects.sharedTrust.setupCommands":"Worktree setup commands","projects.sharedTrust.actions":"Actions","projects.sharedTrust.skip":"Not this time","projects.sharedTrust.trust":"Trust and run","projects.opencodeTrust.title":"Let OpenCode run code from this folder?","projects.opencodeTrust.description":"OpenCode runs the plugins and commands in the configuration of {path} as soon as it opens the folder. Trust them once, and OpenChamber asks again only when they change.","projects.opencodeTrust.plugins":"Plugins","projects.opencodeTrust.commands":"Commands","projects.opencodeTrust.kind.package":"{name} (npm package)","projects.opencodeTrust.kind.config":"{path}: a configuration file OpenChamber can't read","projects.opencodeTrust.kind.mcp":"MCP server {name}","projects.opencodeTrust.kind.lsp":"Language server {name}","projects.opencodeTrust.kind.formatter":"Formatter {name}","projects.opencodeTrust.kind.shell":"Shell","projects.opencodeTrust.paused":"Without trust, agents can't work in this folder, but you can still browse its files and Git changes.","projects.opencodeTrust.skip":"Not this time","projects.opencodeTrust.trust":"Trust and open","projects.opencodeTrust.saveFailed":"Couldn't save your answer. Try again.","projectActions.actions.autoDiscoverTooltip":"Automatically discover and run the development server","projectActions.actions.chooseActionAria":"Choose project action","projectActions.actions.openPreview":"Open Preview","projectActions.actions.runNamedAria":"Run {name}","projectActions.actions.stopNamedAria":"Stop {name}","projectActions.label.fallbackAction":"Action","projectActions.toast.openedUrlFromOutput":"Opened URL from action output","projectActions.toast.openedForwardedUrl":"Opened forwarded URL","projectActions.toast.openedActionUrl":"Opened action URL","projectActions.error.noActiveDirectory":"No active directory","projectActions.error.noActiveDirectoryForAction":"No active directory for action","projectActions.error.failedToCreateTerminalSession":"Failed to create terminal session","projectActions.error.invalidCustomUrlFormat":"Invalid custom URL format","projectActions.error.openUrlTemplateUnresolved":"Couldn't read the branch for the action URL","projectActions.error.selectedDesktopSshForwardUnavailable":"Selected desktop SSH forward is unavailable","projectActions.error.failedToRunAction":"Failed to run action","mcpDropdown.title":"MCP Servers","mcpDropdown.actions.refreshAria":"Refresh","mcpDropdown.actions.openAria":"MCP servers","mcpDropdown.statusAria":"MCP status","mcpDropdown.status.unknown":"Unknown","mcpDropdown.status.connected":"Connected","mcpDropdown.status.failed":"Failed: {error}","mcpDropdown.status.unknownError":"Unknown error","mcpDropdown.status.needsAuth":"Needs authentication","mcpDropdown.status.needsRegistration":"Needs registration: {error}","mcpDropdown.empty.configureInConfig":"Configure MCP servers in Settings.","sessionAuth.error.rateLimitTitle":"Too many attempts","sessionAuth.error.networkTitle":"Unable to reach server","sessionAuth.error.rateLimitDescriptionSingle":"Please wait {minutes} minute before trying again.","sessionAuth.error.rateLimitDescriptionPlural":"Please wait {minutes} minutes before trying again.","sessionAuth.error.networkDescription":"We could not verify the UI session. If you're opening OpenChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings.","sessionAuth.error.retry":"Retry","sessionAuth.error.passkeySetupFailed":"Passkey setup failed.","sessionAuth.error.incorrectPassword":"Incorrect password. Try again.","sessionAuth.error.unexpectedResponse":"Unexpected response from server.","sessionAuth.error.networkRetry":"Network error. Check connection and retry.","sessionAuth.error.passkeySignInCanceled":"Passkey sign-in was canceled.","sessionAuth.error.enterPasswordForPasskey":"Enter your password to add a passkey.","sessionAuth.locked.tunnelTitle":"Tunnel access required","sessionAuth.expired.banner":"Your session expired — log in to continue.","sessionAuth.expired.loginAction":"Log in","sessionAuth.expired.sendBlocked":"Session expired — log in to send messages.","sessionAuth.locked.unlockTitle":"Unlock OpenChamber","sessionAuth.locked.tunnelDescription":"Open this tunnel using the one-time connect link from the desktop app.","sessionAuth.locked.passwordDescription":"This session is password-protected.","sessionAuth.locked.hostSwitcherHint":"Use Local if remote is unreachable.","sessionAuth.actions.cancelPasskey":"Cancel passkey","sessionAuth.actions.usePasskey":"Use passkey","sessionAuth.actions.unlockingAria":"Unlocking","sessionAuth.actions.unlockAria":"Unlock","sessionAuth.actions.trustDevice":"Trust this device","sessionAuth.actions.trustDeviceAria":"Trust this device","sessionAuth.actions.cancelPasskeySetup":"Cancel passkey setup","sessionAuth.actions.addPasskey":"Add passkey","sessionAuth.password.placeholder":"Enter password","sessionAuth.toast.passkeyAdded":"Passkey added","sessionAuth.toast.passkeySetupCanceled":"Passkey setup canceled","desktopHostSwitcher.title":"Instance","desktopHostSwitcher.description":"Switch between Local and remote OpenChamber servers","desktopHostSwitcher.header.current":"Current","desktopHostSwitcher.header.default":"Default","desktopHostSwitcher.header.currentColon":"Current:","desktopHostSwitcher.header.currentDefaultColon":"Current default:","desktopHostSwitcher.status.connected":"Connected","desktopHostSwitcher.status.authRequired":"Auth required","desktopHostSwitcher.status.checking":"Checking","desktopHostSwitcher.status.updateRecommended":"Update recommended","desktopHostSwitcher.status.incompatible":"Incompatible","desktopHostSwitcher.status.wrongService":"Wrong service","desktopHostSwitcher.status.unreachable":"Unreachable","desktopHostSwitcher.status.relayLimit":"Relay limit reached","desktopHostSwitcher.status.unknown":"Unknown","desktopHostSwitcher.status.ping":" · {ms}ms ping","desktopHostSwitcher.statusAria":"Instance status","desktopHostSwitcher.sshPhase.ready":"Ready","desktopHostSwitcher.sshPhase.error":"Error","desktopHostSwitcher.sshPhase.reconnecting":"Reconnecting","desktopHostSwitcher.sshPhase.resolvingConfig":"Resolving config","desktopHostSwitcher.sshPhase.checkingAuth":"Checking auth","desktopHostSwitcher.sshPhase.connectingSsh":"Connecting SSH","desktopHostSwitcher.sshPhase.probingRemote":"Probing remote","desktopHostSwitcher.sshPhase.installing":"Installing","desktopHostSwitcher.sshPhase.updating":"Updating","desktopHostSwitcher.sshPhase.detectingServer":"Detecting server","desktopHostSwitcher.sshPhase.startingServer":"Starting server","desktopHostSwitcher.sshPhase.forwardingPorts":"Forwarding ports","desktopHostSwitcher.sshPhase.idle":"Idle","desktopHostSwitcher.ssh.needInstancesHint":"Need SSH instances? Manage them in Settings.","desktopHostSwitcher.ssh.instanceFallback":"SSH instance","desktopHostSwitcher.ssh.connectingTo":"Connecting to {host}","desktopHostSwitcher.actions.refresh":"Refresh","desktopHostSwitcher.actions.refreshInstancesAria":"Refresh instances","desktopHostSwitcher.actions.remoteSsh":"Remote SSH","desktopHostSwitcher.actions.instanceActionsAria":"Instance actions","desktopHostSwitcher.actions.edit":"Edit","desktopHostSwitcher.actions.delete":"Delete","desktopHostSwitcher.actions.connect":"Connect","desktopHostSwitcher.actions.defaultInstanceAria":"Default instance","desktopHostSwitcher.actions.setAsDefaultAria":"Set as default","desktopHostSwitcher.actions.setAsDefault":"Set as default","desktopHostSwitcher.actions.openInNewWindowAria":"Open in new window","desktopHostSwitcher.actions.openInNewWindow":"Open in new window","desktopHostSwitcher.actions.addInstance":"Add instance","desktopHostSwitcher.actions.cancel":"Cancel","desktopHostSwitcher.actions.save":"Save","desktopHostSwitcher.actions.add":"Add","desktopHostSwitcher.actions.switchToLocal":"Switch to Local","desktopHostSwitcher.actions.retry":"Retry","desktopHostSwitcher.actions.switchInstanceAria":"Switch instance","desktopHostSwitcher.actions.switchInstance":"Switch instance","desktopHostSwitcher.actions.switchToAria":"Switch to {instance}","desktopHostSwitcher.field.labelPlaceholder":"Label","desktopHostSwitcher.field.labelOptionalPlaceholder":"Label (optional)","desktopHostSwitcher.field.urlPlaceholder":"https://host:port","desktopHostSwitcher.state.limitedOnPage":"Instance switcher is limited on this page. Use Local to recover.","desktopHostSwitcher.state.loading":"Loading...","desktopHostSwitcher.state.instanceUnreachable":"Instance unreachable","desktopHostSwitcher.edit.title":"Edit instance","desktopHostSwitcher.add.title":"Add instance","desktopHostSwitcher.error.failedToSave":"Failed to save","desktopHostSwitcher.error.failedToLoad":"Failed to load","desktopHostSwitcher.error.invalidUrl":"Invalid URL (must be http/https)","desktopHostSwitcher.error.pairingRejected":"Pairing link is invalid or expired. Generate a new one.","desktopHostSwitcher.error.pairingFailed":"Pairing failed (HTTP {status}).","desktopHostSwitcher.error.pairingInvalidResponse":"The server returned an invalid pairing response.","desktopHostSwitcher.error.failedToOpenNewWindow":"Failed to open new window","desktopHostSwitcher.instance.local":"Local","desktopHostSwitcher.instance.fallback":"Instance","desktopHostSwitcher.startup.title":"Default SSH instance unavailable","desktopHostSwitcher.startup.connectingTo":"Connecting to {host}...","desktopHostSwitcher.startup.failed":"Failed to connect the default SSH instance.","desktopHostSwitcher.toast.sshConnected":'SSH instance "{host}" connected',"desktopHostSwitcher.toast.sshFailedToConnect":'SSH instance "{host}" failed to connect',"desktopHostSwitcher.toast.instanceUnreachable":'Instance "{host}" is unreachable',"desktopHostSwitcher.toast.relayLimit":'The relay refused the connection to "{host}": too many devices or reconnects. Close OpenChamber on another device or wait a minute, then try again.',"relayConnection.limitReached.title":"The relay refused the connection","relayConnection.limitReached.description":"Too many devices or reconnects for this instance. Close OpenChamber on another device or wait a minute, then try again.","relayConnection.limitReached.retry":"Try again","miniChat.header.newSession":"New session","miniChat.header.session":"Session","miniChat.header.defaultAgent":"Default agent","miniChat.header.noModel":"No model","miniChat.status.busy":"Running","miniChat.status.retry":"Retrying","miniChat.status.idle":"Idle","miniChat.actions.pin":"Pin above other windows","miniChat.actions.unpin":"Unpin window","miniChat.actions.pinAria":"Pin Mini Chat window","miniChat.actions.unpinAria":"Unpin Mini Chat window","miniChat.actions.openMain":"Open in main window","miniChat.actions.openMainAria":"Open session in main window","miniChat.unavailable.title":"Session unavailable","miniChat.unavailable.description":"This session could not be loaded. It may have been deleted, archived, or opened from a different project context.","sessions.sidebar.session.menu.openMiniChatWindow":"Open in Mini Chat Window","header.windowControls.groupAria":"Window controls","header.windowControls.minimize":"Minimize window","header.windowControls.maximize":"Maximize window","header.windowControls.restore":"Restore window","header.windowControls.close":"Close window","errorBoundary.title":"Something went wrong","errorBoundary.description":"The application encountered an unexpected error. This has been logged for debugging.","errorBoundary.state.unknownError":"Unknown error","errorBoundary.state.componentStackLabel":"Component stack:","errorBoundary.actions.errorDetails":"Error details","errorBoundary.actions.tryAgain":"Try again","errorBoundary.actions.copy":"Copy","errorBoundary.actions.copied":"Copied","jsonTreeView.error.emptyJson":"Empty JSON content","jsonTreeView.error.invalidJson":"Invalid JSON","jsonTreeView.error.invalidJsonTitle":"Invalid JSON","jsonTreeView.actions.expandAll":"Expand All","jsonTreeView.actions.collapseAll":"Collapse All","numberInput.actions.decreaseAria":"Decrease value","numberInput.actions.increaseAria":"Increase value","goToLineDialog.field.linePlaceholderShort":"Line","goToLineDialog.field.linePlaceholder":"Line number","goToLineDialog.actions.go":"Go","goToLineDialog.helper.editorUnavailable":"Editor unavailable.","goToLineDialog.helper.currentLineRange":"Current Line: {current}. Type a line number between 1 and {max} to navigate to.","goToLineDialog.helper.goToLine":"Go to line {line}","dialog.common.actions.close":"Close","session.newWorktree.trust.run":"Run","session.newWorktree.trust.skip":"Skip","session.newWorktree.trust.title":"Run setup on code from a fork?","gitView.publish.contributorCommitFirstAction":"Continue","gitView.publish.contributorCommitFirstTitle":"Commit, then choose where to push?","dialog.common.actions.cancel":"Cancel","filesView.toast.relativePathCopied":"Relative path copied","filesView.tree.menu.copyRelativePath":"Copy Relative Path","multiRun.branchSelector.placeholder.selectSourceBranch":"Select source branch...","multiRun.branchSelector.status.loadingBranches":"Loading branches...","multiRun.branchSelector.status.noBranchesFound":"No branches found","multiRun.branchSelector.status.notInGitRepository":"Not in a git repository.","multiRun.branchSelector.groups.localBranches":"Local branches","multiRun.branchSelector.groups.remoteBranches":"Remote branches","multiRun.window.actions.closeAria":"Close multi-run","multiRun.window.description":"OpenChamber Multi-Run window.","voice.status.idle":"Voice Ready","voice.status.listening":"Listening...","voice.status.processing":"Processing...","voice.status.speaking":"Speaking...","voice.status.error":"Voice Error","voice.status.conversationModeActiveAria":"Conversation mode active","voice.action.finishAndTranscribe":"Finish and transcribe voice input","onboarding.common.actions.back":"Back","onboarding.common.copyToClipboard":"Copy to clipboard","onboarding.common.status.copiedToClipboard":"Copied to clipboard","onboarding.chooser.title":"Welcome to OpenChamber","onboarding.chooser.description":"Choose how you want to connect to get started.","onboarding.chooser.tabs.localInstall":"Local Install","onboarding.chooser.tabs.connectRemote":"Connect Remote","onboarding.localSetup.title":"Setting Up OpenCode","onboarding.localSetup.description":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.dialog.selectOpencodeBinary":"Select opencode binary","onboarding.localSetup.errors.cliNotReady":"OpenCode CLI is not ready yet. Please confirm installation is complete and try again.","onboarding.localSetup.errors.detectionFailed":"Detection failed","onboarding.localSetup.windows.title":"Windows setup","onboarding.localSetup.windows.stepInstallWsl":"Install OpenCode with the command below.","onboarding.localSetup.windows.stepInstallWslSuffix":"","onboarding.localSetup.windows.stepRunInstallInWsl":"Run the install command below in a Windows terminal.","onboarding.localSetup.windows.stepSetBinaryPath":"If OpenChamber does not detect OpenCode automatically, set the binary path below.","onboarding.localSetup.intro":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.docs.windows":"Installation guide","onboarding.localSetup.docs.default":"Installation guide","onboarding.localSetup.actions.checking":"Checking…","onboarding.localSetup.actions.checkAndContinue":"I've completed installation, check and continue","onboarding.localSetup.actions.checkNow":"Check now","onboarding.localSetup.helper.checkAndContinue":"Click to check if OpenCode CLI is available. If successful, you'll automatically enter the main screen.","onboarding.localSetup.status.watching":"Waiting for OpenCode v2","onboarding.localSetup.status.autoContinue":"We'll continue automatically once it's detected.","onboarding.localSetup.field.alreadyInstalled":"Already installed? Set the OpenCode CLI path:","onboarding.localSetup.advanced.title":"Set a custom binary path","onboarding.localSetup.troubleshoot.title":"Having trouble?","onboarding.localSetup.actions.browse":"Browse","onboarding.localSetup.actions.apply":"Apply","onboarding.localSetup.helper.saveAndReload":"Saves to OpenChamber settings and reloads OpenCode configuration.","onboarding.localSetup.helper.pinnedByAdministrator":"Your administrator set this path. If OpenCode isn’t there, ask them to install it.","onboarding.localSetup.remotePreference":"Prefer to use a remote server?","onboarding.localSetup.actions.connectRemoteServer":"Connect to Remote Server →","onboarding.localSetup.windows.hintInstallInWsl":"On Windows, install and run OpenCode natively.","onboarding.localSetup.windows.hintDetectionFailed":"If detection fails, set a native path such as opencode.cmd or opencode.exe.","onboarding.localSetup.hint.ensurePath":"Already installed? Make sure opencode is in your PATH.","onboarding.localSetup.hint.setEnv":"Or set OPENCODE_BINARY environment variable.","onboarding.localSetup.hint.missingRuntime":'If you see "env: node: No such file or directory" or "env: bun: No such file or directory", install that runtime or ensure it is on PATH.',"onboarding.remoteConnection.title":"Connect to Remote Server","onboarding.remoteConnection.titleRecovery":"Connect to a Different Server","onboarding.remoteConnection.description":"Enter the address of an OpenChamber server to connect to.","onboarding.remoteConnection.field.serverAddress":"Server Address","onboarding.remoteConnection.field.serverAddressPlaceholder":"https://your-server.example.com:4096","onboarding.remoteConnection.field.nameOptional":"Name (optional)","onboarding.remoteConnection.field.namePlaceholder":"My Remote Server","onboarding.remoteConnection.errors.connectionTestFailed":"Connection test failed","onboarding.remoteConnection.errors.failedToSaveConnection":"Failed to save connection","onboarding.remoteConnection.status.connectedSuccessfully":"Connected successfully ({latencyMs}ms)","onboarding.remoteConnection.status.authWarning":"Server requires authentication. You can still connect.","onboarding.remoteConnection.status.connectionFailed":"Connection Failed","onboarding.remoteConnection.status.suggestionsUnreachable":"Suggestions: Check the server address, verify the server is running, or check your network connection.","onboarding.remoteConnection.status.suggestionsWrongService":"Suggestions: Verify the URL points to an OpenChamber server, or contact the server administrator.","onboarding.remoteConnection.actions.testing":"Testing…","onboarding.remoteConnection.actions.testConnection":"Test Connection","onboarding.remoteConnection.actions.connectAndRestart":"Connect & Restart","onboarding.remoteConnection.actions.whatToDo":"What would you like to do?","onboarding.remoteConnection.actions.chooseDifferentServer":"Choose Different Server","onboarding.remoteConnection.actions.useLocalInstead":"Use Local Instead","onboarding.remoteConnection.probe.authMessage":"Server requires authentication. You can still connect, but may need to provide credentials.","onboarding.remoteConnection.probe.updateRecommendedMessage":"This instance is running a different OpenChamber version. You can connect, but update both apps if something does not work.","onboarding.remoteConnection.probe.incompatibleMessage":"Server is running OpenChamber but is not compatible with this app version. Update OpenChamber on the server, then try again.","onboarding.remoteConnection.probe.wrongServiceMessage":"Server responded but is not running OpenChamber. Verify the address points to an OpenChamber server.","onboarding.remoteConnection.probe.unreachableMessage":"Server is unreachable. Check your network connection and verify the server address.","onboarding.desktopRecovery.localUnavailable.title":"Local OpenCode Unavailable","onboarding.desktopRecovery.localUnavailable.description":"OpenCode CLI could not be started or is not installed. Install OpenCode or connect to a remote server instead.","onboarding.desktopRecovery.localUnavailable.retry":"Retry Local","onboarding.desktopRecovery.localUnavailable.useLocal":"Set Up Local","onboarding.desktopRecovery.noDefaultConnection.title":"No Default Connection","onboarding.desktopRecovery.noDefaultConnection.description":"Your saved default connection could not be found. Choose how you want to connect.","onboarding.desktopRecovery.remoteUnreachable.title":"Remote Server Unreachable","onboarding.desktopRecovery.remoteUnreachable.description":'Could not connect to "{host}". Check your network connection and verify the server address.',"onboarding.desktopRecovery.remoteUnreachable.retry":"Retry Connection","onboarding.desktopRecovery.incompatibleServer.title":"Incompatible Server","onboarding.desktopRecovery.incompatibleServer.description":'The server at "{host}" is not running OpenChamber. Verify the address points to an OpenChamber server.',"onboarding.desktopRecovery.remoteIncompatible.title":"Server Update Required","onboarding.desktopRecovery.remoteIncompatible.description":'The OpenChamber server at "{host}" is not compatible with this app version. Update OpenChamber on the server, then try again.',"onboarding.desktopRecovery.remoteIncompatible.updateServer":"Update server","onboarding.desktopRecovery.remoteIncompatible.updatingServer":"Updating the server...","onboarding.desktopRecovery.remoteIncompatible.updatingHint":"The server installs the update and restarts. The app connects as soon as it is back.","onboarding.desktopRecovery.remoteIncompatible.updateRefused":"The server could not update itself.","onboarding.desktopRecovery.remoteIncompatible.updateAuth":"The server did not accept this app's sign-in, so it could not be updated from here.","onboarding.desktopRecovery.remoteIncompatible.updateTimeout":"The server has not come back with the new version yet. Check it, then retry the connection.","onboarding.desktopRecovery.remoteIncompatible.manualUpdate":"To update it by hand, run this on the server, then restart OpenChamber there:","onboarding.desktopRecovery.common.useLocal":"Use Local","onboarding.desktopRecovery.common.useRemote":"Use Remote","onboarding.desktopRecovery.actions.retrying":"Retrying…","onboarding.desktopRecovery.actions.retryConnection":"Retry Connection","projectConfigError.toast.title":"OpenCode can't load this project's config","projectConfigError.toast.unknownFile":"Project config","projectConfigError.toast.hint":"Fix the file, then retry. Other projects keep working.","projectConfigError.toast.retry":"Retry","projectConfigError.toast.retrying":"Retrying…","startup.initRecovery.title":"Startup failed","startup.serverOutdated.title":"Server update required","startup.serverOutdated.description":"The server runs OpenChamber {version}, and this app needs 2.0 or later there. Update OpenChamber on the server to continue.","startup.serverOutdated.checking":"Checking the server...","startup.serverOutdated.noUpdate":"The server did not offer an update it can install itself.","startup.initRecovery.openCodeUnavailable":"OpenChamber is reachable, but OpenCode is not ready. Check OpenCode on the server, then retry.","startup.initRecovery.binary":"OpenCode executable","startup.initRecovery.error":"OpenCode error","startup.initRecovery.serverUnreachable":"OpenChamber could not reach its server. Check that the server is running, then retry.","startup.initRecovery.loadAgentsFailed":"The server is running, but OpenCode could not load agents. Retry once the cause is fixed.","startup.initRecovery.unexpected":"OpenChamber could not finish starting. Retry once the cause is fixed.","startup.initRecovery.lastError":"Last error","startup.initRecovery.retry":"Retry","startup.initRecovery.retrying":"Retrying…","startup.overlay.slow":"Startup is taking longer than expected…","onboarding.desktopRecovery.placeholders.remoteServer":"the remote server","onboarding.desktopRecovery.placeholders.unknownServer":"unknown","vscodeLayout.title.chat":"Chat","vscodeLayout.title.newSession":"New session","vscodeLayout.title.sessions":"Sessions","vscodeLayout.title.sessionFallback":"Session","vscodeLayout.actions.backToSessionsAria":"Back to sessions","vscodeLayout.actions.archiveAllAria":"Archive all sessions","vscodeLayout.actions.archiveAllConfirm":"Archive all","vscodeLayout.actions.archiveAllSuccess":"Archived {count} session(s)","vscodeLayout.actions.archiveAllError":"Failed to archive {count} session(s)","vscodeLayout.actions.cancel":"Cancel","vscodeLayout.actions.newSessionAria":"New session","vscodeLayout.actions.resizeSessionsSidebarAria":"Resize sessions sidebar","vscodeLayout.actions.settingsAria":"Settings","vscodeLayout.quota.title":"Rate limits","vscodeLayout.quota.mode.used":"Used","vscodeLayout.quota.mode.remaining":"Remaining","vscodeLayout.quota.lastUpdated":"Last updated {time}","vscodeLayout.quota.noRateLimitsAvailable":"No rate limits available.","vscodeLayout.quota.noRateLimitsReported":"No rate limits reported.","vscodeLayout.quota.actions.rateLimitsAria":"Rate limits","vscodeLayout.quota.actions.showUsedAria":"Show used quota","vscodeLayout.quota.actions.showRemainingAria":"Show remaining quota","vscodeLayout.quota.actions.refreshAria":"Refresh rate limits","updateDialog.header.updateAvailable":"Update Available","updateDialog.header.updating":"Updating OpenChamber...","updateDialog.changelog.title":"What's new","updateDialog.status.installingUpdate":"Installing update...","updateDialog.status.serverRestarting":"Server restarting...","updateDialog.status.waitingForServer":"Waiting for server...","updateDialog.status.autoReloadHint":"The page will reload automatically when the update is complete.","updateDialog.fallback.updateViaTerminal":"Or update via terminal:","updateDialog.desktopHostInstall":"OpenChamber {version} is available. Update it on the computer it runs on.","updateDialog.actions.copyCommand":"Copy command","updateDialog.actions.copied":"Copied!","updateDialog.status.downloadingPayload":"Downloading update payload...","updateDialog.actions.downloadUpdate":"Download Update","updateDialog.status.downloading":"Downloading...","updateDialog.actions.restartToUpdate":"Restart to Update","updateDialog.status.restarting":"Restarting...","updateDialog.actions.updateNow":"Update Now","updateDialog.actions.openMobileUpdate":"Open update","updateDialog.status.updating":"Updating...","updateDialog.error.updateFailed":"Update failed","updateDialog.error.takingLonger":"Update is taking longer than expected. Wait a bit and refresh, or run: openchamber update","updateDialog.error.signatureRejected":"The downloaded update was rejected: its code signature does not match this installation. This usually means the running copy was not installed from an official signed release. Install OpenChamber from an official release, then update again.","updateDialog.error.updaterDisabled":"The updater stopped after a failed install. Quit OpenChamber, open it again, and retry the update.","updateDialog.error.restartFailed":"Could not restart to install the update.","updateDialog.error.restartUnavailable":"Installing the update requires the OpenChamber desktop app.","mobileUpdate.toast.available.title":"OpenChamber update available","mobileUpdate.toast.available.description":"Version {version} is ready for Android.","mobileUpdate.toast.actions.download":"Download","opencodeUpdate.toast.available.title":"OpenCode update","opencodeUpdate.toast.available.description":"Version {version} available.","opencodeUpdate.toast.available.manualDescription":"Version {version} available. Update OpenCode the way you installed it, then restart OpenChamber.","opencodeUpdate.toast.actions.update":"Update","opencodeUpdate.toast.actions.reload":"Reload OpenCode","opencodeUpdate.toast.upgrading.title":"Updating OpenCode...","opencodeUpdate.toast.upgrading.description":"Keep OpenChamber open.","opencodeUpdate.toast.updated.title":"OpenCode updated","opencodeUpdate.toast.updated.description":"Update installed.","opencodeUpdate.toast.updated.descriptionWithVersion":"Version {version} installed.","opencodeUpdate.toast.failed.title":"Could not update OpenCode","opencodeUpdate.toast.failed.description":"The OpenCode upgrade failed.","opencodeUpdate.toast.reload.message":"Restarting OpenCode...","memoryDebugPanel.title":"Debug Panel","memoryDebugPanel.tabs.memory":"Memory","memoryDebugPanel.tabs.streaming":"Streaming","memoryDebugPanel.tabs.requests":"Requests","memoryDebugPanel.section.sessionsInMemory":"Sessions in Memory","memoryDebugPanel.section.uiStreamingMetrics":"UI Streaming Metrics","memoryDebugPanel.section.vscodeBridgeMetrics":"VS Code Bridge Metrics","memoryDebugPanel.section.noUiSamples":"No UI streaming samples yet. Start a stream and keep this panel open.","memoryDebugPanel.section.noVscodeSamples":"No VS Code bridge samples yet.","memoryDebugPanel.metric.totalMessages":"Total Messages","memoryDebugPanel.metric.cachedSessions":"Cached Sessions","memoryDebugPanel.metric.userMessages":"User Messages","memoryDebugPanel.metric.assistantMessages":"Assistant Messages","memoryDebugPanel.metric.viewportWindow":"Viewport Window","memoryDebugPanel.metric.zombieTimeout":"Zombie Timeout","memoryDebugPanel.metric.githubTotalRequests":"GitHub Total Requests","memoryDebugPanel.metric.metrics":"Metrics","memoryDebugPanel.metric.samples":"Samples","memoryDebugPanel.metric.lastUpdate":"Last Update","memoryDebugPanel.metric.uiMetrics":"UI Metrics","memoryDebugPanel.metric.vscodeMetrics":"VS Code Metrics","memoryDebugPanel.metric.messageListRenders":"MsgList Renders","memoryDebugPanel.metric.messageListStreamRenders":"MsgList Stream Renders","memoryDebugPanel.metric.chatMessageRenders":"ChatMessage Renders","memoryDebugPanel.metric.chatMessageStreamRenders":"ChatMessage Stream Renders","memoryDebugPanel.metric.chatMessageStaticDuringStream":"ChatMessage Static During Stream","memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn":"ChatMessage Static Outside Active Turn","memoryDebugPanel.metric.messagesValue":"{count} messages","memoryDebugPanel.metric.minutesValue":"{count} minutes","memoryDebugPanel.metric.msgsValue":"{count} msgs","memoryDebugPanel.metric.roleMsgsValue":"U {user} / A {assistant}","memoryDebugPanel.metric.countValue":"count {value}","memoryDebugPanel.metric.avgValue":"avg {value}","memoryDebugPanel.metric.maxValue":"max {value}","memoryDebugPanel.metric.totalValue":"total {value}","memoryDebugPanel.actions.logState":"Log State","memoryDebugPanel.actions.copyJson":"Copy JSON","memoryDebugPanel.tooltip.logCurrentState":"Log current memory state to browser console","memoryDebugPanel.streaming.copy.copied":"Streaming debug JSON copied","memoryDebugPanel.streaming.copy.failed":"Failed to copy JSON","memoryDebugPanel.streaming.copy.hint":"Copy exports both UI and VS Code streaming metrics as JSON","memoryDebugPanel.requests.inFlight":"In flight","memoryDebugPanel.requests.peak":"Peak","memoryDebugPanel.requests.duration":"Duration","memoryDebugPanel.requests.totalRequests":"Total Requests","memoryDebugPanel.requests.tracking":"Tracking","memoryDebugPanel.requests.now":"now","memoryDebugPanel.requests.noSamples":"No requests tracked yet. Keep this panel open to record fetch activity.","memoryDebugPanel.requests.chartLabel":"Fetch requests in flight over time, peak {peak}","memoryDebugPanel.requests.windowHint":"last {seconds}s","memoryDebugPanel.requests.percentileChartLabel":"In-flight request age percentiles (p50, p90, p99, max) over time","memoryDebugPanel.common.idle":"idle","memoryDebugPanel.common.live":"live","memoryDebugPanel.common.notAvailable":"n/a","memoryDebugPanel.common.untitled":"Untitled","directoryTree.field.newDirectoryPlaceholder":"new_directory","textarea.resizeHandleAria":"Resize textarea","sidebar.resize.leftPanelAria":"Resize left panel","sidebar.resize.rightPanelAria":"Resize right panel","mainLayout.mobile.closeDrawerAria":"Close drawer","sortableTabsStrip.aria.tabs":"Tabs","openChamberLogo.aria.logo":"OpenChamber logo","markdownRenderer.code.proposal":"Proposal","markdownRenderer.code.actions.copyTitle":"Copy code","markdownRenderer.code.actions.copiedTitle":"Copied","markdownRenderer.table.actions.copyTitle":"Copy table","markdownRenderer.code.actions.enableWrapTitle":"Enable line wrap","markdownRenderer.code.actions.disableWrapTitle":"Disable line wrap","markdownRenderer.table.actions.enableWrapTitle":"Enable cell wrap","markdownRenderer.table.actions.disableWrapTitle":"Disable cell wrap","markdownRenderer.table.actions.downloadTitle":"Download table","markdownRenderer.table.toast.downloadedAsFormat":"Table downloaded as {format}","markdownRenderer.mermaid.actions.copyTitle":"Copy","markdownRenderer.mermaid.actions.copySourceTitle":"Copy source","markdownRenderer.mermaid.actions.downloadSvgTitle":"Download SVG","markdownRenderer.mermaid.actions.zoomInTitle":"Zoom in","markdownRenderer.mermaid.actions.zoomOutTitle":"Zoom out","markdownRenderer.mermaid.actions.resetViewTitle":"Reset view","markdownRenderer.mermaid.toast.downloadFailed":"Failed to download diagram","common.date.today":"Today","common.date.yesterday":"Yesterday","common.date.yesterdayWithTime":"Yesterday {time}","common.relative.justNow":"Just now","common.relative.minutesAgoShort":"{count}min ago","common.relative.hoursAgoShort":"{count}h ago","common.relative.daysAgoShort":"{count}d ago","common.relative.weeksAgoShort":"{count}w ago","common.relative.yearsAgoShort":"{count}y ago","common.relative.minutesAgoCompact":"{count}m","common.relative.hoursAgoCompact":"{count}h","common.relative.daysAgoCompact":"{count}d","common.relative.weeksAgoCompact":"{count}w","common.relative.monthsAgoCompact":"{count}mo","common.relative.yearsAgoCompact":"{count}y","common.duration.secondsCompact":"{seconds}s","common.duration.minutesSecondsCompact":"{minutes}m {seconds}s","common.duration.hoursMinutesCompact":"{hours}h {minutes}m","contextFileOpen.failure.tooLarge":"{name} is too large to open","contextFileOpen.failure.tooLargeDetail":"More than {count} lines · {size}","contextFileOpen.failure.tooLargeSize":"Larger than {limit} · {size}","contextFileOpen.failure.missing":"{name} was not found","contextFileOpen.failure.unreadable":"Couldn't open {name}","quota.window.5h":"5-Hour","quota.window.7d":"7-Day Limit","quota.window.extraUsage":"Extra Usage","quota.window.weekly":"Weekly","quota.window.daily":"Daily","quota.window.monthly":"Monthly","quota.window.credits":"Credits","quota.value.creditsUsed":"{credits} Credits Used","quota.window.keyLimit":"Key Limit","quota.window.creditsBalance":"Credits Balance","quota.window.monthlyCredits":"Monthly Credits","quota.window.purchasedCredits":"Purchased Credits","quota.window.freeCredits":"Free Credits","quota.window.billingCycle":"Billing Cycle","quota.window.auto":"Auto","quota.window.api":"API","quota.window.planLimit":"Plan Limit","quota.window.onDemand":"On-demand","quota.window.session":"Session","quota.window.premium":"Premium Interactions","quota.window.chat":"Chat Requests","quota.window.completions":"Completions","quota.window.premiumInteractions":"AI Credits","chat.workStatus.ariaLabel":"Work status","chat.workStatus.mobileEmpty":"Nothing to show for this session yet","chat.workStatus.context.label":"Context","chat.workStatus.cost.breakdown":"Session {session} · Subagents {subagents}","chat.workStatus.git.changedFileSingle":"{count} file changed","chat.workStatus.git.changedFilePlural":"{count} files changed","chat.workStatus.pr.untitled":"Untitled pull request","chat.workStatus.mr.untitled":"Untitled merge request","chat.workStatus.pr.draft":"Draft","chat.workStatus.pr.checks":"Checks","chat.workStatus.pr.checksFailed":"{count} failed","chat.workStatus.pr.checksPending":"{count} running","chat.workStatus.pr.checksPassed":"{count} passed","chat.workStatus.attention.merge":"Merge in progress","chat.workStatus.attention.rebase":"Rebase in progress","chat.workStatus.attention.cherryPick":"Cherry-pick in progress","chat.workStatus.attention.revert":"Revert in progress","chat.workStatus.attention.bisect":"Bisect in progress","chat.workStatus.subagent.done":"Done","chat.workStatus.subagent.failed":"Failed","chat.workStatus.subagent.untitled":"Subagent","chat.workStatus.mcp.toggle":"Toggle {name}","chat.workStatus.mcp.needsAuth":"Sign in","chat.workStatus.mcp.failed":"Failed","chat.workStatus.pinned.unavailable":"Pinned message","chat.workStatus.section.session":"Session","chat.workStatus.section.project":"Project","chat.workStatus.section.subagents":"Subagents","chat.workStatus.section.mcp":"MCP","chat.workStatus.section.pinned":"Pinned messages","chat.workStatus.section.tasks":"Tasks","chat.workStatus.subagent.working":"is working","chat.workStatus.subagent.needsPermission":"needs permission","chat.workStatus.subagent.askedQuestion":"asked a question","chat.workStatus.section.contextBreakdown":"Context sources","chat.workStatus.breakdown.skills":"Skills","chat.workStatus.breakdown.pinnedNote":"note","chat.workStatus.breakdown.unpin":"Unpin from context","chat.workStatus.breakdown.pinnedPlan":"plan","chat.workStatus.breakdown.memory":"Agent memory","chat.workStatus.breakdown.pinnedKnowledgeSingle":"{count} pinned","chat.workStatus.breakdown.pinnedKnowledgePlural":"{count} pinned","chat.workStatus.breakdown.mcp":"MCP servers","chat.workStatus.action.openChanges":"Open changes","chat.workStatus.action.openGit":"Open Git panel","chat.workStatus.action.openPr":"Open pull request","chat.workStatus.action.openMr":"Open merge request","chat.workStatus.action.openSubagent":"Open {name}","chat.workStatus.section.usage":"Usage","chat.workStatus.section.telemetry":"Turn stats","chat.workStatus.telemetry.previousTurn":"Previous turn","chat.workStatus.telemetry.previousTurnRate":"Previous turn · {rate}","chat.workStatus.telemetry.responseSpeed":"Response","chat.workStatus.telemetry.responseSpeedDescription":"How fast the final text arrived. Excludes the initial wait, reasoning, and earlier tool calls. An estimate from text timestamps, not a provider speed measurement.","chat.workStatus.telemetry.speed":"Whole turn","chat.workStatus.telemetry.speedDescription":"Tokens generated across all steps, including reasoning, divided by time with tool execution removed. Waiting for the model still counts, so many short tool calls can lower this number.","chat.workStatus.telemetry.elapsed":"Elapsed","chat.workStatus.telemetry.elapsedDescription":"Wall-clock time from the first user message to the final assistant response. Includes model waiting, tool execution, compaction, and other gaps.","chat.workStatus.telemetry.llmDuration":"Model time","chat.workStatus.telemetry.llmDurationDescription":"Time spent on all model steps, including waiting for responses. Tool execution time is removed. This is not just time spent generating text.","chat.workStatus.telemetry.toolDuration":"Tool time","chat.workStatus.telemetry.toolDurationDescription":"Time spent running tools, including failed calls. Tools running at the same time are counted once, not added together.","chat.workStatus.telemetry.ttft":"Average TTFT","chat.workStatus.telemetry.ttftDescription":"Average wait before the first text or reasoning starts in each model step. Hidden when a step has no start after it was created, which is common for tool-only steps and for parts stamped at creation time.","chat.workStatus.telemetry.steps":"Steps","chat.workStatus.telemetry.stepsDescription":"How many times the model was called for this prompt. Reading tool results and deciding what to do next usually takes another step.","chat.workStatus.telemetry.tokens":"Tokens","chat.workStatus.telemetry.tokens.inOut":"{input} ↑ · {output} ↓","chat.workStatus.telemetry.tokensDescription":"↑ Input without cached tokens: {input}. ↓ Generated tokens: {output} for text and tool calls, plus {reasoning} for reasoning. Totals cover all steps of this prompt.","chat.workStatus.telemetry.cacheHit":"Cache","chat.workStatus.telemetry.cacheHitDescription":"Share of input tokens reused from the prompt cache across all steps. Reusing context can reduce cost and waiting, but this is not a speed score.","chat.workStatus.telemetry.cost":"Cost","chat.workStatus.telemetry.costDescription":"Cost reported by the provider for all model steps of this prompt, in US dollars. Excludes separate subagent sessions. Zero can mean a free model or a provider that reports no charge.","chat.workStatus.goal.open":"Manage goal","chat.workStatus.goal.pause":"Pause","chat.workStatus.goal.resume":"Resume","chat.workStatus.goal.updateFailed":"Could not update the goal","chat.workStatus.pinned.unpin":"Unpin message","chat.workStatus.pinned.reveal":"Go to message","chat.workStatus.pinned.unpinFailed":"Could not unpin the message","chat.workStatus.action.openContext":"Open context panel","chat.workStatus.section.linkedIssues":"Linked","chat.workStatus.linkedIssues.openOnProvider":"Open {reference} on {provider}","chat.workStatus.linkedIssues.unlink":"Remove link","chat.workStatus.linkedIssues.unlinkFailed":"Could not remove the link","chat.workStatus.linkedIssues.link":"Link to session","chat.workStatus.linkedIssues.linkFailed":"Could not link","chat.workStatus.breakdown.issueCountSingle":"{count} issue","chat.workStatus.breakdown.issueCountPlural":"{count} issues","chat.workStatus.breakdown.prCountSingle":"{count} PR","chat.workStatus.breakdown.mrCountSingle":"{count} MR","chat.workStatus.breakdown.prCountPlural":"{count} PRs","chat.workStatus.breakdown.mrCountPlural":"{count} MRs","chat.workStatus.breakdown.skillCountSingle":"{count} skill","chat.workStatus.breakdown.skillCountPlural":"{count} skills","chat.workStatus.breakdown.mcpCountSingle":"{count} MCP","chat.workStatus.breakdown.mcpCountPlural":"{count} MCP","chat.workStatus.sections.open":"Choose sections","chat.workStatus.sections.dialogTitle":"Panel sections","chat.workStatus.sections.reorder":"Drag {label} to reorder","chat.workStatus.sections.dragInstructions":"Press Space to pick up a section, use the arrow keys to move it, and press Space to drop. Press Escape to cancel.","chat.workStatus.sections.position":"{label}, position {position} of {count}.","chat.workStatus.sections.dragCancelled":"Reordering cancelled.","chat.workStatus.sections.dialogDescription":"Choose what the work-status panel shows. Hidden sections keep their data — they are only left out of the panel.","chat.workStatus.sections.allHidden":"No sections selected","chat.workStatus.sections.showAll":"Show all","chat.workStatus.sections.noneWarning":"The panel will appear empty.","header.workStatusPanel.toggleAria":"Toggle work-status panel","header.actions.newMiniChat":"New Mini Chat Window","header.actions.newMiniChatAria":"Open a new Mini Chat window","header.actions.openSessionMiniChat":"Open Session in Mini Chat","header.actions.openSessionMiniChatAria":"Open current session in Mini Chat","header.workStatusPanel.hide":"Hide work status","header.workStatusPanel.show":"Show work status","chat.workStatus.mcp.authorizeOpenFailed":"Could not open the authorization page","chat.workStatus.mcp.authorizeFailed":"Authorization failed","chat.formCard.inputNeeded":"Input needed","chat.formCard.fromSubagent":"from a subagent","chat.formCard.required":"Required","chat.formCard.openLink":"Open link","chat.formCard.yes":"Yes","chat.formCard.other":"Other","chat.formCard.yourAnswer":"Your answer","chat.formCard.submit":"Submit","chat.formCard.cancel":"Cancel","chat.formCard.missingRequired":"Fill in the required fields first.","chat.formCard.submitFailed":"Could not submit the answer","chat.formCard.cancelFailed":"Could not cancel the request","chat.formCard.tryAgain":"Try again.","chat.formCard.recoveredNotice":"The turn stopped while waiting. Submit starts a new paid turn.","chat.formDock.progress":"{current} of {total}","chat.formDock.waiting":"{count} more waiting","chat.formDock.back":"Back","chat.formDock.expandAria":"Expand the question","chat.formDock.collapseAria":"Collapse the question","chat.formDock.stepAria":"Question {index}: {title}","chat.formDock.linkInfo":"Open the link, then continue.","chat.permissionCard.title":"Permission required","chat.permissionCard.summary.externalDirectory":"Access files outside the project","chat.permissionCard.summary.read":"Read a file","chat.permissionCard.summary.edit":"Edit files","chat.permissionCard.summary.shell":"Run a command","chat.permissionCard.summary.glob":"Find files","chat.permissionCard.summary.grep":"Search file contents","chat.permissionCard.summary.webfetch":"Open a web page","chat.permissionCard.summary.websearch":"Search the web","chat.permissionCard.summary.skill":"Load a skill","chat.permissionCard.summary.tool":"Use {tool}","chat.permissionCard.summary.inPath":"in {path}","chat.permissionCard.showDetails":"Show details","chat.permissionDock.expandAria":"Expand the permission request","chat.permissionDock.collapseAria":"Collapse the permission request","chat.permissionDock.stepAria":"Request {index}: {tool}","chat.permissionCard.allowOnce":"Allow once","chat.permissionCard.alwaysAllow":"Always allow","chat.permissionCard.alwaysAllowPatterns":"Always: {patterns}","chat.permissionCard.deny":"Deny","chat.permissionCard.replaceAll":"Replaces every occurrence","chat.compaction.running":"Compacting the conversation","chat.compaction.completed":"Conversation compacted","chat.compaction.failed":"Compaction failed","chat.compaction.showSummary":"Show summary","chat.compaction.hideSummary":"Hide summary","chat.dispatchedSession.completed":"Session finished: {title}","chat.dispatchedSession.failed":"Session failed: {title}","chat.dispatchedSession.cancelled":"Session stopped: {title}","chat.dispatchedSession.completedUntitled":"Session finished","chat.dispatchedSession.failedUntitled":"Session failed","chat.dispatchedSession.cancelledUntitled":"Session stopped","chat.dispatchedSession.showAnswer":"Show answer","chat.dispatchedSession.hideAnswer":"Hide answer","chat.dispatchedSession.open":"Open session","chat.revertPopover.staged":"Reverted: {count}","chat.revertPopover.toast.restoreFailed":"Couldn't restore the reverted messages","chat.workStatus.mcp.needsAuthHint":"Sign in to this MCP server from Settings → MCP.","mcpDropdown.toast.authorizeOpenFailed":"Could not open the authorization page","mcpDropdown.toast.authorizeFailed":"Authorization failed","header.services.tooltip.currentInstance":"Current instance: {current} ({toggle})","header.workStatusPanel.showOverlay":"Show work status over the chat","settings.mcp.page.connection.title":"How to reach it","settings.mcp.page.connection.description":"Paste the command that starts it, or the link to a hosted server.","settings.mcp.page.registration.title":"This server needs its own app","settings.mcp.page.registration.description":"It does not hand out credentials automatically. Create an app in the service’s own settings, paste its details here, then sign in.","settings.mcp.page.registration.callbackLabel":"Give the service this address","settings.mcp.page.registration.clientId":"App ID","settings.mcp.page.registration.clientSecret":"App secret","settings.mcp.page.registration.afterSaving":"Save, then press Authorize to sign in.","settings.mcp.page.toast.copiedCallbackUrl":"Address copied","settings.mcp.page.toast.clipboardWriteFailed":"Could not copy to the clipboard","settings.mcp.page.scope.everywhere":"Available in every project","settings.mcp.page.scope.thisProject":"Only in this project","settings.mcp.page.env.description":"Values the server needs, such as an API key.","settings.mcp.page.connection.kindCommand":"Command","settings.mcp.page.connection.kindLink":"Link","settings.mcp.page.connection.hintCommand":"Runs on this machine. Paste a whole command and it is split into one argument per line.","settings.mcp.page.connection.hintLink":"Connects to a server someone else hosts. Paste its https address.","chat.messageBody.actions.askOtherModels":"Ask other models","chat.modelControls.runInParallel":"Run on several models","chat.parallel.defaultTitle":"Parallel run","chat.parallel.exit":"Leave parallel mode","chat.parallel.fuse.judge":"Fuse with {model}","chat.parallel.fuse.off":"Fuse: off","chat.parallel.isolation.shared":"Shared directory","chat.parallel.isolation.worktrees":"Separate worktrees","chat.parallel.models.add":"Add model","chat.parallel.models.decrement":"Run {model} one time less","chat.parallel.models.increment":"Run {model} one more time","chat.parallel.runAria":"Start parallel runs ({count})","chat.parallel.setup.dialogDescription":"Commands run in every new worktree before its prompt, one per line.","chat.parallel.toast.failed":"Could not start the parallel run.","chat.parallel.toast.incomplete":"Every prompt variant needs text and at least one model.","chat.parallel.variant.removeAria":"Remove variant {variant}","chat.parallel.variant.runsPlural":"{count} runs","chat.parallel.variant.runsSingle":"{count} run","chat.parallel.variant.tabsAria":"Prompt variants","multirun.ask.checking":"Checking this answer…","multirun.ask.description":"This chat becomes the first run. Each model gets the same first prompt in its own worktree.","multirun.ask.failed":"Could not ask other models.","multirun.ask.notFirstTurn":"Only the first answer of a chat can be compared for now.","multirun.ask.startPlural":"Run {count} more","multirun.ask.startSingle":"Run {count} more","multirun.ask.title":"Ask other models","multirun.overview.archive.action":"Archive run","multirun.overview.archive.failed":"Some runs could not be archived.","multirun.overview.ask.failed":"Could not add the model to this run.","multirun.overview.ask.working":"Adding…","multirun.overview.bar.fuse":"Fuse results","multirun.overview.bar.hint":"Fuse the answers into one result","multirun.overview.cancel":"Cancel","multirun.overview.card.changesUnavailable":"Changes unavailable","multirun.overview.card.diff":"Diff","multirun.overview.card.filesPlural":"{count} files","multirun.overview.card.filesSingle":"{count} file","multirun.overview.card.noChanges":"No file changes","multirun.overview.card.noReply":"No answer yet","multirun.overview.card.openChat":"Open chat","multirun.overview.card.replyUnavailable":"Answer unavailable","multirun.overview.card.selectAria":"Select {name}","multirun.overview.card.working":"Working…","multirun.overview.fuse.modeAnswers":"Combines the final answers","multirun.overview.fuse.modeCode":"Works in its own worktree and reads each run with git","multirun.overview.fuse.selected":"{count} of {total} selected","multirun.overview.fuse.with":"Fuse with","multirun.overview.fusedResult":"Fused result","multirun.overview.headerTitle":"Run in parallel","multirun.overview.keep.confirm":"Keep and clean up","multirun.overview.keep.confirmPlural":"Keep {name}? The other {count} runs are archived and their worktrees removed. Their work stays recoverable.","multirun.overview.keep.confirmSingle":"Keep {name}? The other run is archived and its worktree removed. Its work stays recoverable.","multirun.overview.keep.done":"Kept {name}","multirun.overview.keep.failed":"Could not clean up the other runs.","multirun.overview.keep.partialPlural":"Kept {name}. {count} runs could not be cleaned up and were left as they were.","multirun.overview.keep.partialSingle":"Kept {name}. One run could not be cleaned up and was left as it was.","multirun.overview.keep.working":"Cleaning up…","multirun.overview.meta.autoFusion":"Fuses with {model} when all finish","multirun.overview.meta.progress":"{done} of {total} finished","multirun.overview.meta.runsPlural":"{count} runs","multirun.overview.meta.runsSingle":"{count} run","multirun.overview.meta.sharedDirectory":"Shared directory","multirun.overview.meta.variants":"{count} prompt variants","multirun.overview.meta.worktrees":"Separate worktrees","multirun.overview.missing":"This run is no longer available.","multirun.overview.rename.aria":"Rename run","multirun.overview.rename.failed":"Some runs kept the old name.","sessions.sidebar.run.collapse":"Hide runs","sessions.sidebar.run.expand":"Show runs","sessions.sidebar.run.laneCountPlural":"{count} runs","sessions.sidebar.run.laneCountSingle":"{count} run","sessions.sidebar.run.openOverviewAria":"Open parallel run {title}","sessions.sidebar.run.menu.openOverview":"Open overview","sessions.sidebar.session.menu.openRunOverview":"Open run overview","chat.parallel.models.effortAria":"Thinking effort: {effort}","chat.parallel.settings.title":"Launch settings","chat.parallel.settings.whereTitle":"Where the runs work","chat.parallel.settings.setupTitle":"Setup commands","chat.parallel.settings.fusionTitle":"Fusion","chat.parallel.settings.variantsTitle":"Prompt variants","chat.parallel.settings.variantsDescription":"Send different prompts, for example to compare skills or wording. Each variant gets its own tab.","chat.parallel.settings.addVariant":"Add a prompt variant","chat.parallel.settings.done":"Done","chat.parallel.settings.openAria":"Launch settings: {summary}","multirun.overview.card.keep":"Keep this","multirun.overview.addModel.action":"Add a model","multirun.overview.addModel.hint":"Runs the same prompt on one more model in this run","chat.parallel.settings.whereShared":"Project directory","chat.parallel.settings.whereSharedHint":"All runs work in your checkout. Best for questions and research.","chat.parallel.settings.whereWorktrees":"Separate worktrees","chat.parallel.settings.whereWorktreesHint":"Each run gets its own branch, so code changes never collide. Keep the best one.","chat.parallel.settings.baseBranchTitle":"Base branch","chat.parallel.settings.fusionOff":"Off","chat.parallel.settings.fusionOffHint":"Compare the results yourself.","chat.parallel.settings.fusionAuto":"Automatic","chat.parallel.settings.fusionAutoHint":"Fuse the results as soon as every run finishes.","chat.parallel.settings.judgeTitle":"Fusion model","multirun.overview.card.detach":"Make a separate session","multirun.overview.card.detachHint":"Leave this run and continue as an ordinary session","multirun.overview.card.detachDone":"{name} is now a separate session","multirun.overview.card.detachFailed":"Could not move this session out of the run.","multirun.overview.card.archive":"Archive this session","multirun.overview.addModel.confirm":"Run","multirun.overview.status.permission":"Waiting for your permission","multirun.overview.status.question":"Waiting for your answer","multirun.overview.status.working":"Working","multirun.overview.status.failed":"Failed","multirun.overview.status.stopped":"Stopped","multirun.overview.status.notStarted":"Not started","multirun.overview.status.noReply":"Finished without an answer","multirun.overview.status.finished":"Finished","multirun.overview.status.count.permission":"{count} waiting for permission","multirun.overview.status.count.question":"{count} waiting for an answer","multirun.overview.status.count.working":"{count} working","multirun.overview.status.count.failed":"{count} failed","multirun.overview.status.count.stopped":"{count} stopped","multirun.overview.status.count.notStarted":"{count} not started","multirun.overview.status.count.noReply":"{count} without an answer","multirun.overview.status.count.finished":"{count} finished","multirun.overview.card.body.permission":"Waiting for your permission to go on. Open the chat to answer.","multirun.overview.card.body.question":"Asked you a question. Open the chat to answer.","multirun.overview.card.body.failed":"Failed. Open the chat for details.","multirun.overview.card.body.notStarted":"Has not started yet.","multirun.overview.card.body.stopped":"Stopped before answering.","multirun.overview.bar.waiting":"Runs waiting for you: {count}. The run can't finish until you answer them.","multirun.overview.prompt.expand":"Show all","multirun.overview.prompt.collapse":"Show less","gitView.changes.revertFileDialogTitle":"Revert file changes?","gitView.changes.revertFileDescription":"This will discard your local changes in {path}.","gitView.changes.revertFileConfirm":"Revert file","diffView.hunk.discardDialogTitle":"Discard this hunk?","diffView.hunk.discardDescription":"This will discard these local changes in {path}.","sessions.sidebar.project.actions.archiveAll":"Archive all sessions","sessions.sidebar.project.archiveAll.title":"Archive sessions in {project}?","sessions.sidebar.project.archiveAll.descriptionSingle":"{count} session moves to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.descriptionPlural":"{count} sessions move to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.nothing":"Nothing to archive: every session here is pinned, running or In work.","contextPanel.browser.devServers.hide":"Hide port {port} from this list","contextPanel.browser.devServers.showHiddenSingle":"Show {count} hidden port","contextPanel.browser.devServers.showHiddenPlural":"Show {count} hidden ports","sidebarFilesTree.menu.openInDefaultApp":"Open in default app","sessions.sidebar.header.displayMode.showChats":"Show chats section","sessions.scheduledTasks.editor.useDefaults.label":"Use session defaults","sessions.scheduledTasks.editor.useDefaults.hint":"Each run takes the default model, thinking level and agent from Settings → Sessions (or the project's own defaults) at the time it starts.","sessions.scheduledTasks.editor.worktree.label":"Run each run in a fresh worktree","sessions.scheduledTasks.editor.worktree.hint":"Each run gets its own worktree and branch.","sessions.scheduledTasks.editor.worktree.baseBranch.label":"Source branch","sessions.scheduledTasks.editor.worktree.cleanup.label":"Clean up worktree after run","sessions.scheduledTasks.editor.worktree.cleanup.hint":"The worktree and its branch are removed when the run ends.","sessions.scheduledTasks.editor.worktree.cleanup.keepHint":"The worktree and its branch stay after the run so you can review the result.","sessions.scheduledTasks.editor.worktree.notRepo":"The project folder is not a git repository; runs will use the checkout as-is.","sessions.scheduledTasks.dialog.usesDefaults":"Session defaults","sessions.moveSession.menu":"Move session…","sessions.moveSession.hint":"Files stay in the old folder","sessions.moveSession.title":"Move session","sessions.moveSession.description":"The session continues in the chosen folder. Files stay where they are.","sessions.moveSession.chooseFolder":"Choose folder…","sessions.moveSession.current":"Current folder","sessions.moveSession.success":"Session moved","sessions.moveSession.failed":"Could not move the session","chat.folderMissing.text":"Folder {name} no longer exists","chat.folderMissing.action":"Move session","chat.worktreeSetup.running":"Setting up the worktree: running the project's setup commands…","chat.draft.creatingSession":"Creating session…","desktopHostSwitcher.startup.fellBackToLocal":"Its connection didn't open, so OpenChamber started on Local. Connect it from the instance switcher once it's reachable.","desktopSafeStart.title":"OpenChamber kept crashing","desktopSafeStart.description":"Panels are closed and folders collapsed.","chat.chatInput.contextPreview.saveEdit":"Save comment","chat.chatInput.contextPreview.cancelEdit":"Cancel editing","sessions.scheduledTasks.dialog.actions.openSession":"Open session","sessions.scheduledTasks.dialog.actions.openSessionAria":"Open the session from the last run of {taskName}","sessions.scheduledTasks.dialog.toast.alreadyRunningSince":"This task already has a run in progress, started at {time}","sessions.scheduledTasks.dialog.toast.alreadyRunning":"This task already has a run in progress","sessions.scheduledTasks.dialog.toast.alreadyQueued":"This task is already waiting in the queue and will run when a slot frees up","chat.modelControls.agentFavoriteAdd":"Add to favorites. With favorites, Tab cycles through them only","notifications.error.bodyFallback":"An error occurred","notifications.question.bodyFallback":"Agent is waiting for your response","notifications.permission.bodyFallback":"Agent is waiting for your approval","notifications.permission.title":"Permission required","chat.promptHistorySearch.title":"Search prompt history","chat.promptHistorySearch.searchPlaceholder":"Search remembered prompts","chat.promptHistorySearch.close":"Close prompt history search","chat.promptHistorySearch.empty":"No prompts to search yet","chat.promptHistorySearch.noMatches":"No matching prompts","chat.promptHistorySearch.attachmentsSingle":"{count} attachment","chat.promptHistorySearch.attachmentsPlural":"{count} attachments","chat.promptHistorySearch.hint":"↑ ↓ to browse · Enter to load · Esc to close","helpDialog.item.searchPromptHistory":"Search prompt history (chat input)"},gl=new Map([[hi,fi]]);async function Mx(e){const t=gl.get(e);if(t)return t;const s=e==="zh-CN"?await Ee(()=>import("./zh-CN-CNdkQtjY.js"),__vite__mapDeps([3,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="fr"?await Ee(()=>import("./fr-CdmUjdKh.js"),__vite__mapDeps([109,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="nl"?await Ee(()=>import("./nl-Ds8N-7nU.js"),__vite__mapDeps([110,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="zh-TW"?await Ee(()=>import("./zh-TW-njZbI3nO.js"),__vite__mapDeps([111,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="es"?await Ee(()=>import("./es-CV0MRSsN.js"),__vite__mapDeps([112,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pt-BR"?await Ee(()=>import("./pt-BR-CxTCCQt5.js"),__vite__mapDeps([113,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="uk"?await Ee(()=>import("./uk-DYlYVGgJ.js"),__vite__mapDeps([114,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ko"?await Ee(()=>import("./ko-CadSaTs-.js"),__vite__mapDeps([115,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pl"?await Ee(()=>import("./pl-BAAqSvOD.js"),__vite__mapDeps([116,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="de"?await Ee(()=>import("./de-Jo819vpe.js"),__vite__mapDeps([117,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ja"?await Ee(()=>import("./ja-BGc1V8I_.js"),__vite__mapDeps([118,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="tr"?await Ee(()=>import("./tr-vj7L-0nl.js"),__vite__mapDeps([119,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ar"?await Ee(()=>import("./ar-CuYBgoCL.js"),__vite__mapDeps([120,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="he"?await Ee(()=>import("./he-B0Jv5rnl.js"),__vite__mapDeps([121,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):{dict:fi};return gl.set(e,s.dict),s.dict}const Wo=yt()((e,t)=>({locale:hi,dictionary:fi,loadingLocale:null,setLocale:s=>{const n=t(),a=gl.get(s);n.locale===s&&n.loadingLocale!==s&&a||(Dz(s),e({locale:s,dictionary:a??n.dictionary,loadingLocale:a?null:s}),!a&&Mx(s).then(i=>{t().locale===s&&e({dictionary:i,loadingLocale:null})}).catch(i=>{console.error(`[i18n] failed to load locale ${s}`,i),t().locale===s&&e({dictionary:fi,loadingLocale:null})}))}}));function Ex(){Wo.getState().setLocale(Bz())}function Lx(e,t,s){const n=e[t]??fi[t]??t;return s?n.replace(/\{([^{}]+)\}/g,(a,i)=>{const o=s[i.trim()];return o==null?a:String(o)}):n}const $q=Object.freeze(Object.defineProperty({__proto__:null,formatMessage:Lx,initializeLocale:Ex,useI18nStore:Wo},Symbol.toStringTag,{value:"Module"})),mf="session",hf=40,qx=1,Vx=100,ff=e=>e==="global"||e==="session",Pd=e=>e!=null&&Number.isInteger(e)&&e>=qx&&e<=Vx,Ux=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Ad=e=>e==="auto"||typeof e=="string"&&Ux.includes(e),Fn="openchamber-input-history.v1",Wx=8,Hx=50,Gx=[40,25,10,5,1],dc=Object.freeze([]);let as=null,vp=0;const $a=(e=mf,t=hf)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),bf=()=>(vp+=1,Date.now()*1e3+vp),kf=e=>JSON.stringify([e]),pl=(e,t,s)=>JSON.stringify([e,t,s]),zd=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},_x=()=>{const e=zd(),t=jt?JSON.stringify(vo(jt.base)):as;if(!e)return t;try{return e.getItem(Fn)??(jt?null:as)}catch{return t}},Cp=bt(g(),Y()),Kx=p({key:g().min(1),source:J([y("file-url"),y("vscode-file")]),filename:g().min(1),mimeType:g().min(1),size:v().finite().nonnegative(),reference:g().min(1)}),Zx=p({text:g(),attachmentKeys:x(g()),restorableAttachments:x(Kx),submittedAt:v().finite().nonnegative()}),Jx=p({touchedAt:v().finite().nonnegative(),entries:x(Y())}),$x=(e,t)=>{try{const s=JSON.parse(e),a=(t===1?xo([g().trim().min(1)]):xo([g().trim().min(1),g().trim().min(1),g().trim().min(1)])).safeParse(s);if(!a.success)return null;if(t===3){const i=ze(a.data[1]);if(!i||i!==a.data[1])return null}return a.data}catch{return null}},Sp=(e,t)=>{const s=[];for(const[n,a]of Object.entries(e)){if(!$x(n,t))continue;const i=Jx.safeParse(a);if(!i.success)continue;const o=i.data.entries.map(r=>Zx.safeParse(r)).filter(r=>r.success).map(r=>r.data);s.push([n,{touchedAt:i.data.touchedAt,entries:o}])}return Object.fromEntries(s)},Qx=()=>{const e=_x();if(e===null)return $a();try{const t=JSON.parse(e),s=p({version:y(1),entryLimit:v().int().optional(),scope:J([y("global"),y("session")]).optional(),global:Cp.default({}),session:Cp.default({})}).safeParse(t);return s.success?{entryLimit:Pd(s.data.entryLimit)?s.data.entryLimit:hf,scope:s.data.scope??mf,globalBuckets:Sp(s.data.global,1),sessionBuckets:Sp(s.data.session,3)}:$a()}catch{const t=zd();if(t)try{t.removeItem(Fn)}catch{}return as=null,$a()}};let jt=null,wo=$a();const Pp=(e,t,s)=>{const n={...e};for(const a of new Set([...Object.keys(t),...Object.keys(s)])){if(JSON.stringify(t[a])===JSON.stringify(s[a]))continue;const i=s[a];if(!i){delete n[a];continue}const o=new Set((t[a]?.entries??[]).map(d=>JSON.stringify(d))),r=new Set(i.entries.map(d=>JSON.stringify(d))),c=(e[a]?.entries??[]).filter(d=>{const u=JSON.stringify(d);return!o.has(u)||r.has(u)}),l=new Set(c.map(d=>JSON.stringify(d)));for(const d of i.entries){const u=JSON.stringify(d);!o.has(u)&&!l.has(u)&&c.push(d)}c.sort((d,u)=>d.submittedAt-u.submittedAt),n[a]={touchedAt:Math.max(i.touchedAt,e[a]?.touchedAt??0),entries:c}}return n},Ea=()=>{const e=Qx();if(wo=e,!jt)return e;const{base:t,value:s}=jt;return ul({entryLimit:s.entryLimit===t.entryLimit?e.entryLimit:s.entryLimit,scope:s.scope===t.scope?e.scope:s.scope,globalBuckets:Pp(e.globalBuckets,t.globalBuckets,s.globalBuckets),sessionBuckets:Pp(e.sessionBuckets,t.sessionBuckets,s.sessionBuckets)})},yf=(e,t)=>e.slice(Math.max(0,e.length-t)),Ap=(e,t,s)=>{const n=Object.entries(e).map(([a,i])=>[a,{touchedAt:i.touchedAt,entries:yf(i.entries,s)}]).sort((a,i)=>i[1].touchedAt-a[1].touchedAt).slice(0,t);return Object.fromEntries(n)},ul=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Ap(e.globalBuckets,Wx,t),sessionBuckets:Ap(e.sessionBuckets,Hx,t)}),vo=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),zp=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),La=e=>{const t=ul(e),s=JSON.stringify(vo(t));jt={base:wo,value:t};const n=zd();if(!n)return as=s,t;try{return n.setItem(Fn,s),jt=null,as=s,t}catch(o){if(!(o instanceof Error)||!zp(o))return as=s,t}try{n.removeItem(Fn)}catch{}for(const o of Gx){const r=ul(t,o),c=JSON.stringify(vo(r));try{return n.setItem(Fn,c),jt=null,as=c,r}catch(l){if(!(l instanceof Error)||!zp(l))return jt={base:wo,value:r},as=c,r}}const a=$a(t.scope,t.entryLimit),i=JSON.stringify(vo(a));try{n.setItem(Fn,i),jt=null}catch{jt={base:wo,value:a}}return as=i,a},Yx=(e,t,s)=>{const n=e.trim(),a=ze(t),i=s.trim();return!n||!a||!i?null:{runtimeKey:n,directory:a,sessionId:i}},wf=e=>e.source==="vscode"&&e.vscodeSource==="file"?ze(e.vscodePath??null):e.dataUrl.trim()||null,Xx=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),ml=e=>{const t=wf(e),s=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),s].join("|")},eT=e=>{const t=wf(e);return!t||!Xx(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:ml(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:ml(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},tT=(e,t)=>({text:e,attachmentKeys:t.map(ml),restorableAttachments:t.map(eT).filter(s=>s!==null)}),sT=(e,t)=>e.length===t.length&&e.every((s,n)=>{const a=t[n];return a!==void 0&&s.key===a.key&&s.source===a.source&&s.filename===a.filename&&s.mimeType===a.mimeType&&s.size===a.size&&s.reference===a.reference}),nT=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((s,n)=>s===t.attachmentKeys[n])&&sT(e.restorableAttachments,t.restorableAttachments),xp=(e,t,s,n)=>{const a=e?[...e.entries]:[];for(const i of t){const o=a.at(-1);nT(o,i)||a.push({text:i.text,attachmentKeys:[...i.attachmentKeys],restorableAttachments:i.restorableAttachments.map(r=>({...r})),submittedAt:bf()})}return{touchedAt:s,entries:yf(a,n)}},aT=La(Ea()),qa=yt(e=>({...aT,applyEntryLimit:t=>{Pd(t)&&e(s=>{const n=Ea();if(n.entryLimit===t)return{...s,...n};const a=La({entryLimit:t,scope:n.scope,globalBuckets:n.globalBuckets,sessionBuckets:n.sessionBuckets});return{...s,...a}})},applyScope:t=>{ff(t)&&e(s=>{const n=Ea();if(n.scope===t)return{...s,...n};const a=La({entryLimit:n.entryLimit,scope:t,globalBuckets:n.globalBuckets,sessionBuckets:n.sessionBuckets});return{...s,...a}})},appendSubmissions:(t,s)=>{s.length!==0&&e(n=>{const a=Ea(),i=bf(),o=kf(t.runtimeKey),r=pl(t.runtimeKey,t.directory,t.sessionId),c=La({entryLimit:a.entryLimit,scope:a.scope,globalBuckets:{...a.globalBuckets,[o]:xp(a.globalBuckets[o],s,i,a.entryLimit)},sessionBuckets:{...a.sessionBuckets,[r]:xp(a.sessionBuckets[r],s,i,a.entryLimit)}});return{...n,...c}})},clearSession:t=>{e(s=>{const n=Ea(),a=pl(t.runtimeKey,t.directory,t.sessionId);if(!(a in n.sessionBuckets))return{...s,...n};const i={...n.sessionBuckets};delete i[a];const o=La({entryLimit:n.entryLimit,scope:n.scope,globalBuckets:n.globalBuckets,sessionBuckets:i});return{...s,...o}})}})),Qq=(e,t)=>t?e.scope==="session"?e.sessionBuckets[pl(t.runtimeKey,t.directory,t.sessionId)]?.entries??dc:e.globalBuckets[kf(t.runtimeKey)]?.entries??dc:dc,vf=["guest","link","external","repository"],iT=new Set([...vf,"linear"]),Rs=g().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!iT.has(e),{message:"Reserved provider id"}),oT=R(["pullRequest","mergeRequest","change"]),rT=R(["checks","pipeline"]),cT=R(["device","pat","cli"]),lT=J([R(["instance-url","personal-access-token","username","http-password"]),g().transform(()=>"unknown")]),dT=g().max(8192).regex(/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/),Tp=g().min(1).max(64),xa=x(g().min(1).max(256)).max(8),gT=p({id:Rs,label:Tp,order:v().int(),terminology:p({changeRequest:oT.catch("pullRequest"),changeRequestPrefix:g().min(1).max(4),issuePrefix:g().min(1).max(4),sharedNumberSpace:z(),abbreviation:g().min(1).max(8),promptNoun:Tp,ci:rT.catch("checks")}),icon:p({sprite:g().max(64).optional(),filledSprite:g().max(64).optional(),path:dT.optional()}),repository:p({nestedNamespaces:z(),pathStyle:y("path").optional().catch(void 0)}),instances:p({format:R(["host","origin"]),defaultInstance:g().min(1).max(256).nullable(),multiple:z(),allowLoopbackHttp:z(),allowPort:z(),reserved:x(g().max(256)).max(16),placeholder:g().max(256),legacyFlow:p({instance:g().min(1).max(256),kind:y("github-com-device")}).optional()}),auth:p({methods:x(J([cT,g().transform(()=>null)])).transform(e=>e.filter(t=>t!==null)),cliName:g().min(1).max(32).optional(),cliTransport:z(),token:p({scopes:x(g().min(1).max(64)).max(32),createPath:g().max(256).optional()}).optional()}),settings:p({fields:x(p({id:g().min(1).max(64),kind:lT,secret:z()})).max(16)}),urls:p({changeRequest:xa,issue:xa,discussion:xa.default([]).catch([]),commit:xa.default([]).catch([]),user:xa.default([]).catch([])}),features:p({referenceSearch:z().default(!1),referenceDetail:z().default(!1),listStatuses:z().default(!1),referencesAcross:z().default(!1),startThread:z().default(!1),reviewDrafts:z().default(!1),reviewDraftFileComments:z().default(!1),authorCanReview:z().default(!1),projectUploads:z().default(!1),issueCloseReason:z().default(!1),changeRequestTemplates:x(g().min(1).max(256)).max(8).default([]),changeRequestPatch:z().default(!0),reviewModel:R(["verdict","votes"]).default("verdict").catch("verdict"),revisions:z().default(!1).catch(!1),submitRequirements:z().default(!1).catch(!1),createByPush:z().default(!1).catch(!1),branchHeads:z().default(!0).catch(!0),discussions:z().default(!1).catch(!1)}),extension:p({guestId:g().min(1).max(128),name:g().min(1).max(200),version:g().min(1).max(64)}).optional().catch(void 0)}),pT=(e,t)=>e.order-t.order||(e.id<t.id?-1:e.id>t.id?1:0),hl=x(gT.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const n of e)!n||t.has(n.id)||(t.add(n.id),s.push(n));return s.sort(pT)}),Ip=new Map,xd=e=>{const t=Ip.get(e);if(t)return t;const s={id:e,label:e,order:Number.MAX_SAFE_INTEGER,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"git-branch"},repository:{nestedNamespaces:!1},instances:{format:"origin",defaultInstance:null,multiple:!1,allowLoopbackHttp:!1,allowPort:!1,reserved:[],placeholder:""},auth:{methods:[],cliTransport:!1},settings:{fields:[]},urls:{changeRequest:[],issue:[],discussion:[],commit:[],user:[]},features:{referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,reviewDrafts:!1,reviewDraftFileComments:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1,reviewModel:"verdict",revisions:!1,submitRequirements:!1,createByPush:!1,branchHeads:!0,discussions:!1}};return Ip.set(e,s),s},uT=16,mT=(e,t)=>{const s=x(xo([g(),t])),n=()=>{try{const a=s.safeParse(JSON.parse(window.localStorage.getItem(e)??"[]"));return a.success?a.data:[]}catch{return[]}};return{read:a=>Ec(a)?null:n().find(([i])=>i===a)?.[1]??null,remember:(a,i)=>{if(Ec(a))return;const o=n().filter(([r])=>r!==a);o.push([a,[...i]]);try{window.localStorage.setItem(e,JSON.stringify(o.slice(-uT)))}catch{}}}},hT=(e,t)=>e===t||e.length===t.length&&JSON.stringify(e)===JSON.stringify(t),fT=e=>Math.min(6e4,2e3*2**Math.max(0,e-1)),Cf=mT("openchamber.sourceControlProviders.v1",hl),Td=e=>({ordered:e,byId:new Map(e.map(t=>[t.id,t]))}),bT=Td([]),Rp=e=>{const t=Cf.read(e);return t?{runtimeKey:e,...Td(t),status:"stale",holdsList:!0}:{runtimeKey:e,...bT,status:"idle",holdsList:!1}};let _s=0,An=null,zn=null,no=0,Qa=null;const jp=()=>{Qa!==null&&clearTimeout(Qa),Qa=null},bn=yt((e,t)=>{const s=n=>{_s+=1,An=null,zn=null,no=0,jp(),e(Rp(n))};return{...Rp(D()),refresh:n=>{const a=D();if(a!==t().runtimeKey&&s(a),An){if(!zn){const d=_s,u=An.then(()=>{if(zn===u&&(zn=null),d===_s)return t().refresh(n)});zn=u}return zn}jp();const i=_s,{holdsList:o,ordered:r}=t();e({status:"loading"});const l=(async()=>{try{const d=await n.providers();if(i!==_s)return;no=0,Cf.remember(a,d),e(o&&hT(r,d)?{status:"ready"}:{...Td(d),status:"ready",holdsList:!0})}catch{if(i!==_s)return;if(o){e({status:"stale"});return}e({status:"error"}),no+=1,Qa=setTimeout(()=>{Qa=null,i===_s&&t().refresh(n)},fT(no))}})().finally(()=>{An===l&&(An=null)});return An=l,l},resetForRuntimeSwitch:s}});queueMicrotask(()=>{const e=bn.getState(),t=D();e.status==="idle"&&t!==e.runtimeKey&&e.resetForRuntimeSwitch(t)});const Yq=()=>bn(yT),kT=e=>{const t=Ft.c(5);let s;t[0]!==e?(s=i=>e?i.byId.get(e):void 0,t[0]=e,t[1]=s):s=t[1];const n=bn(s);let a;return t[2]!==n||t[3]!==e?(a=n??xd(e??""),t[2]=n,t[3]=e,t[4]=a):a=t[4],a},Xq=e=>kT(e).terminology.changeRequest,eV=e=>{const t=Ft.c(2);let s;return t[0]!==e?(s=n=>e&&n.byId.has(e)?"served":n.holdsList?"not-served":"unknown",t[0]=e,t[1]=s):s=t[1],bn(s)},tV=e=>{const t=Ft.c(2);let s;return t[0]!==e?(s=n=>{const a=e?n.byId.get(e):void 0;return a?a.features.changeRequestPatch?"served":"not-served":n.holdsList?"not-served":"unknown"},t[0]=e,t[1]=s):s=t[1],bn(s)},sV=()=>{const e=Ft.c(2),t=bn(wT);let s;return e[0]!==t?(s=n=>(n?t.get(n):void 0)??xd(n??""),e[0]=t,e[1]=s):s=e[1],s},cr=e=>(e?bn.getState().byId.get(e):void 0)??xd(e??"");function yT(e){return e.ordered}function wT(e){return e.byId}const vT=p({text:g(),prefix:g(),suffix:g(),start:v(),page:p({partId:g()}).optional()}),Op=32,Sf=200,CT="[data-chat-quote-root]";function nV(e,t){return[...e.querySelectorAll(`[data-message-id="${CSS.escape(t)}"]`)].flatMap(s=>s.querySelector(CT)??[]).sort((s,n)=>s.getBoundingClientRect().top-n.getBoundingClientRect().top)}function Pf(e,t,s){const n=s+t.text.length,a=e.slice(Math.max(0,s-t.prefix.length),s),i=e.slice(n,n+t.suffix.length);return t.prefix.endsWith(a)&&t.suffix.startsWith(i)}function Dp(e,t,s){const n=e.ownerDocument.createRange();return n.setStart(e,0),n.setEnd(t,s),n.toString().length}function Af(e){const t=[];let s="";for(const n of e)t.push(s.length),s+=n.textContent??"";return{stream:s,bases:t}}function aV(e,t){const s=Array.isArray(e)?e:[e],n=s.findIndex(d=>d.contains(t.startContainer)),a=s.findIndex(d=>d.contains(t.endContainer));if(n<0||a<n)return null;const{stream:i,bases:o}=Af(s),r=o[n]+Dp(s[n],t.startContainer,t.startOffset),c=o[a]+Dp(s[a],t.endContainer,t.endOffset),l=i.slice(r,c);return l.trim()?{text:l,prefix:i.slice(Math.max(0,r-Op),r),suffix:i.slice(c,c+Op),start:r}:null}function ST(e,t){if(!t.text)return null;const s=[];for(let a=e.indexOf(t.text);a!==-1&&s.length<Sf;a=e.indexOf(t.text,a+1))s.push(a);if(s.length<=1)return s[0]??null;if(!t.prefix&&!t.suffix)return null;const n=s.filter(a=>Pf(e,t,a));return n.length===0?null:n.reduce((a,i)=>Math.abs(i-t.start)<Math.abs(a-t.start)?i:a)}function zf(e,t){for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType===3?t.push(s):zf(s,t);return t}function PT(e){const t=new Set;let s=1;for(const n of e){const a=n.closest("[data-message-id]")?.getAttribute("data-message-row");if(!a)return e.length===1;const[i,o]=a.split("/");t.add(i),s=Number(o)}return t.size===s}const Ta=32;function AT(e,t){const{text:s,prefix:n,suffix:a}=t,i=!!(n||a),o=l=>{const d=[];for(let u=e.indexOf(l);u!==-1&&d.length<Sf;u=e.indexOf(l,u+1))d.push(u);return d},r=[];for(const l of o(s))(!i||Pf(e,t,l))&&r.push({start:l,end:l+s.length});if(s.length>Ta&&(r.length===0||!i)){for(const l of o(s.slice(0,Ta))){const d=e.slice(l);d.length<s.length&&s.startsWith(d)&&n.endsWith(e.slice(Math.max(0,l-n.length),l))&&r.push({start:l,end:e.length})}for(const l of o(s.slice(-Ta))){const d=l+Ta;d<s.length&&s.endsWith(e.slice(0,d))&&a.startsWith(e.slice(d,d+a.length))&&r.push({start:0,end:d})}e.length>=Ta&&e.length<s.length&&s.includes(e)&&r.push({start:0,end:e.length})}return i?r[0]??null:new Set(r.map(l=>`${l.start}:${l.end}`)).size===1?r[0]:null}function iV(e,t){const{stream:s}=Af(e);let n,a;if(PT(e))n=ST(s,t),a=(n??0)+t.text.length;else{const r=AT(s,t);n=r?.start??null,a=r?.end??0}if(n===null||a<=n)return null;const i=[];let o=0;for(const r of e){let c=null;for(const l of zf(r,[])){const d=l.data.length;if(!c&&n<o+d&&a>o&&(c=r.ownerDocument.createRange(),c.setStart(l,Math.max(0,n-o)),c.setEnd(r,r.childNodes.length)),c&&a<=o+d)return c.setEnd(l,a-o),i.push(c),i;o+=d}c&&i.push(c)}return null}const zT=nk.gfm,xT=ak().use(ik).use(zT[0],{singleTilde:!1});function oV(e){const t=s=>{if("children"in s){if(s.type==="list")return`
32
+ {summary}`,"chat.chatInput.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.chatInput.toast.openSessionFirst":"Open a session first","chat.chatInput.toast.dictationKeptForOriginalSession":"Dictation saved as a draft in the session where you started it","chat.chatInput.toast.togglePermissionAutoAcceptFailed":"Failed to toggle permission auto-accept","chat.chatInput.reviewComments":"Review comments:","chat.chatInput.reviewCommentsRemove":"Remove review comments","chat.chatInput.previewAnnotations":"Preview annotations:","chat.chatInput.previewContext":"Preview context:","chat.chatInput.previewContextRemove":"Remove preview context","chat.chatInput.projectRoot":"Project root","chat.chatInput.branch":"Branch","chat.chatInput.draftPicker.projectTitle":"Project","chat.chatInput.draftPicker.searchProjects":"Search projects...","chat.chatInput.draftPicker.searchBranches":"Search branches...","chat.chatInput.draftPicker.noProjectsFound":"No projects found.","chat.chatInput.worktrees":"Worktrees","chat.chatInput.worktreeQuick":"Quick worktree","chat.chatInput.worktreeCustom":"New worktree…","chat.chatInput.drop.insertMention":"Drop to insert as mention","chat.chatInput.drop.attachFiles":"Drop files here to attach","chat.chatInput.fileFallback":"file","chat.toolOutputDialog.image.previousAria":"Previous image","chat.toolOutputDialog.image.nextAria":"Next image","chat.toolOutputDialog.image.closeAria":"Close image preview","chat.toolOutputDialog.mermaid.missingSource":"Missing Mermaid source URL.","chat.toolOutputDialog.mermaid.loadFailed":"Unable to load Mermaid diagram.","chat.toolOutputDialog.mermaid.dataUrlMalformed":"The Mermaid data URL is malformed.","chat.toolOutputDialog.mermaid.invalidLocalPath":"The local Mermaid file path is invalid.","chat.toolOutputDialog.mermaid.readFileFailedWithStatus":"Unable to read Mermaid file. Status: {status}.","chat.toolOutputDialog.mermaid.unsupportedUrlProtocol":"The Mermaid URL protocol is unsupported.","chat.toolOutputDialog.mermaid.loadFailedWithStatus":"Unable to load Mermaid diagram. Status: {status}.","chat.toolOutputDialog.mermaid.closeAria":"Close diagram preview","chat.toolOutputDialog.mermaid.loading":"Loading diagram...","chat.toolOutputDialog.mermaid.renderFailed":"Unable to render Mermaid diagram.","chat.toolOutputDialog.mermaid.retry":"Retry","chat.toolOutputDialog.commandCompleted":"Command completed successfully","chat.toolOutputDialog.noOutputProduced":"No output was produced","chat.statusRow.background.action":"Move to background — the agent stops waiting and continues","chat.statusRow.background.failed":"Couldn't move the work to the background","chat.toolPart.background.label":"in background","chat.toolPart.background.stop":"Stop command","chat.toolPart.background.stopLabel":"Stop","chat.toolPart.background.stopFailed":"Couldn't stop the command","chat.toolPart.background.stoppedLabel":"stopped","chat.toolPart.background.stoppedNotice":"Stopped by you. The agent was told this was your stop, not a failure.","chat.toolPart.subagent.stop":"Stop subagent","chat.toolPart.subagent.stopFailed":"Couldn't stop the subagent","chat.toolPart.lspErrors":"LSP errors","chat.toolPart.moreErrors":"+{count} more errors","chat.toolPart.moreRows":"+{count} more rows","chat.toolPart.error":"Error:","chat.toolPart.awaitingResponse":"Awaiting response...","chat.toolPart.noOutputProduced":"No output produced","chat.toolPart.questionsAsked":"Questions asked: {count}","chat.toolPart.filesCount":"Files: {count}","chat.toolPart.moreToolCalls":"+{count} more","chat.toolPart.scriptCalls":"Tool calls","chat.toolPart.outputTruncated":"Output was truncated","chat.toolPart.content.loading":"Loading the result…","chat.toolPart.content.loadFailed":"Couldn't load the result.","chat.toolPart.content.retry":"Retry","chat.toolPart.output":"Output","chat.toolPart.showRawJson":"Show raw JSON","chat.toolPart.showFormattedJson":"Show formatted JSON","chat.toolPart.showNavigableJson":"Show navigable JSON","chat.toolPart.openFile":"Open file","chat.toolPart.openImageExpanded":"Open","chat.toolPart.openFileAtFirstChange":"Open file at first change","chat.toolPart.openFileDiff":"Open file diff","chat.toolPart.copyOutput":"Copy output","chat.toolPart.copiedOutput":"Copied output","chat.toolPart.copyOutputFailed":"Failed to copy output","chat.toolPart.openSubtask":"Open {type} subtask","chat.todo.total":"Total","chat.todo.inProgress":"In Progress","chat.todo.pending":"Pending","chat.todo.completed":"Completed","chat.todo.cancelled":"Cancelled","chat.permissionCard.workingDirectory":"Working Directory:","chat.permissionCard.timeout":"Timeout:","chat.permissionCard.request":"Request:","chat.permissionCard.headers":"Headers:","chat.permissionCard.body":"Body:","chat.permissionCard.action":"Action:","chat.permissionCard.patterns":"Patterns:","chat.permissionToast.sessionFallback":"Session","chat.permissionToast.permissionFallback":"Permission details unavailable","chat.permissionToast.labels.session":"Session:","chat.permissionToast.labels.permission":"Permission:","chat.permissionToast.actions.once":"Once","chat.permissionToast.actions.always":"Always","chat.permissionToast.actions.deny":"Deny","chat.permissionToast.actions.approveOnceAria":"Approve once","chat.permissionToast.actions.approveOnceAriaWithSession":"Approve once for {session}","chat.permissionToast.actions.approveAlwaysAria":"Approve always","chat.permissionToast.actions.approveAlwaysAriaWithSession":"Approve always for {session}","chat.permissionToast.actions.denyAria":"Deny permission","chat.permissionToast.actions.denyAriaWithSession":"Deny permission for {session}","chat.permissionRequest.required":"Permission required:","chat.permissionRequest.actions.once":"Once","chat.permissionRequest.actions.always":"Always","chat.permissionRequest.actions.reject":"Reject","chat.modelControls.provider":"Provider","chat.modelControls.capability.toolCalling":"Tool calling","chat.modelControls.capability.reasoning":"Reasoning","chat.modelControls.modality.text":"Text","chat.modelControls.modality.image":"Image","chat.modelControls.modality.video":"Video","chat.modelControls.modality.audio":"Audio","chat.modelControls.modality.pdf":"PDF","chat.modelControls.capabilities":"Capabilities","chat.modelControls.modalities":"Modalities","chat.modelControls.input":"Input","chat.modelControls.output":"Output","chat.modelControls.limits":"Limits","chat.modelControls.context":"Context","chat.modelControls.metadata":"Metadata","chat.modelControls.knowledge":"Knowledge","chat.modelControls.release":"Release","chat.modelControls.mode":"Mode","chat.modelControls.model":"Model","chat.modelControls.temperature":"Temperature","chat.modelControls.topP":"Top P","chat.modelControls.permissions":"Permissions","chat.modelControls.edit":"Edit","chat.modelControls.bash":"Bash","chat.modelControls.webFetch":"WebFetch","chat.modelControls.customPrompt":"Custom Prompt","chat.modelControls.selectModel":"Select model","chat.modelControls.thinking":"Thinking","chat.modelControls.inheritedVariantTooltip":"Thinking: {variant}, this model's default","chat.modelControls.rememberedVariantTooltip":"Thinking: {variant}, last used with this model","chat.modelControls.default":"Default","chat.modelControls.selectAgent":"Select agent","chat.modelControls.costPerMillion":"Cost ($/1M tokens)","chat.modelControls.metadataUnavailable":"Model metadata unavailable.","chat.modelControls.addNewProvider":"Add new provider","chat.modelControls.noAgentSelected":"No agent selected.","chat.modelControls.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent.`,"chat.modelControls.searchModels":"Search models","chat.modelControls.modelListAria":"Models","chat.modelControls.searchAgents":"Search agents","chat.modelControls.noModelsFound":"No models found","chat.modelControls.favorites":"Favorites","chat.modelControls.agentsSection":"Agents","chat.modelControls.favoriteAgentsCycleHint":"{shortcut} to cycle","chat.modelControls.favoriteAgentsTapHint":"Tap the agent to cycle","chat.modelControls.noAgentsFound":"No agents found","chat.modelControls.recent":"Recent","chat.modelControls.addToFavorites":"Add to favorites","chat.modelControls.removeFromFavorites":"Remove from favorites","chat.modelControls.useModel":"Use model","chat.modelControls.favoriteAria":"Favorite","chat.modelControls.unfavoriteAria":"Unfavorite","chat.modelControls.collapseProvider":"Collapse provider","chat.modelControls.expandProvider":"Expand provider","chat.modelControls.keyboardHint":"↑↓ navigate{thinking} • Enter select • Esc close","chat.modelControls.keyboardHintNavigate":"↑↓ navigate","chat.modelControls.keyboardHintSwitchAgent":"{shortcut} switch agent","chat.modelControls.keyboardHintSwitchThinking":"{shortcut} switch","chat.modelControls.keyboardHintThinking":"←→ thinking","chat.modelControls.reorderProviderTitle":"Drag to reorder provider","chat.modelControls.permissionLabel.custom":"Custom","chat.modelControls.permissionLabel.allow":"Allow","chat.modelControls.permissionLabel.deny":"Deny","chat.modelControls.permissionLabel.ask":"Ask","chat.modelControls.modeValue.primary":"Primary","chat.modelControls.modeValue.subagent":"Subagent","chat.modelControls.modeValue.all":"All","chat.modelControls.modeValue.none":"—","chat.reasoningTrace.thinking":"Thinking","chat.reasoningTrace.expandAria":"Expand reasoning trace","chat.reasoningTrace.collapseAria":"Collapse reasoning trace","chat.reasoningTrace.thought":"Thought","chat.messageBody.subtask.title":"Delegated task","chat.messageBody.subtask.hidePrompt":"Hide prompt","chat.messageBody.subtask.showPrompt":"Show prompt","chat.messageBody.subtask.openSession":"Open subtask session","chat.messageBody.shellCommand.copied":"Copied","chat.messageBody.shellCommand.copyOutput":"Copy output","commandPalette.title":"Command Palette","commandPalette.description":"Search files, sessions, and commands.","commandPalette.input.placeholder":"Search files, sessions, commands...","commandPalette.empty.noResults":"No results found.","commandPalette.empty.searchingFiles":"Searching files...","commandPalette.item.newSession":"New Session","commandPalette.item.newMiniChat":"New Mini Chat Window","commandPalette.item.quickWorktree":"Quick Worktree","commandPalette.item.newWorktreeDialog":"New Worktree…","commandPalette.item.addProject":"Add Project","commandPalette.item.showSessionSwitcher":"Show Session Switcher","commandPalette.item.toggleSidebar":"Toggle Sidebar","commandPalette.item.showContextUsage":"Show Context Usage","commandPalette.item.toggleTerminal":"Toggle Terminal","commandPalette.item.cycleTheme":"Cycle theme","commandPalette.item.showOpenCodeStatus":"Show diagnostic timeline","commandPalette.item.restartOpenCode":"Restart OpenCode","commandPalette.item.toggleMemoryDebug":"Toggle memory debug panel","commandPalette.item.pinSession":"Pin or unpin session","commandPalette.item.copySessionId":"Copy session ID","commandPalette.item.openMultiRun":"Run in parallel","commandPalette.item.openArchive":"Open archived sessions","commandPalette.item.openNotes":"Open notes surface","commandPalette.item.openTodos":"Open todos surface","commandPalette.item.openSettings":"Open Settings...","commandPalette.session.untitled":"Untitled Session","commandPalette.item.reloadUi":"Reload UI","commandPalette.group.openFiles":"Open files","commandPalette.group.commands":"Commands","commandPalette.group.settings":"Settings","chat.search.placeholder":"Search this conversation","chat.search.position":"{current} of {total}","chat.search.noResults":"No results","chat.search.searching":"Searching…","chat.search.tooShort":"3+ characters","chat.search.error":"Couldn't search","chat.search.unavailable":"Not available here","chat.search.previous":"Previous match","chat.search.next":"Next match","chat.search.close":"Close search","commandPalette.group.sessions":"Sessions","commandPalette.group.messages":"Messages","commandPalette.messages.showAll":"Show all message results","commandPalette.messages.placeholder":"Search messages…","commandPalette.messages.back":"Back","commandPalette.messages.filter.scopeLabel":"Where","commandPalette.messages.filter.allProjects":"All projects","commandPalette.messages.filter.thisProject":"This project","commandPalette.messages.filter.authorLabel":"Written by","commandPalette.messages.filter.anyone":"Anyone","commandPalette.messages.filter.you":"You","commandPalette.messages.filter.agent":"Agent","commandPalette.messages.filter.reasoning":"Thinking","commandPalette.messages.inReasoning":"Thinking","commandPalette.messages.tooShort":"Type at least 3 characters to search messages","commandPalette.messages.searching":"Searching messages…","commandPalette.messages.error":"Couldn't search messages","commandPalette.messages.unavailable":"Message search is not available on this server","commandPalette.messages.empty":"No messages found","commandPalette.messages.indexing":"Still indexing older conversations: {done} of {total}.","commandPalette.messages.loadMore":"Load more","commandPalette.messages.byYou":"Your message","commandPalette.messages.byAgent":"Agent reply","commandPalette.group.files":"Files","commandPalette.group.projects":"Projects","commandPalette.footer.navigate":"to navigate","commandPalette.footer.open":"to open","commandPalette.footer.close":"to close","openCodeStatusDialog.title":"Diagnostic timeline","openCodeStatusDialog.description":"Local events in time order. Private log text and remote sources are excluded.","openCodeStatusDialog.actions.download":"Download log","openCodeStatusDialog.toast.collectFailed":"Failed to collect diagnostics","openCodeStatusDialog.actions.copy":"Copy","openCodeStatusDialog.empty.noData":"No data.","openCodeStatusDialog.toast.copiedTitle":"Copied","openCodeStatusDialog.toast.copiedDescription":"Diagnostic log copied to clipboard","openCodeStatusDialog.toast.copyFailed":"Failed to copy diagnostic log","saveProjectPlanDialog.title":"Save Project Plan","saveProjectPlanDialog.description":"Save this plan into your project as a Markdown file.","saveProjectPlanDialog.field.title":"Title","saveProjectPlanDialog.field.titlePlaceholder":"Plan title","saveProjectPlanDialog.field.contentPreview":"Content preview","saveProjectPlanDialog.actions.cancel":"Cancel","saveProjectPlanDialog.actions.save":"Save","saveProjectPlanDialog.actions.saving":"Saving...","branchPickerDialog.title":"Branch Picker","branchPickerDialog.description.localBranchesForProject":"Local branches for {project}","branchPickerDialog.description.selectProject":"Select a project to view branches","branchPickerDialog.search.placeholder":"Search branches...","branchPickerDialog.search.renameBranchPlaceholder":"Rename branch","branchPickerDialog.state.noProjectSelected":"No project selected","branchPickerDialog.state.loadingBranches":"Loading branches...","branchPickerDialog.state.noMatchingBranches":"No matching branches","branchPickerDialog.state.noBranchesFound":"No branches found","branchPickerDialog.badge.head":"HEAD","branchPickerDialog.badge.worktree":"worktree","branchPickerDialog.actions.createWorktreeAria":"Create worktree from branch","branchPickerDialog.actions.renameAria":"Rename branch","branchPickerDialog.actions.deleteAria":"Delete branch","branchPickerDialog.actions.deleteWorktreeAria":"Remove worktree","branchPickerDialog.actions.confirmRenameAria":"Confirm rename","branchPickerDialog.actions.cancelRenameAria":"Cancel rename","branchPickerDialog.actions.confirmDeleteAria":"Confirm delete branch","branchPickerDialog.actions.cancelDeleteAria":"Cancel delete branch","branchPickerDialog.actions.deletePrompt":"Delete","branchPickerDialog.actions.forceDeletePrompt":"Force Delete","branchPickerDialog.tooltip.createWorktree":"Create worktree","branchPickerDialog.tooltip.worktreeAlreadyExists":"Worktree already exists","branchPickerDialog.tooltip.rename":"Rename branch","branchPickerDialog.tooltip.renameDisabledForRoot":"Cannot rename root branch","branchPickerDialog.tooltip.delete":"Delete branch","branchPickerDialog.tooltip.deleteCurrentBranch":"Cannot delete current branch","branchPickerDialog.tooltip.deleteDisabledForRoot":"Cannot delete root branch","branchPickerDialog.tooltip.deleteWorktree":"Remove worktree","branchPickerDialog.tooltip.deleteWorktreeRootProtected":"Cannot remove root worktree","branchPickerDialog.toast.branchRenamed":"Branch renamed","branchPickerDialog.toast.failedToRenameBranch":"Failed to rename branch","branchPickerDialog.toast.branchDeleted":"Branch deleted","branchPickerDialog.toast.branchNotMerged":"Branch is not fully merged","branchPickerDialog.toast.confirmAgainToForceDelete":"Confirm again to force delete","branchPickerDialog.toast.failedToDeleteBranch":"Failed to delete branch","branchPickerDialog.toast.worktreeCreated":"Worktree created","branchPickerDialog.toast.failedToCreateWorktree":"Failed to create worktree","branchPickerDialog.error.failedToLoad":"Failed to load branches","branchPickerDialog.error.renameRejected":"Rename was rejected","branchPickerDialog.error.renameFailed":"Failed to rename branch","branchPickerDialog.error.deleteRejected":"Delete was rejected","branchPickerDialog.error.deleteFailed":"Failed to delete branch","branchPickerDialog.error.createWorktreeFailed":"Failed to create worktree","projectEditDialog.title":"Edit project","projectEditDialog.field.name":"Name","projectEditDialog.field.namePlaceholder":"Project name","projectEditDialog.field.color":"Color","projectEditDialog.field.icon":"Icon","projectEditDialog.field.preview":"Preview","projectEditDialog.field.iconBackground":"Icon Background","projectEditDialog.field.iconBackgroundAria":"Project icon background color","projectEditDialog.option.none":"None","projectEditDialog.actions.uploadIcon":"Upload Icon","projectEditDialog.actions.uploading":"Uploading...","projectEditDialog.actions.discoverFavicon":"Discover Favicon","projectEditDialog.actions.discovering":"Discovering...","projectEditDialog.actions.removeProjectIcon":"Remove Project Icon","projectEditDialog.actions.removing":"Removing...","projectEditDialog.actions.undoRemove":"Undo Remove","projectEditDialog.actions.clear":"Clear","projectEditDialog.actions.cancel":"Cancel","projectEditDialog.actions.save":"Save","projectEditDialog.toast.failedToUploadIcon":"Failed to upload project icon","projectEditDialog.toast.iconUpdated":"Project icon updated","projectEditDialog.toast.failedToRemoveIcon":"Failed to remove project icon","projectEditDialog.toast.iconRemoved":"Project icon removed","projectEditDialog.toast.failedToDiscoverIcon":"Failed to discover project icon","projectEditDialog.toast.customIconAlreadySet":"Custom icon already set for this project","projectEditDialog.toast.iconDiscovered":"Project icon discovered","openInApp.actions.open":"Open","openInApp.actions.openInAria":"Open in {app}","openInApp.actions.copyPath":"Copy Path","openInApp.actions.refreshApps":"Refresh Apps","openInApp.toast.pathCopied":"Path copied to clipboard","projectActions.actions.addActionAria":"Add action","projectActions.actions.addAction":"Add action","projectActions.actions.addNewAction":"Add new action","projectActions.actions.autoDiscover":"Auto-discover dev server","projectActions.menu.sharedBadge":"repo","projects.sharedTrust.title":"Run the commands stored in this repository?","projects.sharedTrust.description":"{path} in this repository defines commands that run on this machine. Trust them once, and OpenChamber asks again only when they change.","projects.sharedTrust.setupCommands":"Worktree setup commands","projects.sharedTrust.actions":"Actions","projects.sharedTrust.skip":"Not this time","projects.sharedTrust.trust":"Trust and run","projects.opencodeTrust.title":"Let OpenCode run code from this folder?","projects.opencodeTrust.description":"OpenCode runs the plugins and commands in the configuration of {path} as soon as it opens the folder. Trust them once, and OpenChamber asks again only when they change.","projects.opencodeTrust.plugins":"Plugins","projects.opencodeTrust.commands":"Commands","projects.opencodeTrust.kind.package":"{name} (npm package)","projects.opencodeTrust.kind.config":"{path}: a configuration file OpenChamber can't read","projects.opencodeTrust.kind.mcp":"MCP server {name}","projects.opencodeTrust.kind.lsp":"Language server {name}","projects.opencodeTrust.kind.formatter":"Formatter {name}","projects.opencodeTrust.kind.shell":"Shell","projects.opencodeTrust.paused":"Without trust, agents can't work in this folder, but you can still browse its files and Git changes.","projects.opencodeTrust.skip":"Not this time","projects.opencodeTrust.trust":"Trust and open","projects.opencodeTrust.saveFailed":"Couldn't save your answer. Try again.","projectActions.actions.autoDiscoverTooltip":"Automatically discover and run the development server","projectActions.actions.chooseActionAria":"Choose project action","projectActions.actions.openPreview":"Open Preview","projectActions.actions.runNamedAria":"Run {name}","projectActions.actions.stopNamedAria":"Stop {name}","projectActions.label.fallbackAction":"Action","projectActions.toast.openedUrlFromOutput":"Opened URL from action output","projectActions.toast.openedForwardedUrl":"Opened forwarded URL","projectActions.toast.openedActionUrl":"Opened action URL","projectActions.error.noActiveDirectory":"No active directory","projectActions.error.noActiveDirectoryForAction":"No active directory for action","projectActions.error.failedToCreateTerminalSession":"Failed to create terminal session","projectActions.error.invalidCustomUrlFormat":"Invalid custom URL format","projectActions.error.openUrlTemplateUnresolved":"Couldn't read the branch for the action URL","projectActions.error.selectedDesktopSshForwardUnavailable":"Selected desktop SSH forward is unavailable","projectActions.error.failedToRunAction":"Failed to run action","mcpDropdown.title":"MCP Servers","mcpDropdown.actions.refreshAria":"Refresh","mcpDropdown.actions.openAria":"MCP servers","mcpDropdown.statusAria":"MCP status","mcpDropdown.status.unknown":"Unknown","mcpDropdown.status.connected":"Connected","mcpDropdown.status.failed":"Failed: {error}","mcpDropdown.status.unknownError":"Unknown error","mcpDropdown.status.needsAuth":"Needs authentication","mcpDropdown.status.needsRegistration":"Needs registration: {error}","mcpDropdown.empty.configureInConfig":"Configure MCP servers in Settings.","sessionAuth.error.rateLimitTitle":"Too many attempts","sessionAuth.error.networkTitle":"Unable to reach server","sessionAuth.error.rateLimitDescriptionSingle":"Please wait {minutes} minute before trying again.","sessionAuth.error.rateLimitDescriptionPlural":"Please wait {minutes} minutes before trying again.","sessionAuth.error.networkDescription":"We could not verify the UI session. If you're opening OpenChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings.","sessionAuth.error.retry":"Retry","sessionAuth.error.passkeySetupFailed":"Passkey setup failed.","sessionAuth.error.incorrectPassword":"Incorrect password. Try again.","sessionAuth.error.unexpectedResponse":"Unexpected response from server.","sessionAuth.error.networkRetry":"Network error. Check connection and retry.","sessionAuth.error.passkeySignInCanceled":"Passkey sign-in was canceled.","sessionAuth.error.enterPasswordForPasskey":"Enter your password to add a passkey.","sessionAuth.locked.tunnelTitle":"Tunnel access required","sessionAuth.expired.banner":"Your session expired — log in to continue.","sessionAuth.expired.loginAction":"Log in","sessionAuth.expired.sendBlocked":"Session expired — log in to send messages.","sessionAuth.locked.unlockTitle":"Unlock OpenChamber","sessionAuth.locked.tunnelDescription":"Open this tunnel using the one-time connect link from the desktop app.","sessionAuth.locked.passwordDescription":"This session is password-protected.","sessionAuth.locked.hostSwitcherHint":"Use Local if remote is unreachable.","sessionAuth.actions.cancelPasskey":"Cancel passkey","sessionAuth.actions.usePasskey":"Use passkey","sessionAuth.actions.unlockingAria":"Unlocking","sessionAuth.actions.unlockAria":"Unlock","sessionAuth.actions.trustDevice":"Trust this device","sessionAuth.actions.trustDeviceAria":"Trust this device","sessionAuth.actions.cancelPasskeySetup":"Cancel passkey setup","sessionAuth.actions.addPasskey":"Add passkey","sessionAuth.password.placeholder":"Enter password","sessionAuth.toast.passkeyAdded":"Passkey added","sessionAuth.toast.passkeySetupCanceled":"Passkey setup canceled","desktopHostSwitcher.title":"Instance","desktopHostSwitcher.description":"Switch between Local and remote OpenChamber servers","desktopHostSwitcher.header.current":"Current","desktopHostSwitcher.header.default":"Default","desktopHostSwitcher.header.currentColon":"Current:","desktopHostSwitcher.header.currentDefaultColon":"Current default:","desktopHostSwitcher.status.connected":"Connected","desktopHostSwitcher.status.authRequired":"Auth required","desktopHostSwitcher.status.checking":"Checking","desktopHostSwitcher.status.updateRecommended":"Update recommended","desktopHostSwitcher.status.incompatible":"Incompatible","desktopHostSwitcher.status.wrongService":"Wrong service","desktopHostSwitcher.status.unreachable":"Unreachable","desktopHostSwitcher.status.relayLimit":"Relay limit reached","desktopHostSwitcher.status.unknown":"Unknown","desktopHostSwitcher.status.ping":" · {ms}ms ping","desktopHostSwitcher.statusAria":"Instance status","desktopHostSwitcher.sshPhase.ready":"Ready","desktopHostSwitcher.sshPhase.error":"Error","desktopHostSwitcher.sshPhase.reconnecting":"Reconnecting","desktopHostSwitcher.sshPhase.resolvingConfig":"Resolving config","desktopHostSwitcher.sshPhase.checkingAuth":"Checking auth","desktopHostSwitcher.sshPhase.connectingSsh":"Connecting SSH","desktopHostSwitcher.sshPhase.probingRemote":"Probing remote","desktopHostSwitcher.sshPhase.installing":"Installing","desktopHostSwitcher.sshPhase.updating":"Updating","desktopHostSwitcher.sshPhase.detectingServer":"Detecting server","desktopHostSwitcher.sshPhase.startingServer":"Starting server","desktopHostSwitcher.sshPhase.forwardingPorts":"Forwarding ports","desktopHostSwitcher.sshPhase.idle":"Idle","desktopHostSwitcher.ssh.needInstancesHint":"Need SSH instances? Manage them in Settings.","desktopHostSwitcher.ssh.instanceFallback":"SSH instance","desktopHostSwitcher.ssh.connectingTo":"Connecting to {host}","desktopHostSwitcher.actions.refresh":"Refresh","desktopHostSwitcher.actions.refreshInstancesAria":"Refresh instances","desktopHostSwitcher.actions.remoteSsh":"Remote SSH","desktopHostSwitcher.actions.instanceActionsAria":"Instance actions","desktopHostSwitcher.actions.edit":"Edit","desktopHostSwitcher.actions.delete":"Delete","desktopHostSwitcher.actions.connect":"Connect","desktopHostSwitcher.actions.defaultInstanceAria":"Default instance","desktopHostSwitcher.actions.setAsDefaultAria":"Set as default","desktopHostSwitcher.actions.setAsDefault":"Set as default","desktopHostSwitcher.actions.openInNewWindowAria":"Open in new window","desktopHostSwitcher.actions.openInNewWindow":"Open in new window","desktopHostSwitcher.actions.addInstance":"Add instance","desktopHostSwitcher.actions.cancel":"Cancel","desktopHostSwitcher.actions.save":"Save","desktopHostSwitcher.actions.add":"Add","desktopHostSwitcher.actions.switchToLocal":"Switch to Local","desktopHostSwitcher.actions.retry":"Retry","desktopHostSwitcher.actions.switchInstanceAria":"Switch instance","desktopHostSwitcher.actions.switchInstance":"Switch instance","desktopHostSwitcher.actions.switchToAria":"Switch to {instance}","desktopHostSwitcher.field.labelPlaceholder":"Label","desktopHostSwitcher.field.labelOptionalPlaceholder":"Label (optional)","desktopHostSwitcher.field.urlPlaceholder":"https://host:port","desktopHostSwitcher.state.limitedOnPage":"Instance switcher is limited on this page. Use Local to recover.","desktopHostSwitcher.state.loading":"Loading...","desktopHostSwitcher.state.instanceUnreachable":"Instance unreachable","desktopHostSwitcher.edit.title":"Edit instance","desktopHostSwitcher.add.title":"Add instance","desktopHostSwitcher.error.failedToSave":"Failed to save","desktopHostSwitcher.error.failedToLoad":"Failed to load","desktopHostSwitcher.error.invalidUrl":"Invalid URL (must be http/https)","desktopHostSwitcher.error.pairingRejected":"Pairing link is invalid or expired. Generate a new one.","desktopHostSwitcher.error.pairingFailed":"Pairing failed (HTTP {status}).","desktopHostSwitcher.error.pairingInvalidResponse":"The server returned an invalid pairing response.","desktopHostSwitcher.error.failedToOpenNewWindow":"Failed to open new window","desktopHostSwitcher.instance.local":"Local","desktopHostSwitcher.instance.fallback":"Instance","desktopHostSwitcher.startup.title":"Default SSH instance unavailable","desktopHostSwitcher.startup.connectingTo":"Connecting to {host}...","desktopHostSwitcher.startup.failed":"Failed to connect the default SSH instance.","desktopHostSwitcher.toast.sshConnected":'SSH instance "{host}" connected',"desktopHostSwitcher.toast.sshFailedToConnect":'SSH instance "{host}" failed to connect',"desktopHostSwitcher.toast.instanceUnreachable":'Instance "{host}" is unreachable',"desktopHostSwitcher.toast.relayLimit":'The relay refused the connection to "{host}": too many devices or reconnects. Close OpenChamber on another device or wait a minute, then try again.',"relayConnection.limitReached.title":"The relay refused the connection","relayConnection.limitReached.description":"Too many devices or reconnects for this instance. Close OpenChamber on another device or wait a minute, then try again.","relayConnection.limitReached.retry":"Try again","miniChat.header.newSession":"New session","miniChat.header.session":"Session","miniChat.header.defaultAgent":"Default agent","miniChat.header.noModel":"No model","miniChat.status.busy":"Running","miniChat.status.retry":"Retrying","miniChat.status.idle":"Idle","miniChat.actions.pin":"Pin above other windows","miniChat.actions.unpin":"Unpin window","miniChat.actions.pinAria":"Pin Mini Chat window","miniChat.actions.unpinAria":"Unpin Mini Chat window","miniChat.actions.openMain":"Open in main window","miniChat.actions.openMainAria":"Open session in main window","miniChat.unavailable.title":"Session unavailable","miniChat.unavailable.description":"This session could not be loaded. It may have been deleted, archived, or opened from a different project context.","sessions.sidebar.session.menu.openMiniChatWindow":"Open in Mini Chat Window","header.windowControls.groupAria":"Window controls","header.windowControls.minimize":"Minimize window","header.windowControls.maximize":"Maximize window","header.windowControls.restore":"Restore window","header.windowControls.close":"Close window","errorBoundary.title":"Something went wrong","errorBoundary.description":"The application encountered an unexpected error. This has been logged for debugging.","errorBoundary.state.unknownError":"Unknown error","errorBoundary.state.componentStackLabel":"Component stack:","errorBoundary.actions.errorDetails":"Error details","errorBoundary.actions.tryAgain":"Try again","errorBoundary.actions.copy":"Copy","errorBoundary.actions.copied":"Copied","jsonTreeView.error.emptyJson":"Empty JSON content","jsonTreeView.error.invalidJson":"Invalid JSON","jsonTreeView.error.invalidJsonTitle":"Invalid JSON","jsonTreeView.actions.expandAll":"Expand All","jsonTreeView.actions.collapseAll":"Collapse All","numberInput.actions.decreaseAria":"Decrease value","numberInput.actions.increaseAria":"Increase value","goToLineDialog.field.linePlaceholderShort":"Line","goToLineDialog.field.linePlaceholder":"Line number","goToLineDialog.actions.go":"Go","goToLineDialog.helper.editorUnavailable":"Editor unavailable.","goToLineDialog.helper.currentLineRange":"Current Line: {current}. Type a line number between 1 and {max} to navigate to.","goToLineDialog.helper.goToLine":"Go to line {line}","dialog.common.actions.close":"Close","session.newWorktree.trust.run":"Run","session.newWorktree.trust.skip":"Skip","session.newWorktree.trust.title":"Run setup on code from a fork?","gitView.publish.contributorCommitFirstAction":"Continue","gitView.publish.contributorCommitFirstTitle":"Commit, then choose where to push?","dialog.common.actions.cancel":"Cancel","filesView.toast.relativePathCopied":"Relative path copied","filesView.tree.menu.copyRelativePath":"Copy Relative Path","multiRun.branchSelector.placeholder.selectSourceBranch":"Select source branch...","multiRun.branchSelector.status.loadingBranches":"Loading branches...","multiRun.branchSelector.status.noBranchesFound":"No branches found","multiRun.branchSelector.status.notInGitRepository":"Not in a git repository.","multiRun.branchSelector.groups.localBranches":"Local branches","multiRun.branchSelector.groups.remoteBranches":"Remote branches","multiRun.window.actions.closeAria":"Close multi-run","multiRun.window.description":"OpenChamber Multi-Run window.","voice.status.idle":"Voice Ready","voice.status.listening":"Listening...","voice.status.processing":"Processing...","voice.status.speaking":"Speaking...","voice.status.error":"Voice Error","voice.status.conversationModeActiveAria":"Conversation mode active","voice.action.finishAndTranscribe":"Finish and transcribe voice input","onboarding.common.actions.back":"Back","onboarding.common.copyToClipboard":"Copy to clipboard","onboarding.common.status.copiedToClipboard":"Copied to clipboard","onboarding.chooser.title":"Welcome to OpenChamber","onboarding.chooser.description":"Choose how you want to connect to get started.","onboarding.chooser.tabs.localInstall":"Local Install","onboarding.chooser.tabs.connectRemote":"Connect Remote","onboarding.localSetup.title":"Setting Up OpenCode","onboarding.localSetup.description":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.dialog.selectOpencodeBinary":"Select opencode binary","onboarding.localSetup.errors.cliNotReady":"OpenCode CLI is not ready yet. Please confirm installation is complete and try again.","onboarding.localSetup.errors.detectionFailed":"Detection failed","onboarding.localSetup.windows.title":"Windows setup","onboarding.localSetup.windows.stepInstallWsl":"Install OpenCode with the command below.","onboarding.localSetup.windows.stepInstallWslSuffix":"","onboarding.localSetup.windows.stepRunInstallInWsl":"Run the install command below in a Windows terminal.","onboarding.localSetup.windows.stepSetBinaryPath":"If OpenChamber does not detect OpenCode automatically, set the binary path below.","onboarding.localSetup.intro":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.docs.windows":"Installation guide","onboarding.localSetup.docs.default":"Installation guide","onboarding.localSetup.actions.checking":"Checking…","onboarding.localSetup.actions.checkAndContinue":"I've completed installation, check and continue","onboarding.localSetup.actions.checkNow":"Check now","onboarding.localSetup.helper.checkAndContinue":"Click to check if OpenCode CLI is available. If successful, you'll automatically enter the main screen.","onboarding.localSetup.status.watching":"Waiting for OpenCode v2","onboarding.localSetup.status.autoContinue":"We'll continue automatically once it's detected.","onboarding.localSetup.field.alreadyInstalled":"Already installed? Set the OpenCode CLI path:","onboarding.localSetup.advanced.title":"Set a custom binary path","onboarding.localSetup.troubleshoot.title":"Having trouble?","onboarding.localSetup.actions.browse":"Browse","onboarding.localSetup.actions.apply":"Apply","onboarding.localSetup.helper.saveAndReload":"Saves to OpenChamber settings and reloads OpenCode configuration.","onboarding.localSetup.helper.pinnedByAdministrator":"Your administrator set this path. If OpenCode isn’t there, ask them to install it.","onboarding.localSetup.remotePreference":"Prefer to use a remote server?","onboarding.localSetup.actions.connectRemoteServer":"Connect to Remote Server →","onboarding.localSetup.windows.hintInstallInWsl":"On Windows, install and run OpenCode natively.","onboarding.localSetup.windows.hintDetectionFailed":"If detection fails, set a native path such as opencode.cmd or opencode.exe.","onboarding.localSetup.hint.ensurePath":"Already installed? Make sure opencode is in your PATH.","onboarding.localSetup.hint.setEnv":"Or set OPENCODE_BINARY environment variable.","onboarding.localSetup.hint.missingRuntime":'If you see "env: node: No such file or directory" or "env: bun: No such file or directory", install that runtime or ensure it is on PATH.',"onboarding.remoteConnection.title":"Connect to Remote Server","onboarding.remoteConnection.titleRecovery":"Connect to a Different Server","onboarding.remoteConnection.description":"Enter the address of an OpenChamber server to connect to.","onboarding.remoteConnection.field.serverAddress":"Server Address","onboarding.remoteConnection.field.serverAddressPlaceholder":"https://your-server.example.com:4096","onboarding.remoteConnection.field.nameOptional":"Name (optional)","onboarding.remoteConnection.field.namePlaceholder":"My Remote Server","onboarding.remoteConnection.errors.connectionTestFailed":"Connection test failed","onboarding.remoteConnection.errors.failedToSaveConnection":"Failed to save connection","onboarding.remoteConnection.status.connectedSuccessfully":"Connected successfully ({latencyMs}ms)","onboarding.remoteConnection.status.authWarning":"Server requires authentication. You can still connect.","onboarding.remoteConnection.status.connectionFailed":"Connection Failed","onboarding.remoteConnection.status.suggestionsUnreachable":"Suggestions: Check the server address, verify the server is running, or check your network connection.","onboarding.remoteConnection.status.suggestionsWrongService":"Suggestions: Verify the URL points to an OpenChamber server, or contact the server administrator.","onboarding.remoteConnection.actions.testing":"Testing…","onboarding.remoteConnection.actions.testConnection":"Test Connection","onboarding.remoteConnection.actions.connectAndRestart":"Connect & Restart","onboarding.remoteConnection.actions.whatToDo":"What would you like to do?","onboarding.remoteConnection.actions.chooseDifferentServer":"Choose Different Server","onboarding.remoteConnection.actions.useLocalInstead":"Use Local Instead","onboarding.remoteConnection.probe.authMessage":"Server requires authentication. You can still connect, but may need to provide credentials.","onboarding.remoteConnection.probe.updateRecommendedMessage":"This instance is running a different OpenChamber version. You can connect, but update both apps if something does not work.","onboarding.remoteConnection.probe.incompatibleMessage":"Server is running OpenChamber but is not compatible with this app version. Update OpenChamber on the server, then try again.","onboarding.remoteConnection.probe.wrongServiceMessage":"Server responded but is not running OpenChamber. Verify the address points to an OpenChamber server.","onboarding.remoteConnection.probe.unreachableMessage":"Server is unreachable. Check your network connection and verify the server address.","onboarding.desktopRecovery.localUnavailable.title":"Local OpenCode Unavailable","onboarding.desktopRecovery.localUnavailable.description":"OpenCode CLI could not be started or is not installed. Install OpenCode or connect to a remote server instead.","onboarding.desktopRecovery.localUnavailable.retry":"Retry Local","onboarding.desktopRecovery.localUnavailable.useLocal":"Set Up Local","onboarding.desktopRecovery.noDefaultConnection.title":"No Default Connection","onboarding.desktopRecovery.noDefaultConnection.description":"Your saved default connection could not be found. Choose how you want to connect.","onboarding.desktopRecovery.remoteUnreachable.title":"Remote Server Unreachable","onboarding.desktopRecovery.remoteUnreachable.description":'Could not connect to "{host}". Check your network connection and verify the server address.',"onboarding.desktopRecovery.remoteUnreachable.retry":"Retry Connection","onboarding.desktopRecovery.incompatibleServer.title":"Incompatible Server","onboarding.desktopRecovery.incompatibleServer.description":'The server at "{host}" is not running OpenChamber. Verify the address points to an OpenChamber server.',"onboarding.desktopRecovery.remoteIncompatible.title":"Server Update Required","onboarding.desktopRecovery.remoteIncompatible.description":'The OpenChamber server at "{host}" is not compatible with this app version. Update OpenChamber on the server, then try again.',"onboarding.desktopRecovery.remoteIncompatible.updateServer":"Update server","onboarding.desktopRecovery.remoteIncompatible.updatingServer":"Updating the server...","onboarding.desktopRecovery.remoteIncompatible.updatingHint":"The server installs the update and restarts. The app connects as soon as it is back.","onboarding.desktopRecovery.remoteIncompatible.updateRefused":"The server could not update itself.","onboarding.desktopRecovery.remoteIncompatible.updateAuth":"The server did not accept this app's sign-in, so it could not be updated from here.","onboarding.desktopRecovery.remoteIncompatible.updateTimeout":"The server has not come back with the new version yet. Check it, then retry the connection.","onboarding.desktopRecovery.remoteIncompatible.manualUpdate":"To update it by hand, run this on the server, then restart OpenChamber there:","onboarding.desktopRecovery.common.useLocal":"Use Local","onboarding.desktopRecovery.common.useRemote":"Use Remote","onboarding.desktopRecovery.actions.retrying":"Retrying…","onboarding.desktopRecovery.actions.retryConnection":"Retry Connection","projectConfigError.toast.title":"OpenCode can't load this project's config","projectConfigError.toast.unknownFile":"Project config","projectConfigError.toast.hint":"Fix the file, then retry. Other projects keep working.","projectConfigError.toast.retry":"Retry","projectConfigError.toast.retrying":"Retrying…","startup.initRecovery.title":"Startup failed","startup.serverOutdated.title":"Server update required","startup.serverOutdated.description":"The server runs OpenChamber {version}, and this app needs 2.0 or later there. Update OpenChamber on the server to continue.","startup.serverOutdated.checking":"Checking the server...","startup.serverOutdated.noUpdate":"The server did not offer an update it can install itself.","startup.initRecovery.openCodeUnavailable":"OpenChamber is reachable, but OpenCode is not ready. Check OpenCode on the server, then retry.","startup.initRecovery.binary":"OpenCode executable","startup.initRecovery.error":"OpenCode error","startup.initRecovery.serverUnreachable":"OpenChamber could not reach its server. Check that the server is running, then retry.","startup.initRecovery.loadAgentsFailed":"The server is running, but OpenCode could not load agents. Retry once the cause is fixed.","startup.initRecovery.unexpected":"OpenChamber could not finish starting. Retry once the cause is fixed.","startup.initRecovery.lastError":"Last error","startup.initRecovery.retry":"Retry","startup.initRecovery.retrying":"Retrying…","startup.overlay.slow":"Startup is taking longer than expected…","onboarding.desktopRecovery.placeholders.remoteServer":"the remote server","onboarding.desktopRecovery.placeholders.unknownServer":"unknown","vscodeLayout.title.chat":"Chat","vscodeLayout.title.newSession":"New session","vscodeLayout.title.sessions":"Sessions","vscodeLayout.title.sessionFallback":"Session","vscodeLayout.actions.backToSessionsAria":"Back to sessions","vscodeLayout.actions.archiveAllAria":"Archive all sessions","vscodeLayout.actions.archiveAllConfirm":"Archive all","vscodeLayout.actions.archiveAllSuccess":"Archived {count} session(s)","vscodeLayout.actions.archiveAllError":"Failed to archive {count} session(s)","vscodeLayout.actions.cancel":"Cancel","vscodeLayout.actions.newSessionAria":"New session","vscodeLayout.actions.resizeSessionsSidebarAria":"Resize sessions sidebar","vscodeLayout.actions.settingsAria":"Settings","vscodeLayout.quota.title":"Rate limits","vscodeLayout.quota.mode.used":"Used","vscodeLayout.quota.mode.remaining":"Remaining","vscodeLayout.quota.lastUpdated":"Last updated {time}","vscodeLayout.quota.noRateLimitsAvailable":"No rate limits available.","vscodeLayout.quota.noRateLimitsReported":"No rate limits reported.","vscodeLayout.quota.actions.rateLimitsAria":"Rate limits","vscodeLayout.quota.actions.showUsedAria":"Show used quota","vscodeLayout.quota.actions.showRemainingAria":"Show remaining quota","vscodeLayout.quota.actions.refreshAria":"Refresh rate limits","updateDialog.header.updateAvailable":"Update Available","updateDialog.header.updating":"Updating OpenChamber...","updateDialog.changelog.title":"What's new","updateDialog.status.installingUpdate":"Installing update...","updateDialog.status.serverRestarting":"Server restarting...","updateDialog.status.waitingForServer":"Waiting for server...","updateDialog.status.autoReloadHint":"The page will reload automatically when the update is complete.","updateDialog.fallback.updateViaTerminal":"Or update via terminal:","updateDialog.desktopHostInstall":"OpenChamber {version} is available. Update it on the computer it runs on.","updateDialog.actions.copyCommand":"Copy command","updateDialog.actions.copied":"Copied!","updateDialog.status.downloadingPayload":"Downloading update payload...","updateDialog.actions.downloadUpdate":"Download Update","updateDialog.status.downloading":"Downloading...","updateDialog.actions.restartToUpdate":"Restart to Update","updateDialog.status.restarting":"Restarting...","updateDialog.actions.updateNow":"Update Now","updateDialog.actions.openMobileUpdate":"Open update","updateDialog.status.updating":"Updating...","updateDialog.error.updateFailed":"Update failed","updateDialog.error.takingLonger":"Update is taking longer than expected. Wait a bit and refresh, or run: openchamber update","updateDialog.error.signatureRejected":"The downloaded update was rejected: its code signature does not match this installation. This usually means the running copy was not installed from an official signed release. Install OpenChamber from an official release, then update again.","updateDialog.error.updaterDisabled":"The updater stopped after a failed install. Quit OpenChamber, open it again, and retry the update.","updateDialog.error.restartFailed":"Could not restart to install the update.","updateDialog.error.restartUnavailable":"Installing the update requires the OpenChamber desktop app.","mobileUpdate.toast.available.title":"OpenChamber update available","mobileUpdate.toast.available.description":"Version {version} is ready for Android.","mobileUpdate.toast.actions.download":"Download","opencodeUpdate.toast.available.title":"OpenCode update","opencodeUpdate.toast.available.description":"Version {version} available.","opencodeUpdate.toast.available.manualDescription":"Version {version} available. Update OpenCode the way you installed it, then restart OpenChamber.","opencodeUpdate.toast.actions.update":"Update","opencodeUpdate.toast.actions.reload":"Reload OpenCode","opencodeUpdate.toast.upgrading.title":"Updating OpenCode...","opencodeUpdate.toast.upgrading.description":"Keep OpenChamber open.","opencodeUpdate.toast.updated.title":"OpenCode updated","opencodeUpdate.toast.updated.description":"Update installed.","opencodeUpdate.toast.updated.descriptionWithVersion":"Version {version} installed.","opencodeUpdate.toast.failed.title":"Could not update OpenCode","opencodeUpdate.toast.failed.description":"The OpenCode upgrade failed.","opencodeUpdate.toast.reload.message":"Restarting OpenCode...","memoryDebugPanel.title":"Debug Panel","memoryDebugPanel.tabs.memory":"Memory","memoryDebugPanel.tabs.streaming":"Streaming","memoryDebugPanel.tabs.requests":"Requests","memoryDebugPanel.section.sessionsInMemory":"Sessions in Memory","memoryDebugPanel.section.uiStreamingMetrics":"UI Streaming Metrics","memoryDebugPanel.section.vscodeBridgeMetrics":"VS Code Bridge Metrics","memoryDebugPanel.section.noUiSamples":"No UI streaming samples yet. Start a stream and keep this panel open.","memoryDebugPanel.section.noVscodeSamples":"No VS Code bridge samples yet.","memoryDebugPanel.metric.totalMessages":"Total Messages","memoryDebugPanel.metric.cachedSessions":"Cached Sessions","memoryDebugPanel.metric.userMessages":"User Messages","memoryDebugPanel.metric.assistantMessages":"Assistant Messages","memoryDebugPanel.metric.viewportWindow":"Viewport Window","memoryDebugPanel.metric.zombieTimeout":"Zombie Timeout","memoryDebugPanel.metric.githubTotalRequests":"GitHub Total Requests","memoryDebugPanel.metric.metrics":"Metrics","memoryDebugPanel.metric.samples":"Samples","memoryDebugPanel.metric.lastUpdate":"Last Update","memoryDebugPanel.metric.uiMetrics":"UI Metrics","memoryDebugPanel.metric.vscodeMetrics":"VS Code Metrics","memoryDebugPanel.metric.messageListRenders":"MsgList Renders","memoryDebugPanel.metric.messageListStreamRenders":"MsgList Stream Renders","memoryDebugPanel.metric.chatMessageRenders":"ChatMessage Renders","memoryDebugPanel.metric.chatMessageStreamRenders":"ChatMessage Stream Renders","memoryDebugPanel.metric.chatMessageStaticDuringStream":"ChatMessage Static During Stream","memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn":"ChatMessage Static Outside Active Turn","memoryDebugPanel.metric.messagesValue":"{count} messages","memoryDebugPanel.metric.minutesValue":"{count} minutes","memoryDebugPanel.metric.msgsValue":"{count} msgs","memoryDebugPanel.metric.roleMsgsValue":"U {user} / A {assistant}","memoryDebugPanel.metric.countValue":"count {value}","memoryDebugPanel.metric.avgValue":"avg {value}","memoryDebugPanel.metric.maxValue":"max {value}","memoryDebugPanel.metric.totalValue":"total {value}","memoryDebugPanel.actions.logState":"Log State","memoryDebugPanel.actions.copyJson":"Copy JSON","memoryDebugPanel.tooltip.logCurrentState":"Log current memory state to browser console","memoryDebugPanel.streaming.copy.copied":"Streaming debug JSON copied","memoryDebugPanel.streaming.copy.failed":"Failed to copy JSON","memoryDebugPanel.streaming.copy.hint":"Copy exports both UI and VS Code streaming metrics as JSON","memoryDebugPanel.requests.inFlight":"In flight","memoryDebugPanel.requests.peak":"Peak","memoryDebugPanel.requests.duration":"Duration","memoryDebugPanel.requests.totalRequests":"Total Requests","memoryDebugPanel.requests.tracking":"Tracking","memoryDebugPanel.requests.now":"now","memoryDebugPanel.requests.noSamples":"No requests tracked yet. Keep this panel open to record fetch activity.","memoryDebugPanel.requests.chartLabel":"Fetch requests in flight over time, peak {peak}","memoryDebugPanel.requests.windowHint":"last {seconds}s","memoryDebugPanel.requests.percentileChartLabel":"In-flight request age percentiles (p50, p90, p99, max) over time","memoryDebugPanel.common.idle":"idle","memoryDebugPanel.common.live":"live","memoryDebugPanel.common.notAvailable":"n/a","memoryDebugPanel.common.untitled":"Untitled","directoryTree.field.newDirectoryPlaceholder":"new_directory","textarea.resizeHandleAria":"Resize textarea","sidebar.resize.leftPanelAria":"Resize left panel","sidebar.resize.rightPanelAria":"Resize right panel","mainLayout.mobile.closeDrawerAria":"Close drawer","sortableTabsStrip.aria.tabs":"Tabs","openChamberLogo.aria.logo":"OpenChamber logo","markdownRenderer.code.proposal":"Proposal","markdownRenderer.code.actions.copyTitle":"Copy code","markdownRenderer.code.actions.copiedTitle":"Copied","markdownRenderer.table.actions.copyTitle":"Copy table","markdownRenderer.code.actions.enableWrapTitle":"Enable line wrap","markdownRenderer.code.actions.disableWrapTitle":"Disable line wrap","markdownRenderer.table.actions.enableWrapTitle":"Enable cell wrap","markdownRenderer.table.actions.disableWrapTitle":"Disable cell wrap","markdownRenderer.table.actions.downloadTitle":"Download table","markdownRenderer.table.toast.downloadedAsFormat":"Table downloaded as {format}","markdownRenderer.mermaid.actions.copyTitle":"Copy","markdownRenderer.mermaid.actions.copySourceTitle":"Copy source","markdownRenderer.mermaid.actions.downloadSvgTitle":"Download SVG","markdownRenderer.mermaid.actions.zoomInTitle":"Zoom in","markdownRenderer.mermaid.actions.zoomOutTitle":"Zoom out","markdownRenderer.mermaid.actions.resetViewTitle":"Reset view","markdownRenderer.mermaid.toast.downloadFailed":"Failed to download diagram","common.date.today":"Today","common.date.yesterday":"Yesterday","common.date.yesterdayWithTime":"Yesterday {time}","common.relative.justNow":"Just now","common.relative.minutesAgoShort":"{count}min ago","common.relative.hoursAgoShort":"{count}h ago","common.relative.daysAgoShort":"{count}d ago","common.relative.weeksAgoShort":"{count}w ago","common.relative.yearsAgoShort":"{count}y ago","common.relative.minutesAgoCompact":"{count}m","common.relative.hoursAgoCompact":"{count}h","common.relative.daysAgoCompact":"{count}d","common.relative.weeksAgoCompact":"{count}w","common.relative.monthsAgoCompact":"{count}mo","common.relative.yearsAgoCompact":"{count}y","common.duration.secondsCompact":"{seconds}s","common.duration.minutesSecondsCompact":"{minutes}m {seconds}s","common.duration.hoursMinutesCompact":"{hours}h {minutes}m","contextFileOpen.failure.tooLarge":"{name} is too large to open","contextFileOpen.failure.tooLargeDetail":"More than {count} lines · {size}","contextFileOpen.failure.tooLargeSize":"Larger than {limit} · {size}","contextFileOpen.failure.missing":"{name} was not found","contextFileOpen.failure.unreadable":"Couldn't open {name}","quota.window.5h":"5-Hour","quota.window.7d":"7-Day Limit","quota.window.extraUsage":"Extra Usage","quota.window.weekly":"Weekly","quota.window.daily":"Daily","quota.window.monthly":"Monthly","quota.window.credits":"Credits","quota.value.creditsUsed":"{credits} Credits Used","quota.window.keyLimit":"Key Limit","quota.window.creditsBalance":"Credits Balance","quota.window.monthlyCredits":"Monthly Credits","quota.window.purchasedCredits":"Purchased Credits","quota.window.freeCredits":"Free Credits","quota.window.billingCycle":"Billing Cycle","quota.window.auto":"Auto","quota.window.api":"API","quota.window.planLimit":"Plan Limit","quota.window.onDemand":"On-demand","quota.window.session":"Session","quota.window.premium":"Premium Interactions","quota.window.chat":"Chat Requests","quota.window.completions":"Completions","quota.window.premiumInteractions":"AI Credits","chat.workStatus.ariaLabel":"Work status","chat.workStatus.mobileEmpty":"Nothing to show for this session yet","chat.workStatus.context.label":"Context","chat.workStatus.cost.breakdown":"Session {session} · Subagents {subagents}","chat.workStatus.git.changedFileSingle":"{count} file changed","chat.workStatus.git.changedFilePlural":"{count} files changed","chat.workStatus.pr.untitled":"Untitled pull request","chat.workStatus.mr.untitled":"Untitled merge request","chat.workStatus.pr.draft":"Draft","chat.workStatus.pr.checks":"Checks","chat.workStatus.pr.checksFailed":"{count} failed","chat.workStatus.pr.checksPending":"{count} running","chat.workStatus.pr.checksPassed":"{count} passed","chat.workStatus.attention.merge":"Merge in progress","chat.workStatus.attention.rebase":"Rebase in progress","chat.workStatus.attention.cherryPick":"Cherry-pick in progress","chat.workStatus.attention.revert":"Revert in progress","chat.workStatus.attention.bisect":"Bisect in progress","chat.workStatus.subagent.done":"Done","chat.workStatus.subagent.failed":"Failed","chat.workStatus.subagent.untitled":"Subagent","chat.workStatus.mcp.toggle":"Toggle {name}","chat.workStatus.mcp.needsAuth":"Sign in","chat.workStatus.mcp.failed":"Failed","chat.workStatus.pinned.unavailable":"Pinned message","chat.workStatus.section.session":"Session","chat.workStatus.section.project":"Project","chat.workStatus.section.subagents":"Subagents","chat.workStatus.section.mcp":"MCP","chat.workStatus.section.pinned":"Pinned messages","chat.workStatus.section.tasks":"Tasks","chat.workStatus.subagent.working":"is working","chat.workStatus.subagent.needsPermission":"needs permission","chat.workStatus.subagent.askedQuestion":"asked a question","chat.workStatus.section.contextBreakdown":"Context sources","chat.workStatus.breakdown.skills":"Skills","chat.workStatus.breakdown.pinnedNote":"note","chat.workStatus.breakdown.unpin":"Unpin from context","chat.workStatus.breakdown.pinnedPlan":"plan","chat.workStatus.breakdown.memory":"Agent memory","chat.workStatus.breakdown.pinnedKnowledgeSingle":"{count} pinned","chat.workStatus.breakdown.pinnedKnowledgePlural":"{count} pinned","chat.workStatus.breakdown.mcp":"MCP servers","chat.workStatus.action.openChanges":"Open changes","chat.workStatus.action.openGit":"Open Git panel","chat.workStatus.action.openPr":"Open pull request","chat.workStatus.action.openMr":"Open merge request","chat.workStatus.action.openSubagent":"Open {name}","chat.workStatus.section.usage":"Usage","chat.workStatus.section.telemetry":"Turn stats","chat.workStatus.telemetry.previousTurn":"Previous turn","chat.workStatus.telemetry.previousTurnRate":"Previous turn · {rate}","chat.workStatus.telemetry.responseSpeed":"Response","chat.workStatus.telemetry.responseSpeedDescription":"How fast the final text arrived. Excludes the initial wait, reasoning, and earlier tool calls. An estimate from text timestamps, not a provider speed measurement.","chat.workStatus.telemetry.speed":"Whole turn","chat.workStatus.telemetry.speedDescription":"Tokens generated across all steps, including reasoning, divided by time with tool execution removed. Waiting for the model still counts, so many short tool calls can lower this number.","chat.workStatus.telemetry.elapsed":"Elapsed","chat.workStatus.telemetry.elapsedDescription":"Wall-clock time from the first user message to the final assistant response. Includes model waiting, tool execution, compaction, and other gaps.","chat.workStatus.telemetry.llmDuration":"Model time","chat.workStatus.telemetry.llmDurationDescription":"Time spent on all model steps, including waiting for responses. Tool execution time is removed. This is not just time spent generating text.","chat.workStatus.telemetry.toolDuration":"Tool time","chat.workStatus.telemetry.toolDurationDescription":"Time spent running tools, including failed calls. Tools running at the same time are counted once, not added together.","chat.workStatus.telemetry.ttft":"Average TTFT","chat.workStatus.telemetry.ttftDescription":"Average wait before the first text or reasoning starts in each model step. Hidden when a step has no start after it was created, which is common for tool-only steps and for parts stamped at creation time.","chat.workStatus.telemetry.steps":"Steps","chat.workStatus.telemetry.stepsDescription":"How many times the model was called for this prompt. Reading tool results and deciding what to do next usually takes another step.","chat.workStatus.telemetry.tokens":"Tokens","chat.workStatus.telemetry.tokens.inOut":"{input} ↑ · {output} ↓","chat.workStatus.telemetry.tokensDescription":"↑ Input without cached tokens: {input}. ↓ Generated tokens: {output} for text and tool calls, plus {reasoning} for reasoning. Totals cover all steps of this prompt.","chat.workStatus.telemetry.cacheHit":"Cache","chat.workStatus.telemetry.cacheHitDescription":"Share of input tokens reused from the prompt cache across all steps. Reusing context can reduce cost and waiting, but this is not a speed score.","chat.workStatus.telemetry.cost":"Cost","chat.workStatus.telemetry.costDescription":"Cost reported by the provider for all model steps of this prompt, in US dollars. Excludes separate subagent sessions. Zero can mean a free model or a provider that reports no charge.","chat.workStatus.goal.open":"Manage goal","chat.workStatus.goal.pause":"Pause","chat.workStatus.goal.resume":"Resume","chat.workStatus.goal.updateFailed":"Could not update the goal","chat.workStatus.pinned.unpin":"Unpin message","chat.workStatus.pinned.reveal":"Go to message","chat.workStatus.pinned.unpinFailed":"Could not unpin the message","chat.workStatus.action.openContext":"Open context panel","chat.workStatus.section.linkedIssues":"Linked","chat.workStatus.linkedIssues.openOnProvider":"Open {reference} on {provider}","chat.workStatus.linkedIssues.unlink":"Remove link","chat.workStatus.linkedIssues.unlinkFailed":"Could not remove the link","chat.workStatus.linkedIssues.link":"Link to session","chat.workStatus.linkedIssues.linkFailed":"Could not link","chat.workStatus.breakdown.issueCountSingle":"{count} issue","chat.workStatus.breakdown.issueCountPlural":"{count} issues","chat.workStatus.breakdown.prCountSingle":"{count} PR","chat.workStatus.breakdown.mrCountSingle":"{count} MR","chat.workStatus.breakdown.prCountPlural":"{count} PRs","chat.workStatus.breakdown.mrCountPlural":"{count} MRs","chat.workStatus.breakdown.skillCountSingle":"{count} skill","chat.workStatus.breakdown.skillCountPlural":"{count} skills","chat.workStatus.breakdown.mcpCountSingle":"{count} MCP","chat.workStatus.breakdown.mcpCountPlural":"{count} MCP","chat.workStatus.sections.open":"Choose sections","chat.workStatus.sections.dialogTitle":"Panel sections","chat.workStatus.sections.reorder":"Drag {label} to reorder","chat.workStatus.sections.dragInstructions":"Press Space to pick up a section, use the arrow keys to move it, and press Space to drop. Press Escape to cancel.","chat.workStatus.sections.position":"{label}, position {position} of {count}.","chat.workStatus.sections.dragCancelled":"Reordering cancelled.","chat.workStatus.sections.dialogDescription":"Choose what the work-status panel shows. Hidden sections keep their data — they are only left out of the panel.","chat.workStatus.sections.allHidden":"No sections selected","chat.workStatus.sections.showAll":"Show all","chat.workStatus.sections.noneWarning":"The panel will appear empty.","header.workStatusPanel.toggleAria":"Toggle work-status panel","header.actions.newMiniChat":"New Mini Chat Window","header.actions.newMiniChatAria":"Open a new Mini Chat window","header.actions.openSessionMiniChat":"Open Session in Mini Chat","header.actions.openSessionMiniChatAria":"Open current session in Mini Chat","header.workStatusPanel.hide":"Hide work status","header.workStatusPanel.show":"Show work status","chat.workStatus.mcp.authorizeOpenFailed":"Could not open the authorization page","chat.workStatus.mcp.authorizeFailed":"Authorization failed","chat.formCard.inputNeeded":"Input needed","chat.formCard.fromSubagent":"from a subagent","chat.formCard.required":"Required","chat.formCard.openLink":"Open link","chat.formCard.yes":"Yes","chat.formCard.other":"Other","chat.formCard.yourAnswer":"Your answer","chat.formCard.submit":"Submit","chat.formCard.cancel":"Cancel","chat.formCard.missingRequired":"Fill in the required fields first.","chat.formCard.submitFailed":"Could not submit the answer","chat.formCard.cancelFailed":"Could not cancel the request","chat.formCard.tryAgain":"Try again.","chat.formCard.recoveredNotice":"The turn stopped while waiting. Submit starts a new paid turn.","chat.formDock.progress":"{current} of {total}","chat.formDock.waiting":"{count} more waiting","chat.formDock.back":"Back","chat.formDock.expandAria":"Expand the question","chat.formDock.collapseAria":"Collapse the question","chat.formDock.stepAria":"Question {index}: {title}","chat.formDock.linkInfo":"Open the link, then continue.","chat.permissionCard.title":"Permission required","chat.permissionCard.summary.externalDirectory":"Access files outside the project","chat.permissionCard.summary.read":"Read a file","chat.permissionCard.summary.edit":"Edit files","chat.permissionCard.summary.shell":"Run a command","chat.permissionCard.summary.glob":"Find files","chat.permissionCard.summary.grep":"Search file contents","chat.permissionCard.summary.webfetch":"Open a web page","chat.permissionCard.summary.websearch":"Search the web","chat.permissionCard.summary.skill":"Load a skill","chat.permissionCard.summary.tool":"Use {tool}","chat.permissionCard.summary.inPath":"in {path}","chat.permissionCard.showDetails":"Show details","chat.permissionDock.expandAria":"Expand the permission request","chat.permissionDock.collapseAria":"Collapse the permission request","chat.permissionDock.stepAria":"Request {index}: {tool}","chat.permissionCard.allowOnce":"Allow once","chat.permissionCard.alwaysAllow":"Always allow","chat.permissionCard.alwaysAllowPatterns":"Always: {patterns}","chat.permissionCard.deny":"Deny","chat.permissionCard.replaceAll":"Replaces every occurrence","chat.compaction.running":"Compacting the conversation","chat.compaction.completed":"Conversation compacted","chat.compaction.failed":"Compaction failed","chat.compaction.showSummary":"Show summary","chat.compaction.hideSummary":"Hide summary","chat.dispatchedSession.completed":"Session finished: {title}","chat.dispatchedSession.failed":"Session failed: {title}","chat.dispatchedSession.cancelled":"Session stopped: {title}","chat.dispatchedSession.completedUntitled":"Session finished","chat.dispatchedSession.failedUntitled":"Session failed","chat.dispatchedSession.cancelledUntitled":"Session stopped","chat.dispatchedSession.showAnswer":"Show answer","chat.dispatchedSession.hideAnswer":"Hide answer","chat.dispatchedSession.open":"Open session","chat.revertPopover.staged":"Reverted: {count}","chat.revertPopover.toast.restoreFailed":"Couldn't restore the reverted messages","chat.workStatus.mcp.needsAuthHint":"Sign in to this MCP server from Settings → MCP.","mcpDropdown.toast.authorizeOpenFailed":"Could not open the authorization page","mcpDropdown.toast.authorizeFailed":"Authorization failed","header.services.tooltip.currentInstance":"Current instance: {current} ({toggle})","header.workStatusPanel.showOverlay":"Show work status over the chat","settings.mcp.page.connection.title":"How to reach it","settings.mcp.page.connection.description":"Paste the command that starts it, or the link to a hosted server.","settings.mcp.page.registration.title":"This server needs its own app","settings.mcp.page.registration.description":"It does not hand out credentials automatically. Create an app in the service’s own settings, paste its details here, then sign in.","settings.mcp.page.registration.callbackLabel":"Give the service this address","settings.mcp.page.registration.clientId":"App ID","settings.mcp.page.registration.clientSecret":"App secret","settings.mcp.page.registration.afterSaving":"Save, then press Authorize to sign in.","settings.mcp.page.toast.copiedCallbackUrl":"Address copied","settings.mcp.page.toast.clipboardWriteFailed":"Could not copy to the clipboard","settings.mcp.page.scope.everywhere":"Available in every project","settings.mcp.page.scope.thisProject":"Only in this project","settings.mcp.page.env.description":"Values the server needs, such as an API key.","settings.mcp.page.connection.kindCommand":"Command","settings.mcp.page.connection.kindLink":"Link","settings.mcp.page.connection.hintCommand":"Runs on this machine. Paste a whole command and it is split into one argument per line.","settings.mcp.page.connection.hintLink":"Connects to a server someone else hosts. Paste its https address.","chat.messageBody.actions.askOtherModels":"Ask other models","chat.modelControls.runInParallel":"Run on several models","chat.parallel.defaultTitle":"Parallel run","chat.parallel.exit":"Leave parallel mode","chat.parallel.fuse.judge":"Fuse with {model}","chat.parallel.fuse.off":"Fuse: off","chat.parallel.isolation.shared":"Shared directory","chat.parallel.isolation.worktrees":"Separate worktrees","chat.parallel.models.add":"Add model","chat.parallel.models.decrement":"Run {model} one time less","chat.parallel.models.increment":"Run {model} one more time","chat.parallel.runAria":"Start parallel runs ({count})","chat.parallel.setup.dialogDescription":"Commands run in every new worktree before its prompt, one per line.","chat.parallel.toast.failed":"Could not start the parallel run.","chat.parallel.toast.incomplete":"Every prompt variant needs text and at least one model.","chat.parallel.variant.removeAria":"Remove variant {variant}","chat.parallel.variant.runsPlural":"{count} runs","chat.parallel.variant.runsSingle":"{count} run","chat.parallel.variant.tabsAria":"Prompt variants","multirun.ask.checking":"Checking this answer…","multirun.ask.description":"This chat becomes the first run. Each model gets the same first prompt in its own worktree.","multirun.ask.failed":"Could not ask other models.","multirun.ask.notFirstTurn":"Only the first answer of a chat can be compared for now.","multirun.ask.startPlural":"Run {count} more","multirun.ask.startSingle":"Run {count} more","multirun.ask.title":"Ask other models","multirun.overview.archive.action":"Archive run","multirun.overview.archive.failed":"Some runs could not be archived.","multirun.overview.ask.failed":"Could not add the model to this run.","multirun.overview.ask.working":"Adding…","multirun.overview.bar.fuse":"Fuse results","multirun.overview.bar.hint":"Fuse the answers into one result","multirun.overview.cancel":"Cancel","multirun.overview.card.changesUnavailable":"Changes unavailable","multirun.overview.card.diff":"Diff","multirun.overview.card.filesPlural":"{count} files","multirun.overview.card.filesSingle":"{count} file","multirun.overview.card.noChanges":"No file changes","multirun.overview.card.noReply":"No answer yet","multirun.overview.card.openChat":"Open chat","multirun.overview.card.replyUnavailable":"Answer unavailable","multirun.overview.card.selectAria":"Select {name}","multirun.overview.card.working":"Working…","multirun.overview.fuse.modeAnswers":"Combines the final answers","multirun.overview.fuse.modeCode":"Works in its own worktree and reads each run with git","multirun.overview.fuse.selected":"{count} of {total} selected","multirun.overview.fuse.with":"Fuse with","multirun.overview.fusedResult":"Fused result","multirun.overview.headerTitle":"Run in parallel","multirun.overview.keep.confirm":"Keep and clean up","multirun.overview.keep.confirmPlural":"Keep {name}? The other {count} runs are archived and their worktrees removed. Their work stays recoverable.","multirun.overview.keep.confirmSingle":"Keep {name}? The other run is archived and its worktree removed. Its work stays recoverable.","multirun.overview.keep.done":"Kept {name}","multirun.overview.keep.failed":"Could not clean up the other runs.","multirun.overview.keep.partialPlural":"Kept {name}. {count} runs could not be cleaned up and were left as they were.","multirun.overview.keep.partialSingle":"Kept {name}. One run could not be cleaned up and was left as it was.","multirun.overview.keep.working":"Cleaning up…","multirun.overview.meta.autoFusion":"Fuses with {model} when all finish","multirun.overview.meta.progress":"{done} of {total} finished","multirun.overview.meta.runsPlural":"{count} runs","multirun.overview.meta.runsSingle":"{count} run","multirun.overview.meta.sharedDirectory":"Shared directory","multirun.overview.meta.variants":"{count} prompt variants","multirun.overview.meta.worktrees":"Separate worktrees","multirun.overview.missing":"This run is no longer available.","multirun.overview.rename.aria":"Rename run","multirun.overview.rename.failed":"Some runs kept the old name.","sessions.sidebar.run.collapse":"Hide runs","sessions.sidebar.run.expand":"Show runs","sessions.sidebar.run.laneCountPlural":"{count} runs","sessions.sidebar.run.laneCountSingle":"{count} run","sessions.sidebar.run.openOverviewAria":"Open parallel run {title}","sessions.sidebar.run.menu.openOverview":"Open overview","sessions.sidebar.session.menu.openRunOverview":"Open run overview","chat.parallel.models.effortAria":"Thinking effort: {effort}","chat.parallel.settings.title":"Launch settings","chat.parallel.settings.whereTitle":"Where the runs work","chat.parallel.settings.setupTitle":"Setup commands","chat.parallel.settings.fusionTitle":"Fusion","chat.parallel.settings.variantsTitle":"Prompt variants","chat.parallel.settings.variantsDescription":"Send different prompts, for example to compare skills or wording. Each variant gets its own tab.","chat.parallel.settings.addVariant":"Add a prompt variant","chat.parallel.settings.done":"Done","chat.parallel.settings.openAria":"Launch settings: {summary}","multirun.overview.card.keep":"Keep this","multirun.overview.addModel.action":"Add a model","multirun.overview.addModel.hint":"Runs the same prompt on one more model in this run","chat.parallel.settings.whereShared":"Project directory","chat.parallel.settings.whereSharedHint":"All runs work in your checkout. Best for questions and research.","chat.parallel.settings.whereWorktrees":"Separate worktrees","chat.parallel.settings.whereWorktreesHint":"Each run gets its own branch, so code changes never collide. Keep the best one.","chat.parallel.settings.baseBranchTitle":"Base branch","chat.parallel.settings.fusionOff":"Off","chat.parallel.settings.fusionOffHint":"Compare the results yourself.","chat.parallel.settings.fusionAuto":"Automatic","chat.parallel.settings.fusionAutoHint":"Fuse the results as soon as every run finishes.","chat.parallel.settings.judgeTitle":"Fusion model","multirun.overview.card.detach":"Make a separate session","multirun.overview.card.detachHint":"Leave this run and continue as an ordinary session","multirun.overview.card.detachDone":"{name} is now a separate session","multirun.overview.card.detachFailed":"Could not move this session out of the run.","multirun.overview.card.archive":"Archive this session","multirun.overview.addModel.confirm":"Run","multirun.overview.status.permission":"Waiting for your permission","multirun.overview.status.question":"Waiting for your answer","multirun.overview.status.working":"Working","multirun.overview.status.failed":"Failed","multirun.overview.status.stopped":"Stopped","multirun.overview.status.notStarted":"Not started","multirun.overview.status.noReply":"Finished without an answer","multirun.overview.status.finished":"Finished","multirun.overview.status.count.permission":"{count} waiting for permission","multirun.overview.status.count.question":"{count} waiting for an answer","multirun.overview.status.count.working":"{count} working","multirun.overview.status.count.failed":"{count} failed","multirun.overview.status.count.stopped":"{count} stopped","multirun.overview.status.count.notStarted":"{count} not started","multirun.overview.status.count.noReply":"{count} without an answer","multirun.overview.status.count.finished":"{count} finished","multirun.overview.card.body.permission":"Waiting for your permission to go on. Open the chat to answer.","multirun.overview.card.body.question":"Asked you a question. Open the chat to answer.","multirun.overview.card.body.failed":"Failed. Open the chat for details.","multirun.overview.card.body.notStarted":"Has not started yet.","multirun.overview.card.body.stopped":"Stopped before answering.","multirun.overview.bar.waiting":"Runs waiting for you: {count}. The run can't finish until you answer them.","multirun.overview.prompt.expand":"Show all","multirun.overview.prompt.collapse":"Show less","gitView.changes.revertFileDialogTitle":"Revert file changes?","gitView.changes.revertFileDescription":"This will discard your local changes in {path}.","gitView.changes.revertFileConfirm":"Revert file","diffView.hunk.discardDialogTitle":"Discard this hunk?","diffView.hunk.discardDescription":"This will discard these local changes in {path}.","sessions.sidebar.project.actions.archiveAll":"Archive all sessions","sessions.sidebar.project.archiveAll.title":"Archive sessions in {project}?","sessions.sidebar.project.archiveAll.descriptionSingle":"{count} session moves to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.descriptionPlural":"{count} sessions move to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.nothing":"Nothing to archive: every session here is pinned, running or In work.","contextPanel.browser.devServers.hide":"Hide port {port} from this list","contextPanel.browser.devServers.showHiddenSingle":"Show {count} hidden port","contextPanel.browser.devServers.showHiddenPlural":"Show {count} hidden ports","sidebarFilesTree.menu.openInDefaultApp":"Open in default app","sessions.sidebar.header.displayMode.showChats":"Show chats section","sessions.scheduledTasks.editor.useDefaults.label":"Use session defaults","sessions.scheduledTasks.editor.useDefaults.hint":"Each run takes the default model, thinking level and agent from Settings → Sessions (or the project's own defaults) at the time it starts.","sessions.scheduledTasks.editor.worktree.label":"Run each run in a fresh worktree","sessions.scheduledTasks.editor.worktree.hint":"Each run gets its own worktree and branch.","sessions.scheduledTasks.editor.worktree.baseBranch.label":"Source branch","sessions.scheduledTasks.editor.worktree.cleanup.label":"Clean up worktree after run","sessions.scheduledTasks.editor.worktree.cleanup.hint":"The worktree and its branch are removed when the run ends.","sessions.scheduledTasks.editor.worktree.cleanup.keepHint":"The worktree and its branch stay after the run so you can review the result.","sessions.scheduledTasks.editor.worktree.notRepo":"The project folder is not a git repository; runs will use the checkout as-is.","sessions.scheduledTasks.dialog.usesDefaults":"Session defaults","sessions.moveSession.menu":"Move session…","sessions.moveSession.hint":"Files stay in the old folder","sessions.moveSession.title":"Move session","sessions.moveSession.description":"The session continues in the chosen folder. Files stay where they are.","sessions.moveSession.chooseFolder":"Choose folder…","sessions.moveSession.current":"Current folder","sessions.moveSession.success":"Session moved","sessions.moveSession.failed":"Could not move the session","chat.folderMissing.text":"Folder {name} no longer exists","chat.folderMissing.action":"Move session","chat.worktreeSetup.running":"Setting up the worktree: running the project's setup commands…","chat.draft.creatingSession":"Creating session…","desktopHostSwitcher.startup.fellBackToLocal":"Its connection didn't open, so OpenChamber started on Local. Connect it from the instance switcher once it's reachable.","desktopSafeStart.title":"OpenChamber kept crashing","desktopSafeStart.description":"Panels are closed and folders collapsed.","chat.chatInput.contextPreview.saveEdit":"Save comment","chat.chatInput.contextPreview.cancelEdit":"Cancel editing","sessions.scheduledTasks.dialog.actions.openSession":"Open session","sessions.scheduledTasks.dialog.actions.openSessionAria":"Open the session from the last run of {taskName}","sessions.scheduledTasks.dialog.toast.alreadyRunningSince":"This task already has a run in progress, started at {time}","sessions.scheduledTasks.dialog.toast.alreadyRunning":"This task already has a run in progress","sessions.scheduledTasks.dialog.toast.alreadyQueued":"This task is already waiting in the queue and will run when a slot frees up","chat.modelControls.agentFavoriteAdd":"Add to favorites. With favorites, Tab cycles through them only","notifications.error.bodyFallback":"An error occurred","notifications.question.bodyFallback":"Agent is waiting for your response","notifications.permission.bodyFallback":"Agent is waiting for your approval","notifications.permission.title":"Permission required","chat.promptHistorySearch.title":"Search prompt history","chat.promptHistorySearch.searchPlaceholder":"Search remembered prompts","chat.promptHistorySearch.close":"Close prompt history search","chat.promptHistorySearch.empty":"No prompts to search yet","chat.promptHistorySearch.noMatches":"No matching prompts","chat.promptHistorySearch.attachmentsSingle":"{count} attachment","chat.promptHistorySearch.attachmentsPlural":"{count} attachments","chat.promptHistorySearch.hint":"↑ ↓ to browse · Enter to load · Esc to close","helpDialog.item.searchPromptHistory":"Search prompt history (chat input)"},gl=new Map([[hi,fi]]);async function Mx(e){const t=gl.get(e);if(t)return t;const s=e==="zh-CN"?await Ee(()=>import("./zh-CN-C4Ip1vNN.js"),__vite__mapDeps([3,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="fr"?await Ee(()=>import("./fr-BKEy-Z_2.js"),__vite__mapDeps([109,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="nl"?await Ee(()=>import("./nl-X6CZmwET.js"),__vite__mapDeps([110,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="zh-TW"?await Ee(()=>import("./zh-TW-BmwR7rb1.js"),__vite__mapDeps([111,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="es"?await Ee(()=>import("./es-DMJlwy06.js"),__vite__mapDeps([112,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pt-BR"?await Ee(()=>import("./pt-BR-QNheuCzR.js"),__vite__mapDeps([113,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="uk"?await Ee(()=>import("./uk-Dos-a0OZ.js"),__vite__mapDeps([114,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ko"?await Ee(()=>import("./ko-DXd5Gg_L.js"),__vite__mapDeps([115,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pl"?await Ee(()=>import("./pl-CmAyO7EH.js"),__vite__mapDeps([116,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="de"?await Ee(()=>import("./de-DM_yQ7AG.js"),__vite__mapDeps([117,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ja"?await Ee(()=>import("./ja-lqTz_4gG.js"),__vite__mapDeps([118,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="tr"?await Ee(()=>import("./tr-4WQrywE1.js"),__vite__mapDeps([119,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ar"?await Ee(()=>import("./ar-BrwaPZTB.js"),__vite__mapDeps([120,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="he"?await Ee(()=>import("./he-BnqH_lWh.js"),__vite__mapDeps([121,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):{dict:fi};return gl.set(e,s.dict),s.dict}const Wo=yt()((e,t)=>({locale:hi,dictionary:fi,loadingLocale:null,setLocale:s=>{const n=t(),a=gl.get(s);n.locale===s&&n.loadingLocale!==s&&a||(Dz(s),e({locale:s,dictionary:a??n.dictionary,loadingLocale:a?null:s}),!a&&Mx(s).then(i=>{t().locale===s&&e({dictionary:i,loadingLocale:null})}).catch(i=>{console.error(`[i18n] failed to load locale ${s}`,i),t().locale===s&&e({dictionary:fi,loadingLocale:null})}))}}));function Ex(){Wo.getState().setLocale(Bz())}function Lx(e,t,s){const n=e[t]??fi[t]??t;return s?n.replace(/\{([^{}]+)\}/g,(a,i)=>{const o=s[i.trim()];return o==null?a:String(o)}):n}const $q=Object.freeze(Object.defineProperty({__proto__:null,formatMessage:Lx,initializeLocale:Ex,useI18nStore:Wo},Symbol.toStringTag,{value:"Module"})),mf="session",hf=40,qx=1,Vx=100,ff=e=>e==="global"||e==="session",Pd=e=>e!=null&&Number.isInteger(e)&&e>=qx&&e<=Vx,Ux=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Ad=e=>e==="auto"||typeof e=="string"&&Ux.includes(e),Fn="openchamber-input-history.v1",Wx=8,Hx=50,Gx=[40,25,10,5,1],dc=Object.freeze([]);let as=null,vp=0;const $a=(e=mf,t=hf)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),bf=()=>(vp+=1,Date.now()*1e3+vp),kf=e=>JSON.stringify([e]),pl=(e,t,s)=>JSON.stringify([e,t,s]),zd=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},_x=()=>{const e=zd(),t=jt?JSON.stringify(vo(jt.base)):as;if(!e)return t;try{return e.getItem(Fn)??(jt?null:as)}catch{return t}},Cp=bt(g(),Y()),Kx=p({key:g().min(1),source:J([y("file-url"),y("vscode-file")]),filename:g().min(1),mimeType:g().min(1),size:v().finite().nonnegative(),reference:g().min(1)}),Zx=p({text:g(),attachmentKeys:x(g()),restorableAttachments:x(Kx),submittedAt:v().finite().nonnegative()}),Jx=p({touchedAt:v().finite().nonnegative(),entries:x(Y())}),$x=(e,t)=>{try{const s=JSON.parse(e),a=(t===1?xo([g().trim().min(1)]):xo([g().trim().min(1),g().trim().min(1),g().trim().min(1)])).safeParse(s);if(!a.success)return null;if(t===3){const i=ze(a.data[1]);if(!i||i!==a.data[1])return null}return a.data}catch{return null}},Sp=(e,t)=>{const s=[];for(const[n,a]of Object.entries(e)){if(!$x(n,t))continue;const i=Jx.safeParse(a);if(!i.success)continue;const o=i.data.entries.map(r=>Zx.safeParse(r)).filter(r=>r.success).map(r=>r.data);s.push([n,{touchedAt:i.data.touchedAt,entries:o}])}return Object.fromEntries(s)},Qx=()=>{const e=_x();if(e===null)return $a();try{const t=JSON.parse(e),s=p({version:y(1),entryLimit:v().int().optional(),scope:J([y("global"),y("session")]).optional(),global:Cp.default({}),session:Cp.default({})}).safeParse(t);return s.success?{entryLimit:Pd(s.data.entryLimit)?s.data.entryLimit:hf,scope:s.data.scope??mf,globalBuckets:Sp(s.data.global,1),sessionBuckets:Sp(s.data.session,3)}:$a()}catch{const t=zd();if(t)try{t.removeItem(Fn)}catch{}return as=null,$a()}};let jt=null,wo=$a();const Pp=(e,t,s)=>{const n={...e};for(const a of new Set([...Object.keys(t),...Object.keys(s)])){if(JSON.stringify(t[a])===JSON.stringify(s[a]))continue;const i=s[a];if(!i){delete n[a];continue}const o=new Set((t[a]?.entries??[]).map(d=>JSON.stringify(d))),r=new Set(i.entries.map(d=>JSON.stringify(d))),c=(e[a]?.entries??[]).filter(d=>{const u=JSON.stringify(d);return!o.has(u)||r.has(u)}),l=new Set(c.map(d=>JSON.stringify(d)));for(const d of i.entries){const u=JSON.stringify(d);!o.has(u)&&!l.has(u)&&c.push(d)}c.sort((d,u)=>d.submittedAt-u.submittedAt),n[a]={touchedAt:Math.max(i.touchedAt,e[a]?.touchedAt??0),entries:c}}return n},Ea=()=>{const e=Qx();if(wo=e,!jt)return e;const{base:t,value:s}=jt;return ul({entryLimit:s.entryLimit===t.entryLimit?e.entryLimit:s.entryLimit,scope:s.scope===t.scope?e.scope:s.scope,globalBuckets:Pp(e.globalBuckets,t.globalBuckets,s.globalBuckets),sessionBuckets:Pp(e.sessionBuckets,t.sessionBuckets,s.sessionBuckets)})},yf=(e,t)=>e.slice(Math.max(0,e.length-t)),Ap=(e,t,s)=>{const n=Object.entries(e).map(([a,i])=>[a,{touchedAt:i.touchedAt,entries:yf(i.entries,s)}]).sort((a,i)=>i[1].touchedAt-a[1].touchedAt).slice(0,t);return Object.fromEntries(n)},ul=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Ap(e.globalBuckets,Wx,t),sessionBuckets:Ap(e.sessionBuckets,Hx,t)}),vo=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),zp=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),La=e=>{const t=ul(e),s=JSON.stringify(vo(t));jt={base:wo,value:t};const n=zd();if(!n)return as=s,t;try{return n.setItem(Fn,s),jt=null,as=s,t}catch(o){if(!(o instanceof Error)||!zp(o))return as=s,t}try{n.removeItem(Fn)}catch{}for(const o of Gx){const r=ul(t,o),c=JSON.stringify(vo(r));try{return n.setItem(Fn,c),jt=null,as=c,r}catch(l){if(!(l instanceof Error)||!zp(l))return jt={base:wo,value:r},as=c,r}}const a=$a(t.scope,t.entryLimit),i=JSON.stringify(vo(a));try{n.setItem(Fn,i),jt=null}catch{jt={base:wo,value:a}}return as=i,a},Yx=(e,t,s)=>{const n=e.trim(),a=ze(t),i=s.trim();return!n||!a||!i?null:{runtimeKey:n,directory:a,sessionId:i}},wf=e=>e.source==="vscode"&&e.vscodeSource==="file"?ze(e.vscodePath??null):e.dataUrl.trim()||null,Xx=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),ml=e=>{const t=wf(e),s=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),s].join("|")},eT=e=>{const t=wf(e);return!t||!Xx(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:ml(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:ml(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},tT=(e,t)=>({text:e,attachmentKeys:t.map(ml),restorableAttachments:t.map(eT).filter(s=>s!==null)}),sT=(e,t)=>e.length===t.length&&e.every((s,n)=>{const a=t[n];return a!==void 0&&s.key===a.key&&s.source===a.source&&s.filename===a.filename&&s.mimeType===a.mimeType&&s.size===a.size&&s.reference===a.reference}),nT=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((s,n)=>s===t.attachmentKeys[n])&&sT(e.restorableAttachments,t.restorableAttachments),xp=(e,t,s,n)=>{const a=e?[...e.entries]:[];for(const i of t){const o=a.at(-1);nT(o,i)||a.push({text:i.text,attachmentKeys:[...i.attachmentKeys],restorableAttachments:i.restorableAttachments.map(r=>({...r})),submittedAt:bf()})}return{touchedAt:s,entries:yf(a,n)}},aT=La(Ea()),qa=yt(e=>({...aT,applyEntryLimit:t=>{Pd(t)&&e(s=>{const n=Ea();if(n.entryLimit===t)return{...s,...n};const a=La({entryLimit:t,scope:n.scope,globalBuckets:n.globalBuckets,sessionBuckets:n.sessionBuckets});return{...s,...a}})},applyScope:t=>{ff(t)&&e(s=>{const n=Ea();if(n.scope===t)return{...s,...n};const a=La({entryLimit:n.entryLimit,scope:t,globalBuckets:n.globalBuckets,sessionBuckets:n.sessionBuckets});return{...s,...a}})},appendSubmissions:(t,s)=>{s.length!==0&&e(n=>{const a=Ea(),i=bf(),o=kf(t.runtimeKey),r=pl(t.runtimeKey,t.directory,t.sessionId),c=La({entryLimit:a.entryLimit,scope:a.scope,globalBuckets:{...a.globalBuckets,[o]:xp(a.globalBuckets[o],s,i,a.entryLimit)},sessionBuckets:{...a.sessionBuckets,[r]:xp(a.sessionBuckets[r],s,i,a.entryLimit)}});return{...n,...c}})},clearSession:t=>{e(s=>{const n=Ea(),a=pl(t.runtimeKey,t.directory,t.sessionId);if(!(a in n.sessionBuckets))return{...s,...n};const i={...n.sessionBuckets};delete i[a];const o=La({entryLimit:n.entryLimit,scope:n.scope,globalBuckets:n.globalBuckets,sessionBuckets:i});return{...s,...o}})}})),Qq=(e,t)=>t?e.scope==="session"?e.sessionBuckets[pl(t.runtimeKey,t.directory,t.sessionId)]?.entries??dc:e.globalBuckets[kf(t.runtimeKey)]?.entries??dc:dc,vf=["guest","link","external","repository"],iT=new Set([...vf,"linear"]),Rs=g().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!iT.has(e),{message:"Reserved provider id"}),oT=R(["pullRequest","mergeRequest","change"]),rT=R(["checks","pipeline"]),cT=R(["device","pat","cli"]),lT=J([R(["instance-url","personal-access-token","username","http-password"]),g().transform(()=>"unknown")]),dT=g().max(8192).regex(/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/),Tp=g().min(1).max(64),xa=x(g().min(1).max(256)).max(8),gT=p({id:Rs,label:Tp,order:v().int(),terminology:p({changeRequest:oT.catch("pullRequest"),changeRequestPrefix:g().min(1).max(4),issuePrefix:g().min(1).max(4),sharedNumberSpace:z(),abbreviation:g().min(1).max(8),promptNoun:Tp,ci:rT.catch("checks")}),icon:p({sprite:g().max(64).optional(),filledSprite:g().max(64).optional(),path:dT.optional()}),repository:p({nestedNamespaces:z(),pathStyle:y("path").optional().catch(void 0)}),instances:p({format:R(["host","origin"]),defaultInstance:g().min(1).max(256).nullable(),multiple:z(),allowLoopbackHttp:z(),allowPort:z(),reserved:x(g().max(256)).max(16),placeholder:g().max(256),legacyFlow:p({instance:g().min(1).max(256),kind:y("github-com-device")}).optional()}),auth:p({methods:x(J([cT,g().transform(()=>null)])).transform(e=>e.filter(t=>t!==null)),cliName:g().min(1).max(32).optional(),cliTransport:z(),token:p({scopes:x(g().min(1).max(64)).max(32),createPath:g().max(256).optional()}).optional()}),settings:p({fields:x(p({id:g().min(1).max(64),kind:lT,secret:z()})).max(16)}),urls:p({changeRequest:xa,issue:xa,discussion:xa.default([]).catch([]),commit:xa.default([]).catch([]),user:xa.default([]).catch([])}),features:p({referenceSearch:z().default(!1),referenceDetail:z().default(!1),listStatuses:z().default(!1),referencesAcross:z().default(!1),startThread:z().default(!1),reviewDrafts:z().default(!1),reviewDraftFileComments:z().default(!1),authorCanReview:z().default(!1),projectUploads:z().default(!1),issueCloseReason:z().default(!1),changeRequestTemplates:x(g().min(1).max(256)).max(8).default([]),changeRequestPatch:z().default(!0),reviewModel:R(["verdict","votes"]).default("verdict").catch("verdict"),revisions:z().default(!1).catch(!1),submitRequirements:z().default(!1).catch(!1),createByPush:z().default(!1).catch(!1),branchHeads:z().default(!0).catch(!0),discussions:z().default(!1).catch(!1)}),extension:p({guestId:g().min(1).max(128),name:g().min(1).max(200),version:g().min(1).max(64)}).optional().catch(void 0)}),pT=(e,t)=>e.order-t.order||(e.id<t.id?-1:e.id>t.id?1:0),hl=x(gT.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const n of e)!n||t.has(n.id)||(t.add(n.id),s.push(n));return s.sort(pT)}),Ip=new Map,xd=e=>{const t=Ip.get(e);if(t)return t;const s={id:e,label:e,order:Number.MAX_SAFE_INTEGER,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"git-branch"},repository:{nestedNamespaces:!1},instances:{format:"origin",defaultInstance:null,multiple:!1,allowLoopbackHttp:!1,allowPort:!1,reserved:[],placeholder:""},auth:{methods:[],cliTransport:!1},settings:{fields:[]},urls:{changeRequest:[],issue:[],discussion:[],commit:[],user:[]},features:{referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,reviewDrafts:!1,reviewDraftFileComments:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1,reviewModel:"verdict",revisions:!1,submitRequirements:!1,createByPush:!1,branchHeads:!0,discussions:!1}};return Ip.set(e,s),s},uT=16,mT=(e,t)=>{const s=x(xo([g(),t])),n=()=>{try{const a=s.safeParse(JSON.parse(window.localStorage.getItem(e)??"[]"));return a.success?a.data:[]}catch{return[]}};return{read:a=>Ec(a)?null:n().find(([i])=>i===a)?.[1]??null,remember:(a,i)=>{if(Ec(a))return;const o=n().filter(([r])=>r!==a);o.push([a,[...i]]);try{window.localStorage.setItem(e,JSON.stringify(o.slice(-uT)))}catch{}}}},hT=(e,t)=>e===t||e.length===t.length&&JSON.stringify(e)===JSON.stringify(t),fT=e=>Math.min(6e4,2e3*2**Math.max(0,e-1)),Cf=mT("openchamber.sourceControlProviders.v1",hl),Td=e=>({ordered:e,byId:new Map(e.map(t=>[t.id,t]))}),bT=Td([]),Rp=e=>{const t=Cf.read(e);return t?{runtimeKey:e,...Td(t),status:"stale",holdsList:!0}:{runtimeKey:e,...bT,status:"idle",holdsList:!1}};let _s=0,An=null,zn=null,no=0,Qa=null;const jp=()=>{Qa!==null&&clearTimeout(Qa),Qa=null},bn=yt((e,t)=>{const s=n=>{_s+=1,An=null,zn=null,no=0,jp(),e(Rp(n))};return{...Rp(D()),refresh:n=>{const a=D();if(a!==t().runtimeKey&&s(a),An){if(!zn){const d=_s,u=An.then(()=>{if(zn===u&&(zn=null),d===_s)return t().refresh(n)});zn=u}return zn}jp();const i=_s,{holdsList:o,ordered:r}=t();e({status:"loading"});const l=(async()=>{try{const d=await n.providers();if(i!==_s)return;no=0,Cf.remember(a,d),e(o&&hT(r,d)?{status:"ready"}:{...Td(d),status:"ready",holdsList:!0})}catch{if(i!==_s)return;if(o){e({status:"stale"});return}e({status:"error"}),no+=1,Qa=setTimeout(()=>{Qa=null,i===_s&&t().refresh(n)},fT(no))}})().finally(()=>{An===l&&(An=null)});return An=l,l},resetForRuntimeSwitch:s}});queueMicrotask(()=>{const e=bn.getState(),t=D();e.status==="idle"&&t!==e.runtimeKey&&e.resetForRuntimeSwitch(t)});const Yq=()=>bn(yT),kT=e=>{const t=Ft.c(5);let s;t[0]!==e?(s=i=>e?i.byId.get(e):void 0,t[0]=e,t[1]=s):s=t[1];const n=bn(s);let a;return t[2]!==n||t[3]!==e?(a=n??xd(e??""),t[2]=n,t[3]=e,t[4]=a):a=t[4],a},Xq=e=>kT(e).terminology.changeRequest,eV=e=>{const t=Ft.c(2);let s;return t[0]!==e?(s=n=>e&&n.byId.has(e)?"served":n.holdsList?"not-served":"unknown",t[0]=e,t[1]=s):s=t[1],bn(s)},tV=e=>{const t=Ft.c(2);let s;return t[0]!==e?(s=n=>{const a=e?n.byId.get(e):void 0;return a?a.features.changeRequestPatch?"served":"not-served":n.holdsList?"not-served":"unknown"},t[0]=e,t[1]=s):s=t[1],bn(s)},sV=()=>{const e=Ft.c(2),t=bn(wT);let s;return e[0]!==t?(s=n=>(n?t.get(n):void 0)??xd(n??""),e[0]=t,e[1]=s):s=e[1],s},cr=e=>(e?bn.getState().byId.get(e):void 0)??xd(e??"");function yT(e){return e.ordered}function wT(e){return e.byId}const vT=p({text:g(),prefix:g(),suffix:g(),start:v(),page:p({partId:g()}).optional()}),Op=32,Sf=200,CT="[data-chat-quote-root]";function nV(e,t){return[...e.querySelectorAll(`[data-message-id="${CSS.escape(t)}"]`)].flatMap(s=>s.querySelector(CT)??[]).sort((s,n)=>s.getBoundingClientRect().top-n.getBoundingClientRect().top)}function Pf(e,t,s){const n=s+t.text.length,a=e.slice(Math.max(0,s-t.prefix.length),s),i=e.slice(n,n+t.suffix.length);return t.prefix.endsWith(a)&&t.suffix.startsWith(i)}function Dp(e,t,s){const n=e.ownerDocument.createRange();return n.setStart(e,0),n.setEnd(t,s),n.toString().length}function Af(e){const t=[];let s="";for(const n of e)t.push(s.length),s+=n.textContent??"";return{stream:s,bases:t}}function aV(e,t){const s=Array.isArray(e)?e:[e],n=s.findIndex(d=>d.contains(t.startContainer)),a=s.findIndex(d=>d.contains(t.endContainer));if(n<0||a<n)return null;const{stream:i,bases:o}=Af(s),r=o[n]+Dp(s[n],t.startContainer,t.startOffset),c=o[a]+Dp(s[a],t.endContainer,t.endOffset),l=i.slice(r,c);return l.trim()?{text:l,prefix:i.slice(Math.max(0,r-Op),r),suffix:i.slice(c,c+Op),start:r}:null}function ST(e,t){if(!t.text)return null;const s=[];for(let a=e.indexOf(t.text);a!==-1&&s.length<Sf;a=e.indexOf(t.text,a+1))s.push(a);if(s.length<=1)return s[0]??null;if(!t.prefix&&!t.suffix)return null;const n=s.filter(a=>Pf(e,t,a));return n.length===0?null:n.reduce((a,i)=>Math.abs(i-t.start)<Math.abs(a-t.start)?i:a)}function zf(e,t){for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType===3?t.push(s):zf(s,t);return t}function PT(e){const t=new Set;let s=1;for(const n of e){const a=n.closest("[data-message-id]")?.getAttribute("data-message-row");if(!a)return e.length===1;const[i,o]=a.split("/");t.add(i),s=Number(o)}return t.size===s}const Ta=32;function AT(e,t){const{text:s,prefix:n,suffix:a}=t,i=!!(n||a),o=l=>{const d=[];for(let u=e.indexOf(l);u!==-1&&d.length<Sf;u=e.indexOf(l,u+1))d.push(u);return d},r=[];for(const l of o(s))(!i||Pf(e,t,l))&&r.push({start:l,end:l+s.length});if(s.length>Ta&&(r.length===0||!i)){for(const l of o(s.slice(0,Ta))){const d=e.slice(l);d.length<s.length&&s.startsWith(d)&&n.endsWith(e.slice(Math.max(0,l-n.length),l))&&r.push({start:l,end:e.length})}for(const l of o(s.slice(-Ta))){const d=l+Ta;d<s.length&&s.endsWith(e.slice(0,d))&&a.startsWith(e.slice(d,d+a.length))&&r.push({start:0,end:d})}e.length>=Ta&&e.length<s.length&&s.includes(e)&&r.push({start:0,end:e.length})}return i?r[0]??null:new Set(r.map(l=>`${l.start}:${l.end}`)).size===1?r[0]:null}function iV(e,t){const{stream:s}=Af(e);let n,a;if(PT(e))n=ST(s,t),a=(n??0)+t.text.length;else{const r=AT(s,t);n=r?.start??null,a=r?.end??0}if(n===null||a<=n)return null;const i=[];let o=0;for(const r of e){let c=null;for(const l of zf(r,[])){const d=l.data.length;if(!c&&n<o+d&&a>o&&(c=r.ownerDocument.createRange(),c.setStart(l,Math.max(0,n-o)),c.setEnd(r,r.childNodes.length)),c&&a<=o+d)return c.setEnd(l,a-o),i.push(c),i;o+=d}c&&i.push(c)}return null}const zT=nk.gfm,xT=ak().use(ik).use(zT[0],{singleTilde:!1});function oV(e){const t=s=>{if("children"in s){if(s.type==="list")return`
33
33
  ${s.children.map(t).join(`
34
34
  `)}
35
35
  `;if(s.type==="listItem"){const i=s.children.map(o=>t(o)).join(`
@@ -82,4 +82,4 @@ ${e.sessionId}`,tn=e=>{const[t,s,...n]=e.split(`
82
82
  ${t}`,Ia=(e,t)=>({...t,directory:e.directory}),gc=(e,t)=>On(ZT,"/api/message-queue",{directory:e?`/spaces/${e}`:null,signal:t}),io=new Set,Lp=new Map,Vt=new Map,Ra=new Map;let pc=0;const qp=e=>Object.fromEntries(Object.entries(e).map(([t,s])=>[t,s.map(n=>({...n,text:n.text??n.content}))])),eI=(e,t)=>{const s=e??{},n=t<2?s.queuedMessages??{}:{};return{queuedMessages:t<2?{}:qp(s.queuedMessages??{}),quarantinedLegacyMessages:qp({...s.quarantinedLegacyMessages??{},...n}),followUpBehavior:WT(s.followUpBehavior,s.queueModeEnabled??null)}},Wt=(e,t)=>{const{[t]:s,...n}=e;return n},oo=(e,t,s)=>{const n=(e.queuedMessages[t]??[]).filter(a=>a.id!==s);return n.length===0?{queuedMessages:Wt(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:n}}},tI=(e,t,s,n)=>{let a=e.queuedMessages,i=e.sendingIds;for(const o of new Set([...Object.keys(a),...Object.keys(i)])){const r=tn(o);r?.runtimeKey!==t||r.sessionId!==s||(Vt.get(o)??-1)>n||(Vt.set(o,n),a=Wt(a,o),i=Wt(i,o))}return{queuedMessages:a,sendingIds:i}},kl=yt()(oa(Pi((e,t)=>{let s=null,n=!1;const a=(c,l,d,u="")=>{if(d!==D()||Js(c.directory)!==u||(Ra.get(Ep(d,u))??-1)>l)return;const m=bl(c.sessionId,c.directory,d);if(!m){if(c.items.length>0)return;e(b=>tI(b,d,c.sessionId,l));return}const f=gt(m);(Vt.get(f)??-1)>l||(Vt.set(f,l),e(b=>{const k=c.items.map(ao),w=k.length>0?{...b.queuedMessages,[f]:k}:Wt(b.queuedMessages,f),T=c.sendingId?{...b.sendingIds,[f]:[c.sendingId]}:Wt(b.sendingIds,f);return{queuedMessages:w,sendingIds:T}}))},i=async c=>{const l=Js(c.directory);try{const d=await gc(l),u=d.sessions.find(m=>m.sessionId===c.sessionId)??{sessionId:c.sessionId,directory:c.directory,items:[],sendingId:null};a(u,d.revision,c.runtimeKey,l)}catch{}},o=async(c,l,d)=>{try{const u=await On(Ya,l,Ia(c,d));a(u.session,u.revision,c.runtimeKey,Js(c.directory))}catch(u){console.warn("[queue] server update failed:",u),await i(c)}},r=(c,l,d)=>{const u=Ep(l,d);return(Ra.get(u)??-1)>c.revision?!1:(Ra.set(u,c.revision),e(m=>{const f=S=>(Vt.get(S)??-1)>c.revision,b=S=>{const E=tn(S);return E?.runtimeKey===l&&Js(E.directory)===d},k=S=>!b(S)||f(S),w={},T={};for(const[S,E]of Object.entries(m.queuedMessages))k(S)&&(w[S]=E);for(const[S,E]of Object.entries(m.sendingIds))k(S)&&(T[S]=E);for(const S of c.sessions){if(Js(S.directory)!==d)continue;const E=bl(S.sessionId,S.directory,l);if(!E)continue;const H=gt(E);f(H)||(Vt.set(H,c.revision),S.items.length>0&&(w[H]=S.items.map(ao)),S.sendingId&&(T[H]=[S.sendingId]))}return{queuedMessages:w,sendingIds:T}}),!0)};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:jf,sendingIds:{},addToQueue:async(c,l)=>{const d=gt(c),u=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,m={id:u,content:l.content,text:l.text??l.content,createdAt:Date.now(),sendConfig:l.sendConfig};if(l.agentMention&&(m.agentMention=l.agentMention),l.attachments&&l.attachments.length>0&&(m.attachments=l.attachments),l.context&&l.context.length>0&&(m.context=l.context),l.goal&&(m.goal=l.goal),e(k=>{const w=k.queuedMessages[d]??[],T={...k.queuedMessages,[d]:[...w,m].slice(-20)},S=Object.keys(T);if(S.length>Fp){S.sort((E,H)=>(T[E]?.[0]?.createdAt??0)-(T[H]?.[0]?.createdAt??0));for(const E of S.slice(0,S.length-Fp))delete T[E]}return{queuedMessages:T}}),!Ss())return;if(!l.sendConfig)throw e(k=>oo(k,d,u)),new Error("A queued message needs a provider and model to be delivered later.");const f=Yx(c.runtimeKey,c.directory,c.sessionId),b=tT(l.content,l.attachments??[]);try{const k=await On(Ya,`${Zs(c.sessionId)}/items`,Ia(c,Ks("POST",{directory:c.directory,item:Mp(l,l.sendConfig)})));e(w=>oo(w,d,u)),a(k.session,k.revision,c.runtimeKey,Js(c.directory)),f&&qa.getState().appendSubmissions(f,[b])}catch(k){throw e(w=>oo(w,d,u)),k}},removeFromQueue:(c,l)=>{const d=gt(c);e(u=>oo(u,d,l)),Ss()&&o(c,`${Zs(c.sessionId)}/items/${encodeURIComponent(l)}`,Ks("DELETE"))},reorderQueue:(c,l,d)=>{if(l===d)return;const u=gt(c),m=t().queuedMessages[u];if(!m)return;const f=m.findIndex(T=>T.id===l),b=m.findIndex(T=>T.id===d);if(f===-1||b===-1)return;const k=m.slice(),[w]=k.splice(f,1);if(k.splice(b,0,w),e(T=>({queuedMessages:{...T.queuedMessages,[u]:k}})),Ss()){const T=k.map(S=>S.id);o(c,`${Zs(c.sessionId)}/order`,Ks("PUT",{itemIds:T}))}},popToInput:async(c,l)=>{const[d]=await t().takeForSend(c,l);return d??null},takeForSend:async(c,l)=>{const d=gt(c);if(Ss())try{const k=Js(c.directory);if(l){const T=await On(JT,`${Zs(c.sessionId)}/items/${encodeURIComponent(l)}/take`,Ia(c,Ks("POST")));return a(T.session,T.revision,c.runtimeKey,k),[ao(T.item)]}const w=await On($T,`${Zs(c.sessionId)}/take`,Ia(c,Ks("POST")));return a(w.session,w.revision,c.runtimeKey,k),w.items.map(ao)}catch(k){throw await i(c),k}const u=t(),m=u.sendingIds[d]??[],f=(u.queuedMessages[d]??[]).filter(k=>(l?k.id===l:!0)&&!m.includes(k.id));if(f.length===0)return[];const b=new Set(f.map(k=>k.id));return e(k=>{const w=(k.queuedMessages[d]??[]).filter(T=>!b.has(T.id));return w.length===0?{queuedMessages:Wt(k.queuedMessages,d)}:{queuedMessages:{...k.queuedMessages,[d]:w}}}),f},clearQueue:c=>{const l=gt(c);e(d=>{const u=d.sendingIds[l]??[],m=(d.queuedMessages[l]??[]).filter(f=>u.includes(f.id));return m.length>0?{queuedMessages:{...d.queuedMessages,[l]:m}}:{queuedMessages:Wt(d.queuedMessages,l)}}),Ss()&&o(c,Zs(c.sessionId),Ks("DELETE"))},forgetQueue:c=>{const l=gt(c);Vt.delete(l),e(d=>({queuedMessages:Wt(d.queuedMessages,l),sendingIds:Wt(d.sendingIds,l)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(c,l)=>{const d=gt(c);e(u=>{const m=u.sendingIds[d]??[];return m.includes(l)?u:{sendingIds:{...u.sendingIds,[d]:[...m,l]}}})},clearSending:(c,l)=>{const d=gt(c);e(u=>{const m=u.sendingIds[d];if(!m||!m.includes(l))return u;const f=m.filter(b=>b!==l);return f.length===0?{sendingIds:Wt(u.sendingIds,d)}:{sendingIds:{...u.sendingIds,[d]:f}}})},getSendableQueue:c=>{const l=gt(c),d=t(),u=d.queuedMessages[l]??[],m=d.sendingIds[l];return!m||m.length===0?u:u.filter(f=>!m.includes(f.id))},setFollowUpBehavior:c=>{e({followUpBehavior:c}),Ht({followUpBehavior:c})},getQueueForTarget:c=>t().queuedMessages[gt(c)]??[],hydrate:()=>{if(!Ss())return Promise.resolve();const c=D();if(s?.runtimeKey===c)return s.promise;const l=++pc,d=()=>l===pc&&c===D(),u=(async()=>{let b=Lp.get(c);for(b||(b={items:Object.entries(t().queuedMessages).flatMap(([w,T])=>{const S=tn(w);return!S||S.runtimeKey!==c?[]:T.map(E=>({target:S,message:E}))}),pending:null},Lp.set(c,b));b.pending||b.items.length>0;){if(!d())return;if(b.pending){await b.pending;continue}const k=b.items.shift();if(!k?.message.sendConfig)continue;const{target:w,message:T}=k,S=On(Ya,`${Zs(w.sessionId)}/items`,Ia(w,Ks("POST",{directory:w.directory,item:Mp(T,k.message.sendConfig)}))).then(()=>{}).catch(H=>{console.warn("[queue] failed to migrate a locally queued message to the server:",H)});b.pending=S;const E=b;S.then(()=>{E.pending===S&&(E.pending=null)}),await S}if(d())do{n=!1;let k;try{k=await gc("",AbortSignal.timeout(15e3))}catch(w){if(!d())return;if(n)continue;throw w}if(!d())return;io.add(c),r(k,c,"")}while(n&&d())})(),m={runtimeKey:c,promise:u};s=m;const f=()=>{s===m&&(s=null)};return u.then(f,f),u},resync:()=>(s?.runtimeKey===D()&&(n=!0),t().hydrate()),refreshSpaceQueue:async c=>{if(!Ss())return;const l=D();let d;try{d=await gc(c,AbortSignal.timeout(15e3))}catch{return}l===D()&&(io.add(l),r(d,l,c))},applyServerSession:a,resetForRuntimeSwitch:c=>{if(pc+=1,s=null,n=!1,c){for(const l of Ra.keys())l.startsWith(`${c}
83
83
  `)&&Ra.delete(l);for(const l of Vt.keys())tn(l)?.runtimeKey===c&&Vt.delete(l)}!c||!io.has(c)||e(l=>{const d={},u={};for(const[m,f]of Object.entries(l.queuedMessages))tn(m)?.runtimeKey===c?Vt.delete(m):d[m]=f;for(const[m,f]of Object.entries(l.sendingIds))tn(m)?.runtimeKey!==c&&(u[m]=f);return{queuedMessages:d,sendingIds:u}})}}},{name:"message-queue-store",version:3,storage:md(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const s=tn(t)?.runtimeKey;return!s||!io.has(s)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:eI}),{name:"message-queue-store"})),sI=p({type:y("openchamber:message-queue.updated"),properties:p({revision:v(),session:Dd,spaceId:g().optional()})}),fV=(e,t)=>{if(!Ss())return;const s=sI.safeParse(e);if(!s.success)return;const{session:n,revision:a,spaceId:i}=s.data.properties;kl.getState().applyServerSession(n,a,t,i??"")},Of=[{id:"server",icon:"server"},{id:"cloud",icon:"cloud"},{id:"database",icon:"database-2"},{id:"terminal",icon:"terminal-box"},{id:"code",icon:"code-box"},{id:"ai",icon:"brain-ai-3"}],nI=new Set(Of.map(e=>e.id)),aI=e=>typeof e=="string"&&nI.has(e),bV=e=>Of.find(t=>t.id===e)?.icon??"server",iI=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const s=new TextEncoder().encode(t);let n="";for(const i of s)n+=String.fromCharCode(i);return`path_${typeof btoa=="function"?btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},kV=e=>{if(!e.startsWith("path_"))return"";const t=e.slice(5);if(!t||!/^[A-Za-z0-9_-]+$/.test(t))return"";try{const s=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(s,n=>n.charCodeAt(0)))}catch{return""}},V=e=>t=>{const s=e.safeParse(t);return s.success?s.data:void 0},ua=v().refine(Number.isFinite),st=g().transform(e=>e.trim()),Ie=st.pipe(g().min(1)),ms=bt(g(),Y()),I=V(z()),Be=V(g().min(1)),Dn=V(st),$s=V(Ie),ja=e=>V(g().max(e)),xn=e=>V(st.transform(t=>t.slice(0,e))),ae=e=>V(st.pipe(R(e))),Qs=V(ua),uc=(e,t)=>V(ua.transform(s=>Math.max(e,Math.min(t,Math.round(s))))),mc=e=>V(ua.transform(t=>Math.max(e,Math.round(t)))),oI=V(ua.positive().transform(Math.floor)),rI=V(J([oi(),ua])),cI=V(J([oi(),st.transform(e=>e.length>0?e:null)])),lI=V(J([oi(),st])),Bd=x(Y()).transform(e=>e.filter(t=>g().min(1).safeParse(t).success)),Tn=V(Bd.transform(e=>Array.from(new Set(e.map(String))))),hc=V(Bd.transform(e=>e.map(String))),dI=ms.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const a=x(Y()).safeParse(n);a.success&&(t[s]=a.data.filter(i=>g().safeParse(i).success).map(String))}return t}),fc=V(dI.pipe(bt(g(),x(g())).refine(e=>Object.keys(e).length>0))),gI=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[s,n]of Object.entries(e)){const a=s.trim();a&&aI(n)&&(t[a]=n)}return t},pI=p({providerID:Ie,modelID:Ie}),bc=e=>V(x(Y()).transform(t=>{const s=[],n=new Set;for(const a of t){const i=pI.safeParse(a);if(!i.success)continue;const o=`${i.data.providerID}/${i.data.modelID}`;if(!n.has(o)&&(n.add(o),s.push(i.data),s.length>=e))break}return s})),uI=V(ms.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){if(!s)continue;const a=Bd.safeParse(n);if(!a.success)continue;const i=Array.from(new Set(a.data.map(String)));i.length>0&&(t[s]=i.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),mI=V(ms.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const a=s.trim();if(!a)continue;if(n===null){t[a]=null;continue}const i=Ie.safeParse(n);i.success&&(t[a]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),hI=V(ms.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const a=s.trim(),i=Ie.safeParse(n);!a||!i.success||(t[a]=i.data)}return t})),ro={completion:{title:"Task Complete",message:"Your task has finished."},error:{title:"Error Occurred",message:"An error occurred while processing your task."},question:{title:"Input Needed",message:"Please provide input to continue."},subtask:{title:"Subtask Complete",message:"A subtask has finished."}},fI=p({title:g().catch(""),message:g().catch("")}),bI=V(ms.transform(e=>{const t=o=>{const r=fI.safeParse(e[o]);return r.success?r.data:void 0},s=t("completion"),n=t("error"),a=t("question"),i=t("subtask");if(!(!s&&!n&&!a&&!i))return{completion:s??ro.completion,error:n??ro.error,question:a??ro.question,subtask:i??ro.subtask}}).pipe(Fu(e=>e!==void 0))),Vp=ms.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,s])=>{const n=g().safeParse(s);return n.success?[[t,n.data]]:[]}))),kI=p({id:Y().transform(e=>String(e??"")),label:Y().transform(e=>String(e??"")),models:x(Y()).transform(e=>e.filter(t=>g().safeParse(t).success).map(String)).catch([]),order:v().catch(0)}),yI=V(ms.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const a=ms.safeParse(n);if(!a.success)continue;const i={},o=x(Y()).safeParse(a.data.customGroups);o.success&&(i.customGroups=o.data.flatMap(l=>{const d=kI.safeParse(l);return d.success?[d.data]:[]}));const r=Vp.safeParse(a.data.modelAssignments);r.success&&(i.modelAssignments=r.data);const c=Vp.safeParse(a.data.renamedGroups);c.success&&(i.renamedGroups=c.data),Object.keys(i).length>0&&(t[s]=i)}return t}).refine(e=>Object.keys(e).length>0)),wI=p({id:Ie,name:Ie,hostname:Ie.transform(e=>e.toLowerCase())}),vI=V(x(Y()).transform(e=>{const t=[],s=new Set,n=new Set;for(const a of e){const i=wI.safeParse(a);i.success&&(s.has(i.data.id)||n.has(i.data.hostname)||(s.add(i.data.id),n.add(i.data.hostname),t.push(i.data)))}return t})),CI=V(ms.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const a=s.trim(),i=Ie.safeParse(n);!a||!i.success||(t[a]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),SI=p({id:Ie,label:Ie,source:Ie,subpath:st.optional().catch(void 0),gitIdentityId:st.optional().catch(void 0)}),PI=V(x(Y()).transform(e=>{const t=[],s=new Set;for(const n of e){const a=SI.safeParse(n);if(!a.success||s.has(a.data.id))continue;s.add(a.data.id);const i={id:a.data.id,label:a.data.label,source:a.data.source};a.data.subpath&&(i.subpath=a.data.subpath),a.data.gitIdentityId&&(i.gitIdentityId=a.data.gitIdentityId),t.push(i)}return t})),AI=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,kc=ua.nonnegative(),zI=p({path:Ie,label:Ie.optional().catch(void 0),labelSource:R(["auto","manual"]).optional().catch(void 0),icon:Ie.optional().catch(void 0),iconImage:J([oi(),p({mime:Ie,updatedAt:kc.transform(Math.round).pipe(v().positive()),source:R(["custom","auto"])})]).optional().catch(void 0),color:Ie.optional().catch(void 0),iconBackground:J([oi(),st.pipe(g().regex(AI)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:kc.optional().catch(void 0),lastOpenedAt:kc.optional().catch(void 0),sidebarCollapsed:z().optional().catch(void 0),defaultModel:Ie.optional().catch(void 0),defaultAgent:Ie.optional().catch(void 0),defaultVariant:Ie.optional().catch(void 0)}),xI=V(x(Y()).transform(e=>{const t=[],s=new Set,n=new Set;for(const a of e){const i=zI.safeParse(a);if(!i.success)continue;const o=ze(i.data.path);if(!o)continue;const r=iI(o);if(!r||s.has(r)||n.has(o))continue;s.add(r),n.add(o);const c={id:r,path:o};i.data.label&&(c.label=i.data.label),i.data.label&&i.data.labelSource&&(c.labelSource=i.data.labelSource),i.data.icon&&(c.icon=i.data.icon),i.data.iconImage!==void 0&&(c.iconImage=i.data.iconImage),i.data.color&&(c.color=i.data.color),i.data.iconBackground!==void 0&&(c.iconBackground=i.data.iconBackground),i.data.addedAt!==void 0&&(c.addedAt=i.data.addedAt),i.data.lastOpenedAt!==void 0&&(c.lastOpenedAt=i.data.lastOpenedAt),i.data.defaultModel&&(c.defaultModel=i.data.defaultModel),i.data.defaultAgent&&(c.defaultAgent=i.data.defaultAgent),i.data.defaultVariant&&(c.defaultVariant=i.data.defaultVariant),i.data.sidebarCollapsed!==void 0&&(c.sidebarCollapsed=i.data.sidebarCollapsed),t.push(c)}return t}).refine(e=>e.length>0)),TI=R(["steer","queue"]),II=(e,t)=>{const s=TI.safeParse(e);if(s.success)return s.data;if(e==="immediate")return"steer";const n=z().safeParse(t.queueModeEnabled);if(n.success)return n.data?"queue":"steer"},RI=st.pipe(R(["collapsed","summary"])),jI=(e,t)=>{if(t.chatRenderMode==="sorted")return"collapsed";const s=RI.safeParse(e);return s.success?s.data:void 0},OI=V(st.pipe(R(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),DI=V(st.pipe(R(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),BI=V(st.transform(e=>e.replace(/\s+/g," ").slice(0,64))),FI=e=>V(x(Y()).transform(t=>{const s=[];for(const n of t){const a=st.transform(i=>i.toLowerCase()).safeParse(n);a.success&&e(a.data)&&!s.includes(a.data)&&s.push(a.data)}return s})),Fd=e=>V(Fu(e)),bi=(e,t)=>(s,n)=>{const a=e(s,n);return a===void 0?void 0:t(a)},h=e=>e,P=(e,t,s={})=>({read:()=>A.getState()[e],write:t,autoSave:s.autoSave??!0}),St=e=>t=>{A.setState({[e]:t})},Up=()=>globalThis.window?.__zustand_config_store__??null,Et=e=>({read:()=>Up()?.getState()[e],write:t=>{Up()?.setState({[e]:t})},autoSave:!1}),Pt=e=>({read:()=>Rt.getState()[e],write:t=>{Rt.setState({[e]:t})},autoSave:!1}),NI=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],MI=Fd(Ad),EI=Fd(RP),LI=Fd(jP),qI=V(g().refine(ff)),VI=V(v().refine(Pd)),UI=bi(Dn,e=>nr(e,void 0)),WI=bi(V(x(Y())),zz),HI=bi(V(x(Y())),e=>Lh(e)),GI=ae(["ask","attach","inline","inline-double-paste"]),_I=ae(["default","vim"]),KI=(e,t)=>{let s=e;const n=(a,i)=>{if(s.some(c=>c.type==="command"&&c.name===a))return;const o=s.findIndex(c=>c.type==="command"&&c.name===i),r=o>=0?o+1:s.length;s=[...s.slice(0,r),{type:"command",name:a},...s.slice(r)]};return t.draftStartersCraftGoalAdded!==!0&&n("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==!0&&n("schedule-task","craft-goal"),s},Ti={themeId:h({scope:"profile",perSurface:!0,parse:Be}),useSystemTheme:h({scope:"profile",perSurface:!0,parse:I}),themeVariant:h({scope:"profile",derived:!0,parse:ae(["light","dark"])}),lightThemeId:h({scope:"profile",perSurface:!0,parse:Be}),darkThemeId:h({scope:"profile",perSurface:!0,parse:Be}),locale:h({scope:"profile",parse:ae(Rz),ui:{read:()=>Wo.getState().locale,write:e=>Wo.getState().setLocale(e),autoSave:!1}}),lastDirectory:h({scope:"instance",adopt:"bootstrap-only",parse:Be}),homeDirectory:h({scope:"instance",parse:Be}),opencodeBinary:h({scope:"instance",parse:Dn}),serverUpdateChannel:h({scope:"instance",surfaces:["web"],parse:ae(["stable","canary"])}),projects:h({scope:"instance",parse:xI}),activeProjectId:h({scope:"instance",adopt:"bootstrap-only",parse:Be}),securityScopedBookmarks:h({scope:"instance",surfaces:["desktop"],parse:hc}),pinnedDirectories:h({scope:"instance",parse:Tn}),desktopLanAccessEnabled:h({scope:"instance",surfaces:["desktop"],parse:I}),desktopKeepAwakeEnabled:h({scope:"instance",surfaces:["desktop"],parse:I}),desktopMinimizeToTrayEnabled:h({scope:"instance",surfaces:["desktop"],parse:I}),desktopUpdateChannel:h({scope:"instance",surfaces:["desktop"],parse:ae(["stable","canary"])}),desktopMacMenuBarEnabled:h({scope:"instance",surfaces:["desktop"],parse:I}),desktopLinuxNativeFrame:h({scope:"instance",surfaces:["desktop"],parse:I}),desktopUiPassword:h({scope:"instance",secret:!0,surfaces:["desktop"],parse:Dn}),hasDesktopUiPassword:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:I}),desktopLanAccessActive:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:I}),desktopLanAccessBlockedReason:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:Dn}),githubClientId:h({scope:"instance",parse:$s}),githubScopes:h({scope:"instance",parse:$s}),gitlabClientId:h({scope:"instance",parse:$s}),skillCatalogs:h({scope:"instance",parse:PI}),defaultGitIdentityId:h({scope:"instance",parse:Dn}),permissionAutoAccept:h({scope:"instance",parse:V(p({sessions:bt(g().min(1),J([z(),R(["ask","safety","auto"])])).catch({}),revision:v().int().nonnegative().catch(0)}))}),permissionDefaultMode:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:V(R(["ask","safety","auto"])),ui:P("permissionDefaultMode",e=>A.getState().setPermissionDefaultMode(e))}),messageSearchEnabled:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:I,ui:P("messageSearchEnabled",e=>A.getState().setMessageSearchEnabled(e))}),messageSearchReasoningEnabled:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:I,ui:P("messageSearchReasoningEnabled",e=>A.getState().setMessageSearchReasoningEnabled(e))}),agentControlToolEnabled:h({scope:"instance",parse:I,ui:P("agentControlToolEnabled",e=>A.getState().setAgentControlToolEnabled(e))}),agentScheduleToolEnabled:h({scope:"instance",parse:I,ui:P("agentScheduleToolEnabled",e=>A.getState().setAgentScheduleToolEnabled(e))}),agentWebToolEnabled:h({scope:"instance",parse:I,ui:P("agentWebToolEnabled",e=>A.getState().setAgentWebToolEnabled(e))}),browserProvider:h({scope:"instance",parse:Be,ui:P("browserProvider",e=>A.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:h({scope:"instance",parse:I,ui:P("agentNotifyToolEnabled",e=>A.getState().setAgentNotifyToolEnabled(e))}),agentRenderToolEnabled:h({scope:"instance",parse:I,ui:P("agentRenderToolEnabled",e=>A.getState().setAgentRenderToolEnabled(e))}),agentImageToolEnabled:h({scope:"instance",parse:I,ui:P("agentImageToolEnabled",e=>A.getState().setAgentImageToolEnabled(e))}),agentImageModel:h({scope:"instance",parse:Be,ui:P("agentImageModel",e=>A.getState().setAgentImageModel(e))}),agentSecretToolEnabled:h({scope:"instance",parse:I,ui:P("agentSecretToolEnabled",e=>A.getState().setAgentSecretToolEnabled(e))}),agentToolsCodeMode:h({scope:"instance",parse:I,ui:P("agentToolsCodeMode",e=>A.getState().setAgentToolsCodeMode(e))}),agentMemoryToolEnabled:h({scope:"instance",parse:I,ui:P("agentMemoryToolEnabled",e=>A.getState().setAgentMemoryToolEnabled(e))}),agentKnowledgeToolEnabled:h({scope:"instance",parse:I,ui:P("agentKnowledgeToolEnabled",e=>A.getState().setAgentKnowledgeToolEnabled(e))}),agentWorkflowToolEnabled:h({scope:"instance",parse:I,ui:P("agentWorkflowToolEnabled",e=>A.getState().setAgentWorkflowToolEnabled(e))}),isolatedSpacesEnabled:h({scope:"instance",parse:I,ui:P("isolatedSpacesEnabled",e=>A.getState().setIsolatedSpacesEnabled(e))}),isolatedSpacesIdleStop:h({scope:"instance",parse:V(p({enabled:z(),hours:v().int().min(1).max(168)}).strict())}),isolatedSpacesSshHost:h({scope:"instance",parse:xn(320)}),agentMemoryFeatureAvailable:h({scope:"instance",computed:!0,parse:I,ui:P("agentMemoryFeatureAvailable",e=>A.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),agentWorkflowFeatureAvailable:h({scope:"instance",computed:!0,parse:I,ui:P("agentWorkflowFeatureAvailable",e=>A.getState().setAgentWorkflowFeatureAvailable(e),{autoSave:!1})}),overviewFeatureAvailable:h({scope:"instance",computed:!0,parse:I,ui:P("overviewFeatureAvailable",e=>A.getState().setOverviewFeatureAvailable(e),{autoSave:!1})}),routingFeatureAvailable:h({scope:"instance",computed:!0,parse:I,ui:P("routingFeatureAvailable",e=>A.getState().setRoutingFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:h({scope:"instance",parse:xn(128)}),autoDeleteEnabled:h({scope:"instance",parse:I,ui:P("autoDeleteEnabled",e=>A.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:h({scope:"instance",parse:uc(1,365),ui:P("autoDeleteAfterDays",e=>A.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:h({scope:"instance",parse:I,ui:P("sessionRetentionOnlyArchived",e=>A.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionAction:h({scope:"instance",parse:ae(["archive","delete"]),ui:P("sessionRetentionAction",e=>A.getState().setSessionRetentionAction(e))}),mergedWorktreeCleanupEnabled:h({scope:"instance",parse:I,ui:P("mergedWorktreeCleanupEnabled",e=>A.getState().setMergedWorktreeCleanupEnabled(e))}),worktreeArchiveOnDoneEnabled:h({scope:"instance",parse:I,ui:P("worktreeArchiveOnDoneEnabled",e=>A.getState().setWorktreeArchiveOnDoneEnabled(e))}),terminalShell:h({scope:"instance",parse:MI,ui:P("terminalShell",e=>A.getState().setTerminalShell(e))}),terminalLoginShells:h({scope:"instance",parse:FI(Ad),ui:P("terminalLoginShells",e=>A.getState().setTerminalLoginShells(e))}),openInAppId:h({scope:"instance",parse:$s}),dictationEnabled:h({scope:"profile",parse:I,ui:Et("dictationEnabled")}),dictationAutoSend:h({scope:"profile",parse:I,ui:Et("dictationAutoSend")}),sttProvider:h({scope:"instance",parse:OI,ui:Et("sttProvider")}),sttServerUrl:h({scope:"instance",parse:xn(2048),ui:Et("sttServerUrl")}),sttEndpointPath:h({scope:"instance",parse:V(g().trim().max(1024)),ui:Et("sttEndpointPath")}),sttModel:h({scope:"instance",parse:xn(256),ui:Et("sttModel")}),sttLocalModel:h({scope:"instance",parse:xn(256),ui:Et("sttLocalModel")}),sttLanguage:h({scope:"profile",parse:xn(64),ui:Et("sttLanguage")}),sttCorrectTranscript:h({scope:"profile",parse:I,ui:Et("sttCorrectTranscript")}),tunnelProvider:h({scope:"instance",parse:bi($s,e=>e.toLowerCase())}),tunnelMode:h({scope:"instance",parse:V(g().transform(e=>e.trim().toLowerCase()).pipe(R(["quick","managed-remote","managed-local","serve","funnel"])))}),tunnelHttpsPort:h({scope:"instance",parse:uc(1,65535)}),tunnelBootstrapTtlMs:h({scope:"instance",parse:rI}),tunnelSessionTtlMs:h({scope:"instance",parse:Qs}),managedLocalTunnelConfigPath:h({scope:"instance",parse:cI}),managedRemoteTunnelHostname:h({scope:"instance",parse:Dn}),managedRemoteTunnelToken:h({scope:"instance",secret:!0,parse:lI}),hasManagedRemoteTunnelToken:h({scope:"instance",computed:!0,parse:I}),managedRemoteTunnelPresets:h({scope:"instance",parse:vI}),managedRemoteTunnelSelectedPresetId:h({scope:"instance",parse:$s}),managedRemoteTunnelPresetTokens:h({scope:"instance",secret:!0,parse:CI}),sidebarProjectDisplayMode:h({scope:"profile",parse:ae(["all","single"]),ui:Pt("projectDisplayMode")}),sidebarViewMode:h({scope:"profile",perSurface:!0,parse:ae(["projects","timeline"]),ui:Pt("sidebarViewMode")}),sidebarListSessionGrouping:h({scope:"profile",perSurface:!0,parse:ae(["project","time"]),ui:Pt("listSessionGrouping")}),sidebarGrouping:h({scope:"profile",perSurface:!0,parse:ae(["project","time"]),ui:Pt("sidebarGrouping")}),sidebarKeepWorkInPlace:h({scope:"profile",perSurface:!0,parse:I,ui:Pt("keepWorkInPlace")}),sidebarProjectSortOrder:h({scope:"profile",parse:ae(["manual","a-z","z-a","date-added","recent"]),ui:Pt("projectSortOrder")}),sidebarShowChatsSection:h({scope:"profile",perSurface:!0,parse:I,ui:Pt("showChatsSection")}),sidebarShowWorkSection:h({scope:"profile",perSurface:!0,parse:I,ui:Pt("showWorkSection")}),sidebarShowPinnedSection:h({scope:"profile",perSurface:!0,parse:I,ui:Pt("showPinnedSection")}),sidebarDetailedZoneRows:h({scope:"profile",perSurface:!0,parse:I,ui:Pt("detailedZoneRows")}),sidebarWorktreeNameByBranch:h({scope:"profile",parse:I,ui:Pt("worktreeNameByBranch")}),sidebarSections:h({scope:"profile",parse:V(ol),ui:{read:()=>Rt.getState().sections,write:e=>Rt.getState().setSections(e),autoSave:!1}}),sidebarPinLists:h({scope:"profile",parse:V(af),ui:{read:()=>Rt.getState().pinLists,write:e=>Rt.getState().setPinLists(e),autoSave:!1}}),sidebarHiddenSections:h({scope:"profile",perSurface:!0,parse:V(of),ui:{read:()=>Rt.getState().hiddenSections,write:e=>Rt.getState().setHiddenSections(e),autoSave:!1}}),workStatusSectionOrder:h({scope:"profile",parse:bi(hc,Lo),ui:P("workStatusSectionOrder",e=>A.getState().setWorkStatusSectionOrder(e))}),workStatusPanelEnabled:h({scope:"profile",parse:I,ui:P("workStatusPanelEnabled",e=>A.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:h({scope:"profile",parse:HI,ui:{read:()=>A.getState().workStatusHiddenSections,write:(e,t)=>{const s=t.workStatusHiddenSectionsExplicit===!0;A.setState({workStatusHiddenSections:Lh(e,s),workStatusHiddenSectionsExplicit:s})},autoSave:!0}}),workStatusHiddenSectionsExplicit:h({scope:"profile",parse:I,ui:P("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:h({scope:"profile",parse:I,ui:P("showReasoningTraces",e=>A.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:h({scope:"profile",perSurface:!0,parse:I,ui:P("streamingAutoFollowEnabled",e=>A.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:h({scope:"profile",parse:I,ui:P("collapsibleThinkingBlocks",e=>A.getState().setCollapsibleThinkingBlocks(e))}),expandReasoningWhileStreaming:h({scope:"profile",parse:I,ui:P("expandReasoningWhileStreaming",e=>A.getState().setExpandReasoningWhileStreaming(e))}),showTextJustificationActivity:h({scope:"profile",parse:I}),chatRenderMode:h({scope:"profile",parse:ae(["sorted","live"])}),activityRenderMode:h({scope:"profile",parse:jI,ui:P("activityRenderMode",e=>A.getState().setActivityRenderMode(e))}),mermaidRenderingMode:h({scope:"profile",parse:ae(["svg","ascii"]),ui:P("mermaidRenderingMode",e=>A.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:h({scope:"profile",parse:ae(["markdown","plain"]),ui:P("userMessageRenderingMode",e=>A.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:h({scope:"profile",parse:I,ui:P("collapsibleUserMessages",e=>A.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:h({scope:"profile",perSurface:!0,parse:I,ui:P("stickyUserHeader",e=>A.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:h({scope:"profile",perSurface:!0,parse:I,ui:P("promptNavigatorEnabled",e=>A.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:h({scope:"profile",perSurface:!0,parse:I,ui:P("wideChatLayoutEnabled",e=>A.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:h({scope:"profile",parse:I,ui:P("showSplitAssistantMessageActions",e=>A.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:h({scope:"profile",parse:I,ui:P("showToolFileIcons",e=>A.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:h({scope:"profile",parse:I,ui:P("codeBlockLineWrap",e=>A.getState().setCodeBlockLineWrap(e))}),tableCellWrap:h({scope:"profile",parse:I,ui:P("tableCellWrap",e=>A.getState().setTableCellWrap(e))}),copyMessagesAsPlainText:h({scope:"profile",parse:I,ui:P("copyMessagesAsPlainText",e=>A.getState().setCopyMessagesAsPlainText(e))}),showTurnChangedFiles:h({scope:"profile",parse:I,ui:P("showTurnChangedFiles",e=>A.getState().setShowTurnChangedFiles(e))}),toolJsonViewMode:h({scope:"profile",parse:ae(["summary","formatted","raw"]),ui:P("toolJsonViewMode",e=>A.getState().setToolJsonViewMode(e))}),timeFormatPreference:h({scope:"profile",parse:ae(["auto","12h","24h"]),ui:P("timeFormatPreference",e=>A.getState().setTimeFormatPreference(e))}),weekStartPreference:h({scope:"profile",parse:ae(["auto","sunday","monday"]),ui:P("weekStartPreference",e=>A.getState().setWeekStartPreference(e))}),messageStreamTransport:h({scope:"profile",parse:ae(["auto","ws","sse"]),ui:Et("settingsMessageStreamTransport")}),diffLayoutPreference:h({scope:"profile",parse:ae(["dynamic","inline","side-by-side"]),ui:P("diffLayoutPreference",e=>A.getState().setDiffLayoutPreference(e))}),diffWrapLines:h({scope:"profile",parse:I,ui:P("diffWrapLines",e=>A.getState().setDiffWrapLines(e))}),diffHideWhitespace:h({scope:"profile",parse:I,ui:P("diffHideWhitespace",e=>A.getState().setDiffHideWhitespace(e))}),gitChangesViewMode:h({scope:"profile",parse:ae(["flat","tree"]),ui:P("gitChangesViewMode",e=>A.getState().setGitChangesViewMode(e))}),gitmojiEnabled:h({scope:"profile",parse:I}),defaultFileViewerPreview:h({scope:"profile",parse:I}),directoryShowHidden:h({scope:"profile",parse:I,ui:{read:Sz,write:e=>Pz(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:h({scope:"profile",parse:I,ui:{read:Tz,write:e=>Iz(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:h({scope:"profile",parse:_I,ui:P("fileEditorKeymap",e=>A.getState().setFileEditorKeymap(e))}),fileEditorVimMappings:h({scope:"profile",parse:ja(1e4),ui:P("fileEditorVimMappings",e=>A.getState().setFileEditorVimMappings(e))}),autoSaveEnabled:h({scope:"profile",parse:I,ui:P("autoSaveEnabled",e=>A.getState().setAutoSaveEnabled(e))}),fileEditorWrapLines:h({scope:"profile",parse:I,ui:P("fileEditorWrapLines",e=>A.getState().setFileEditorWrapLines(e))}),confirmFileTreeMove:h({scope:"profile",parse:I,ui:P("confirmFileTreeMove",e=>A.getState().setConfirmFileTreeMove(e))}),fileTreeSide:h({scope:"profile",surfaces:["web","desktop"],parse:ae(["left","right"]),ui:P("fileTreeSide",e=>A.getState().setFileTreeSide(e))}),layoutAnimations:h({scope:"profile",surfaces:["web","desktop"],parse:I,ui:P("layoutAnimations",e=>A.getState().setLayoutAnimations(e))}),openLinksInBrowserPanel:h({scope:"profile",surfaces:["desktop"],parse:I,ui:P("openLinksInBrowserPanel",e=>A.getState().setOpenLinksInBrowserPanel(e))}),liveBrowserTabLimit:h({scope:"profile",surfaces:["desktop"],parse:uc(jh,Oh),ui:P("liveBrowserTabLimit",e=>A.getState().setLiveBrowserTabLimit(e))}),openTrackerLinksOnBoard:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:I,ui:P("openTrackerLinksOnBoard",e=>A.getState().setOpenTrackerLinksOnBoard(e))}),terminalCloseOnExit:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:I,ui:P("terminalCloseOnExit",e=>A.getState().setTerminalCloseOnExit(e))}),autoCreateWorktree:h({scope:"profile",parse:I}),sessionTabsEnabled:h({scope:"profile",surfaces:["web","desktop","vscode"],parse:I,ui:P("sessionTabsEnabled",e=>A.getState().setSessionTabsEnabled(e))}),sessionTabsPerWorkspace:h({scope:"profile",surfaces:["web","desktop"],parse:I,ui:P("sessionTabsPerWorkspace",e=>A.getState().setSessionTabsPerWorkspace(e))}),allowPromptingSubagentSessions:h({scope:"profile",parse:I,ui:P("allowPromptingSubagentSessions",e=>A.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:h({scope:"profile",parse:I,ui:P("inputSpellcheckEnabled",e=>A.getState().setInputSpellcheckEnabled(e))}),enterToSend:h({scope:"profile",parse:I,ui:P("enterToSend",e=>A.getState().setEnterToSend(e))}),enterToSendConfigured:h({scope:"profile",parse:I,ui:P("enterToSendConfigured",e=>A.getState().setEnterToSendConfigured(e))}),mobileReturnKeySends:h({scope:"profile",parse:I,ui:P("mobileReturnKeySends",e=>A.getState().setMobileReturnKeySends(e))}),largeTextPasteBehavior:h({scope:"profile",parse:GI,ui:P("largeTextPasteBehavior",e=>A.getState().setLargeTextPasteBehavior(e))}),savePastedImagesAsFiles:h({scope:"profile",parse:I,ui:P("savePastedImagesAsFiles",e=>A.getState().setSavePastedImagesAsFiles(e))}),followUpBehavior:h({scope:"profile",parse:II,ui:{read:()=>kl.getState().followUpBehavior,write:e=>kl.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:h({scope:"profile",parse:I}),inputHistoryScope:h({scope:"profile",parse:qI,ui:{read:()=>qa.getState().scope,write:e=>qa.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:h({scope:"profile",parse:VI,ui:{read:()=>qa.getState().entryLimit,write:e=>qa.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:h({scope:"profile",parse:WI,ui:{read:()=>A.getState().globalDraftStarters??void 0,write:(e,t)=>A.getState().setGlobalDraftStarters(KI(e,t)),autoSave:!1}}),draftStartersVisible:h({scope:"profile",parse:I,ui:P("draftStartersVisible",e=>A.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:h({scope:"profile",parse:I}),draftStartersScheduleTaskAdded:h({scope:"profile",parse:I}),fontSize:h({scope:"profile",perSurface:!0,parse:Qs,ui:P("fontSize",e=>A.getState().setFontSize(e))}),terminalFontSize:h({scope:"profile",perSurface:!0,parse:Qs,ui:P("terminalFontSize",e=>A.getState().setTerminalFontSize(e))}),editorFontSize:h({scope:"profile",perSurface:!0,parse:Qs,ui:P("editorFontSize",e=>A.getState().setEditorFontSize(e))}),uiFont:h({scope:"profile",parse:EI,ui:P("uiFont",e=>A.getState().setUiFont(e))}),monoFont:h({scope:"profile",parse:LI,ui:P("monoFont",e=>A.getState().setMonoFont(e))}),customUiFont:h({scope:"profile",parse:ja(100),ui:P("customUiFont",e=>A.getState().setCustomUiFont(e))}),customMonoFont:h({scope:"profile",parse:ja(100),ui:P("customMonoFont",e=>A.getState().setCustomMonoFont(e))}),uiFontWeight:h({scope:"profile",parse:ae(CP),ui:P("uiFontWeight",e=>A.getState().setUiFontWeight(e))}),padding:h({scope:"profile",perSurface:!0,parse:Qs,ui:P("padding",e=>A.getState().setPadding(e))}),cornerRadius:h({scope:"profile",perSurface:!0,parse:Qs,ui:P("cornerRadius",e=>A.getState().setCornerRadius(e))}),shortcutOverrides:h({scope:"profile",parse:hI,ui:P("shortcutOverrides",St("shortcutOverrides"))}),defaultModel:h({scope:"profile",parse:Be}),defaultVariant:h({scope:"profile",parse:Be}),defaultAgent:h({scope:"profile",parse:Be}),smallModelUseDefault:h({scope:"profile",parse:I}),smallModelOverride:h({scope:"profile",parse:Be}),smallModelVariant:h({scope:"profile",parse:Be}),walkthroughModelOverride:h({scope:"profile",parse:Be}),walkthroughModelVariant:h({scope:"profile",parse:Be}),fallbackModel:h({scope:"profile",parse:Be}),fallbackVariant:h({scope:"profile",parse:Be}),accountSwitchProviders:h({scope:"profile",parse:Tn}),zenModel:h({scope:"profile",parse:$s}),favoriteModels:h({scope:"profile",parse:bc(64),ui:P("favoriteModels",St("favoriteModels"),{autoSave:!1})}),hiddenModels:h({scope:"profile",parse:bc(1024),ui:P("hiddenModels",St("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:h({scope:"profile",parse:Tn,ui:P("collapsedModelProviders",St("collapsedModelProviders"),{autoSave:!1})}),customProviderIcons:h({scope:"profile",parse:gI,ui:P("customProviderIcons",St("customProviderIcons"),{autoSave:!1})}),recentModels:h({scope:"profile",parse:bc(16),ui:P("recentModels",St("recentModels"),{autoSave:!1})}),lastSelectedModel:h({scope:"profile",parse:Be,ui:P("lastSelectedModel",St("lastSelectedModel"))}),recentAgents:h({scope:"profile",parse:Tn,ui:P("recentAgents",St("recentAgents"),{autoSave:!1})}),favoriteAgents:h({scope:"profile",parse:Tn,ui:P("favoriteAgents",St("favoriteAgents"),{autoSave:!1})}),recentEfforts:h({scope:"profile",parse:uI,ui:P("recentEfforts",St("recentEfforts"),{autoSave:!1})}),lastUsedEfforts:h({scope:"profile",parse:mI,ui:P("lastUsedEfforts",St("lastUsedEfforts"),{autoSave:!1})}),providerOrder:h({scope:"profile",parse:Tn,ui:P("providerOrder",e=>A.getState().setProviderOrder(e))}),sessionRecapEnabled:h({scope:"profile",parse:I,ui:P("sessionRecapEnabled",e=>A.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:h({scope:"profile",parse:I,ui:P("sessionSuggestionEnabled",e=>A.getState().setSessionSuggestionEnabled(e))}),sessionWorkEnabled:h({scope:"profile",parse:I,ui:P("sessionWorkEnabled",e=>A.getState().setSessionWorkEnabled(e))}),sessionReviewOfferEnabled:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:I,ui:P("sessionReviewOfferEnabled",e=>A.getState().setSessionReviewOfferEnabled(e))}),sessionGoalEnabled:h({scope:"profile",parse:I,ui:P("sessionGoalEnabled",e=>A.getState().setSessionGoalEnabled(e))}),sessionGoalChecker:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:ae(["classifier","small-model"]),ui:P("sessionGoalChecker",e=>A.getState().setSessionGoalChecker(e))}),sessionGoalMaxAutoTurns:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:V(v().refine(vh)),ui:P("sessionGoalMaxAutoTurns",e=>A.getState().setSessionGoalMaxAutoTurns(e))}),sessionGoalDefaultBudgetEnabled:h({scope:"profile",parse:I,ui:P("sessionGoalDefaultBudgetEnabled",e=>A.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:h({scope:"profile",parse:oI,ui:P("sessionGoalDefaultBudget",e=>A.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:h({scope:"profile",parse:I,ui:P("summarizeLastMessage",e=>A.getState().setSummarizeLastMessage(e))}),summaryThreshold:h({scope:"profile",parse:mc(0),ui:P("summaryThreshold",e=>A.getState().setSummaryThreshold(e))}),summaryLength:h({scope:"profile",parse:mc(10),ui:P("summaryLength",e=>A.getState().setSummaryLength(e))}),maxLastMessageLength:h({scope:"profile",parse:mc(10),ui:P("maxLastMessageLength",e=>A.getState().setMaxLastMessageLength(e))}),showDeletionDialog:h({scope:"profile",parse:I,ui:P("showDeletionDialog",e=>A.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:h({scope:"profile",parse:I,ui:P("nativeNotificationsEnabled",e=>A.getState().setNativeNotificationsEnabled(e))}),notificationMode:h({scope:"profile",parse:ae(["always","hidden-only"]),ui:P("notificationMode",e=>A.getState().setNotificationMode(e))}),notifyOnSubtasks:h({scope:"profile",parse:I,ui:P("notifyOnSubtasks",e=>A.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:h({scope:"profile",parse:I,ui:P("notifyOnCompletion",e=>A.getState().setNotifyOnCompletion(e))}),notifyOnPullRequests:h({scope:"profile",parse:I,ui:P("notifyOnPullRequests",e=>A.getState().setNotifyOnPullRequests(e))}),notifyOnError:h({scope:"profile",parse:I,ui:P("notifyOnError",e=>A.getState().setNotifyOnError(e))}),notifyOnQuestion:h({scope:"profile",parse:I,ui:P("notifyOnQuestion",e=>A.getState().setNotifyOnQuestion(e))}),notificationTemplates:h({scope:"profile",parse:bI,ui:P("notificationTemplates",e=>A.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:h({scope:"profile",parse:I,ui:P("showOpenCodeUpdateNotifications",e=>A.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:h({scope:"profile",parse:I,ui:P("reportUsage",e=>A.getState().setReportUsage(e))}),usageDisplayMode:h({scope:"profile",parse:ae(["usage","remaining"])}),usageDropdownProviders:h({scope:"profile",parse:hc}),usageSelectedModels:h({scope:"profile",parse:fc}),usageCollapsedFamilies:h({scope:"profile",parse:fc}),usageExpandedFamilies:h({scope:"profile",parse:fc}),usageModelGroups:h({scope:"profile",parse:yI}),globalBehaviorPrompt:h({scope:"profile",parse:ja(1024*1024)}),responseStyleEnabled:h({scope:"profile",parse:I}),responseStylePreset:h({scope:"profile",parse:ae(NI)}),responseStyleCustomInstructions:h({scope:"profile",parse:ja(5e4)}),pwaAppName:h({scope:"instance",surfaces:["web"],parse:BI}),pwaOrientation:h({scope:"instance",surfaces:["web"],parse:ae(["system","portrait","landscape"])}),mobileKeyboardMode:h({scope:"device",surfaces:["mobile"],parse:UI,ui:P("mobileKeyboardMode",e=>A.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:h({scope:"device",surfaces:["desktop"],parse:DI,ui:P("desktopWindowControlsPosition",e=>A.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:h({scope:"device",surfaces:["desktop"],parse:ae(["classic","traffic-lights"]),ui:P("desktopWindowControlsStyle",e=>A.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:h({scope:"device",surfaces:["mobile","web"],parse:Qs,ui:P("inputBarOffset",e=>A.getState().setInputBarOffset(e))})},ZI=e=>Object.prototype.hasOwnProperty.call(Ti,e),Ii=Object.keys(Ti).filter(ZI),Df=e=>Ti[e].scope==="device",Ri=e=>Ti[e],JI=e=>!Ti[e].computed&&!Df(e),$I=bt(g(),Y()),QI=e=>{const t=$I.safeParse(e);if(!t.success)return null;const s=t.data,n={};for(const a of Ii){const o=Ri(a).parse(s[a],s);o!==void 0&&Object.assign(n,{[a]:o})}return n},YI=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),XI=e=>{for(const t of Ii){const s=Ri(t);if(!s.ui)continue;const n=e[t];n!==void 0&&(YI(s.ui.read(),n)||s.ui.write(n,e))}},eR=Ii.filter(e=>Ri(e).ui?.autoSave===!0),yV=()=>{const e={};for(const t of eR){const n=Ri(t).ui?.read();n!==void 0&&Object.assign(e,{[t]:n})}return e},tR=Ii.filter(e=>{const t=Ri(e);return t.scope!=="device"&&!t.secret&&!t.computed}),Bf=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},Wp="openchamber.settingsMirror.v2.index",sR="openchamber.deviceSeeded.v1:",nR=e=>`${sR}${encodeURIComponent(e)}`,aR=(e,t)=>{const s=nR(t);let n=!1;try{n=localStorage.getItem(s)===null,n&&localStorage.setItem(s,String(Date.now()))}catch{n=!1}if(n)return e;const a={};for(const i of Ii)e[i]===void 0||Df(i)||Object.assign(a,{[i]:e[i]});return a},iR="openchamber.settingsMirror.v2:",oR=5,yl=e=>`${iR}${encodeURIComponent(e)}`,ws=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},rR=(e,t)=>{const s={};for(const i of tR)e[i]!==void 0&&Object.assign(s,{[i]:e[i]});localStorage.setItem(yl(t),JSON.stringify(s));let n=[];try{const i=JSON.parse(localStorage.getItem(Wp)??"[]");Array.isArray(i)&&(n=i.filter(o=>typeof o=="string"))}catch{n=[]}const a=[t,...n.filter(i=>i!==t)].slice(0,oR);for(const i of n)a.includes(i)||localStorage.removeItem(yl(i));localStorage.setItem(Wp,JSON.stringify(a))},cR=e=>{if(!(typeof window>"u")){if(rR(e,D()),ws("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),Bf(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(s=>s.sidebarCollapsed===!0).map(s=>s.id).filter(s=>typeof s=="string"&&s.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(e.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof e.directoryShowHidden=="boolean"?localStorage.setItem("directoryTreeShowHidden",e.directoryShowHidden?"true":"false"):localStorage.removeItem("directoryTreeShowHidden"),typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),ws("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}else localStorage.removeItem("openchamber.pwaName");if(Th(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion=="string"){const t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem("opencode-update-toast-dismissed-version",t):localStorage.removeItem("opencode-update-toast-dismissed-version")}else localStorage.removeItem("opencode-update-toast-dismissed-version");typeof e.dictationEnabled=="boolean"?localStorage.setItem("dictationEnabled",String(e.dictationEnabled)):localStorage.removeItem("dictationEnabled"),e.dictationAutoSend!==void 0?localStorage.setItem("dictationAutoSend",String(e.dictationAutoSend)):localStorage.removeItem("dictationAutoSend"),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),ws("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),ws("sttEndpointPath",e.sttEndpointPath??null),ws("sttModel",typeof e.sttModel=="string"?e.sttModel:null),ws("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),ws("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null),ws("sttCorrectTranscript",e.sttCorrectTranscript===void 0?null:String(e.sttCorrectTranscript))}},wl=(e,t,s=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:s}}))};let vl="idle",co=null;const Cl=new Set,lR=()=>vl,dR=e=>(Cl.add(e),()=>Cl.delete(e)),gR=e=>{dr(),Ot(e)},Ot=e=>{co&&(clearTimeout(co),co=null);const t=e==="saved"?"idle":e;t!==vl&&(vl=t,Cl.forEach(s=>s())),t==="error"&&(co=setTimeout(()=>Ot("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},Ff=()=>{const e=A.persist;if(e&&typeof e=="object")return e},Nf=()=>ra()?.settings??null,Mf=()=>`/api/config/settings?${$h}=${rr()}`,pR=e=>{XI(e)},Ho=e=>QI(e);class uR{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const s=this.mutations.at(-1),n=s?[...this.operations].some(a=>a.revision>=s.revision):!0;s&&!n?(s.revision=this.revision,s.changes={...s.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const s={revision:t};return this.operations.add(s),s}reconcile(t,s){let n=t;for(const a of this.mutations)a.revision<=s.revision||(n={...n,...a.changes});return n}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const s=Math.min(...[...this.operations].map(({revision:n})=>n));this.mutations=this.mutations.filter(n=>n.revision>s)}reset(){this.mutations=[],this.operations.clear()}}let Nd=0,js=null,ta={},Sl=!1;const mR=()=>Sl,Pl=e=>{Sl=!0;try{pR(e)}finally{Sl=!1}};let sn=null,Bt=null,Kt=null,et=null,Xa=[],Hp=!1,Go=0,Co=[];const ot=new uR,hR=2e3,fR=200,Md=()=>({runtimeKey:D(),generation:Nd}),lr=e=>Object.keys(e),Ef=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),So=e=>{ta={...ta,...e}},bR=e=>{const t={...ta};for(const s of e)delete t[s];ta=t},kR=e=>{const t={};for(const s of lr(e))Ef(e[s],ta[s])||Object.assign(t,{[s]:e[s]});return t},ki=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,Lf=e=>{let t=null;for(const s of Co)ki(s.context,e)&&(t={...t??{},...s.changes});return Bt&&Kt&&ki(Kt,e)&&(t={...t??{},...Bt}),t},Gp=(e,t)=>{const s=Lf(t);return e&&s?{...e,...s}:e},Re=e=>e.generation===Nd&&e.runtimeKey===D(),Oa=()=>{Bt&&(et&&(clearTimeout(et),et=null),_o({keepalive:!0}))},dr=()=>{if(!(Hp||typeof window>"u")){Hp=!0,Qo(e=>{e.runtimeKey!==e.previousRuntimeKey&&(et&&clearTimeout(et),Bt&&_o())}),Yo(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Nd+=1,ot.reset(),Go=0,js=null,sn=null,ta={},Ot("saved"))});try{window.addEventListener("pagehide",Oa,{capture:!0}),window.addEventListener("beforeunload",Oa,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Oa()}),document.addEventListener("freeze",Oa)),mn()&&Ee(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([122,4,108])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||Oa()})).catch(()=>{})}catch{}}},qf=async(e=Md())=>{if(dr(),js&&ki(js.context,e)&&Date.now()-js.at<hR)return Gp(js.value,e);if(sn&&ki(sn.context,e))return sn.promise;const t=ot.begin(),s=Lf(e),n=i=>{if(!Re(e)||!i)return null;const o=Gp(ot.reconcile({...i,...s},t),e);js={value:o,at:Date.now(),context:e};const r={};for(const c of lr(i))Ef(i[c],o?.[c])&&Object.assign(r,{[c]:i[c]});return So(r),o},a={context:e,promise:(async()=>{const i=Nf();if(i)try{const o=await i.load();if(!Re(e))return null;const r=Ho(o.settings);return n(r)}catch(o){if(!Re(e))return null;console.warn("Failed to load shared settings from runtime settings API:",o)}if(!Re(e))return null;try{const o=await C(Mf(),{method:"GET",headers:{Accept:"application/json"}});if(!Re(e)||!o.ok)return null;const r=await o.json().catch(()=>null);if(!Re(e))return null;const c=Ho(r);return n(c)}catch(o){return Re(e)&&console.warn("Failed to load shared settings from server:",o),null}})()};return sn=a,a.promise.finally(()=>{ot.finish(t),sn===a&&(sn=null)}),a.promise},yR=async e=>{const t=e?.bootstrap!==!1,s=e?.adoptTheme??t;if(typeof window>"u")return;dr();const n=Md(),a=ot.begin(),i=[Ff(),Rt.persist],o=d=>!d?.hasHydrated||d.hasHydrated()||!d.onFinishHydration?Promise.resolve():new Promise(u=>{let m=!1;const f=()=>{m||(m=!0,u())},b=d.onFinishHydration(()=>{b?.(),f()});d.hasHydrated?.()&&f()}),r=()=>Promise.all(i.map(o)).then(()=>{}),c=d=>!Bt||!Kt||!Re(Kt)?d:{...d,...Bt},l=async d=>{if(!Re(n))return;let u=c(ot.reconcile(d,a));if(await r(),!!Re(n)){u=aR(c(ot.reconcile(d,a)),n.runtimeKey);try{cR(u)}catch(m){console.warn("persistToLocalStorage failed:",m)}try{Pl(u)}catch(m){console.warn("applyDesktopUiPreferences failed:",m)}wl(u,t,s)}};try{const d=await qf(n);d&&Re(n)?await l(d):Re(n)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(d){Re(n)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",d)}finally{ot.finish(a)}};async function _o({keepalive:e=!1}={}){let t=!1;const s=Bt,n=Kt,a=Go,i=Xa;Bt=null,Kt=null,Go=0,et=null,Xa=[];try{if(!s||!n||Object.keys(s).length===0||!Re(n)){t=!0,Ot("saved");return}const o=ot.begin(a),r={context:n,changes:{...s}};Co.push(r),So(s);const c=()=>bR(lr(s));try{const l=Nf();if(l)try{const d=Ho(await l.save(s));if(!Re(n))return;if(d){So(d);const u=ot.reconcile(d,o);Pl(u),wl(u,!1),js=null}d||c(),t=!!d,Ot(d?"saved":"error");return}catch(d){if(!Re(n))return;console.warn("Failed to update settings via runtime settings API:",d)}if(!Re(n))return;try{const d=await C(Mf(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s),keepalive:e});if(!Re(n))return;if(!d.ok){console.warn("Failed to update shared settings via API:",d.status,d.statusText),c(),Ot("error");return}const u=Ho(await d.json().catch(()=>null));if(!Re(n))return;if(u){So(u);const m=ot.reconcile(u,o);Pl(m),wl(m,!1),t=!0,Ot("saved"),js=null}else c(),Ot("error")}catch(d){Re(n)&&(console.warn("Failed to update shared settings via API:",d),c(),Ot("error"))}}finally{Co=Co.filter(l=>l!==r),ot.finish(o)}}finally{i.forEach(o=>o({ok:t}))}}const wR=()=>qf(),Ht=async e=>{if(typeof window>"u")return{ok:!1};dr();const t=Md();Kt&&!ki(Kt,t)&&(et&&clearTimeout(et),_o());const s={};for(const o of lr(e))JI(o)&&Object.assign(s,{[o]:e[o]});const n=ot.record(s),a=kR({...Bt??{},...s});if(Object.keys(a).length===0){Bt=null,Kt=null,et&&(clearTimeout(et),et=null);const o=Xa;return Xa=[],o.forEach(r=>r({ok:!0})),Ot("saved"),{ok:!0}}Bt=a,Kt=t,Go=n,Ot("saving"),et&&clearTimeout(et);const i=new Promise(o=>{Xa.push(o)});return et=setTimeout(()=>{_o()},fR),i},vR=async()=>{if(typeof window>"u")return;const e=Ff();try{const t=await VA();if(!t)return;const s=()=>qA(t);if(e?.hasHydrated?.()){s();return}if(s(),e?.onFinishHydration){const n=e.onFinishHydration(()=>{n?.(),s()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},wV=Object.freeze(Object.defineProperty({__proto__:null,applyPersistedHomeDirectoryToWindow:Bf,getRuntimeSettingsMirrorStorageKey:yl,getSettingsSaveState:lR,initializeAppearancePreferences:vR,isApplyingServerSettings:mR,loadDesktopSettings:wR,reportSettingsSaveState:gR,subscribeToSettingsSaveState:dR,syncDesktopSettings:yR,updateDesktopSettings:Ht},Symbol.toStringTag,{value:"Module"})),vV="openchamber:chats",yc=new Map,Vf=new Map,Al=new Set,Uf=(e,...t)=>[e.replace(/[\\/]+$/,""),...t].join("/");function Wf(e){const t=ze(e);return t?Uf(t,".config","openchamber","chats"):null}function Nn(e,t){return!e.split("/").some(s=>s===".."||s===".")&&(e===t||e.startsWith(`${t}/`))}function Hf(){return Vf.get(D())}function CR(e){const t=ze(e),s=Hf();return!t||!s?null:Nn(t,s.configured)||Nn(t,s.canonicalConfigured)?s.configured:Nn(t,s.legacy)||Nn(t,s.canonicalLegacy)?s.legacy:null}function SR(e){return CR(e)!==null}function CV(e,t){if(SR(e))return!0;const s=ze(e),n=Wf(t);return!!(s&&n&&Nn(s,n))}function PR(){return Hf()?.configured??null}function SV(e){return Al.add(e),()=>Al.delete(e)}async function ji(){const e=D(),t=yc.get(e);if(t)return t;const s=Ke.getFilesystemHomeInfo().then(({home:n,chatsRoot:a,canonicalChatsRoot:i,canonicalLegacyChatsRoot:o})=>{const r=Wf(n),c=ze(a)??r;if(!r||!c)throw new Error("Unable to resolve chat directories");const l={configured:c,legacy:r,canonicalConfigured:ze(i)??c,canonicalLegacy:ze(o)??r};Vf.set(e,l);for(const d of Al)d();return l}).catch(n=>{throw yc.delete(e),n});return yc.set(e,s),s}async function AR(){await ji()}async function zR(){return(await ji()).configured}function PV(){return AR().catch(()=>{})}async function AV(e=new Date){const t=D(),s=await ji();if(D()!==t)throw new Error("Runtime changed while preparing chat directory");const n=[e.getFullYear(),String(e.getMonth()+1).padStart(2,"0"),String(e.getDate()).padStart(2,"0")].join("-"),a=globalThis.crypto?.randomUUID?.()??`${e.getTime()}-${Math.random().toString(36).slice(2)}`,i=Uf(s.configured,n,`session-${a}`);return await Ke.createDirectory(i),i}async function Gf(e,t,s){const n=ze(e);if(!n)return;const a=[t.configured,t.legacy,t.canonicalConfigured,t.canonicalLegacy];if(a.includes(n)||!a.some(o=>Nn(n,o)))return;const i=await s("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!i.ok&&i.status!==404)throw new Error(`Failed to delete chat directory (${i.status})`)}async function zV(e){if(!ze(e))return;const t=D(),s=await ji();if(D()!==t)throw new Error("Runtime changed while deleting chat directory");await Gf(e,s,C)}async function xV(e){const t=await Wm(e),s=await ji();if(D()!==e)throw new Error("Runtime changed while preparing chat cleanup");return async n=>{await t(async({fetch:a})=>{await Gf(n,s,a)})}}const xR=3e4,TR=40,IR=60,RR=(e,t,s,n,a,i,o)=>{const r=t.trim(),c=s.trim().toLowerCase();return JSON.stringify([e,r,c,n,a,i,o])},_p=(e,t)=>{try{const s=JSON.parse(e);return Array.isArray(s)&&s[1]===t}catch{return!1}},jR=yt()(oa((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,a=IR,i){if(!s||s.trim().length===0)return[];const o=s.trim(),r=D(),c=typeof n=="string"?n.trim():"",l=!!i?.includeHidden,d=i?.respectGitignore??!0,u=i?.type==="directory"?"directory":"file",m=RR(r,o,c,a,l,d,u),f=Date.now(),b=t().cache[m];if(b&&f-b.timestamp<xR)return b.files;const k=t().inFlight[m];if(k)return k;const w=u==="file"&&(l||!d)?ra()?.files:void 0,T=w?t().searchFiles(o,c,a,{type:u}):Ke.searchFiles(c,{directory:o,limit:a,type:u});let S=!1;const E=w?w.search({directory:o,query:c,maxResults:a,includeHidden:l,respectGitignore:d}).then(Z=>Z.map(N=>{const ce=N.path.replace(/\\/g,"/"),$=N.preview?.[0]?N.preview[0].replace(/\\/g,"/"):ce,lt=$.split("/").filter(Boolean).pop()||ce.split("/").filter(Boolean).pop()||"";return{name:lt,path:ce,relativePath:$,extension:lt.includes(".")?lt.split(".").pop()?.toLowerCase():void 0}})).catch(Z=>(S=!0,console.warn("Supplemental file search failed; keeping indexed results:",Z),[])):Promise.resolve([]),H=Promise.all([T,E]).then(([Z,N])=>{if(N.length===0)return Z;const ce=new Set(Z.map($=>$.path.replace(/\\/g,"/")));return[...Z,...N.filter($=>ce.has($.path)?!1:(ce.add($.path),!0))].slice(0,a)}).then(Z=>(S||e(N=>{if(N.inFlight[m]!==H)return N;const ce={...N.cache,[m]:{files:Z,timestamp:Date.now()}},$=N.cacheKeys.filter(lt=>lt!==m);for($.push(m);$.length>TR;){const lt=$.shift();lt&&delete ce[lt]}return{cache:ce,cacheKeys:$}}),Z)).finally(()=>{e(Z=>{if(Z.inFlight[m]!==H)return Z;const N={...Z.inFlight};return delete N[m],{inFlight:N}})});return e(Z=>({inFlight:{...Z.inFlight,[m]:H}})),H},invalidateDirectory(s){if(!s||s.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const n=s.trim();e(a=>{const i={...a.cache},o=a.cacheKeys.filter(l=>_p(l,n)?(delete i[l],!1):!0),r=Object.entries(a.inFlight).filter(([l])=>!_p(l,n)),c=Object.fromEntries(r);return{cache:i,cacheKeys:o,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),OR=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},zl="openchamber_stream_perf",DR=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(zl)==="1"}catch{return!1}};let _f=DR(),Kf=!1;const kn=()=>_f||Kf,Zf=()=>{kn()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},Kp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Jf=()=>{if(!kn()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},$f=e=>Array.from(e.entries()).map(([t,s])=>({metric:t,count:s.count,avg:s.count>0?Number((s.total/s.count).toFixed(3)):0,max:Number(s.max.toFixed(3)),total:Number(s.total.toFixed(3)),last:Number(s.last.toFixed(3))})).sort((t,s)=>s.total-t.total||s.count-t.count),Ed=(e,t)=>{const s=Jf();if(!s)return;const n=s.counters.get(e)??{count:0,total:0,max:0,last:0};n.count+=1,n.total+=t,n.max=Math.max(n.max,t),n.last=t,s.counters.set(e,n),s.lastUpdatedAt=Date.now()},BR=e=>{if(_f=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(zl,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(zl),Zf()}catch{}},TV=e=>{if(Kf=e,!(typeof window>"u")){if(e){Jf();return}Zf()}},FR=()=>{typeof window>"u"||(kn()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},NR=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!kn()||!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:$f(e.counters)}},IV=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!kn()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,s=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:s,durationMs:t?Math.max(0,Date.now()-t):0,entries:$f(e.counters)}},RV=(e,t=1)=>{Ed(e,t)},jV=(e,t)=>{Ed(e,t)},OV=e=>{!kn()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},DV=(e,t)=>{if(!kn())return t();const s=Kp();try{return t()}finally{Ed(e,Kp()-s)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:BR,reset:FR,getSnapshot:NR});var MR={};const ER=e=>!e.isHomeReady&&(e.currentDirectory==="/"||e.currentDirectory===""),Zp=(e,t)=>di()?t||"":!je()&&t||e,Qf=async()=>{if(je()&&!di())return null;const e=D();try{const t=await zR();return D()!==e?null:(di()&&await Ke.createDirectory(t),t)}catch{return null}};let cs=null,xl=0,Yf=!0;const mt=zi(),Jp=mt.getItem("lastDirectory"),LR=typeof Jp=="string"&&Jp.length>0,In=e=>{try{jR.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},sa=e=>ze(e)??"",qR=(e,t)=>{const s=e.trim();return s.startsWith("~")?s==="~"?t||s:(s.startsWith("~/")||s.startsWith("~\\"))&&t?`${t}${s.slice(1)}`:s:s},Po=(e,t)=>{const s=qR(e,t);return sa(s)},VR=()=>{const e=mt.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=sa(e);return t.length>0?t:null},UR=()=>{const e=mt.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=sa(e);return t.length>0?t:null},WR=()=>{if(typeof process>"u")return null;const e=MR,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const n=sa(t);return n.length>0?n:null}const s=process?.cwd?.();if(typeof s=="string"&&s.trim().length>0){const n=sa(s);return n.length>0?n:null}return null},Ld=()=>{if(typeof window<"u"){if(cs)return cs;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return cs=t,mt.setItem("homeDirectory",t),t;const s=VR();if(s&&!je())return cs=s,s}const e=WR();return e||"/"},Va=e=>{const t=ze(e);return t&&t!=="/"?t:null},Xf=async()=>{try{const s=await Ke.getFilesystemHome(),n=Va(s);if(n)return n}catch(s){console.warn("Failed to obtain filesystem home directory:",s)}if(!Yf)return"/";try{const s=await Ke.getSystemInfo(),n=Va(s?.homeDirectory);if(n)return n}catch(s){console.warn("Failed to get home directory from system info:",s)}try{const s=await dm(),n=Va(s);if(n)return n}catch(s){console.warn("Failed to obtain desktop-integrated home directory:",s)}const e=Ld(),t=Va(e);return t||e},HR=()=>{if(!je())return null;const e=Kl()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=sa(e);return t.length>0?t:null},yi=HR()||Ld(),wi=(()=>{const e=UR();return e&&!je()?Po(e,yi):je()&&!di()?yi:""})();wi&&Ke.setDirectory(wi);const GR=!!(yi&&yi!=="/"&&wi),qd=yt()(oa((e,t)=>({currentDirectory:wi,directoryHistory:[wi],historyIndex:0,homeDirectory:yi,hasPersistedDirectory:LR,isHomeReady:GR,isSwitchingDirectory:!1,setDirectory:(s,n)=>{const a=cs||t().homeDirectory||mt.getItem("homeDirectory"),i=Po(s,a);OR()&&console.log("[DirectoryStore] setDirectory called with path:",i),Ke.setDirectory(i),In(),e(o=>{const r=o.directoryHistory[o.historyIndex]===i,c=r?o.directoryHistory:[...o.directoryHistory.slice(0,o.historyIndex+1),i];return mt.setItem("lastDirectory",i),Ht({lastDirectory:i}),{currentDirectory:i,directoryHistory:c,historyIndex:r?o.historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const s=t();if(s.historyIndex>0){const n=s.historyIndex-1,a=s.directoryHistory[n];Ke.setDirectory(a),In(),mt.setItem("lastDirectory",a),Ht({lastDirectory:a}),e({currentDirectory:a,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const s=t();if(s.historyIndex<s.directoryHistory.length-1){const n=s.historyIndex+1,a=s.directoryHistory[n];Ke.setDirectory(a),In(),mt.setItem("lastDirectory",a),Ht({lastDirectory:a}),e({currentDirectory:a,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=t(),a=cs||t().homeDirectory||Ld();if(s===a)return;const i=Hv(s);i&&n(i)},goToNoProjectDirectory:async()=>{const s=D(),n=t().currentDirectory,[a,i]=await Promise.all([cs||t().homeDirectory||Xf(),Qf()]);if(D()!==s||t().currentDirectory!==n)return;const o=Zp(a,i);Ke.setDirectory(o),In(),mt.removeItem("lastDirectory"),Ht({lastDirectory:""}),e(r=>{const c=r.directoryHistory[r.historyIndex]===o,l=c?r.directoryHistory:[...r.directoryHistory.slice(0,r.historyIndex+1),o];return{currentDirectory:o,directoryHistory:l,historyIndex:c?r.historyIndex:l.length-1,hasPersistedDirectory:!1,isHomeReady:!0,isSwitchingDirectory:!1}})},synchronizeHomeDirectory:(s,n)=>{const a=t(),i=s;cs=i;const o=a.homeDirectory!==i,r=mt.getItem("lastDirectory"),c=typeof r=="string"&&r.length>0,l=Zp(i,n),d=ER(a)||!c&&(a.currentDirectory==="/"||a.currentDirectory===a.homeDirectory||a.currentDirectory===PR()||!a.currentDirectory);if(!o&&!d){a.isHomeReady||e({isHomeReady:!0});return}const u=typeof i=="string"&&i!==""&&i!=="/",m=a.currentDirectory?Po(a.currentDirectory,i):a.currentDirectory,f=a.directoryHistory.map(S=>Po(S,i)),b=f.some((S,E)=>S!==a.directoryHistory[E]),k=!!(m&&m!==a.currentDirectory),w=d&&(!je()||di())&&!n,T={homeDirectory:i,hasPersistedDirectory:c,isHomeReady:u&&!w};if(d?(T.currentDirectory=l,T.directoryHistory=[l],T.historyIndex=0,T.isSwitchingDirectory=!1):(k||b)&&(T.currentDirectory=m,T.directoryHistory=f,T.historyIndex=Math.min(a.historyIndex,f.length-1),T.isSwitchingDirectory=!1),e(()=>T),(d||k)&&u&&!w){const S=d?l:m;Ke.setDirectory(S),In(),d||(mt.setItem("lastDirectory",S),Ht({lastDirectory:S}))}Ht({homeDirectory:i})},resetForRuntimeSwitch:()=>{Ke.setDirectory(void 0),In(),e({currentDirectory:"/",directoryHistory:["/"],historyIndex:0,homeDirectory:"/",hasPersistedDirectory:!1,isHomeReady:!1,isSwitchingDirectory:!1})}}),{name:"directory-store"}));let ei=null;const Tl=()=>{const e=++xl,t=Promise.all([Xf(),Qf()]).then(([s,n])=>{if(e!==xl)return;const a=Va(s);a&&mt.setItem("homeDirectory",a),qd.getState().synchronizeHomeDirectory(s,n)}).finally(()=>{ei===t&&(ei=null)});return ei=t,t},BV=async()=>{ei&&await ei,!qd.getState().isHomeReady&&await Tl()};typeof window<"u"&&(Tl(),Yo(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Yf=!1),cs=null,xl+=1,queueMicrotask(()=>{Tl()})}));const _R=we("type",[p({id:g(),type:y("open")}),p({id:g(),type:y("message"),data:g(),binary:z()}),p({id:g(),type:y("error")}),p({id:g(),type:y("close"),code:v().int(),reason:g()})]),KR=ok("RuntimeWebSocket"),ZR=(e,t,s)=>{const n=new URL(e),a=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"||n.username||n.password?null:(n.protocol=n.protocol==="wss:"?"https:":"http:",n.origin===a.origin&&n.pathname.startsWith(a.pathname)?{...s}:null)},JR=e=>{const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let s="";for(let n=0;n<t.length;n+=8192)s+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(s)},$R=(e,t,s=[],n=KR)=>{if(new Set(s).size!==s.length||s.some(b=>!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(b)))throw new SyntaxError("Invalid WebSocket protocols");const a=crypto.randomUUID();let i=0,o=null,r=!1,c=Promise.resolve(),l=0;const d=(b,k)=>{i!==3&&(i=3,o?.remove().catch(()=>{}),o=null,globalThis.window?.removeEventListener("pagehide",f),m.onclose?.({code:b,reason:k}))},u=()=>{i!==3&&(m.onerror?.(),d(1006,""),r&&n.close({id:a,code:1e3,reason:""}).catch(()=>{}))},m={get readyState(){return i},binaryType:"arraybuffer",onopen:null,onmessage:null,onerror:null,onclose:null,send(b){if(i===0)throw new DOMException("WebSocket is connecting","InvalidStateError");if(i!==1)return;const k=b instanceof ArrayBuffer||ArrayBuffer.isView(b),w=k?b.byteLength:new TextEncoder().encode(b).byteLength;if(l+=w,l>16*1024*1024){u();return}const T=k?JR(b):b;c=c.then(async()=>{i!==3&&await n.send({id:a,data:T,binary:k})}).catch(u).finally(()=>{l-=w})},close(b=1e3,k=""){if(b!==1e3&&(b<3e3||b>4999||!Number.isInteger(b)))throw new DOMException("Invalid close code","InvalidAccessError");if(new TextEncoder().encode(k).byteLength>123)throw new SyntaxError("Close reason is too long");if(!(i>=2)){if(i=2,!r){d(1e3,"");return}c=c.then(()=>n.close({id:a,code:b,reason:k})).catch(u)}}},f=()=>m.close();return globalThis.window?.addEventListener("pagehide",f),n.addListener("socketEvent",b=>{const k=_R.safeParse(b);if(!k.success||k.data.id!==a||i===3)return;const w=k.data;switch(w.type){case"open":if(i!==0)return;i=1,m.onopen?.();break;case"message":{if(i!==1)return;let T=w.data;if(w.binary)try{T=Uint8Array.from(atob(w.data),S=>S.charCodeAt(0)).buffer}catch{u();return}m.onmessage?.({data:T});break}case"error":u();break;case"close":d(w.code,w.reason);break}}).then(async b=>{if(i===3){await b.remove();return}o=b,r=!0,c=n.open({id:a,url:e,headers:{...t},protocols:s}),await c}).catch(u),m},QR=(e,t)=>{const s=ca();if(s)return s.openWebSocket(Wk(e),t);const n=la();if(Object.keys(n).length>0&&mn()){const a=ZR(e,ls().api("/"),n);if(a)return $R(e,a,t)}return jy(new WebSocket(e))},eb=1,Mn=512*1024,wc=8*1024,YR=0,Rn=1,XR=15e3,na=new TextEncoder,Vd=new TextDecoder,Ud=R(["interactive","command"]),tb=R(["running","exited","error"]),ej=R(["node","bun"]),Wd=we("type",[p({type:y("terminal")}),p({type:y("project-action"),actionId:g(),executionId:g()})]),tj=p({sessionId:g(),cols:v(),rows:v(),status:tb,mode:Ud.optional(),purpose:Wd.optional()}),sj=p({sessionId:g(),cwd:g(),status:R(["running","exited"]),createdAt:v().nullable().optional().transform(e=>e??null),mode:Ud.optional(),purpose:Wd.optional()}),$p={mode:Ud.optional(),purpose:Wd.optional()},nj=we("t",[p({t:y("hello")}),p({t:y("pong")}),p({t:y("error"),s:g().optional(),message:g().optional(),code:g().optional(),fatal:z().optional()}),p({t:y("snapshot"),s:g(),q:v().int().nonnegative().default(0),history:g().default(""),status:tb,cols:v().int().positive().optional(),rows:v().int().positive().optional(),exitCode:v().nullish().transform(e=>e??void 0),signal:v().nullable().optional(),runtime:ej.optional(),ptyBackend:g().optional(),...$p}),p({t:y("output"),s:g(),q:v().int().nonnegative(),d:g(),r:g().optional()}),p({t:y("exit"),s:g(),q:v().int().nonnegative(),exitCode:v().nullish().transform(e=>e??void 0),signal:v().nullable().optional()}),p({t:y("restarted"),s:g(),q:v().int().nonnegative(),history:g().default(""),...$p})]),aj=e=>{const t=na.encode(JSON.stringify(e)),s=new Uint8Array(t.length+1);return s[0]=eb,s.set(t,1),s},ij=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):na.encode(e);t[0]===eb&&(t=t.subarray(1));try{return nj.safeParse(JSON.parse(Vd.decode(t))).data??null}catch{return null}};class oj extends Error{code;constructor(t,s){super(t),this.name="TerminalRequestError",this.code=s}}const FV=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,rj=p({error:g().optional(),code:g().optional()}),gr=async(e,t)=>{const s=rj.safeParse(await e.json().catch(()=>null)).data;return new oj(s?.error??t,s?.code??null)},cj=e=>{const t=na.encode(e);if(t.byteLength<=Mn)return e;let s=t.byteLength-Mn;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;return Vd.decode(t.subarray(s))},Il=e=>{for(let t=0;t<e.length;t+=1){const s=e.charCodeAt(t);if(s>=55296&&s<=56319){const n=e.charCodeAt(++t);if(n<56320||n>57343||Number.isNaN(n))return!1}else if(s>=56320&&s<=57343)return!1}return!0},Rl=e=>{if(e.malformed!==null)return e.malformed;const t=new Uint8Array(e.byteLength);let s=0;for(const n of e.parts)t.set(n.bytes.subarray(n.start,n.end),s),s+=n.end-n.start;return Vd.decode(t)},jl=(e,t)=>{if(t.length>=Mn){let n=t.length-Mn;for(;n<t.length&&(t[n]&192)===128;)n+=1;const a=t.slice(n);e.parts=[{bytes:a,start:0,end:a.length}],e.byteLength=a.length;return}const s=e.parts.at(-1);if(s&&s.bytes.length===wc&&s.end+t.length<=s.bytes.length)s.bytes.set(t,s.end),s.end+=t.length;else if(t.length<wc){const n=new Uint8Array(wc);n.set(t),e.parts.push({bytes:n,start:0,end:t.length})}else e.parts.push({bytes:t,start:0,end:t.length});for(e.byteLength+=t.length;e.byteLength>Mn;){const n=e.parts[0],a=e.byteLength-Mn,i=n.start+a;if(i>=n.end){e.byteLength-=n.end-n.start,e.parts.shift();continue}let o=i;for(;o<n.end&&(n.bytes[o]&192)===128;)o+=1;e.byteLength-=o-n.start,n.start=o,n.start===n.end&&e.parts.shift()}},lj=(e,t)=>{if(t){if(e.malformed!==null||!Il(t)){const s=cj(Rl(e)+t);if(e.parts=[],e.byteLength=0,!Il(s)){e.malformed=s;return}e.malformed=null,jl(e,na.encode(s));return}jl(e,na.encode(t))}},Qp=e=>{const t={parts:[],byteLength:0,malformed:null};return Il(e)?e&&jl(t,na.encode(e)):t.malformed=e,t},dj=p({sessions:x(Y())});class gj{constructor(t=sb(null)){this.dependencies=t}dependencies;socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=!1;subscribe(t,s){this.cancelIdleClose();const n={handlers:s,lastSequence:-1},a=this.subscribers.get(t)??new Set,i=a.size===0;a.add(n),this.subscribers.set(t,a);const o=this.projections.get(t);o&&(n.lastSequence=o.sequence,s.onEvent({type:"snapshot",sequence:o.sequence,data:Rl(o.history),cols:o.cols,rows:o.rows,status:o.status,mode:o.mode,purpose:o.purpose,exitCode:o.exitCode,signal:o.signal,runtime:o.runtime,ptyBackend:o.ptyBackend}));const r=this.socket?.readyState===Rn;return this.ensureConnected().then(()=>{const c=this.subscribers.get(t);i&&r&&c===a&&c.size>0&&this.send({t:"attach",v:3,s:t})}).catch(c=>{a.has(n)&&(s.onError?.(c,!1),this.scheduleReconnect())}),()=>{const c=this.subscribers.get(t);if(c?.delete(n),c?.size===0&&(this.subscribers.delete(t),this.projections.delete(t),this.send({t:"detach",v:3,s:t})),this.subscribers.size===0){if(this.cancelReconnect(),this.failures=0,this.socket?.readyState===Rn){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,s){if(s&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s}))))throw new Error("Terminal connection is unavailable")}dispose(){this.disposed=!0,this.generation+=1,this.opening=null,this.subscribers.clear(),this.projections.clear(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.cancelIdleClose(),this.wakeCleanup?.(),this.wakeCleanup=null,this.closeSocket()}forget(t){this.projections.delete(t)}noteResize(t,s,n){const a=this.projections.get(t);a&&this.projections.set(t,{...a,cols:s,rows:n})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===Rn)return;if(this.opening)return await this.opening,this.socket?.readyState===Rn?void 0:this.ensureConnected();const t=this.generation,s=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((n,a)=>{let i=!1,o=!1,r=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,d=()=>{r||o||!l()||(r=!0,this.dependencies.clearUrlAuthToken?.())},u=f=>{i||(i=!0,clearTimeout(m),f?a(f):n())},m=setTimeout(()=>{d(),c?.close(),u(new Error("Terminal connection timed out"))},1e4);try{const f=this.dependencies.openSocket();c=f,f.binaryType="arraybuffer",this.socket=f,f.onopen=()=>{if(!l()){f.close(),u(new Error("Terminal runtime changed"));return}o=!0,this.failures=0,this.send({t:"hello",v:3});for(const b of this.subscribers.keys())this.send({t:"attach",v:3,s:b});this.startKeepalive(),u()},f.onmessage=b=>{this.handleMessage(b.data)},f.onerror=()=>{const b=l();b&&d(),u(new Error("Terminal WebSocket failed")),b&&this.subscribers.size>0&&this.scheduleReconnect()},f.onclose=()=>{const b=l();b&&(this.stopKeepalive(),d()),this.socket===f&&(this.socket=null),u(new Error("Terminal WebSocket closed")),b&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(f){u(f instanceof Error?f:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=s;try{await s}finally{this.opening===s&&(this.opening=null)}}handleMessage(t){const s=ij(t);if(!s||s.t==="hello"||s.t==="pong")return;if(s.t==="error"){const i=new Error(s.message??"Terminal error");i.code=s.code;const o=s.s?[s.s]:[...this.subscribers.keys()];for(const r of o)for(const c of this.subscribers.get(r)??[])c.handlers.onError?.(i,s.fatal===!0);return}if(!s.s)return;const n=this.subscribers.get(s.s);if(!n)return;if(s.t==="snapshot"){const i={sequence:s.q??0,history:Qp(s.history??""),cols:s.cols,rows:s.rows,status:s.status,mode:s.mode,purpose:s.purpose,exitCode:s.exitCode,signal:s.signal??null,runtime:s.runtime,ptyBackend:s.ptyBackend};this.projections.set(s.s,i);const o=Rl(i.history);for(const r of n)r.lastSequence=i.sequence,r.handlers.onEvent({type:"snapshot",sequence:i.sequence,data:o,cols:i.cols,rows:i.rows,status:i.status,mode:i.mode,purpose:i.purpose,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend});return}const a=this.projections.get(s.s);a&&s.q>a.sequence&&(s.t==="output"?(lj(a.history,s.r??s.d),this.projections.set(s.s,{...a,sequence:s.q})):s.t==="exit"?this.projections.set(s.s,{...a,sequence:s.q,status:"exited",exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&this.projections.set(s.s,{...a,sequence:s.q,history:Qp(s.history??""),status:"running",mode:s.mode??a.mode,purpose:s.purpose??a.purpose,exitCode:void 0,signal:null}));for(const i of n)s.q<=i.lastSequence||(i.lastSequence=s.q,s.t==="output"?i.handlers.onEvent({type:"data",sequence:s.q,data:s.d,replayData:s.r}):s.t==="exit"?i.handlers.onEvent({type:"exit",sequence:s.q,exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&i.handlers.onEvent({type:"snapshot",sequence:s.q,data:s.history??"",status:"running",mode:s.mode??a?.mode,purpose:s.purpose??a?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==Rn)return!1;try{return this.socket.send(aj(t)),!0}catch{return!1}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const s=typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine?6e4:Math.min(500*2**Math.min(this.failures-1,10),8e3);for(const a of this.subscribers.values())for(const i of a)i.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const n=()=>{typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null,this.ensureConnected().catch(()=>this.scheduleReconnect()))};typeof window<"u"&&window.addEventListener("online",n),typeof document<"u"&&document.addEventListener("visibilitychange",n),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",n),typeof document<"u"&&document.removeEventListener("visibilitychange",n)},this.reconnectTimer=setTimeout(n,s)}scheduleIdleClose(){this.idleCloseTimer||this.disposed||(this.idleCloseTimer=setTimeout(()=>{this.idleCloseTimer=null,!(this.disposed||this.subscribers.size>0)&&(this.generation+=1,this.opening=null,this.closeSocket())},XR))}cancelIdleClose(){this.idleCloseTimer&&(clearTimeout(this.idleCloseTimer),this.idleCloseTimer=null)}startKeepalive(){this.stopKeepalive(),this.keepaliveTimer=setInterval(()=>this.send({t:"ping",v:3}),45e3)}stopKeepalive(){this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null}cancelReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null}closeSocket(){this.stopKeepalive();const t=this.socket;this.socket=null,t&&(t.readyState===YR||t.readyState===Rn)&&t.close()}}const pj="",Ko=new Map,uj=e=>e===null?"/api/terminal/ws":`/api/terminal/ws?directory=${encodeURIComponent(Rm(e))}`;function sb(e){return{refreshAuth:tr,openSocket:()=>QR(ls().websocket(uj(e))),clearUrlAuthToken:Ai}}function Oi(e){const t=kt(e),s=t??pj,n=Ko.get(s);if(n)return n;const a=new gj(sb(t));return Ko.set(s,a),a}async function mj(e){const t=await C("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),directory:e.cwd});if(!t.ok)throw await gr(t,"Failed to create terminal session");const s=await t.json().catch(()=>null),n=tj.safeParse(s).data;if(!n)throw new Error("Failed to create terminal session");return n}async function hj(e){const t=await C(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`,{directory:e});if(!t.ok)throw await gr(t,"Failed to list terminal sessions");const s=await t.json().catch(()=>null),n=dj.safeParse(s).data?.sessions;if(!Array.isArray(n))throw new Error("Failed to list terminal sessions");const a=[];for(const i of n){const o=sj.safeParse(i).data;o&&a.push(o)}return a}async function fj(e,t){e.length!==0&&await ma("/api/terminal/touch","POST",{sessionIds:e},t)}async function bj(){const e=await C("/api/terminal/shells");if(!e.ok)throw await gr(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(s=>s&&typeof s=="object"&&Ad(s.id)&&typeof s.name=="string"&&typeof s.supportsLogin=="boolean"):[]}function kj(e,t,s,n){return Oi(n).subscribe(e,{onEvent:t,onError:s})}async function yj(e,t,s){await Oi(s).write(e,t)}async function ma(e,t,s,n){const a={method:t,directory:n};s!==void 0&&(a.headers={"Content-Type":"application/json"},a.body=JSON.stringify(s));const i=await C(e,a);if(!i.ok)throw await gr(i,"Terminal command failed");return i}async function wj(e,t,s,n){await ma(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:s},n),Oi(n).noteResize(e,t,s)}async function vj(e,t,s){await ma(`/api/terminal/${e}/appearance`,"POST",t,s)}async function Cj(e,t){await ma(`/api/terminal/${e}`,"DELETE",void 0,t),Oi(t).forget(e)}async function Sj(e,t){return(await ma(`/api/terminal/${e}/restart`,"POST",t,t.cwd)).json()}async function Pj(e){const s=await(await ma("/api/terminal/force-kill","POST",e,e.cwd)).json().catch(()=>null),n=Oi(e.cwd);if(Array.isArray(s?.killedSessionIds))for(const a of s.killedSessionIds)typeof a=="string"&&n.forget(a);else e.sessionId&&n.forget(e.sessionId)}function NV(){for(const e of Ko.values())e.dispose();Ko.clear()}const Aj=()=>({async listShells(){return bj()},async listSessions(e){return hj(e)},async touchSessions(e,t){await fj(e,t)},async createSession(e){return mj(e)},connect(e,t,s){const n=kj(e,t.onEvent,t.onError,s);return{close:()=>n()}},async sendInput(e,t,s){await yj(e,t,s)},async resize(e){await wj(e.sessionId,e.cols,e.rows,e.directory)},async updateAppearance(e,t,s){await vj(e,t,s)},async close(e,t){await Cj(e,t)},async restartSession(e,t){return Sj(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows,themeMode:t.themeMode,terminalBackground:t.terminalBackground,terminalForeground:t.terminalForeground,shell:t.shell,loginShell:t.loginShell})},async forceKill(e){await Pj(e)}});class Hd extends Error{code;status;constructor(t,s,n){super(s),this.name="GitNetworkOperationRequestError",this.code=t,this.status=n}}class nb extends Error{code;status;remoteName;constructor(t,s,n,a){super(s),this.name="GitWorktreeRequestError",this.code=t,this.status=n,this.remoteName=a}}class zj extends Error{provider;constructor(t,s){super(t),this.name="SourceControlInstanceOtherProviderError",this.provider=s}}const xj=g().trim().min(1).max(200),ti=g().trim().min(1).max(512),lo=g().trim().max(512).nullable().optional(),Tj=p({provider:Rs,instance:ti,accountId:ti}).strict(),Ij=R(["account","ssh","system","anonymous"]),aa=p({id:xj,name:ti,userName:ti,userEmail:ti,account:Tj.nullable().optional(),transport:Ij.optional(),sshCredentialId:lo,signCommits:z().optional(),signingKey:lo,color:lo,icon:lo}).strict().superRefine((e,t)=>{e.transport==="account"&&!e.account&&t.addIssue({code:"custom",path:["account"],message:"An account transport requires an account"}),e.transport==="ssh"&&!e.sshCredentialId?.trim()&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"An SSH transport requires a managed key"}),e.transport!=="ssh"&&e.sshCredentialId&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"Only an SSH transport names a managed key"})}),MV=e=>e?.transport??"system",Rj=x(aa).max(256).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Git identity profile IDs must be unique"),ab=p({userName:g().max(512).nullable(),userEmail:g().max(512).nullable()}).strict(),jj=p({success:z(),profile:aa.nullable()}).strict(),EV=e=>!!e.userName&&!!e.userEmail&&(e.transport==="account"&&!!e.account||e.transport==="anonymous"||e.transport==="system"||e.transport===void 0||e.transport==="ssh"&&!!e.sshCredentialId),Ol=new Set,Oj=e=>(Ol.add(e),()=>{Ol.delete(e)}),ib=e=>{for(const t of Ol)t(e)},Dl=new Set,Dj=(e,t)=>JSON.stringify([t,ze(e)]);function LV(e){return Dl.add(e),()=>{Dl.delete(e)}}function Bj(e,t){const s=Dj(e,t);for(const n of Dl)n(s)}class Fj extends Error{reason;constructor(t,s){super(t),this.name="GitPathUnavailableError",this.reason=s}}const Nj=p({error:g(),code:R(["path_not_found","nested_repository","untracked_directory"])}),Gd=p({headCommit:g().nullable(),indexCommit:g().nullable(),worktreeCommit:g().nullable(),hasTrackedChanges:z(),hasUntrackedFiles:z(),hasConflict:z()}),O="/api/git",ob=p({diff:g()}),Mj=p({files:x(p({path:g(),status:g(),revision:g().optional()}))}),Ej=p({error:g()}),Lj=p({files:x(p({path:g(),previousPath:g().optional(),changeType:g(),insertions:v(),deletions:v(),isBinary:z()}))}),Yp=p({hash:g(),date:g(),message:g(),refs:g(),body:g(),author_name:g(),author_email:g(),filesChanged:v(),insertions:v(),deletions:v(),parents:x(g())}),qj=p({all:x(Yp),latest:Yp.nullable(),total:v()}),Vj=p({diff:g(),submodule:Gd.nullable().default(null)}),Uj=p({diffs:x(J([p({path:g(),diff:g(),submodule:Gd.nullable().default(null)}),p({path:g(),error:g(),code:R(["path_not_found","nested_repository","untracked_directory"]).nullable()})]))}),Wj=p({original:g(),modified:g(),path:g(),isBinary:z().optional(),submodule:Gd.nullable().default(null)});async function _d(e,t){const s=await e.json().catch(()=>null),n=p({code:y("not_repository"),error:g()}).safeParse(s);if(e.status===409&&n.success)return new Error(n.data.error);const a=Nj.safeParse(s);return a.success&&(e.status===404||e.status===422)?new Fj(a.data.error,a.data.code):new Error(`${t}: ${e.statusText}`)}async function pr(e,t){const s=Ej.safeParse(await e.json().catch(()=>null));return new Error(s.success?s.data.error:`${t}: ${e.statusText}`)}const rb=1200,cb=5e3,vi=new Map,En=new Map,lb=new Map,Zo=new Map,go=new Map,Hj=256,Gj=900*1e3,_j=3600*1e3,Di=8192,Kj=/^[A-Za-z0-9_-]{1,200}$/,Bl=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i,Zj=/^[A-Za-z0-9_-]{43}$/,Jj=/^SHA256:[A-Za-z0-9+/]{43}=?$/,Qt=e=>g().trim().min(1).max(e),db=g().regex(Kj),ur=g().regex(Zj),Ps=Qt(1024),Kd=Qt(4096),Pe=Qt(512),gb=g().min(1).max(4096).refine(e=>e.trim()===e&&!Array.from(e).some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)&&e!==".."&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")&&!/^[A-Za-z]:\//.test(e),"Checkout path must be repository-relative"),Xp=g().max(4096).refine(e=>{if(!e)return!0;try{const t=new URL(e);return!t.username&&!t.password&&!t.search&&!t.hash}catch{return e.includes("://")?!1:!/[?#]/.test(e)}},"Git remote display URLs must not contain credentials, query parameters, or fragments"),$j=x(p({name:Pe,fetchUrl:Xp,pushUrl:Xp}).strict()).max(256),Qj=p({selectionId:db,provenanceRevision:v().int().safe().positive(),sourceSha:g().regex(Bl),expiresInMs:v().int().safe().positive().max(900*1e3)}).strict(),Yj=p({remote:p({name:Pe,endpoint:p({displayUrl:Kd,fingerprint:ur}).strict()}).strict(),transportMode:y("managed"),classification:R(["contributor-fork","own-fork","bound-repository","other"])}).strict(),Xj=we("kind",[p({kind:y("ordinary")}).strict(),p({kind:y("contributor"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,provenanceRevision:v().int().safe().positive(),candidates:x(Yj).max(128)}).strict()]),eO=p({state:y("awaiting-trust"),digest:ur,actions:x(p({kind:R(["post-checkout-hook","project-start-command","setup-command"]),label:g().max(65536)}).strict()).max(3)}).strict(),Dt=new Map,tO=e=>{if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&t[1].split("/").every(s=>s&&s!=="."&&s!==".."))}try{const t=new URL(e),s=decodeURIComponent(t.pathname);return(t.protocol==="https:"||t.protocol==="ssh:")&&!t.username&&!t.password&&!t.search&&!t.hash&&!!(t.hostname&&t.pathname&&t.pathname!=="/")&&!/[\0-\x20\x7f\\]/.test(s)&&s.split("/").slice(1).every(n=>n&&n!=="."&&n!=="..")}catch{return!1}},Ln=p({displayUrl:Kd.refine(tO),fingerprint:ur}).strict(),sO=p({displayName:Qt(1024),fingerprint:ur}).strict(),nO=p({id:Pe,platform:R(["web","desktop","vscode"]),label:Qt(512).optional()}).strict(),aO=we("kind",[p({kind:y("provider"),provider:Pe,instance:Kd,accountId:Pe,login:Pe.optional()}).strict(),p({kind:y("ssh-key"),fingerprint:g().regex(Jj)}).strict()]),vc=we("mode",[p({mode:y("anonymous"),verification:p({status:y("anonymous")}).strict()}).strict(),p({mode:y("managed"),verification:p({status:y("verified"),method:R(["credential","git-identity"])}).strict(),actor:aO.optional()}).strict(),p({mode:y("system"),verification:p({status:y("unverified"),reason:y("system-credentials")}).strict()}).strict()]),iO=J([vc,p({fetch:vc,push:vc}).strict()]),Ao=p({name:Pe,endpoint:Ln}).strict(),Cc={repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Ao,sourceRef:Ps,destinationRef:Ps},oO=we("operation",[p({operation:y("push"),...Cc,forceWithLease:p({expectedRemoteSha:g().regex(Bl)}).strict().optional(),configureUpstream:z().optional()}).strict(),we("fetchScope",[p({operation:y("fetch"),fetchScope:y("ref").optional(),...Cc}).strict(),p({operation:y("fetch"),fetchScope:y("remote"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Ao,force:z()}).strict()]),p({operation:y("pull"),...Cc}).strict(),p({operation:y("delete-remote-branch"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Ao,destinationRef:Ps}).strict(),p({operation:y("checkout-hydration"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Ao,requirements:x(p({kind:R(["submodule","lfs"]),path:gb,endpoint:Ln}).strict()).max(256)}).strict(),p({operation:y("sync"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,fetch:p({name:Pe,endpoint:Ln,sourceRef:Ps,destinationRef:Ps}).strict(),pull:p({destinationRef:Ps}).strict(),push:p({name:Pe,endpoint:Ln,sourceRef:Ps,destinationRef:Ps,forceWithLease:p({expectedRemoteSha:g().regex(Bl)}).strict().optional()}).strict()}).strict(),p({operation:y("clone"),remote:Ln,destination:sO}).strict()]),rO=R(["validated","authenticated","transferred","updated-local-repository","checked-out","cleaned-up"]),mr=R(["INVALID_REQUEST","NOT_FOUND","STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","AUTHENTICATION_REQUIRED","DESTINATION_SELECTION_REQUIRED","CONTRIBUTOR_MANAGED_TRANSPORT_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","CONFLICT","CANCELLED","TIMEOUT","OUTCOME_UNKNOWN","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"]),Da=e=>p({code:R(e),message:Qt(Di)}).strict(),cO=p({step:R(["fetch","pull","push"]),status:R(["succeeded","skipped","conflicted","failed","cancelled"]),error:p({code:mr,message:Qt(Di)}).strict().optional()}).strict(),pb=R(["succeeded","authorization-required","invalid","client-missing","failed","cancelled","not-needed"]),lO=["cancelled","invalid","client-missing","authorization-required","failed"],eu=p({path:gb,status:pb,endpoint:Ln.optional(),error:p({code:mr,message:Qt(Di)}).strict().optional()}).strict().superRefine((e,t)=>{(e.status!=="succeeded"&&e.status!=="not-needed")!==(e.error!==void 0)&&t.addIssue({code:"custom",message:"Git hydration status and error do not match"})}),ub=p({status:pb,submodules:x(eu).max(256),lfs:x(eu).max(256)}).strict().superRefine((e,t)=>{const s=[...e.submodules,...e.lfs].map(a=>a.status);let n="succeeded";!s.length||s.every(a=>a==="not-needed")?n="not-needed":n=lO.find(a=>s.includes(a))??"succeeded",e.status!==n&&t.addIssue({code:"custom",message:"Git hydration summary does not match its results"})}),dO=p({status:R(["pending","ready","failed"]),phase:R(["directory-created","git-ready","setup-ready"]).optional(),error:Qt(Di).nullable(),errorCode:mr.optional(),updatedAt:v().int().safe().nonnegative(),hydration:ub.optional()}).strict().superRefine((e,t)=>{e.status!=="failed"&&(e.errorCode||e.hydration)&&t.addIssue({code:"custom",message:"Only failed worktree bootstrap status may include failure details"})}),Zd=p({error:Qt(Di),code:mr}).strict(),vs={operationId:db,runtimeIdentity:nO,transport:iO,target:oO,completedSteps:x(rO),stepResults:x(cO).length(3).optional(),hydration:ub.optional()},gO=we("state",[p({...vs,state:y("planned")}).strict(),p({...vs,state:y("running")}).strict(),p({...vs,state:y("succeeded")}).strict(),p({...vs,state:y("partial"),error:Da(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),p({...vs,state:y("failed"),error:Da(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),p({...vs,state:y("cancelled"),error:Da(["CANCELLED","TIMEOUT"])}).strict(),p({...vs,state:y("outcome-unknown"),error:Da(["OUTCOME_UNKNOWN"])}).strict(),p({...vs,state:y("conflicted"),error:Da(["STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","CONFLICT"])}).strict()]).superRefine((e,t)=>{e.target.operation==="clone"&&e.state==="partial"&&!e.completedSteps.includes("checked-out")&&t.addIssue({code:"custom",message:"Partial clone must retain a completed checkout"});const s=e.target.operation==="sync",n=e.state!=="planned"&&e.state!=="running";s&&n&&e.stepResults===void 0&&t.addIssue({code:"custom",message:"Sync operation result is missing step results"});for(const a of e.stepResults??[])(a.status!=="succeeded"&&a.status!=="skipped")!==(a.error!==void 0)&&t.addIssue({code:"custom",message:"Git sync step status and error do not match"});!s&&e.stepResults!==void 0&&t.addIssue({code:"custom",message:"Non-sync operation contains sync step results"}),e.state==="succeeded"&&e.hydration&&e.hydration.status!=="succeeded"&&e.hydration.status!=="not-needed"&&t.addIssue({code:"custom",message:"Successful Git operation contains incomplete hydration"}),s!=="fetch"in e.transport&&t.addIssue({code:"custom",message:"Git operation transport does not match its target"})}),mb=e=>e.trim(),Bi=(e,t)=>JSON.stringify([e,mb(t)]),hr=(e,t,s)=>JSON.stringify([e,mb(t),s??"full"]),Ci=(e,t)=>lb.get(Bi(e,t))??0,Jd=(e,t)=>{const s=Bi(e,t);lb.set(s,Ci(e,t)+1);for(const n of[void 0,"light"]){const a=hr(e,t,n);vi.delete(a),En.delete(a)}},pO=(e,t,s)=>JSON.stringify([e,t,s]),$d=(e=Date.now())=>{for(const[t,s]of Dt){const n=s.terminalState?_j:Gj;s.observedAt<=e-n&&Dt.delete(t)}for(;Dt.size>Hj;){let t=null;for(const[s,n]of Dt)n.terminalState&&(!t||n.observedAt<t.observedAt)&&(t={key:s,observedAt:n.observedAt});if(!t)for(const[s,n]of Dt)(!t||n.observedAt<t.observedAt)&&(t={key:s,observedAt:n.observedAt});if(!t)return;Dt.delete(t.key)}},Fl=(e,t,s)=>{$d();for(const[n,a]of Dt)if(a.runtimeKey===e&&a.operationId===t&&(!s||a.runtimeIdentity.id===s))return{key:n,value:a};return null},uO=(e,t)=>{let s=null;for(const[n,a]of Dt)if(a.runtimeKey===e&&a.operationId===t){if(s)return;s=n}s&&Dt.delete(s)},mO=(e,t)=>{$d();const s=Date.now();for(const n of Dt.values())n.runtimeKey===e&&n.operationId===t&&!n.terminalState&&(n.observedAt=s)},Gt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),hO=e=>JSON.stringify(e,(t,s)=>{if(t==="forceWithLease")return;if(t!=="displayUrl")return s;const n=g().safeParse(s);if(!n.success||n.data.includes("://"))return s;const a=n.data.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/);return a?`${a[1]}:${a[2]}`:n.data}),fO=e=>{const t=e.trim();try{const s=new URL(t);return s.username="",s.password="",s.hostname=s.hostname.toLowerCase(),s.search="",s.hash="",s.toString().replace(/\/$/,"")}catch{const s=t.match(/^([^@/:\s]+)@([^/:\s]+):(.+)$/);return s?`${s[1]}@${s[2].toLowerCase()}:${s[3].replace(/[?#].*$/,"")}`:t.replace(/[?#].*$/,"")}},bO=(e,t)=>{if(t.target.operation!==e.operation)throw new Error("Malformed Git network operation plan response");if(e.operation==="sync"){if(!("fetch"in t.transport)||t.transport.fetch.mode!==e.fetch.transportMode||t.transport.push.mode!==e.push.transportMode)throw new Error("Malformed Git network operation plan response");const a={...e.push.remote,sourceRef:e.push.sourceRef,destinationRef:e.push.destinationRef,forceWithLease:e.push.forceWithLease},i={operation:"sync",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,fetch:{...e.fetch.remote,sourceRef:e.fetch.sourceRef,destinationRef:e.fetch.destinationRef},pull:e.pull,push:a};if(!Gt(t.target,i))throw new Error("Malformed Git network operation plan response");return}if("fetch"in t.transport)throw new Error("Malformed Git network operation plan response");if(e.operation==="checkout-hydration"){const a=t.target;if(a.operation!=="checkout-hydration"||!Gt({repositoryId:a.repositoryId,bindingRevision:a.bindingRevision,configRevision:a.configRevision,remote:a.remote},{repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote}))throw new Error("Malformed Git network operation plan response");return}if(t.transport.mode!==e.transportMode)throw new Error("Malformed Git network operation plan response");if(e.operation==="clone"){const a=t.target;if(a.operation!=="clone")throw new Error("Malformed Git network operation plan response");const i=e.destinationPath.trim().split(/[\\/]/).filter(Boolean).at(-1);if(a.remote.displayUrl!==fO(e.remoteUrl)||a.destination.displayName!==i)throw new Error("Malformed Git network operation plan response");return}if(e.operation==="delete-remote-branch"){if(!Gt(t.target,{operation:"delete-remote-branch",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,destinationRef:e.destinationRef}))throw new Error("Malformed Git network operation plan response");return}if(e.operation==="fetch"&&e.fetchScope==="remote"){const a=t.target;if(a.operation!=="fetch"||a.fetchScope!=="remote"||!Gt(a,{operation:"fetch",fetchScope:"remote",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,force:a.force}))throw new Error("Malformed Git network operation plan response");return}const s={repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,sourceRef:e.sourceRef,destinationRef:e.destinationRef},n=e.operation==="fetch"?{operation:"fetch",fetchScope:e.fetchScope,...s}:{operation:e.operation,...s};if(e.operation==="push"&&e.forceWithLease&&Object.assign(n,{forceWithLease:e.forceWithLease}),e.operation==="push"&&e.configureUpstream&&Object.assign(n,{configureUpstream:!0}),!Gt(t.target,n))throw new Error("Malformed Git network operation plan response")},kO=e=>e.target.operation==="clone"?!1:e.state==="succeeded"?!0:e.completedSteps.includes("transferred")||e.completedSteps.includes("updated-local-repository"),Nl=(e,t,s=!1)=>"fetch"in e||"fetch"in t?"fetch"in e&&"fetch"in t&&Nl(e.fetch,t.fetch,s)&&Nl(e.push,t.push,s):e.mode===t.mode&&Gt(e.verification,t.verification)&&(e.mode!=="managed"||t.mode==="managed"&&(!e.actor||s&&!t.actor||Gt(e.actor,t.actor)));Oj(e=>{Jd(D(),e),Zo.delete(Bi(D(),e))});const ha=e=>{ib(e)},xe=async(e,t)=>{const s=await t.json();return ha(e),s};function B(e,t,s){const n={...s};return t&&(n.directory=t),ls().api(e,n)}const yO=15,tu=200,wO=e=>e==="worktrees"?`${O}/project-worktrees`:`${O}/projects`,vO=(e,t)=>JSON.stringify(e==="status"||e==="root"?{directories:t,fields:[e]}:{directories:t}),CO=(e,t)=>`${e}\0${kt(t)??""}`,si=new Map,su=async e=>{const t=si.get(e);if(si.delete(e),!t)return;if(t.runtimeKey!==D()){const r=new Error("Runtime changed before project repository batch was sent");for(const c of t.waiters.values())for(const l of c)l.reject(r);return}const s=[...t.waiters.keys()],n=new Map;for(const r of s)n.set(r,Ci(t.runtimeKey,r));const a=wO(t.field),i=new Map,o=[];for(let r=0;r<s.length;r+=tu)o.push(s.slice(r,r+tu));await Promise.all(o.map(async r=>{try{const c=await C(B(a,r[0]),{method:"POST",headers:{"Content-Type":"application/json"},body:vO(t.field,r)});if(!c.ok)throw new Error(`Failed to read project repositories: ${c.statusText}`);const l=await c.json();for(const d of l?.projects??[])i.set(d.directory,d)}catch(c){const l=c instanceof Error?c.message:"Failed to read project repositories";for(const d of r)i.set(d,{directory:d,error:l})}}));for(const[r,c]of i)typeof c.isGitRepository=="boolean"&&Zo.set(Bi(t.runtimeKey,r),{value:c.isGitRepository,expiresAt:Date.now()+cb}),c.status&&Ci(t.runtimeKey,r)===n.get(r)&&vi.set(hr(t.runtimeKey,r,void 0),{value:c.status,expiresAt:Date.now()+rb});for(const[r,c]of t.waiters){const l=i.get(r)??null;for(const d of c)l?l.error?d.reject(new Error(l.error)):l.errors?.includes(t.field)?d.reject(new Error(`Failed to read project ${t.field}`)):d.resolve(l):d.reject(new Error("Project repository read missing from batch response"))}},fr=(e,t)=>{const s=D(),n=CO(t,e),a=si.get(n);a&&a.runtimeKey!==s&&su(n);let i=si.get(n);i||(i={runtimeKey:s,field:t,waiters:new Map,timer:null},si.set(n,i));const o=i;return new Promise((r,c)=>{const l=o.waiters.get(e)??[];l.push({resolve:r,reject:c}),o.waiters.set(e,l),o.timer===null&&(o.timer=setTimeout(()=>{su(n)},yO))})};async function SO(e){const t=D(),s=Date.now(),n=e.filter(a=>{const i=hr(t,a,void 0),o=vi.get(i);return!(o&&o.expiresAt>s)&&!En.has(i)});await Promise.allSettled(n.map(a=>fr(a,"status")))}async function PO(e){const t=Bi(D(),e),s=Date.now(),n=Zo.get(t);if(n&&n.expiresAt>s)return n.value;const a=go.get(t);if(a)return a;const i=(async()=>{const r=(await fr(e,"repo")).isGitRepository===!0;return Zo.set(t,{value:r,expiresAt:Date.now()+cb}),r})();go.set(t,i);try{return await i}finally{go.get(t)===i&&go.delete(t)}}class AO extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function qV(e){const t=await C("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new AO;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const s=await t.json();if(!Array.isArray(s?.repositories))throw new Error("Unexpected git directories response");return s.repositories.map(n=>ze(n?.path??null)).filter(n=>n!==null)}async function zO(e,t){const s=t?.mode,n=D();t?.fresh&&Jd(n,e);const a=hr(n,e,s),i=Date.now(),o=vi.get(a);if(o&&o.expiresAt>i)return o.value;const r=En.get(a);if(r)return r;const c=(async()=>{const l=Ci(n,e),d=await C(B(`${O}/status`,e,s?{mode:s}:void 0));if(!d.ok)throw new Error(`Failed to get git status: ${d.statusText}`);const u=await d.json();return Ci(n,e)===l&&vi.set(a,{value:u,expiresAt:Date.now()+rb}),u})();En.set(a,c);try{return await c}finally{En.get(a)===c&&En.delete(a)}}async function VV(e){const t=await fr(e,"root");return{root:t.root?t.root:e}}async function UV(e){const t=await C(B(`${O}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve the repository folder: ${t.statusText}`);const s=await t.json().catch(()=>({}));if(s.prefix===void 0||s.prefix===null)throw new Error("The server did not report the repository folder");return s.prefix}async function WV(e){const t=await C(B(`${O}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const s=await t.json().catch(()=>({}));return{root:typeof s.root=="string"&&s.root?s.root:e}}async function HV(e,t){const s=await C(B(`${O}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!s.ok)throw new Error(`Failed to get git commit summaries: ${s.statusText}`);const n=await s.json().catch(()=>({}));return{commits:Array.isArray(n.commits)?n.commits.map(a=>({sha:typeof a.sha=="string"?a.sha:"",short:typeof a.short=="string"?a.short:"",subject:typeof a.subject=="string"?a.subject:""})).filter(a=>a.sha&&a.short):[]}}async function xO(e,t){const{path:s,staged:n,contextLines:a}=t;if(!s)throw new Error("path is required to fetch git diff");const i=await C(B(`${O}/diff`,e,{path:s,staged:n?"true":void 0,context:a}));if(!i.ok)throw await _d(i,"Failed to get git diff");return Vj.parse(await i.json())}const nu=1e3;async function TO(e,t){const{paths:s,staged:n,contextLines:a}=t,i=[];for(let o=0;o<s.length;o+=nu){const r=await C(B(`${O}/diffs`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s.slice(o,o+nu),staged:n===!0,context:a})});if(!r.ok)throw await _d(r,"Failed to get git diffs");for(const c of Uj.parse(await r.json()).diffs)i.push("diff"in c?{path:c.path,ok:!0,diff:{diff:c.diff,submodule:c.submodule}}:{path:c.path,ok:!1,error:c.error,reason:c.code})}return i}async function IO(e,t){const{base:s,head:n,path:a,contextLines:i,includeWorkingTree:o}=t;if(!s||!n)throw new Error("base and head are required to fetch git range diff");const r=await C(B(`${O}/range-diff`,e,{base:s,head:n,path:a||void 0,context:i,includeWorkingTree:o}));if(!r.ok)throw await pr(r,"Failed to get git range diff");return ob.parse(await r.json())}async function RO(e,t){const s=await C(B(`${O}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!s.ok)throw await pr(s,"Failed to get commit diff");return ob.parse(await s.json())}async function jO(e,t){const{base:s,head:n,includeWorkingTree:a}=t;if(!s||!n)throw new Error("base and head are required to fetch git range files");const i=await C(B(`${O}/range-files`,e,{base:s,head:n,includeWorkingTree:a}));if(!i.ok)throw await pr(i,"Failed to get git range files");return Mj.parse(await i.json()).files}async function OO(e,t){if(!t)throw new Error("branch is required to get branch base");const s=await C(B(`${O}/branch-base`,e,{branch:t}));if(!s.ok)throw new Error(`Failed to get branch base: ${s.statusText}`);return s.json()}async function DO(e,t){const{path:s,staged:n}=t;if(!s)throw new Error("path is required to fetch git file diff");const a=await C(B(`${O}/file-diff`,e,{path:s,staged:n?"true":void 0}));if(!a.ok)throw await _d(a,"Failed to get git file diff");return Wj.parse(await a.json())}async function BO(e,t,s){if(!t)throw new Error("path is required to revert git changes");const n=await C(B(`${O}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:s?.scope})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to revert git changes")}ha(e)}async function FO(e,t){await hb(e,[t])}async function hb(e,t){const s=t.map(a=>a.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to stage git changes");const n=await C(B(`${O}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to stage git changes")}ha(e)}async function NO(e,t){await fb(e,[t])}async function fb(e,t){const s=t.map(a=>a.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to unstage git changes");const n=await C(B(`${O}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to unstage git changes")}ha(e)}async function MO(e,t,s){await Qd(e,t,s,"stage")}async function EO(e,t,s){await Qd(e,t,s,"unstage")}async function LO(e,t,s){await Qd(e,t,s,"discard")}async function Qd(e,t,s,n){if(!t)throw new Error("path is required to apply a git hunk");if(typeof s!="string"||!s.trim())throw new Error("patch is required to apply a git hunk");const a=await C(B(`${O}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:s,action:n})});if(!a.ok){const i=await a.json().catch(()=>({error:a.statusText}));throw new Error(i.error||"Failed to apply git hunk")}ha(e)}async function qO(e){if(!e)return!1;const t=await C(B(`${O}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function VO(e,t){const s=await C(B(`${O}/branches`,e,t?.remote?{remote:t.remote}:void 0));if(!s.ok)throw new Error(`Failed to get branches: ${s.statusText}`);return s.json()}async function UO(e,t){const s=await C(B(`${O}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!s.ok)throw new Error(`Failed to get branch push status: ${s.statusText}`);return s.json()}async function WO(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const s=await C(B(`${O}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to delete branch")}return xe(e,s)}async function HO(e,t){const s=t?.remote?.trim();if(!s)throw new Error("remote is required to remove a remote");const n=await C(B(`${O}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:s})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to remove remote")}return xe(e,n)}async function GO(e,t,s){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const n={files:t};s?.zenModel&&(n.zenModel=s.zenModel),s?.providerId&&(n.providerId=s.providerId),s?.modelId&&(n.modelId=s.modelId);const a=await C(B(`${O}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok){const c=await a.json().catch(()=>({error:a.statusText}));console.error("[git-generation][browser] http error",{status:a.status,statusText:a.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const i=await a.json();if(!i?.message||typeof i.message!="object")throw new Error("Malformed commit generation response");const o=typeof i.message.subject=="string"&&i.message.subject.trim().length>0?i.message.subject.trim():"",r=Array.isArray(i.message.highlights)?i.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:o,highlights:r}}}async function _O(e,t){const{base:s,head:n,context:a,zenModel:i,providerId:o,modelId:r}=t;if(!s||!n)throw new Error("base and head are required");const c={base:s,head:n};a?.trim()&&(c.context=a.trim()),i&&(c.zenModel=i),o&&(c.providerId=o),r&&(c.modelId=r);const l=await C(B(`${O}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const f=await l.json().catch(()=>({error:l.statusText}));throw new Error(f.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),u=typeof d?.title=="string"?d.title:"",m=typeof d?.body=="string"?d.body:"";if(!u&&!m)throw new Error("Malformed PR description response");return{title:u,body:m}}async function au(e){return(await fr(e,"worktrees")).worktrees??[]}async function iu(e,t){const s=await C(B(`${O}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to validate worktree")}return s.json()}async function KO(e){const t=await C(B(`${O}/worktrees/bootstrap-status`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to get worktree bootstrap status")}return dO.parse(await t.json())}async function ZO(e,t){const s=await C(B(`${O}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to preview worktree")}return s.json()}async function ou(e,t){const s=await C(B(`${O}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=p({error:g().optional(),code:g().optional(),remoteName:g().optional()}).strict().parse(await s.json().catch(()=>({error:s.statusText})));throw new nb(n.code||"UNKNOWN",n.error||"Failed to create worktree",s.status,n.remoteName)}return s.json()}async function ru(e,t){const s=await C(B(`${O}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to delete worktree")}return s.json()}const JO=p({title:g(),branch:g()});async function $O(e,t,s="user"){const n=await C(B(`${O}/worktrees/title`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t,by:s})}),a=await n.json().catch(()=>null);if(!n.ok){const o=p({error:g()}).safeParse(a).data?.error;throw new Error(o||"Failed to rename the task")}const i=JO.safeParse(a);if(!i.success)throw new Error("Malformed task title response");return i.data}const QO=p({pinned:z(),branch:g()});async function YO(e,t,s=null){const n=await C(B(`${O}/worktrees/pin`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s?{pinned:t,list:s}:{pinned:t})}),a=await n.json().catch(()=>null);if(!n.ok){const o=p({error:g()}).safeParse(a).data?.error;throw new Error(o||"Failed to pin the task")}const i=QO.safeParse(a);if(!i.success)throw new Error("Malformed pin response");return i.data}const bb=p({id:g().min(1),ref:g().min(1),commit:g().min(1),head:g(),path:g().min(1),branch:g(),branchExists:z(),title:g(),archivedAt:v(),sessionIds:x(g())}),br=async(e,t,s,n,a)=>{const i=await C(B(`${O}/worktrees/archives${e}`,t),{...s,headers:s.body?{"Content-Type":"application/json"}:void 0});if(!i.ok){const o=p({error:g().optional(),code:g().optional()}).catch({}).parse(await i.json().catch(()=>null)),r=o.error||i.statusText||a;throw o.code?new nb(o.code,r,i.status):new Error(r)}return n.parse(await i.json())},XO=(e,t)=>br("",e,{method:"POST",body:JSON.stringify(t)},bb,"Failed to archive worktree"),eD=async e=>(await br("",e,{method:"GET"},p({archives:x(bb)}),"Failed to list worktree archives")).archives,tD=(e,t)=>br("/restore",e,{method:"POST",body:JSON.stringify({id:t})},p({id:g(),conflicts:z()}),"Failed to restore worktree archive"),sD=(e,t)=>br("",e,{method:"DELETE",body:JSON.stringify(t)},p({id:g(),branchDeleted:z()}),"Failed to delete worktree archive"),nD=p({ref:g(),commit:g().min(1),head:g().min(1)});async function aD(e,t){const s=await C(B(`${O}/worktrees/snapshot`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to snapshot worktree")}return nD.parse(await s.json())}async function iD(e,t,s={}){const n=await C(B(`${O}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:s.addAll??!1,files:s.files,stageFiles:s.stageFiles})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to create commit")}return xe(e,n)}async function oD(e,t={}){const s=D(),n=await C(B(`${O}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to push")}const a=await xe(e,n);return a.success&&Bj(e,s),a}async function rD(e,t={}){const s=await C(B(`${O}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to pull")}return xe(e,s)}async function cD(e,t={}){const s=await C(B(`${O}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to fetch")}return xe(e,s)}const kb=async(e,t,s)=>{const n=await C(e,t);if(!n.ok){const a=Zd.parse(await n.json());throw a.code==="NOT_FOUND"&&s&&uO(s.runtimeKey,s.operationId),new Hd(a.code,a.error,n.status)}return gO.parse(await n.json())},lD=(e,t,s)=>{if(s.operationId!==e)throw new Error("Malformed Git network operation response");const n=Fl(t,e,s.runtimeIdentity.id);if(!n&&Fl(t,e))throw new Error("Malformed Git network operation response");if(n){const a=n.value.transport,i=s.state!=="planned"&&s.state!=="running",o=Gt(n.value.target,s.target)||i&&hO(n.value.target)===JSON.stringify(s.target);if(!Gt(n.value.runtimeIdentity,s.runtimeIdentity)||!o||!Nl(a,s.transport,i))throw new Error("Malformed Git network operation response");if(n.value.terminalState&&(s.state==="planned"||s.state==="running"||s.state!==n.value.terminalState))throw new Error("Malformed Git network operation response");Gt(a,s.transport)===!1&&(n.value.transport=s.transport),s.state!=="planned"&&s.state!=="running"?n.value.terminalState||(kO(s)&&(Jd(n.value.runtimeKey,n.value.directory),n.value.runtimeKey===D()&&ib(n.value.directory)),n.value.terminalState=s.state,n.value.observedAt=Date.now()):n.value.observedAt=Date.now()}if(D()!==t)throw new Error("Git network operation response belongs to a stale runtime");return s};async function dD(e){const t=D(),s=await kb(`${O}/network-operations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(s.state!=="planned")throw new Error("Malformed Git network operation plan response");if(D()!==t)throw new Error("Git network operation response belongs to a stale runtime");bO(e,s);const n=pO(t,s.runtimeIdentity.id,s.operationId);if(Fl(t,s.operationId,s.runtimeIdentity.id)?.value.terminalState)throw new Error("Malformed Git network operation plan response");return Dt.set(n,{operationId:s.operationId,runtimeKey:t,directory:e.operation==="clone"?e.destinationPath:e.directory,runtimeIdentity:s.runtimeIdentity,transport:s.transport,target:s.target,observedAt:Date.now()}),$d(),s}async function gD(e){const t=await C(`${O}/contributor-destinations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const s=Zd.parse(await t.json());throw new Hd(s.code,s.error,t.status)}return Qj.parse(await t.json())}async function pD(e){const t=D(),s=await C(B(`${O}/contributor-destinations`,e));if(!s.ok){const a=Zd.parse(await s.json());throw new Hd(a.code,a.error,s.status)}const n=Xj.parse(await s.json());if(D()!==t)throw new Error("Contributor destinations belong to a stale runtime");return n}async function uD(e){const t=await C(B(`${O}/worktrees/checkout-trust`,e));if(!t.ok)throw new Error((await t.json()).error||"Failed to inspect checkout actions");return eO.parse(await t.json())}async function mD(e,t,s){const n=await C(B(`${O}/worktrees/checkout-trust`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({digest:t,decision:s})});if(!n.ok)throw new Error((await n.json()).error||"Failed to apply checkout trust decision");return p({state:g().min(1)}).passthrough().parse(await n.json())}const Yd=async(e,t)=>{const s=D();mO(s,e);const n=t?`/${t}`:"",a=t?{method:"POST"}:void 0,i=await kb(`${O}/network-operations/${encodeURIComponent(e)}${n}`,a,{runtimeKey:s,operationId:e});return lD(e,s,i)};async function hD(e){return Yd(e,"execute")}async function fD(e){return Yd(e)}async function bD(e){return Yd(e,"cancel")}async function kD(e){const t=await C(B(`${O}/stashes`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to list stashes")}return t.json()}async function yD(e,t){const s=await C(B(`${O}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to count stash files")}return s.json()}async function yb(e,t={}){const s=await C(B(`${O}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to stash changes")}return xe(e,s)}const Xd=async(e,t,s)=>{const n=await C(B(`${O}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||`Failed to ${t}`)}return xe(e,n)},wD=(e,t)=>Xd(e,"stash/apply",t),wb=(e,t)=>Xd(e,"stash/pop",t),vD=(e,t)=>Xd(e,"stash/drop",t);async function CD(e,t){const s=await C(B(`${O}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to checkout branch")}return xe(e,s)}async function SD(e,t,s){const n=await C(B(`${O}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:s})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to create branch")}return xe(e,n)}async function PD(e,t,s){const n=await C(B(`${O}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:s})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to rename branch")}return xe(e,n)}async function AD(e,t={}){const s=await C(B(`${O}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(`Failed to get git log: ${n.error||s.statusText}`)}return qj.parse(await s.json())}const zD=p({sha:g().regex(/^[0-9a-f]{40}$/),changeId:g().regex(/^I[0-9a-f]{40}$/)});async function xD(e,t){const s=await C(B(`${O}/change-id`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedHead:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to add a Change-Id")}return ha(e),zD.parse(await s.json())}async function TD(e,t){const s=await C(B(`${O}/commit-files`,e,{hash:t}));if(!s.ok)throw await pr(s,"Failed to get commit files");return Lj.parse(await s.json())}async function ID(e,t,s,n){const a=await C(B(`${O}/commit-file-diff`,e,{hash:t,path:s,binary:n?"true":void 0}));if(!a.ok)throw new Error(`Failed to get commit file diff: ${a.statusText}`);return a.json()}async function RD(){const e=await C(B(`${O}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return Rj.parse(await e.json())}async function jD(e){const t=aa.parse(e),s=await C(B(`${O}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to create git identity")}return aa.parse(await s.json())}async function OD(e,t){const s=aa.parse(t);if(s.id!==e)throw new Error("Git identity profile ID does not match the update target");const n=await C(B(`${O}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to update git identity")}return aa.parse(await n.json())}async function DD(e){const t=await C(B(`${O}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to delete git identity")}}async function BD(e){if(!e)return null;const t=await C(B(`${O}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const s=await t.json();return s?ab.parse(s):null}async function FD(e){if(!e)return!1;const t=await C(B(`${O}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function ND(){const e=await C(B(`${O}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();if(!t)return null;const s=ab.parse(t);return s.userName||s.userEmail?s:null}async function MD(e,t){const s=await C(B(`${O}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to set git identity")}return jj.parse(await s.json())}async function ED(e){const t=await C(B(`${O}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return $j.parse(await t.json())}async function LD(e,t){const s=await C(B(`${O}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to rebase")}return xe(e,s)}async function qD(e){const t=await C(B(`${O}/rebase/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort rebase")}return xe(e,t)}async function VD(e,t){const s=await C(B(`${O}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to merge")}return xe(e,s)}async function UD(e,t){const s=await C(B(`${O}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to checkout commit")}return xe(e,s)}async function WD(e,t){const s=await C(B(`${O}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to cherry-pick")}return xe(e,s)}async function HD(e,t){const s=await C(B(`${O}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to revert commit")}return xe(e,s)}async function GD(e,t,s,n){const a=await C(B(`${O}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:s,force:n})});if(!a.ok){const i=await a.json().catch(()=>({error:a.statusText}));throw new Error(i.error||"Failed to reset")}return xe(e,a)}async function _D(e){const t=await C(B(`${O}/merge/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort merge")}return xe(e,t)}async function KD(e){const t=await C(B(`${O}/rebase/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue rebase")}return xe(e,t)}async function ZD(e){const t=await C(B(`${O}/merge/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue merge")}return xe(e,t)}async function JD(e,t){return await yb(e,{message:t?.message}),{success:!0}}async function $D(e){return await wb(e,{ref:"stash@{0}"}),{success:!0}}async function QD(e){const t=await C(B(`${O}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function YD(e,t){const s=await C(`${O}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!s.ok)throw new Error(`Failed to validate worktree directory: ${s.statusText}`);return s.json()}async function XD(e){const t=await C(`${O}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const eB=/^[a-z][a-z0-9-]{0,31}$/,vb=e=>Object.prototype.toString.call(e)==="[object String]"&&eB.test(e),tB=e=>Object.prototype.toString.call(e)==="[object String]"&&/^[\x20-\x39\x3b-\x7e]{1,256}$/.test(e)&&e.trim()===e,Cb=e=>e!==null&&Object.prototype.toString.call(e)==="[object Object]"&&Object.getPrototypeOf(e)===Object.prototype,sB=e=>Object.prototype.toString.call(e)==="[object String]",ut=e=>sB(e)&&e.length>0,cu=(e,t=512)=>ut(e)&&e.length<=t&&e.trim()===e&&!/[\0\r\n]/.test(e),nB=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/,aB=e=>{const t=e.toLowerCase();return t==="localhost"||t==="::1"||t==="[::1]"||nB.test(t)},iB=e=>{if(!e.instance.includes("://"))return/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(e.instance);try{const t=new URL(e.instance),s=aB(t.hostname);return t.origin===e.instance&&!t.username&&!t.password&&["","/"].includes(t.pathname)&&!t.search&&!t.hash&&(t.protocol==="https:"||t.protocol==="http:"&&s)}catch{return!1}},oB=e=>e.providerUserId.startsWith(`${e.instance}#`)&&/^\d+$/.test(e.providerUserId.slice(e.instance.length+1)),os=(e,t,s=[])=>Cb(e)&&t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>t.includes(n)||s.includes(n)),lu=e=>{let t;try{t=decodeURIComponent(e)}catch{return!1}const s=t.replace(/^\/+|\/+$/g,"");return!!(s&&!/[\0\r\n]/.test(s)&&!s.split("/").some(n=>!n||n==="."||n===".."))},rB=e=>{if(!ut(e)||e.trim()!==e||e.length>4096||/[\0\r\n]/.test(e))return!1;if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&lu(`/${t[1]}`))}try{const t=new URL(e);return["http:","https:","ssh:"].includes(t.protocol)&&!!t.hostname&&(!t.username||t.protocol==="ssh:")&&!t.password&&!t.search&&!t.hash&&lu(t.pathname)}catch{return!1}},Ml=e=>os(e,["displayUrl","fingerprint"])&&rB(e.displayUrl)&&ut(e.fingerprint)&&e.fingerprint.length<=128&&/^[A-Za-z0-9_-]+$/.test(e.fingerprint),po=Ml,du=e=>["managed","system","anonymous"].includes(e.mode)&&(e.mode==="managed"?ut(e.credentialId):!Object.hasOwn(e,"credentialId")),cB=e=>Cb(e)&&Object.hasOwn(e,"status")&&(e.status==="unavailable"&&os(e,["status"])||e.status==="available"&&(os(e,["status","transport","fingerprint"])&&e.transport==="ssh"&&/^SHA256:[A-Za-z0-9+/]{43}=?$/.test(e.fingerprint)||os(e,["status","transport","provider","instance","source","username","providerUserId"])&&e.transport==="https"&&vb(e.provider)&&["oauth","pat","cli"].includes(e.source)&&cu(e.instance,2048)&&tB(e.username)&&cu(e.providerUserId)&&iB(e)&&oB(e))),Sc=(e,t)=>new Set(e.map(t)).size===e.length,Ba=()=>Object.assign(new Error("Source control binding storage is invalid"),{code:"INVALID_SOURCE_CONTROL_BINDINGS"}),lB=(e,t=!1)=>{if(!os(e,["repositoryId","revision","state","configRevision","providers","remotes"],["auxiliary"])||!ut(e.repositoryId)||!Number.isSafeInteger(e.revision)||e.revision<1||!ut(e.configRevision)||!["bound","needs-attention"].includes(e.state)||!Array.isArray(e.providers)||!Array.isArray(e.remotes)||!Array.isArray(e.auxiliary))throw Ba();for(const s of e.providers)if(!os(s,["provider","instance","accountId","primaryRemote","readiness","endpoint"],["repository"])||!vb(s.provider)||!ut(s.instance)||!ut(s.accountId)||!ut(s.primaryRemote)||s.repository!==void 0&&(!os(s.repository,["owner","name"])||!ut(s.repository.owner)||!ut(s.repository.name))||!["ready","confirmation-required","account-unavailable","config-changed"].includes(s.readiness)||!(s.endpoint===null&&s.readiness!=="ready"||po(s.endpoint)))throw Ba();for(const s of e.remotes)if(!os(s,["name","fetch","push","mode","readiness"],["credentialId",...t&&s.mode==="managed"?["presentation"]:[],...t?["inherited"]:[]])||!ut(s.name)||!po(s.fetch)||!po(s.push)||!du(s)||s.presentation!==void 0&&!cB(s.presentation)||s.inherited!==void 0&&(s.inherited!==!0||s.readiness!=="ready")||s.mode==="anonymous"&&!s.fetch.displayUrl.startsWith("https://")||!["ready","confirmation-required","config-changed"].includes(s.readiness))throw Ba();for(const s of e.auxiliary??[])if(!os(s,["kind","endpoint","mode","readiness"],["credentialId"])||!["submodule","lfs"].includes(s.kind)||!po(s.endpoint)||!du(s)||s.mode==="anonymous"&&!s.endpoint.displayUrl.startsWith("https://")||!["ready","confirmation-required"].includes(s.readiness))throw Ba();if((e.auxiliary?.length??0)>256||!Sc(e.remotes,s=>s.name)||!Sc(e.providers,s=>`${s.provider}\0${s.instance}\0${s.primaryRemote}`)||!Sc(e.auxiliary??[],s=>`${s.kind}\0${s.endpoint.fingerprint}`))throw Ba()},dB=e=>[...e.providers,...e.remotes,...e.auxiliary].some(t=>t.readiness!=="ready")?"needs-attention":"bound",gB=e=>(lB(e,!0),structuredClone(e)),pB=(e,t)=>{const s=new Map(t.remotes.map(o=>[o.name,o])),n=e.providers.map(o=>o.readiness==="ready"&&o.endpoint?.fingerprint!==s.get(o.primaryRemote)?.fetch.fingerprint?{...o,readiness:"config-changed"}:o),a=e.remotes.map(o=>{const r=s.get(o.name);return o.readiness==="ready"&&(!r||o.fetch.fingerprint!==r.fetch.fingerprint||o.push.fingerprint!==r.push.fingerprint)?{...o,readiness:"config-changed"}:o}),i={...e,providers:n,remotes:a};return i.state=dB(i),i},gu={referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1},Sb=[{id:"github",label:"GitHub",order:0,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"github",filledSprite:"github-fill"},repository:{nestedNamespaces:!1},instances:{format:"host",defaultInstance:"github.com",multiple:!0,allowLoopbackHttp:!1,allowPort:!1,reserved:["github.com"],placeholder:"https://github.example.com",legacyFlow:{instance:"github.com",kind:"github-com-device"}},auth:{methods:["device","pat","cli"],cliName:"gh",cliTransport:!0,token:{scopes:["repo","read:org","workflow","read:user","user:email"],createPath:"/settings/tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:!1},{id:"token",kind:"personal-access-token",secret:!0}]},urls:{changeRequest:["/{owner}/{repo}/pull/{number}"],issue:["/{owner}/{repo}/issues/{number}"],commit:["/{owner}/{repo}/commit/{sha}"],user:["/{user}"]},features:{...gu,referenceSearch:!0,referenceDetail:!0,listStatuses:!0,referencesAcross:!0,issueCloseReason:!0,changeRequestPatch:!0}},{id:"gitlab",label:"GitLab",order:1,terminology:{changeRequest:"mergeRequest",changeRequestPrefix:"!",issuePrefix:"#",sharedNumberSpace:!1,abbreviation:"MR",promptNoun:"merge request",ci:"pipeline"},icon:{sprite:"gitlab"},repository:{nestedNamespaces:!0},instances:{format:"origin",defaultInstance:"https://gitlab.com",multiple:!0,allowLoopbackHttp:!0,allowPort:!0,reserved:[],placeholder:"https://gitlab.example.com"},auth:{methods:["device","pat","cli"],cliName:"glab",cliTransport:!1,token:{scopes:["api"],createPath:"/-/user_settings/personal_access_tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:!1},{id:"token",kind:"personal-access-token",secret:!0}]},urls:{changeRequest:["/{namespace+}/{repo}/-/merge_requests/{number}"],issue:["/{namespace+}/{repo}/-/issues/{number}","/{namespace+}/{repo}/-/work_items/{number}"],commit:["/{namespace+}/{repo}/-/commit/{sha}"],user:["/{user}"]},features:{...gu,startThread:!0,authorCanReview:!0,projectUploads:!0,changeRequestPatch:!0,changeRequestTemplates:[".gitlab/merge_request_templates/Default.md"]}}],fa=(e,t)=>`/api/source-control/${e.provider}${t}`,uB=p({providers:x(Y())}),mB=p({error:g()}),hB=async e=>{const t=await e("/api/source-control/providers",{headers:{Accept:"application/json"}});if(t.status===404)return hl.parse(Sb);const s=await t.json().catch(()=>null);if(!t.ok){const i=mB.safeParse(s);throw new Error(i.success&&i.data.error||t.statusText||"Failed to load source control providers")}const n=uB.parse(s).providers,a=hl.parse(n);if(n.length>0&&a.length===0)throw new Error("Source control providers response contained no readable provider");return a},Pb=p({state:R(["success","failure","pending","unknown"]),total:v(),success:v(),failure:v(),pending:v(),inProgress:v().optional(),queued:v().optional(),startedAt:g().optional()}),Pc={number:v(),title:g(),url:g(),body:g(),bodyTruncated:z(),createdAt:g().nullable(),updatedAt:g().nullable(),author:p({login:g(),avatarUrl:g().optional()}).nullable(),labels:x(p({name:g(),color:g().optional()})),commentCount:v(),sourceRepo:p({owner:g(),repo:g(),source:g()})},Ab=we("kind",[p({kind:y("issue"),...Pc,state:R(["open","completed","not_planned"])}),p({kind:y("pull"),...Pc,state:R(["open","closed","merged"]),draft:z(),head:g(),base:g(),headSha:g(),headRepo:p({owner:g(),repo:g(),url:g(),cloneUrl:g().optional(),sshUrl:g().optional()}).nullable()}),p({kind:y("discussion"),...Pc,state:R(["open","resolved","outdated","duplicate"]),answered:z().nullable(),upvotes:v(),locked:z(),category:p({name:g(),emoji:g().nullable(),answerable:z()})})]),fB=we("connected",[p({connected:y(!1)}),p({connected:y(!0),repo:p({owner:g(),repo:g(),url:g()}).nullable(),items:x(Ab),cursor:g().nullable(),hasMore:z(),total:v()})]),pu={author:p({login:g(),avatarUrl:g().optional()}).nullable(),body:g(),createdAt:g().nullable(),url:g(),path:g().nullable(),line:v().nullable(),review:R(["approved","changes_requested","commented","dismissed"]).nullable(),excerpt:p({startLine:v().int().positive(),lines:x(g()).max(200)}).optional().catch(void 0)},bB=we("connected",[p({connected:y(!1)}),p({connected:y(!0),detail:p({number:v(),comments:x(p({...pu,thread:p({id:g().min(1),resolved:z(),canResolve:z(),canReply:z(),replies:x(p(pu))}).optional(),answer:p({chosen:z(),canChange:z()}).optional()})),commentTotal:v(),pull:p({reviewDecision:R(["approved","changes_requested","review_required"]).nullable(),reviewers:x(p({id:g(),login:g(),avatarUrl:g().optional()})).default([]),checks:Pb.nullable().optional(),additions:v(),deletions:v(),changedFiles:v(),commits:x(p({sha:g(),headline:g(),author:p({login:g(),avatarUrl:g().optional()}).nullable(),authorName:g().nullable(),committedAt:g().nullable(),url:g().nullable()})).default([]),commitTotal:v().nullable().default(null),stack:p({number:v().nullable(),base:g(),layers:x(p({number:v(),title:g(),url:g(),state:R(["open","closed","merged"]),draft:z(),head:g()}))}).nullable().optional().catch(void 0)}).nullable(),discussion:p({canComment:z(),canClose:z(),canReopen:z()}).optional()}).nullable()})]),kB=Mi({items:x(Ab.and(p({directory:g().min(1)}))),cursor:g().nullable(),hasMore:z(),total:v().int().nonnegative(),repositories:x(J([Mi({directory:g().min(1),status:y("included"),repo:Mi({owner:g(),repo:g(),url:g(),host:g().optional()})}),Mi({directory:g().min(1),status:R(["no-repo","disconnected","invalid-context","error"])})]))}),yB=we("connected",[p({connected:y(!1)}),p({connected:y(!0),statuses:x(p({owner:g(),repo:g(),number:v(),checks:Pb.nullable(),mergeable:z().nullable(),mergeableState:g().nullable()}))})]),wB=p({error:g()}),kr=e=>{const t=new URLSearchParams({directory:e.directory,instance:e.instance,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},Fi=async(e,t,s)=>{const n=await e.json().catch(()=>null);if(!e.ok){const a=wB.safeParse(n);throw new Error(a.success&&a.data.error||e.statusText||s)}return t.parse(n)},vB=async(e,t,s)=>{const n=kr(t);n.set("kind",s.kind),s.state&&n.set("state",s.state),s.people&&n.set("people",s.people),s.query?.trim()&&n.set("query",s.query.trim()),s.cursor&&n.set("cursor",s.cursor);const a=await e(fa(t,"/references"),{query:n,headers:{Accept:"application/json"}}),i=await Fi(a,fB,"Failed to load issues and pull requests");return i.connected?{...i,items:i.items.map(o=>({...o,provider:t.provider}))}:i},CB=async(e,t,s)=>{const n=kr(t);n.set("owner",s.owner),n.set("repo",s.repo),n.set("number",String(s.number)),s.kind==="discussion"&&n.set("kind","discussion");const a=s.host?.trim();a&&a!=="github.com"&&n.set("host",a);const i=await e(fa(t,"/references/detail"),{query:n,headers:{Accept:"application/json"}});return Fi(i,bB,"Failed to load issue or pull request detail")},uu=p({login:g(),avatarUrl:g().optional()}).nullable(),mu=R(["old","new"]),SB=we("connected",[p({connected:y(!1)}),p({connected:y(!0),viewerIsAuthor:z(),headSha:g(),draft:p({id:g(),body:g(),comments:x(p({id:g(),path:g(),side:mu,line:v().int().nullable(),startLine:v().int().nullable(),body:g(),author:uu}))}).nullable(),threads:x(p({id:g(),path:g(),side:mu,line:v().int().nullable(),startLine:v().int().nullable(),resolved:z(),canReply:z(),canResolve:z(),comments:x(p({id:g(),body:g(),createdAt:g(),url:g(),author:uu}))})),truncated:z()})]),PB=async(e,t,s)=>{const n=kr(t);n.set("owner",s.owner),n.set("repo",s.repo),n.set("number",String(s.number));const a=await e(fa(t,"/pr/review/state"),{query:n,headers:{Accept:"application/json"}});return Fi(a,SB,"Failed to load the review")},AB=async(e,t,s)=>{const[n]=t;if(!n||t.some(o=>o.provider!==n.provider))throw new Error("A search across repositories needs contexts of one provider");const a=await e(fa(n,"/references/across"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({contexts:t,...s,query:s.query?.trim()})}),i=await Fi(a,kB,"Failed to load issues and pull requests");return{...i,items:i.items.map(o=>({...o,provider:n.provider}))}},zB=async(e,t,s)=>{const n=kr(t);n.set("pulls",s.map(i=>{const o=i.host?.trim().toLowerCase();return`${i.owner}/${i.repo}#${i.number}${o&&o!=="github.com"?`@${o}`:""}`}).join(","));const a=await e(fa(t,"/references/status"),{query:n,headers:{Accept:"application/json"}});return Fi(a,yB,"Failed to load pull request statuses")};class Ns extends Error{constructor(t,s){super(t),this.code=s}code}const yr=new Map,zb=e=>{for(const t of e)yr.set(t.id,{format:t.instances.format,label:t.label,pathStyle:t.repository.pathStyle==="path"})},eg=(e,t)=>K(t)&&(t.trim().length>0||t===""&&yr.get(e.provider)?.pathStyle!==!1);zb(Sb);const Si=e=>yr.get(e.provider)?.label??e.provider,xB=e=>{const t=e.instance.trim();let s;try{s=new URL(t.includes("://")?t:`https://${t}`)}catch{throw new Error(`Invalid source control instance: ${e.instance}`)}const n=["localhost","127.0.0.1","::1","[::1]"].includes(s.hostname.toLowerCase());if(s.username||s.password||s.search||s.hash||s.pathname&&s.pathname!=="/"||s.protocol!=="https:"&&!(s.protocol==="http:"&&n))throw new Error(`Invalid ${Si(e)} instance: ${e.instance}`);return{provider:e.provider,instance:s.origin}},TB=e=>{const t=e.instance.trim().toLowerCase().replace(/\.$/,"");let s=t;if(t.includes("://"))try{const n=new URL(t);if(n.protocol!=="https:"||n.username||n.password||n.port||n.search||n.hash||n.pathname&&n.pathname!=="/")throw new Error(`Invalid ${Si(e)} instance: ${e.instance}`);s=n.hostname.toLowerCase().replace(/\.$/,"")}catch{throw new Error(`Invalid ${Si(e)} instance: ${e.instance}`)}return{provider:e.provider,instance:s}},W=e=>{const t=(yr.get(e.provider)?.format??"origin")==="host"?TB(e):xB(e);return e.instanceSshUrl?.trim()?{...t,instanceSshUrl:e.instanceSshUrl.trim()}:t},xb=e=>{if(!e||!K(e.repositoryId)||!e.repositoryId||!K(e.configRevision)||!e.configRevision||Object.prototype.toString.call(e.bare)!=="[object Boolean]"||!Array.isArray(e.remotes))throw new Error("Source control response contained an invalid repository context");const t=e.remotes.map(s=>{if(!s||!K(s.name)||!s.name||!Ml(s.fetch)||!Ml(s.push))throw new Error("Source control response contained an invalid repository remote");return{name:s.name,fetch:{displayUrl:s.fetch.displayUrl,fingerprint:s.fetch.fingerprint},push:{displayUrl:s.push.displayUrl,fingerprint:s.push.fingerprint}}});return{repositoryId:e.repositoryId,configRevision:e.configRevision,bare:e.bare,remotes:t}},_n=e=>{const t=xb(e.repository);if(!Number.isInteger(e.revision)||e.revision<0)throw new Error("Source control response contained an invalid binding revision");if(e.binding===null)return{status:"missing",repository:t,revision:e.revision,binding:null};const s=gB(e.binding);if(!s||s.repositoryId!==t.repositoryId||s.revision!==e.revision||!K(s.configRevision)||!Array.isArray(s.providers)||!Array.isArray(s.auxiliary)||s.state!=="bound"&&s.state!=="needs-attention")throw new Error("Source control response contained an invalid repository binding");const n=pB({...s,providers:s.providers.map(a=>({...a,...W(a)}))},t);return{status:n.state,repository:t,revision:e.revision,binding:n}},hu=async(e,t,s)=>{const n=await e(t,{query:new URLSearchParams({directory:s}),headers:{Accept:"application/json"}}),a=await n.json();if(!n.ok)throw new Ns(a.error||n.statusText||"Source control repository request failed",a.code);return a},IB=async(e,t=C)=>{const s=await t("/api/source-control/binding/transport",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new Ns(n.error||"Git transport configuration failed",n.code);return{status:"configured",binding:_n(n)}},RB=async(e,t=C)=>{const s=await t("/api/source-control/binding/transport/remove",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new Ns(n.error||"Git transport removal failed",n.code);return{status:"removed",binding:_n(n)}},jB=async(e,t=C)=>{const s=await t("/api/source-control/binding/auxiliary",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new Ns(n.error||"Git auxiliary transport configuration failed",n.code);return{status:"configured",binding:_n(n)}},He=async(e,t,s,n={},a)=>{const i=W(t),o=await e(fa(i,s),{...n,query:new URLSearchParams([["instance",i.instance],...a?Array.from(a.entries()):[]]),headers:{Accept:"application/json",...n.headers}}),r=await o.json();if(!o.ok){const c=r?.error||o.statusText||"Source control request failed";throw r?.code==="SOURCE_CONTROL_INSTANCE_OTHER_PROVIDER"&&j(r.provider)?new zj(c,r.provider):new Ns(c,r?.code)}return r},ts=e=>{const t=new URLSearchParams({directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},OB=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!j(t)))throw new Error("Source control response contained invalid incomplete projects");return[...e]}},de=(e,t,s,n)=>He(e,t,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),Zt=(e,t)=>{const s=Object.keys(e);return s.length===t.length&&s.every(n=>t.includes(n))};function fe(e,t,s){const n=e.target;if(!j(e.directory)||!j(e.repositoryId)||!j(e.accountId)||!Rb(e.bindingRevision)||!j(e.primaryRemote)||!j(e.idempotencyKey)||!n||!eg(t,n.project?.owner)||!j(n.project?.name)||s==="create"&&("number"in n||"headSha"in n)||s==="create"&&(!j(n.head)||!j(n.base))||s==="existing"&&!$t(n.number)||n.number!==void 0&&!$t(n.number)||n.head!==void 0&&!j(n.head)||n.base!==void 0&&!j(n.base)||n.headSha!==void 0&&!j(n.headSha))throw new Error("Source control mutation context is invalid");const a={...t,directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:e.bindingRevision,primaryRemote:e.primaryRemote,idempotencyKey:e.idempotencyKey};if(s==="create"){if(!j(n.head)||!j(n.base))throw new Error("Source control mutation context is invalid");return{...a,target:{project:{owner:n.project.owner,name:n.project.name},head:n.head,base:n.base}}}if(!$t(n.number))throw new Error("Source control mutation context is invalid");const i={project:{owner:n.project.owner,name:n.project.name},number:n.number};return n.head!==void 0&&(i.head=n.head),n.base!==void 0&&(i.base=n.base),n.headSha!==void 0&&(i.headSha=n.headSha),{...a,target:i}}const DB=(e,t)=>e.repositoryId===t.repositoryId&&e.bindingRevision===t.bindingRevision&&e.primaryRemote===t.primaryRemote&&e.project.owner===t.target.project.owner&&e.project.name===t.target.project.name&&(t.target.number===void 0||e.number===t.target.number)&&(t.target.head===void 0||e.head===t.target.head)&&(t.target.base===void 0||e.base===t.target.base)&&(t.target.headSha===void 0||e.headSha===t.target.headSha),BB=(e,t)=>t.startsWith(`${e.instance}#`)&&/^\d+$/.test(t.slice(e.instance.length+1)),be=(e,t,s,n)=>{const a=e?.actor,i=e?.target,o=i?.project;if(!e||!Zt(e,["status","actor","target","replayed","result"])||e.status!=="succeeded"||!Ae(e.replayed)||!a||!Zt(a,["provider","instance","providerAccountId"])||a.provider!==s.provider||a.instance!==s.instance||!j(a.providerAccountId)||!BB(s,a.providerAccountId)||!i||!Zt(i,["repositoryId","bindingRevision","primaryRemote","project",...["number","head","base","headSha"].filter(c=>i[c]!==void 0)])||!j(i.repositoryId)||!Rb(i.bindingRevision)||!j(i.primaryRemote)||!o||!Zt(o,["id","owner","name"])||!j(o.id)||!eg(s,o.owner)||!j(o.name)||i.number!==void 0&&!$t(i.number)||i.head!==void 0&&!j(i.head)||i.base!==void 0&&!j(i.base)||i.headSha!==void 0&&!j(i.headSha)||!DB(i,t)||!e.result||Object.prototype.toString.call(e.result)!=="[object Object]")throw new Error("Source control response contained an invalid mutation receipt");const r={repositoryId:i.repositoryId,bindingRevision:i.bindingRevision,primaryRemote:i.primaryRemote,project:{id:o.id,owner:o.owner,name:o.name}};return i.number!==void 0&&(r.number=i.number),i.head!==void 0&&(r.head=i.head),i.base!==void 0&&(r.base=i.base),i.headSha!==void 0&&(r.headSha=i.headSha),{status:"succeeded",actor:{...s,providerAccountId:a.providerAccountId},target:r,replayed:e.replayed,result:n(e.result)}},We=e=>{if(!Zt(e,[]))throw new Error("Source control response contained an invalid mutation result");return{}},FB=["queued","merging","auto-merge","cancelled"],NB=e=>FB.find(t=>t===e)??null,MB=e=>{if(!Zt(e,e.stacked===void 0?[]:["stacked"])||e.stacked!==void 0&&!Ae(e.stacked))throw new Error("Source control response contained an invalid create result");return e.stacked===void 0?{}:{stacked:e.stacked}},EB=e=>{const t=["merged",...e.message===void 0?[]:["message"],...e.outcome===void 0?[]:["outcome"]],s=e.outcome===void 0?void 0:NB(e.outcome);if(!Zt(e,t)||!Ae(e.merged)||e.message!==void 0&&!K(e.message)||s===null)throw new Error("Source control response contained an invalid merge result");const n={merged:e.merged};return e.message!==void 0&&(n.message=e.message),s!==void 0&&(n.outcome=s),n},LB=e=>{if(!Zt(e,["commented"])||!Ae(e.commented))throw new Error("Source control response contained an invalid review result");return{commented:e.commented}},fu=async(e,t,s,n)=>{const a=W(t),i=ts(t);i.set("owner",s.owner),i.set("repo",s.repo);const o=await He(e,a,n,{},i);if(o.connected!==!0)throw new Error(`${Si(a)} is not connected`);if(!Array.isArray(o.items))throw new Error("Source control response contained an invalid list");return o.items},qB=e=>e.map(t=>{if(!j(t.name)||t.color!==void 0&&!K(t.color))throw new Error("Source control response contained an invalid label");return t.color?{name:t.name,color:t.color}:{name:t.name}}),VB=e=>e.map(t=>{if(!j(t.id)||!j(t.login)||t.avatarUrl!==void 0&&!hs(t.avatarUrl))throw new Error("Source control response contained an invalid user");return t.avatarUrl?{id:t.id,login:t.login,avatarUrl:t.avatarUrl}:{id:t.id,login:t.login}}),Ac=e=>{if(!Zt(e,["state"])||e.state!=="open"&&e.state!=="closed")throw new Error("Source control response contained an invalid state result");return{state:e.state}},UB=e=>{if(!Zt(e,["ready"])||!Ae(e.ready))throw new Error("Source control response contained an invalid ready result");return{ready:e.ready}},rt=(e,t)=>{const s=e?.username||e?.login;if(!e||!gs(e.id)||!j(s)||!sF(e,t)||e.avatarUrl!==void 0&&!hs(e.avatarUrl)||e.name!==void 0&&!K(e.name)||e.email!==void 0&&!K(e.email))throw new Error("Source control response contained an invalid user");const n={...t,id:String(e.id),username:s};return e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.name&&(n.name=e.name),e.email&&(n.email=e.email),n},ia=(e,t)=>{if(!e||!gs(e.id)||!eg(t,e.owner)||!j(e.name)||!hs(e.url)||!ht(e,t)||e.cloneUrl!==void 0&&!j(e.cloneUrl)||e.sshUrl!==void 0&&!j(e.sshUrl)||e.defaultBranch!==void 0&&!j(e.defaultBranch)||e.defaultBranchSha!==void 0&&e.defaultBranchSha!==null&&!j(e.defaultBranchSha)||e.remoteName!==void 0&&e.remoteName!==null&&!j(e.remoteName))throw new Error("Source control response contained an invalid project");const s={...t,id:String(e.id),owner:e.owner,name:e.name,url:e.url};return e.cloneUrl&&(s.cloneUrl=e.cloneUrl),e.sshUrl&&(s.sshUrl=e.sshUrl),e.defaultBranch&&(s.defaultBranch=e.defaultBranch),e.defaultBranchSha!==void 0&&(s.defaultBranchSha=e.defaultBranchSha),e.remoteName!==void 0&&(s.remoteName=e.remoteName),s},Tb=(e,t)=>{if(e==null)return null;if(!e.summary)throw new Error("Source control response contained an invalid CI summary");if(iF(e.summary),e.runs!==void 0){if(!Array.isArray(e.runs)||e.runs.some(s=>!s||!gs(s.id)||!j(s.name)||!ht(s,t)||s.detailsUrl!==void 0&&!hs(s.detailsUrl)))throw new Error("Source control response contained invalid CI runs");for(const s of e.runs){if(s.startedAt!==void 0&&!j(s.startedAt)||s.completedAt!==void 0&&!j(s.completedAt)||s.status!==void 0&&!j(s.status)||s.conclusion!==void 0&&s.conclusion!==null&&!K(s.conclusion))throw new Error("Source control response contained invalid CI run fields");if(s.application!==void 0&&(Object.prototype.toString.call(s.application)!=="[object Object]"||s.application.name!==void 0&&!K(s.application.name)||s.application.slug!==void 0&&!K(s.application.slug)))throw new Error("Source control response contained an invalid CI application");if(s.job!==void 0&&(Object.prototype.toString.call(s.job)!=="[object Object]"||s.job.runId!==void 0&&!gs(s.job.runId)||s.job.jobId!==void 0&&!gs(s.job.jobId)||s.job.url!==void 0&&!hs(s.job.url)||s.job.name!==void 0&&!K(s.job.name)||s.job.workflowName!==void 0&&!K(s.job.workflowName)||s.job.conclusion!==void 0&&s.job.conclusion!==null&&!K(s.job.conclusion)))throw new Error("Source control response contained an invalid CI job");if(s.job?.steps!==void 0&&(!Array.isArray(s.job.steps)||s.job.steps.some(n=>!n||!j(n.name)||n.status!==void 0&&!K(n.status)||n.conclusion!==void 0&&n.conclusion!==null&&!K(n.conclusion)||n.number!==void 0&&(!Number.isInteger(n.number)||n.number<0)||n.startedAt!==void 0&&!j(n.startedAt)||n.completedAt!==void 0&&!j(n.completedAt))))throw new Error("Source control response contained invalid CI steps");if(s.output!==void 0&&(Object.prototype.toString.call(s.output)!=="[object Object]"||s.output.title!==void 0&&!K(s.output.title)||s.output.summary!==void 0&&!K(s.output.summary)||s.output.text!==void 0&&!K(s.output.text)))throw new Error("Source control response contained invalid CI output");if(s.annotations!==void 0&&(!Array.isArray(s.annotations)||s.annotations.some(n=>!n||!j(n.message)||n.path!==void 0&&!K(n.path)||n.startLine!==void 0&&(!Number.isInteger(n.startLine)||n.startLine<0)||n.endLine!==void 0&&(!Number.isInteger(n.endLine)||n.endLine<0)||n.level!==void 0&&!K(n.level)||n.title!==void 0&&!K(n.title)||n.rawDetails!==void 0&&!K(n.rawDetails))))throw new Error("Source control response contained invalid CI annotations")}}return{summary:{state:e.summary.state,total:e.summary.total,success:e.summary.success,failure:e.summary.failure,pending:e.summary.pending,inProgress:e.summary.inProgress,queued:e.summary.queued,startedAt:e.summary.startedAt},runs:e.runs?.map(s=>({...t,id:String(s.id),name:s.name,status:s.status,conclusion:s.conclusion,startedAt:s.startedAt,completedAt:s.completedAt,detailsUrl:s.detailsUrl,application:s.application,job:s.job,output:s.output,annotations:s.annotations}))}},El=(e,t)=>{if(!e||!gs(e.id)||!Number.isInteger(e.number)||e.number<1||!j(e.title)||!hs(e.url)||!["open","closed","merged"].includes(e.state)||!Ae(e.draft)||!j(e.base)||!j(e.head)||!ht(e,t)||e.body!==void 0&&!K(e.body)||e.headSha!==void 0&&!j(e.headSha)||e.author!==void 0&&e.author!==null&&!ht(e.author,t)||e.createdAt!==void 0&&!j(e.createdAt)||e.updatedAt!==void 0&&!j(e.updatedAt)||e.headLabel!==void 0&&!j(e.headLabel)||e.mergeable!==void 0&&e.mergeable!==null&&!Ae(e.mergeable)||e.mergeableState!==void 0&&e.mergeableState!==null&&!K(e.mergeableState)||e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(n=>!n||!j(n.name)||n.color!==void 0&&!K(n.color)))||e.workInProgress!==void 0&&!Ae(e.workInProgress)||e.private!==void 0&&!Ae(e.private)||e.topic!==void 0&&!K(e.topic)||e.hashtags!==void 0&&(!Array.isArray(e.hashtags)||e.hashtags.some(n=>!j(n)))||e.revisionNumber!==void 0&&!$t(e.revisionNumber))throw new Error("Source control response contained an invalid change request");const s={...t,id:String(e.id),number:e.number,project:ia(e.project,t),title:e.title,url:e.url,state:e.state,draft:e.draft,base:e.base,head:e.head};return e.body!==void 0&&(s.body=e.body),e.headSha&&(s.headSha=e.headSha),e.author!==void 0&&e.author!==null&&(s.author=rt(e.author,t)),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),e.headLabel&&(s.headLabel=e.headLabel),e.headProject!==void 0&&e.headProject!==null&&(s.headProject=ia(e.headProject,t)),e.mergeable!==void 0&&(s.mergeable=e.mergeable),e.mergeableState!==void 0&&(s.mergeableState=e.mergeableState),e.labels!==void 0&&(s.labels=e.labels.map(n=>({name:n.name,color:n.color}))),e.workInProgress!==void 0&&(s.workInProgress=e.workInProgress),e.private!==void 0&&(s.private=e.private),e.topic&&(s.topic=e.topic),e.hashtags!==void 0&&(s.hashtags=[...e.hashtags]),e.revisionNumber!==void 0&&(s.revisionNumber=e.revisionNumber),s},bu=(e,t)=>{if(!e||!gs(e.id)||!Number.isInteger(e.number)||e.number<1||!j(e.title)||!hs(e.url)||e.state!=="open"&&e.state!=="closed"||!ht(e,t)||e.body!==void 0&&!K(e.body)||e.author!==void 0&&e.author!==null&&!ht(e.author,t)||e.createdAt!==void 0&&!j(e.createdAt)||e.updatedAt!==void 0&&!j(e.updatedAt))throw new Error("Source control response contained an invalid issue");if(e.assignees!==void 0&&(!Array.isArray(e.assignees)||e.assignees.some(n=>!ht(n,t))))throw new Error("Source control response contained invalid issue assignees");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(n=>!n||!j(n.name)||n.color!==void 0&&!K(n.color))))throw new Error("Source control response contained invalid issue labels");const s={...t,id:String(e.id),number:e.number,project:ia(e.project,t),title:e.title,url:e.url,state:e.state};return e.body!==void 0&&(s.body=e.body),e.author!==void 0&&(s.author=e.author?rt(e.author,t):null),e.assignees!==void 0&&(s.assignees=e.assignees.map(n=>rt(n,t))),e.labels!==void 0&&(s.labels=e.labels.map(n=>({name:n.name,color:n.color}))),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),s},WB=e=>{if(!e||!j(e.sha)||!K(e.headline)||e.authorName!==null&&!K(e.authorName)||e.committedAt!==null&&!j(e.committedAt)||e.url!==null&&!hs(e.url))throw new Error("Source control response contained an invalid commit");return{sha:e.sha,headline:e.headline,authorName:e.authorName,committedAt:e.committedAt,url:e.url}},HB=["open","closed","merged"],GB=e=>{if(!e||!j(e.base)||!Array.isArray(e.layers)||e.number!==null&&!Number.isSafeInteger(e.number))throw new Error("Source control response contained an invalid merge request chain");return{number:e.number,base:e.base,layers:e.layers.map(t=>{const s=HB.find(n=>n===t?.state);if(!t||!Number.isSafeInteger(t.number)||!K(t.title)||!hs(t.url)||!s||!Ae(t.draft)||!j(t.head))throw new Error("Source control response contained an invalid merge request chain");return{number:t.number,title:t.title,url:t.url,state:s,draft:t.draft,head:t.head}})}},Ib=e=>{try{return GB(e)}catch{return}},_B=(e,t)=>{if(!e||e.state!=="approved"&&e.state!=="changes_requested"||!j(e.url)||e.createdAt!==null&&!j(e.createdAt))throw new Error("Source control response contained an invalid review verdict");const s={state:e.state,url:e.url,createdAt:e.createdAt};return e.author&&(s.author=rt(e.author,t)),s},KB=["approved","rejected","recommended","disliked","neutral"],ZB=["satisfied","unsatisfied","overridden","not-applicable","error","forced"],JB=["rework","trivial-rebase","merge-first-parent-update","no-code-change","no-change"],ni=e=>wr(e)&&Number.isInteger(e)&&e>=-10&&e<=10,$B=(e,t)=>{if(!e||!ni(e.value)||e.revision!==void 0&&!$t(e.revision))throw new Error("Source control response contained an invalid vote");const s={user:rt(e.user,t),value:e.value};return e.revision!==void 0&&(s.revision=e.revision),s},QB=(e,t)=>{const s=KB.find(n=>n===e?.status);if(!e||!j(e.name)||!s||!ni(e.defaultValue)||!Ae(e.blocking)||!Array.isArray(e.values)||e.values.some(n=>!n||!ni(n.value)||!K(n.description))||!Array.isArray(e.permitted)||e.permitted.some(n=>!ni(n))||!Array.isArray(e.votes))throw new Error("Source control response contained an invalid vote label");return{name:e.name,values:e.values.map(n=>({value:n.value,description:n.description})),defaultValue:e.defaultValue,permitted:[...e.permitted],blocking:e.blocking,status:s,votes:e.votes.map(n=>$B(n,t))}},YB=e=>{const t=ZB.find(n=>n===e?.status);if(!e||!j(e.name)||!t||e.description!==void 0&&!K(e.description))throw new Error("Source control response contained an invalid submit requirement");const s={name:e.name,status:t};return e.description&&(s.description=e.description),s},XB=(e,t)=>{const s=e?.kind===void 0?void 0:JB.find(a=>a===e.kind);if(!e||!$t(e.number)||!j(e.sha)||!j(e.ref)||e.createdAt!==null&&!j(e.createdAt)||e.kind!==void 0&&!s)throw new Error("Source control response contained an invalid revision");const n={number:e.number,sha:e.sha,createdAt:e.createdAt,ref:e.ref};return e.uploader&&(n.uploader=rt(e.uploader,t)),s&&(n.kind=s),n},eF=e=>{if(!e||!j(e.sha)||e.changeId!==null&&!j(e.changeId)||e.uploadedAs!==null&&!$t(e.uploadedAs))throw new Error("Source control response contained an invalid local revision");return{sha:e.sha,changeId:e.changeId,uploadedAs:e.uploadedAs}},tF=(e,t)=>{if(e?.revision!==void 0&&!$t(e.revision))throw new Error("Source control response contained an invalid review comment");const s={...Ll(e,t),path:e.path,line:e.line,position:e.position};return e.revision!==void 0&&(s.revision=e.revision),s},Ll=(e,t)=>{if(!e||!gs(e.id)||!j(e.url)||!K(e.body)||!ht(e,t)||e.author!==void 0&&e.author!==null&&!ht(e.author,t)||e.createdAt!==void 0&&!j(e.createdAt)||e.updatedAt!==void 0&&!j(e.updatedAt))throw new Error("Source control response contained an invalid comment");const s=e.thread;if(s!==void 0&&(!s||!gs(s.id)||!Ae(s.resolved)||!Ae(s.resolvable)||!Ae(s.first)||s.canResolve!==void 0&&!Ae(s.canResolve)||s.canReply!==void 0&&!Ae(s.canReply)))throw new Error("Source control response contained an invalid comment thread");const n={...t,id:String(e.id),url:e.url,body:e.body};return s&&(n.thread={id:String(s.id),resolved:s.resolved,resolvable:s.resolvable,first:s.first},s.canResolve!==void 0&&(n.thread.canResolve=s.canResolve),s.canReply!==void 0&&(n.thread.canReply=s.canReply)),e.author&&(n.author=rt(e.author,t)),e.createdAt&&(n.createdAt=e.createdAt),e.updatedAt&&(n.updatedAt=e.updatedAt),n},K=e=>Object.prototype.toString.call(e)==="[object String]",Ae=e=>Object.prototype.toString.call(e)==="[object Boolean]",wr=e=>Object.prototype.toString.call(e)==="[object Number]",j=e=>K(e)&&e.trim().length>0,$t=e=>wr(e)&&Number.isSafeInteger(e)&&e>=1,Rb=e=>wr(e)&&Number.isSafeInteger(e)&&e>=0,gs=e=>j(e)||Number.isFinite(e),hs=e=>{if(!j(e))return!1;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"}catch{return!1}},ht=(e,t)=>e?.provider===t.provider&&e.instance===t.instance,sF=(e,t)=>e.provider===void 0&&e.instance===void 0?!0:ht(e,t),nF=(e,t)=>{if(!wr(e)||!Number.isInteger(e)||e<1||!Ae(t))throw new Error("Source control response contained invalid pagination");return{page:e,hasMore:t}},ku=(e,t)=>{const s={items:t,...nF(e.page,e.hasMore)},n=OB(e.incompleteProjectIds);return n?.length&&(s.incompleteProjectIds=n),s},aF=e=>{if(!e||!Array.isArray(e.branches)||e.branches.some(t=>!j(t)))throw new Error("Source control response contained invalid branches");return[...e.branches]},iF=e=>{if(!["success","failure","pending","unknown"].includes(e.state)||!Number.isInteger(e.total)||e.total<0||!Number.isInteger(e.success)||e.success<0||!Number.isInteger(e.failure)||e.failure<0||!Number.isInteger(e.pending)||e.pending<0||e.inProgress!==void 0&&(!Number.isInteger(e.inProgress)||e.inProgress<0)||e.queued!==void 0&&(!Number.isInteger(e.queued)||e.queued<0)||e.startedAt!==void 0&&!j(e.startedAt))throw new Error("Source control response contained an invalid CI summary")},oF=(e,t,s)=>{if(!e||!ht(e.identity,t)||!j(e.branch)||e.branch!==s||e.project===void 0||e.changeRequest===void 0||e.fetchedAt!==void 0&&(!Number.isFinite(e.fetchedAt)||e.fetchedAt<0)||e.canMerge!==void 0&&!Ae(e.canMerge)||e.defaultBranch!==void 0&&e.defaultBranch!==null&&!j(e.defaultBranch)||e.resolvedRemoteName!==void 0&&e.resolvedRemoteName!==null&&!j(e.resolvedRemoteName))throw new Error("Source control response contained an invalid change request status");const n={identity:t,project:e.project===null?null:ia(e.project,t),branch:e.branch,changeRequest:e.changeRequest===null?null:El(e.changeRequest,t)};if(e.ci!==void 0&&(n.ci=Tb(e.ci,t)),e.canMerge!==void 0&&(n.canMerge=e.canMerge),e.defaultBranch!==void 0&&(n.defaultBranch=e.defaultBranch),e.resolvedRemoteName!==void 0&&(n.resolvedRemoteName=e.resolvedRemoteName),e.fetchedAt!==void 0&&(n.fetchedAt=e.fetchedAt),e.localRevision!==void 0&&(n.localRevision=eF(e.localRevision)),e.stack===null)n.stack=null;else if(e.stack!==void 0){const a=Ib(e.stack);a&&(n.stack=a)}return n},zc=(e,t)=>(e??[]).map(s=>{if(!j(s.id)||s.id!==s.credentialId||!$t(s.credentialRevision)||!j(s.providerUserId)||!["available","unavailable"].includes(s.providerUserStatus)||!Ae(s.current)||!["oauth","pat","cli"].includes(s.source)||!["valid","invalid"].includes(s.status))throw new Error("Source control response contained an invalid auth credential");return{id:s.id,credentialId:s.credentialId,credentialRevision:s.credentialRevision,providerUserId:s.providerUserId,providerUserStatus:s.providerUserStatus,user:rt(s.user,t),scope:s.scope,current:s.current,source:s.source,status:s.status}}),xc=(e,t)=>{if(!e.connected){if(!e.status){const s={...t,status:"disconnected",connected:!1};return e.cli&&(s.cli={available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?rt(e.cli.user,t):void 0}),s.accounts=zc(e.accounts,t),s}return{...e,...t,connected:!1,accounts:zc(e.accounts,t)}}return{...t,status:"connected",connected:!0,user:rt(e.user,t),scope:e.scope,accounts:zc(e.accounts,t),cli:e.cli?{available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?rt(e.cli.user,t):void 0}:void 0}},rF=(e={})=>{const t=e.fetch??C;return{repositoryContext:async s=>xb(await hu(t,"/api/source-control/repository-context",s)),repositoryBinding:async s=>_n(await hu(t,"/api/source-control/binding",s)),resetRepositoryBinding:async s=>{const n=await t("/api/source-control/binding/reset",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),a=await n.json();if(!n.ok)throw new Ns(a.error||n.statusText||"Source control binding reset failed",a.code);return _n(a)},repositoryProviderBindingMutate:async s=>{const n=await t("/api/source-control/binding/provider",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),a=await n.json();if(!n.ok)throw new Ns(a.error||n.statusText||"Source control binding request failed",a.code);return _n(a)},providers:async()=>{const s=await hB(t);return zb(s),s},authInstances:async()=>{const s=await t("/api/source-control/instances",{headers:{Accept:"application/json"}}),n=await s.json();if(!s.ok)throw new Error(n.error||s.statusText||"Failed to list source control instances");return n.instances.map(W)},capabilities:async s=>{const n=await He(t,s,"/capabilities");return{identity:W(n.identity),authentication:n.authentication,authenticationMethods:n.authenticationMethods,multipleAccounts:n.multipleAccounts,projects:n.projects,issues:n.issues,changeRequests:n.changeRequests,draftChangeRequests:n.draftChangeRequests,mergeChangeRequests:n.mergeChangeRequests,mergeMethods:n.mergeMethods?[...n.mergeMethods]:void 0,ci:n.ci}},authStatus:async s=>{const n=W(s);return xc(await He(t,n,"/auth/status"),n)},authStart:async s=>{const n=await He(t,s,"/auth/start",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),a={flowId:n.flowId,userCode:n.userCode,verificationUri:n.verificationUri,expiresIn:n.expiresIn,interval:n.interval};return n.verificationUriComplete&&(a.verificationUriComplete=n.verificationUriComplete),n.scope&&(a.scope=n.scope),a},authComplete:async(s,n)=>{let a;try{a=await de(t,s,"/auth/complete",{flowId:n})}catch(o){if(o instanceof Ns&&o.code==="SOURCE_CONTROL_OAUTH_FLOW_UNAVAILABLE")return{status:"error",code:"expired",message:o.message};throw o}if(a.connected){const o={status:"connected",user:rt(a.user,W(s))};return a.scope&&(o.scope=a.scope),o}if(a.status==="authorization_pending"||a.status==="slow_down"){const o={status:"pending"};return a.status==="slow_down"&&(o.slowDown=!0),o}let i="provider-error";return a.status==="access_denied"?i="access-denied":a.status==="expired_token"&&(i="expired"),{status:"error",code:i,message:a.error||a.status||`${Si(s)} authentication failed`}},authSetToken:async(s,n,a)=>{const i=W(s);return await de(t,i,"/auth/token",a?.username?{token:n,username:a.username}:{token:n}),xc(await He(t,i,"/auth/status"),i)},authSetSshUrl:async(s,n)=>{const a=W(s),i=await de(t,a,"/auth/ssh-url",{sshUrl:n});if(i.sshUrl!==null&&!j(i.sshUrl))throw new Error("Source control response contained an invalid SSH URL");return{sshUrl:i.sshUrl??null}},authDisconnect:async(s,n)=>{if(!j(n)||n.trim()!==n)throw new Error("Source control credential accountId is required");const a=new URLSearchParams({accountId:n}),i=await He(t,s,"/auth",{method:"DELETE"},a);if(!Ae(i.removed))throw new Error("Source control response contained an invalid account removal result");return{removed:i.removed}},authActivate:async(s,n)=>{const a=W(s);return xc(await de(t,a,"/auth/activate",{accountId:n}),a)},authSetCliDisabled:async(s,n)=>{const a=W(s);return{disabled:!!(await de(t,a,"/auth/cli",{disabled:n})).disabled}},changeRequestStatus:async(s,n,a)=>{const i=W(s),o=ts(s);o.set("branch",n),a?.force&&o.set("force","true");const r=await He(t,i,"/pr/status",{},o);return oF(r,i,n)},changeRequestCreate:async s=>{const n=W(s),i={...fe(s,n,"create"),title:s.title};s.body!==void 0&&(i.body=s.body),s.draft!==void 0&&(i.draft=s.draft),s.remote&&(i.remote=s.remote),s.headRemote&&(i.headRemote=s.headRemote);const o=await de(t,n,"/pr/create",i);return be(o,s,n,MB)},changeRequestUpdate:async s=>{const n=W(s),a={...fe(s,n,"existing"),title:s.title};s.body!==void 0&&(a.body=s.body);const i=await de(t,n,"/pr/update",a);return be(i,s,n,We)},changeRequestMerge:async s=>{const n=W(s),a=await de(t,n,"/pr/merge",{...fe(s,n,"existing"),method:s.method,cancel:s.cancel});return be(a,s,n,EB)},changeRequestReady:async s=>{const n=W(s),a=await de(t,n,"/pr/ready",fe(s,n,"existing"));return be(a,s,n,UB)},changeRequestComment:async s=>{const n=W(s),a=await de(t,n,"/pr/comment",{...fe(s,n,"existing"),body:s.body});return be(a,s,n,We)},changeRequestStartThread:async s=>{const n=W(s),a=await de(t,n,"/pr/thread/start",{...fe(s,n,"existing"),body:s.body});return be(a,s,n,We)},changeRequestReplyToThread:async s=>{const n=W(s),a=await de(t,n,"/pr/thread/reply",{...fe(s,n,"existing"),threadId:s.threadId,body:s.body});return be(a,s,n,We)},changeRequestResolveThread:async s=>{const n=W(s),a=await de(t,n,"/pr/thread/resolve",{...fe(s,n,"existing"),threadId:s.threadId,resolved:s.resolved});return be(a,s,n,We)},changeRequestReview:async s=>{const n=W(s),a=fe(s,n,"existing");let i;if(s.votes!==void 0){const r=Object.entries(s.votes);if(s.verdict!==void 0||r.length===0&&s.publishDrafts!==!0||r.some(([c,l])=>!j(c)||!ni(l)))throw new Error("Source control review input is invalid");i={...a,votes:Object.fromEntries(r),publishDrafts:s.publishDrafts}}else i={...a,verdict:s.verdict};s.body!==void 0&&(i.body=s.body);const o=await de(t,n,"/pr/review",i);return be(o,s,n,LB)},changeRequestReviewState:(s,n)=>PB(t,s,n),changeRequestReviewComment:async s=>{const n=W(s),a=s.line===void 0?{path:s.path}:{path:s.path,side:s.side,line:s.line,startLine:s.startLine},i=await de(t,n,"/pr/review/comment",{...fe(s,n,"existing"),...a,body:s.body});return be(i,s,n,We)},changeRequestReviewCommentUpdate:async s=>{const n=W(s),a=await de(t,n,"/pr/review/comment/update",{...fe(s,n,"existing"),commentId:s.commentId,body:s.body});return be(a,s,n,We)},changeRequestReviewCommentDelete:async s=>{const n=W(s),a=await de(t,n,"/pr/review/comment/delete",{...fe(s,n,"existing"),commentId:s.commentId});return be(a,s,n,We)},changeRequestReviewDiscard:async s=>{const n=W(s),a=await de(t,n,"/pr/review/discard",fe(s,n,"existing"));return be(a,s,n,We)},changeRequestSetState:async s=>{const n=W(s),a=await de(t,n,"/pr/state",{...fe(s,n,"existing"),state:s.state});return be(a,s,n,Ac)},issueSetState:async s=>{const n=W(s),a=await de(t,n,"/issues/state",{...fe(s,n,"existing"),state:s.state});return be(a,s,n,Ac)},changeRequestSetLabels:async s=>{const n=W(s),a=await de(t,n,"/pr/labels",{...fe(s,n,"existing"),labels:s.labels});return be(a,s,n,We)},issueSetLabels:async s=>{const n=W(s),a=await de(t,n,"/issues/labels",{...fe(s,n,"existing"),labels:s.labels});return be(a,s,n,We)},changeRequestSetReviewers:async s=>{const n=W(s),a=await de(t,n,"/pr/reviewers",{...fe(s,n,"existing"),reviewers:s.reviewers});return be(a,s,n,We)},refreshProviderReads:async(s,n)=>{const a="item"in n?new URLSearchParams({scope:"item",owner:n.item.owner,repo:n.item.repo,number:String(n.item.number)}):new URLSearchParams({scope:"lists"});await He(t,s,"/read-cache/refresh",{method:"POST"},a)},referenceLabels:async(s,n)=>qB(await fu(t,s,n,"/references/labels")),referenceReviewers:async(s,n)=>VB(await fu(t,s,n,"/references/reviewers")),issueComment:async s=>{const n=W(s),a=await de(t,n,"/issues/comment",{...fe(s,n,"existing"),body:s.body});return be(a,s,n,We)},discussionComment:async s=>{const n=W(s),a={...fe(s,n,"existing"),body:s.body};s.replyTo&&(a.replyTo=s.replyTo);const i=await de(t,n,"/discussions/comment",a);return be(i,s,n,We)},discussionSetState:async s=>{const n=W(s),a=fe(s,n,"existing"),i=await de(t,n,"/discussions/state",s.state==="closed"?{...a,state:"closed",reason:s.reason}:{...a,state:"open"});return be(i,s,n,Ac)},discussionSetAnswer:async s=>{const n=W(s),a=await de(t,n,"/discussions/answer",{...fe(s,n,"existing"),commentId:s.commentId,answer:s.answer});return be(a,s,n,We)},discussionSetLabels:async s=>{const n=W(s),a=await de(t,n,"/discussions/labels",{...fe(s,n,"existing"),labels:s.labels});return be(a,s,n,We)},changeRequestsList:async(s,n)=>{const a=W(s),i=ts(s);i.set("page",String(n?.page??1)),n?.query&&i.set("query",n.query),n?.state&&i.set("state",n.state),n?.people&&i.set("people",n.people);const o=await He(t,a,"/pulls/list",{},i);if(!o||!Array.isArray(o.items))throw new Error("Source control response contained invalid change requests");return ku(o,o.items.map(r=>El(r,a)))},changeRequestContext:async(s,n,a)=>{const i=W(s),o=ts(s);o.set("number",String(n)),a?.includeDiff&&o.set("diff","1"),a?.includeCIDetails&&o.set("checkDetails","1"),a?.includeTimeline&&o.set("timeline","1"),a?.revision&&o.set("revision",a.revision),a?.project&&(o.set("owner",a.project.owner),o.set("repo",a.project.name));const r=await He(t,i,"/pulls/context",{},o),c={identity:i,project:r.project?ia(r.project,i):null,changeRequest:r.changeRequest?El(r.changeRequest,i):null,issueComments:r.issueComments.map(l=>Ll(l,i)),reviewComments:r.reviewComments.map(l=>tF(l,i)),files:r.files.map(l=>({...l})),diff:r.diff,ci:Tb(r.ci,i),fetchedAt:r.fetchedAt};if(r.commits&&(c.commits=r.commits.map(WB),c.commitsComplete=r.commitsComplete!==!1,c.verdicts=(r.verdicts??[]).map(l=>_B(l,i)),r.reviewers&&(c.reviewers=r.reviewers.map(l=>rt(l,i)))),r.stack===null)c.stack=null;else if(r.stack!==void 0){const l=Ib(r.stack);l&&(c.stack=l)}if(r.voteLabels!==void 0){if(!Array.isArray(r.voteLabels))throw new Error("Source control response contained invalid vote labels");c.voteLabels=r.voteLabels.map(l=>QB(l,i))}if(r.submitRequirements!==void 0){if(!Array.isArray(r.submitRequirements))throw new Error("Source control response contained invalid submit requirements");c.submitRequirements=r.submitRequirements.map(YB)}if(r.revisions!==void 0){if(!Array.isArray(r.revisions))throw new Error("Source control response contained invalid revisions");c.revisions=r.revisions.map(l=>XB(l,i))}return c},issuesList:async(s,n)=>{const a=W(s),i=ts(s);i.set("page",String(n?.page??1)),n?.query&&i.set("query",n.query),n?.state&&i.set("state",n.state),n?.people&&i.set("people",n.people);const o=await He(t,a,"/issues/list",{},i);if(!o||!Array.isArray(o.items))throw new Error("Source control response contained invalid issues");return ku(o,o.items.map(r=>bu(r,a)))},issueGet:async(s,n,a)=>{const i=W(s),o=ts(s);o.set("number",String(n)),a&&(o.set("owner",a.owner),o.set("repo",a.name));const r=await He(t,i,"/issues/get",{},o);return r===null?null:bu(r,i)},issueComments:async(s,n,a)=>{const i=W(s),o=ts(s);o.set("number",String(n)),a&&(o.set("owner",a.owner),o.set("repo",a.name));const r=await He(t,i,"/issues/comments",{},o);if(!Array.isArray(r))throw new Error("Source control response contained invalid comments");return r.map(c=>Ll(c,i))},projectUpstream:async s=>{const n=W(s),a=ts(s),i=await He(t,n,"/repo/upstream",{},a);if(!i||!ht(i.identity,n)||!Ae(i.isFork)||i.upstream!==null&&i.upstream===void 0||i.isFork!==!!i.upstream)throw new Error("Source control response contained an invalid upstream");return{identity:n,isFork:i.isFork,upstream:i.upstream?ia(i.upstream,n):null}},projectBranches:async(s,n,a)=>{const i=W(s),o=ts(s);o.set("owner",n),o.set("repo",a);const r=await He(t,i,"/repo/branches",{},o);return aF(r)},references:(s,n)=>vB(t,s,n),referencesAcross:(s,n)=>AB(t,s,n),referenceDetail:(s,n)=>CB(t,s,n),changeRequestListStatuses:(s,n)=>zB(t,s,n)}},cF=p({status:y("unsupported"),reason:y("host-setup-required")}).strict(),jb=g().regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/),ql=p({credentialId:g().regex(/^ocgit:v1:ssh:[A-Za-z0-9_-]{1,267}$/),label:y("SSH"),fingerprint:jb,capability:J([p({status:y("ready")}).strict(),p({status:y("unavailable"),reason:R(["unreadable","encrypted-or-unverifiable","fingerprint-mismatch"])}).strict()])}).strict(),lF=ql.extend({capability:p({status:y("ready")}).strict()}),yu=g().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),dF=J([p({candidateId:g().regex(/^[A-Za-z0-9_-]{1,200}$/),label:yu,fingerprint:jb,capability:p({status:y("ready")}).strict()}).strict(),p({label:yu,capability:p({status:y("unavailable"),reason:R(["unreadable","encrypted-or-unverifiable","insecure-permissions"])}).strict()}).strict()]),gF=J([cF,p({status:y("available"),credentials:x(ql).max(256)}).strict(),p({status:y("discovered"),candidates:x(dF).max(128),truncated:z()}).strict(),p({status:y("imported"),credentials:x(ql).max(256),selectedCredential:lF}).strict(),p({status:y("rejected"),reason:R(["candidate-expired","candidate-changed","fingerprint-mismatch","candidate-unavailable","inventory-full"])}).strict()]),pF=async(e,t=C)=>{const s=await t("/api/git/managed-ssh-credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw new Error("Managed SSH inventory request failed");const n=gF.parse(await s.json());if(n.status==="imported"&&!n.credentials.some(a=>a.credentialId===n.selectedCredential.credentialId&&a.fingerprint===n.selectedCredential.fingerprint&&a.capability.status==="ready"))throw new Error("Managed SSH import response is inconsistent");return n},uF=()=>({managedSshCredentials:pF,configureTransportBinding:IB,removeTransportBinding:RB,configureAuxiliaryBinding:jB,checkIsGitRepository:PO,getGitStatus:zO,prefetchProjectStatuses:SO,getGitDiff:xO,getGitDiffs:TO,getGitFileDiff:DO,getGitRangeDiff:IO,getGitRangeFiles:jO,getBranchBase:OO,revertGitFile:BO,stageGitFile:FO,stageGitFiles:hb,unstageGitFile:NO,unstageGitFiles:fb,stageGitHunk:MO,unstageGitHunk:EO,revertGitHunk:LO,isLinkedWorktree:qO,getGitBranches:VO,getGitUnpushedBranchCounts:UO,deleteGitBranch:WO,removeRemote:HO,generateCommitMessage:GO,generatePullRequestDescription:_O,listGitWorktrees:au,validateGitWorktree:iu,createGitWorktree:ou,deleteGitWorktree:ru,validateWorktreeDirectory:YD,canonicalizeWorktreeState:XD,createGitCommit(e,t,s){return iD(e,t,s)},gitPush:oD,gitPull:rD,gitFetch:cD,planNetworkOperation:dD,issueContributorDestination:gD,listContributorDestinations:pD,inspectCheckoutTrust:uD,decideCheckoutTrust:mD,executeNetworkOperation:hD,getNetworkOperation:fD,cancelNetworkOperation:bD,listGitStashes:kD,countGitStashFiles:yD,stashGitChanges:yb,applyGitStash:wD,popGitStash:wb,dropGitStash:vD,checkoutBranch:CD,createBranch:SD,renameBranch:PD,getGitLog(e,t){return AD(e,t)},addChangeIdToHead:xD,getCommitFiles:TD,getCommitFileDiff:ID,getGitCommitDiff:RO,getCurrentGitIdentity:BD,hasLocalIdentity:FD,setGitIdentity:MD,getGitIdentities:RD,createGitIdentity:jD,updateGitIdentity:OD,deleteGitIdentity:DD,getGlobalGitIdentity:ND,getRemotes:ED,rebase:LD,abortRebase:qD,continueRebase:KD,merge:VD,abortMerge:_D,continueMerge:ZD,checkoutCommit:UD,cherryPick:WD,revertCommit:HD,resetToCommit:GD,stash:JD,stashPop:$D,getConflictDetails:QD,worktree:{list:au,validate:iu,bootstrapStatus:KO,preview:ZO,create:ou,remove:ru,setTitle:$O,setPinned:YO,snapshot:aD,archive:XO,listArchives:eD,restoreArchive:tD,deleteArchive:sD}});let wu=null;const mF=()=>window.Capacitor,hF=e=>e.getPlatform?.()!=="android"||!e.registerPlugin?null:(wu??=e.registerPlugin("FileShare"),wu),fF=async e=>{const t=new Uint8Array(await e.arrayBuffer());let s="";for(let n=0;n<t.length;n+=32768)s+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(s)},bF=async e=>{const t=mF(),s=t?hF(t):null;if(s){await s.share({fileName:e.name,mimeType:e.type||"application/octet-stream",data:await fF(e)});return}if(!navigator.canShare?.({files:[e]}))throw new Error("File sharing is unavailable in this mobile runtime");await navigator.share({files:[e]})},ye=e=>e.replace(/\\/g,"/"),kF=(e,t)=>Ke.searchFiles(e,t),yF=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new It("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:ye(t?.directory||t?.path||e),entries:t.entries.filter(n=>!!(n&&typeof n.name=="string"&&typeof n.path=="string")).map(n=>({name:n.name,path:ye(n.path),isDirectory:!!n.isDirectory}))}},pt=(e,t,s)=>{const n=e?.(),a=kt(s),i=t||(a!==null&&kt(n)!==a?Rm(a):n);return i?{"x-opencode-directory":i}:void 0},wF=p({matches:x(p({path:g(),relativePath:g(),line:v().int().positive(),column:v().int().positive(),text:g(),ranges:x(xo([v().int().nonnegative(),v().int().nonnegative()])),cutStart:z()})),stopped:R(["limit","deadline"]).nullable()}),vF=p({error:g().optional(),reason:g().optional()}),CF=p({files:x(p({path:g(),relativePath:g()}))}),SF=({getDirectory:e,searchFiles:t=kF})=>({async listDirectory(s,n){const a=ye(s),i=new URLSearchParams;a&&i.set("path",a),n?.respectGitignore&&i.set("respectGitignore","true");const o=await C("/api/fs/list",{query:i,headers:pt(e,void 0,a)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new It(c.error||"Failed to list directory",{reason:_a(c.reason),status:o.status})}const r=await o.json();return yF(a,r)},async search(s){const n=ye(s.directory),a=!!s.includeHidden,i=s.respectGitignore!==!1;if(a||!i){const r=new URLSearchParams;r.set("query",s.query),n&&r.set("directory",n),typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)&&r.set("limit",String(s.maxResults)),a&&r.set("includeHidden","true"),i||r.set("respectGitignore","false");const c=await C("/api/fs/search",{query:r,headers:pt(e,n)});if(!c.ok){const d=await c.json().catch(()=>({error:c.statusText}));throw new Error(d.error||"Failed to search files")}const l=CF.safeParse(await c.json().catch(()=>null));if(!l.success)throw new It("File search returned an invalid response",{reason:"invalid-response"});return l.data.files.map(d=>({path:ye(d.path),preview:[ye(d.relativePath)]}))}return(await t(s.query,{directory:n,limit:typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)?s.maxResults:void 0,type:"file"})).map(r=>({path:ye(r.path),preview:[ye(r.relativePath)]}))},async searchContents(s){const n=ye(s.directory),a=new URLSearchParams({query:s.query,regex:s.regex?"true":"false"});s.limit!==void 0&&a.set("limit",String(s.limit)),s.includeHidden&&a.set("includeHidden","true"),s.respectGitignore===!1&&a.set("respectGitignore","false");const i=await C("/api/fs/find-in-files",{query:a,cache:"no-store",signal:s.signal,headers:pt(e,n)});if(i.ok){const c=wF.safeParse(await i.json().catch(()=>null));if(!c.success)throw new It("Content search returned an invalid response",{reason:"invalid-response"});return{status:"ok",matches:c.data.matches.map(l=>({...l,path:ye(l.path)})),stopped:c.data.stopped}}const o=vF.safeParse(await i.json().catch(()=>null)),r=o.success?o.data.reason:void 0;if(i.status===501&&r==="search-unavailable")return{status:"unavailable"};if(i.status===400&&r==="invalid-pattern")return{status:"invalid-pattern",message:o.success&&o.data.error?o.data.error:"Invalid regular expression"};throw new It(o.success&&o.data.error||i.statusText||"Failed to search file contents",{status:i.status})},async createDirectory(s){const n=ye(s),a=await C("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...pt(e,void 0,n)},body:JSON.stringify({path:n})});if(!a.ok){const o=await a.json().catch(()=>({error:a.statusText}));throw new Error(o.error||"Failed to create directory")}const i=await a.json();return{success:!!i?.success,path:typeof i?.path=="string"?ye(i.path):n}},async statFile(s,n){const a=ye(s),i=new URLSearchParams({path:a});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant);const o=await C("/api/fs/stat",{query:i,signal:AbortSignal.timeout(3e4),headers:pt(e,n?.directory,a)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new Error(c.error||"Failed to stat file")}const r=await o.json().catch(()=>({}));return{path:typeof r.path=="string"?ye(r.path):a,isFile:!!r.isFile,size:typeof r.size=="number"?r.size:0,mtimeMs:typeof r.mtimeMs=="number"?r.mtimeMs:void 0}},async readFile(s,n){const a=ye(s),i=new URLSearchParams({path:a});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&i.set("optional","true");const o=await C("/api/fs/read",{query:i,signal:AbortSignal.timeout(3e4),cache:n?.optional||n?.fresh?"no-store":"default",headers:pt(e,n?.directory,a)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new Error(c.error||"Failed to read file")}return{content:await o.text(),path:a}},async writeFile(s,n){const a=ye(s),i=await C("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...pt(e,void 0,a)},body:JSON.stringify({path:a,content:n})});if(!i.ok){const r=await i.json().catch(()=>({error:i.statusText}));throw new Error(r.error||"Failed to write file")}const o=await i.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?ye(o.path):a}},async uploadFile(s,n,a){const i=ye(s),o=await C("/api/fs/upload",{method:"POST",query:{path:i,overwrite:a?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...pt(e,a?.directory,i)},body:n});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new It(c.error||"Failed to upload file",{reason:_a(c.reason),status:o.status})}const r=await o.json().catch(()=>({}));return{success:!!r.success,path:r.path?ye(r.path):i}},async delete(s){const n=ye(s),a=await C("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...pt(e,void 0,n)},body:JSON.stringify({path:n})});if(!a.ok){const o=await a.json().catch(()=>({error:a.statusText}));throw new Error(o.error||"Failed to delete file")}return{success:!!(await a.json().catch(()=>({}))).success}},async rename(s,n){const a=await C("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...pt(e,void 0,s)},body:JSON.stringify({oldPath:s,newPath:n})});if(!a.ok){const o=await a.json().catch(()=>({error:a.statusText}));throw new It(o.error||"Failed to rename file",{reason:_a(o.reason),status:a.status})}const i=await a.json().catch(()=>({}));return{success:!!i.success,path:i.path?ye(i.path):n}},async revealPath(s){const n=await C("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...pt(e,void 0,s)},body:JSON.stringify({path:ye(s)})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(s,n){const a=ye(s),i=new URLSearchParams({path:a,download:"true"});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant);const o=await C("/api/fs/raw",{query:i,headers:pt(e,n?.directory,a)});if(!o.ok)throw new Error(`Download failed (${o.status})`);const r=await o.blob(),c=a.split("/").pop()||"file";if(window.Capacitor?.isNativePlatform?.()===!0){await bF(new File([r],c,{type:r.type||"application/octet-stream"}));return}const d=URL.createObjectURL(r),u=document.createElement("a");u.href=d,u.download=c,document.body.appendChild(u),u.click(),document.body.removeChild(u),setTimeout(()=>URL.revokeObjectURL(d),100)}}),PF="/api/config/settings",vu=()=>`${PF}?${$h}=${rr()}`,AF="/api/config/reload",Cu=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},zF=()=>({async load(){const e=await C(vu(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:Cu(await e.json()),source:"web"}},async save(e){const t=await C(vu(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to save settings")}return Cu(await t.json())},async restartOpenCode(){const e=await C(AF,{method:"POST"});if(!e.ok){const t=await e.json().catch(()=>({error:e.statusText}));throw new Error(t.error||"Failed to restart OpenCode")}return{restarted:!0}}}),xF=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),TF=p({type:y("openchamber:notification-navigation"),url:g().url(),expiresAt:v().finite()});let ai=null;function Ob(e){if(!ai)return!1;try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin&&t.pathname===window.location.pathname&&ai(t)}catch{return!1}}function GV(e){ai=e;const t="serviceWorker"in navigator?navigator.serviceWorker:null,s=n=>{const a=TF.safeParse(n.data),i=n.ports[0];if(!(!a.success||!i))try{const o=n.origin===window.location.origin&&Date.now()<a.data.expiresAt&&Ob(a.data.url);i.postMessage(o)}catch{i.postMessage(!1)}finally{i.close()}};return t?.addEventListener("message",s),()=>{t?.removeEventListener("message",s),ai===e&&(ai=null)}}const IF=1500,Vl=5e3,RF="openchamber-notification-claim:",ii=new Map,jF=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),OF=e=>{if(typeof e!="string")return null;const t=e.trim();return t?`/?session=${encodeURIComponent(t)}`:null},Db=e=>{const t=typeof e?.sessionId=="string"?e.sessionId.trim():"";if(!t)return;const s=OF(t);if(s)return{url:s,sessionId:t}},Bb=(e,t)=>{const s={body:e?.body,tag:e?.tag};return t&&(s.data=t),s},DF=e=>{try{if(typeof window>"u"||(typeof window.focus=="function"&&window.focus(),!e)||`${window.location.pathname}${window.location.search}`===e.url||Ob(e.url))return;window.location.assign(e.url)}catch{}},BF=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.trim()).join("|")},FF=e=>{for(const[t,s]of ii)e-s>Vl&&ii.delete(t)},NF=e=>{const t=BF(e);if(!t)return!0;const s=Date.now();FF(s);const n=ii.get(t)??0;if(s-n<Vl)return!1;try{if(typeof window<"u"&&window.localStorage){const a=`${RF}${t}`,i=Number(window.localStorage.getItem(a)??"0");if(Number.isFinite(i)&&s-i<Vl)return ii.set(t,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(a),window.localStorage.setItem(a,String(s))}}catch{}return ii.set(t,s),!0},Fb=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(s=>{setTimeout(()=>s(null),IF)})])??e}catch{return e}},MF=async e=>{const t=await Fb();if(!t||typeof t.showNotification!="function")return!1;try{const s=Db(e);return await t.showNotification(e?.title??"OpenChamber",Bb(e,s)),!0}catch(s){return console.warn("Failed to send notification via service worker",s),!1}},EF=async()=>{const e=await Fb();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},LF=async e=>{if(e?.requireHidden&&typeof document<"u"&&document.hasFocus())return!0;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",e),!1;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),!1;if(!jF()&&await EF()||!NF(e))return!0;try{if(await MF(e))return!0;const t=Db(e),s=new Notification(e?.title??"OpenChamber",Bb(e,t));return s.onclick=n=>{n.preventDefault(),DF(t),s.close()},!0}catch(t){return console.warn("Failed to send notification",t),!1}},qF=async e=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,runtimeKey:e?.runtimeKey,requireHidden:e?.requireHidden,showWhenFocused:e?.showWhenFocused}}),!0}catch(s){return console.warn("Failed to send native notification (desktop)",s),!1}},VF=()=>({async notifyAgentCompletion(e){return await qF(e)||await LF(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),jn=async(e,t)=>{try{const s=await C(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return s.ok?await s.json():null}catch{return null}},UF=()=>({async getVapidPublicKey(){return jn("/api/push/vapid-public-key")},async subscribe(e){return jn("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return jn("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return jn("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return jn("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return jn("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),WF=new Set(vf),HF=g().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!WF.has(e),{message:"Reserved tracker id"}),GF=e=>{try{return new RegExp(e),!0}catch{return!1}},Su=g().min(1).max(2048).refine(GF),Lt=z().catch(!1),_F=p({id:HF,name:g().min(1).max(64),authMethods:x(g()).transform(e=>e.filter(t=>t==="oauth"||t==="token")),capabilities:p({multipleAccounts:Lt,stateUpdate:Lt,children:Lt,labels:Lt,priority:Lt,filters:p({people:Lt,priority:Lt}).catch({people:!1,priority:!1}),projectMapping:Lt,sessionComments:Lt,hostAccess:Lt}),stateFilters:x(g().min(1).max(32)).max(32),urlPatterns:x(p({host:g().min(1).max(256),path:Su,query:p({name:g().min(1).max(64)}).optional().catch(void 0)}).nullable().catch(null)).max(8).transform(e=>e.filter(t=>t!==null)),identifierPattern:Su}),KF=x(_F.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const n of e)!n||t.has(n.id)||(t.add(n.id),s.push(n));return s}),Pu=new Map,_V=e=>{const t=Pu.get(e);if(t)return t;const s={id:e,name:e,authMethods:[],capabilities:{multipleAccounts:!1,stateUpdate:!1,children:!1,labels:!1,priority:!1,filters:{people:!1,priority:!1},projectMapping:!1,sessionComments:!1,hostAccess:!1},stateFilters:["open","all"],urlPatterns:[],identifierPattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$"};return Pu.set(e,s),s},ZF=p({error:g()}),Nb=async(e,t)=>{const s=ZF.safeParse(await e.json().catch(()=>null));return new Error(s.success&&s.data.error.trim()||e.statusText||t)};async function Mb(e,t,s,n,a){const i=new Headers({Accept:"application/json"});s.body!==void 0&&i.set("Content-Type","application/json");const o=await e(t,{method:s.method,body:s.body,headers:i});if(!o.ok)throw await Nb(o,a);const r=n.safeParse(await o.json().catch(()=>null));if(!r.success)throw new Error(`${a}: unreadable answer`);return r.data}const _e=g().trim().min(1),ft=g().trim().nullish().catch(null).transform(e=>e||null),Eb=R(["triage","backlog","todo","in-progress","done","canceled"]),JF=R(["none","urgent","high","medium","low"]),Ms=e=>x(Y()).catch([]).transform(t=>t.flatMap(s=>{const n=e.safeParse(s);return n.success?[n.data]:[]})),tg=p({name:ft,avatarUrl:ft}).nullish().catch(null).transform(e=>e&&(e.name||e.avatarUrl)?e:null),$F=g().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null}),QF=p({id:ft,name:g().trim().catch(""),category:Eb.nullable().catch(null)}).nullish().catch(null).transform(e=>e??null),YF=p({total:v().int().positive(),done:v(),more:z().catch(!1)}).nullish().catch(null).transform(e=>e?{...e,done:Math.min(Math.max(e.done,0),e.total)}:null),Lb={provider:_e,id:_e,identifier:_e,title:_e,url:_e,state:QF,priority:JF.nullish().catch(null),assignee:tg.optional(),container:p({id:_e,key:ft,name:_e}).nullish().catch(null),updatedAt:ft.optional()},qb=p(Lb),Vb=p({...Lb,labels:Ms(p({id:_e,name:_e,color:$F})).optional(),parent:qb.nullish().catch(null),progress:YF.optional()}),XF=Vb,eN=p({id:_e,body:g().catch(""),createdAt:ft,author:tg}),tN=Vb.extend({description:g().nullish().catch(null).transform(e=>e??null),comments:Ms(eN),children:Ms(qb),childrenMore:z().catch(!1)}),ba=p({connected:y(!1)}).transform(()=>({connected:!1})),sN=J([ba,p({connected:y(!0),items:Ms(XF),cursor:ft,hasMore:z().catch(!1)})]),Au=J([ba,p({connected:y(!0),item:tN.nullish().catch(null).transform(e=>e??null)})]),nN=p({id:_e,name:_e,category:Eb.nullable().catch(null),position:v().catch(0)}),aN=J([ba,p({connected:y(!0),states:Ms(nN)})]),Tc=p({id:_e,name:ft,user:tg.optional(),current:z().catch(!1),authorizedAt:v().nullish().catch(null),status:R(["valid","invalid"]).optional().catch(void 0),invalidReason:g().trim().min(1).max(256).optional().catch(void 0),method:R(["oauth","token"]).optional().catch(void 0)}),zu=p({instance:g().trim().min(1).max(2048).nullable().catch(null),instances:J([p({kind:y("fixed"),origin:g().trim().min(1).max(2048)}),p({kind:y("user"),label:g().trim().min(1).max(64),placeholder:g().trim().min(1).max(256).optional()})]),hasClient:z().catch(!1),redirectUri:g().trim().min(1).max(2048).nullable().catch(null)}),xu=J([p({connected:y(!1),accounts:Ms(Tc).optional(),connect:zu.optional().catch(void 0)}),p({connected:y(!0),account:Tc.nullish().catch(null),accounts:Ms(Tc),connect:zu.optional().catch(void 0)})]),iN=["UNSUPPORTED","INSTANCE_REQUIRED","INSTANCE_MISMATCH","UNSUPPORTED_INSTANCE","TOKEN_REQUIRED","TOKEN_REFUSED","USERNAME_REQUIRED","USERNAME_INVALID","CLIENT_MISSING","CONNECT_SUPERSEDED","TRACKER_UNAVAILABLE"],oN=p({error:g().optional(),code:g().optional()}),Tu=async e=>{if(e.ok)return{ok:!0};const t=oN.safeParse(await e.json().catch(()=>null));if(!t.success)return{ok:!1,code:"failed",message:null};const s=R(iN).safeParse(t.data.code);return{ok:!1,code:s.success?s.data:"failed",message:t.data.error?.trim()||null}},rN=p({authorizationUrl:_e,expiresIn:v().positive()}),Iu=J([ba,p({connected:y(!0),defaultProjectPath:ft,containers:Ms(p({id:_e,key:ft,name:_e,projectPath:ft}))})]),Jo=p({sessionComments:z()}),Ub=J([ba,p({connected:y(!0),posted:y(!0),commentId:ft}),p({connected:y(!0),posted:y(!1),skipped:R(["already-posted","issue-not-found","not-started","disabled","origin-not-public"])})]),cN=new Map([["triage","triage"],["backlog","backlog"],["unstarted","todo"],["started","in-progress"],["completed","done"],["canceled","canceled"],["duplicate","canceled"]]),Wb=e=>e?cN.get(e)??null:null,lN=new Map([["linear","linear"]]),KV=e=>lN.get(e)??"tracker",Hb={id:"linear",name:"Linear",authMethods:["oauth"],capabilities:{multipleAccounts:!0,stateUpdate:!0,children:!0,labels:!0,priority:!0,filters:{people:!0,priority:!0},projectMapping:!0,sessionComments:!0,hostAccess:!0},stateFilters:["open","all","backlog","todo","in-progress","inReview","done","canceled","duplicate"],urlPatterns:[{host:"linear.app",path:"^/[^/]+/issue/([A-Za-z][A-Za-z0-9]*-\\d+)(?:/|$)"}],identifierPattern:"^[A-Za-z][A-Za-z0-9]*-\\d+$"},dN=["none","urgent","high","medium","low"],gN=new Map([["in-progress","started"],["done","completed"]]),Ze=g().trim().min(1),Je=g().trim().nullish().catch(null).transform(e=>e||null),ln=e=>x(Y()).catch([]).transform(t=>t.flatMap(s=>{const n=e.safeParse(s);return n.success?[n.data]:[]})),vr=p({name:Je,displayName:Je,avatarUrl:Je}).nullish().catch(null).transform(e=>{const t=e?.displayName||e?.name||null,s=e?.avatarUrl??null;return t||s?{name:t,avatarUrl:s}:null}),pN=p({id:Je,name:Je,type:Je}).nullish().catch(null).transform(e=>e&&(e.id||e.name||e.type)?{id:e.id,name:e.name??"",category:Wb(e.type)}:null),Gb={id:Ze,identifier:Ze,title:Ze,url:Ze,state:pN,assignee:vr,team:p({id:Ze,key:Je,name:Ze}).nullish().catch(null),priority:v().int().nullish().catch(null),updatedAt:Je},Ul=(e,t)=>({provider:t,id:e.id,identifier:e.identifier,title:e.title,url:e.url,state:e.state,priority:e.priority!=null?dN[e.priority]??null:null,assignee:e.assignee,container:e.team?{id:e.team.id,key:e.team.key,name:e.team.name}:null,updatedAt:e.updatedAt}),_b=p(Gb),Kb=p({...Gb,labels:ln(p({id:Ze,name:Ze,color:g().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null})})),parent:_b.nullish().catch(null),subIssueProgress:p({total:v().int().positive(),done:v(),more:z().catch(!1)}).nullish().catch(null)}),Zb=(e,t)=>({...Ul(e,t),labels:e.labels,parent:e.parent?Ul(e.parent,t):null,progress:e.subIssueProgress?{...e.subIssueProgress,done:Math.min(Math.max(e.subIssueProgress.done,0),e.subIssueProgress.total)}:null}),uN=Kb.extend({description:g().nullish().catch(null),comments:ln(p({id:Ze,body:g().catch(""),createdAt:Je,user:vr})),subIssues:ln(_b),subIssuesMore:z().catch(!1)}),mN=(e,t)=>({...Zb(e,t),description:e.description??null,comments:e.comments.map(s=>({id:s.id,body:s.body,createdAt:s.createdAt,author:s.user})),children:e.subIssues.map(s=>Ul(s,t)),childrenMore:e.subIssuesMore}),hN=p({id:Ze,name:Je,current:z().catch(!1),user:vr,authorizedAt:v().nullish().catch(null)}),Ru=p({connected:z(),user:vr,organization:p({id:Ze,name:Je}).nullish().catch(null),workspaces:ln(hN)}).transform(e=>{if(!e.connected)return{connected:!1};const t=[...e.workspaces];return t.length===0&&e.organization&&t.push({id:e.organization.id,name:e.organization.name,user:e.user,current:!0,authorizedAt:null}),{connected:!0,account:t.find(s=>s.current)??null,accounts:t}}),fN=e=>{const t=new URLSearchParams,s=(i,o)=>{const r=o?.trim();r&&t.set(i,r)},n=e?.state?.trim();s("query",e?.query),s("cursor",e?.cursor),s("status",n?gN.get(n)??n:void 0),s("assignee",e?.people),s("teamId",e?.containerId),s("priority",e?.priority);const a=t.toString();return a?`?${a}`:""},bN=e=>{const t=async(o,r,c,l,d)=>{if(o!==Hb.id)throw new Error(`Unknown tracker: ${o}`);return Mb(e,`/api/linear${r}`,c,l,d)},s={method:"GET"},n=o=>J([ba,o]),a=o=>n(p({connected:y(!0),issue:uN.nullish().catch(null)}).transform(({issue:r})=>({connected:!0,item:r?mN(r,o):null}))),i=n(p({connected:y(!0),defaultProjectPath:Je,teams:ln(p({id:Ze,key:Je,name:Ze,projectPath:Je}))}).transform(({defaultProjectPath:o,teams:r})=>({connected:!0,defaultProjectPath:o,containers:r})));return{authStatus:o=>t(o,"/auth/status",s,Ru,"Failed to load Linear status"),authStart:(o,r)=>t(o,"/auth/start",{method:"POST",body:JSON.stringify({origin:r})},p({authorizationUrl:Ze,expiresIn:v().positive()}),"Failed to start Linear auth"),authConnectToken:async()=>({ok:!1,code:"UNSUPPORTED",message:null}),authSaveOAuthClient:async()=>({ok:!1,code:"UNSUPPORTED",message:null}),authDisconnect:o=>t(o,"/auth",{method:"DELETE"},p({removed:z().catch(!1)}),"Failed to disconnect Linear").then(({removed:r})=>({removed:r})),authActivate:(o,r)=>t(o,"/auth/activate",{method:"POST",body:JSON.stringify({organizationId:r})},Ru,"Failed to switch Linear workspace"),list:(o,r)=>t(o,`/issues/list${fN(r)}`,s,n(p({connected:y(!0),issues:ln(Kb),cursor:Je,hasMore:z().catch(!1)}).transform(({issues:c,cursor:l,hasMore:d})=>({connected:!0,items:c.map(u=>Zb(u,o)),cursor:l,hasMore:d}))),"Failed to load Linear issues"),refreshListReads:async o=>{await t(o,"/read-cache/refresh?scope=lists",{method:"POST"},Y(),"Failed to refresh Linear lists")},get:(o,r)=>t(o,`/issues/get?${new URLSearchParams({id:r}).toString()}`,s,a(o),"Failed to load Linear issue"),states:(o,r)=>t(o,`/issues/states?${new URLSearchParams({teamId:r}).toString()}`,s,n(p({connected:y(!0),states:ln(p({id:Ze,name:Ze,type:Je,position:v().catch(0)}).transform(({id:c,name:l,type:d,position:u})=>({id:c,name:l,category:Wb(d),position:u})))})),"Failed to load Linear workflow states"),updateState:(o,r)=>t(o,"/issues/update",{method:"POST",body:JSON.stringify({id:r.id,stateId:r.stateId})},a(o),"Failed to update Linear issue"),mappingGet:o=>t(o,"/mapping",s,i,"Failed to load Linear mapping"),mappingSet:(o,r)=>t(o,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:r.defaultProjectPath,teamProjectPaths:r.containerProjectPaths})},i,"Failed to save Linear mapping"),sessionStatusPost:(o,r)=>t(o,"/session-status",{method:"POST",body:JSON.stringify({kind:r.kind,sessionId:r.sessionId,issueIdentifier:r.identifier,sessionOrigin:r.sessionOrigin})},Ub,"Failed to post Linear session status"),preferencesGet:o=>t(o,"/preferences",s,Jo,"Failed to load Linear preferences"),preferencesSet:(o,r)=>t(o,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:r.sessionComments})},Jo,"Failed to save Linear preferences")}},kN=p({providers:x(Y())}),yN=e=>{const t=e?.split(";")[0]?.trim().toLowerCase()??"";return t==="application/json"||t.endsWith("+json")};async function wN(e){const t=await e("/api/tracker/providers",{headers:{Accept:"application/json"}});if(t.status===404)return{kind:"legacy-linear"};if(!t.ok)throw await Nb(t,"Failed to load trackers");if(!yN(t.headers.get("content-type")))return{kind:"legacy-linear"};const s=kN.parse(await t.json().catch(()=>null)).providers,n=KF.parse(s);if(s.length>0&&n.length===0)throw new Error("Trackers response contained no readable tracker");return{kind:"tracker",descriptors:n}}const Ic=(e,t)=>`/api/tracker/${encodeURIComponent(e)}${t}`,vN=({fetch:e=C,runtimeKey:t=D}={})=>{const s=bN(e);let n=null;const a=()=>{const l=wN(e),d={runtimeKey:t(),request:l};return n=d,l.catch(()=>{n===d&&(n=null)}),l},i=async()=>(await((n?.runtimeKey===t()?n.request:null)??a())).kind==="legacy-linear",o=(l,d,u,m,f)=>Mb(e,Ic(l,d),u,m,f),r={method:"GET"},c=l=>{const d=new URLSearchParams,u=(f,b)=>{const k=b?.trim();k&&d.set(f,k)};u("query",l?.query),u("cursor",l?.cursor),u("state",l?.state),u("people",l?.people),u("priority",l?.priority),u("containerId",l?.containerId);const m=d.toString();return m?`?${m}`:""};return{async providers(){const l=await a();return l.kind==="legacy-linear"?[Hb]:l.descriptors},async authStatus(l){return await i()?s.authStatus(l):o(l,"/auth/status",r,xu,"Failed to load tracker status")},async authStart(l,d,u){if(await i())return s.authStart(l,d);const m=u?.instance?{origin:d,instance:u.instance}:{origin:d};return o(l,"/auth/start",{method:"POST",body:JSON.stringify(m)},rN,"Failed to start tracker sign-in")},async authConnectToken(l,d){if(await i())return s.authConnectToken(l,d);try{const u=await e(Ic(l,"/auth/token"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(d)});return await Tu(u)}catch{return{ok:!1,code:"failed",message:null}}},async authSaveOAuthClient(l,d){if(await i())return s.authSaveOAuthClient(l,d);try{const u=await e(Ic(l,"/auth/oauth-client"),{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(d)});return await Tu(u)}catch{return{ok:!1,code:"failed",message:null}}},async authDisconnect(l){return await i()?s.authDisconnect(l):o(l,"/auth",{method:"DELETE"},p({removed:z().catch(!1)}),"Failed to disconnect tracker").then(({removed:d})=>({removed:d}))},async authActivate(l,d){return await i()?s.authActivate(l,d):o(l,"/auth/activate",{method:"POST",body:JSON.stringify({accountId:d})},xu,"Failed to switch tracker account")},async list(l,d){return await i()?s.list(l,d):o(l,`/items/list${c(d)}`,r,sN,"Failed to load tracker items")},async refreshListReads(l){if(await i())return s.refreshListReads(l);await o(l,"/read-cache/refresh?scope=lists",{method:"POST"},Y(),"Failed to refresh tracker lists")},async get(l,d){return await i()?s.get(l,d):o(l,`/items/get?${new URLSearchParams({id:d}).toString()}`,r,Au,"Failed to load tracker item")},async states(l,d){return await i()?s.states(l,d):o(l,`/states?${new URLSearchParams({containerId:d}).toString()}`,r,aN,"Failed to load workflow states")},async updateState(l,d){return await i()?s.updateState(l,d):o(l,"/items/update",{method:"POST",body:JSON.stringify({id:d.id,stateId:d.stateId})},Au,"Failed to update tracker item")},async mappingGet(l){return await i()?s.mappingGet(l):o(l,"/mapping",r,Iu,"Failed to load project mapping")},async mappingSet(l,d){return await i()?s.mappingSet(l,d):o(l,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:d.defaultProjectPath,containerProjectPaths:d.containerProjectPaths})},Iu,"Failed to save project mapping")},async sessionStatusPost(l,d){return await i()?s.sessionStatusPost(l,d):o(l,"/session-status",{method:"POST",body:JSON.stringify({kind:d.kind,sessionId:d.sessionId,identifier:d.identifier,sessionOrigin:d.sessionOrigin})},Ub,"Failed to post session status")},async preferencesGet(l){return await i()?s.preferencesGet(l):o(l,"/preferences",r,Jo,"Failed to load tracker preferences")},async preferencesSet(l,d){return await i()?s.preferencesSet(l,d):o(l,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:d.sessionComments})},Jo,"Failed to save tracker preferences")}}},Cs=async e=>await e.json().catch(()=>null),CN=p({identityConflict:z().catch(!1)}),ju=async(e,t)=>{const s=await C(e,{method:t,headers:{Accept:"application/json"}}),n=await s.json().catch(()=>null),a=CN.safeParse(n);if(!s.ok||!a.success)throw new Error(s.statusText||"Failed to read relay status");return a.data},SN=()=>({async listClients(){const e=await C("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Cs(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load remote clients");return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){const t=await C("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),s=await Cs(t);if(!t.ok||!s?.client||typeof s.token!="string")throw new Error(s?.error||t.statusText||"Failed to create remote client token");return s},async createPairingSession(e={}){const t=await C("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),s=await Cs(t);if(!t.ok||typeof s?.pairing?.secret!="string"||!s?.server)throw new Error(s?.error||t.statusText||"Failed to create pairing session");return s},async listPendingPairings(){const e=await C("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Cs(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pending pairings");return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){const e=await C("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Cs(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pairing transports");return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable!==!1}},async cancelPairing(e){const t=await C(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Cs(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to cancel pairing");return{cancelled:s.cancelled===!0}},async revokeClient(e){const t=await C(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Cs(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to revoke remote client");return s},getRelayHostStatus:()=>ju("/api/openchamber/relay/status","GET"),resetRelayIdentity:()=>ju("/api/openchamber/relay/reset-identity","POST"),async purgeRevokedClients(){const e=await C("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Cs(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),PN=(e={})=>{const t=e.urls??Gl();return oy(t),{clipboard:hy(),themeFiles:fy(),runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Aj(),git:uF(),files:SF({getDirectory:()=>qd.getState().currentDirectory}),settings:zF(),permissions:xF(),notifications:VF(),sourceControl:rF(),trackers:vN(),push:UF(),clientAuth:SN()}},AN=3e3,Ou=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},zN=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__OPENCHAMBER_API_BASE_URL__),clientToken:e(window.__OPENCHAMBER_CLIENT_TOKEN__),localOrigin:e(window.__OPENCHAMBER_LOCAL_ORIGIN__),runtimeHeaders:window.__OPENCHAMBER_RUNTIME_HEADERS__,relayHostId:e(window.__OPENCHAMBER_RELAY_HOST_ID__),explicitRuntime:window.__OPENCHAMBER_EXPLICIT_RUNTIME__===!0}};let Wl=Promise.resolve();const ZV=()=>Wl,JV=()=>{const{apiBaseUrl:e,clientToken:t,localOrigin:s,runtimeHeaders:n,relayHostId:a,explicitRuntime:i}=zN(),o=Yu(),r=a||(o?.target==="remote"?o.hostId:""),c=em({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});dy({apiBaseUrl:e,runtimeKey:Ou(e,s)?"local":r?`host:${r}`:null});const l=u=>{const m=u.trim(),f=window.__OPENCHAMBER_DESKTOP__?.invoke;!m||!f||f("desktop_set_window_runtime_key",{runtimeKey:m}).catch(()=>{})};l(D()),Yo(u=>l(u.runtimeKey)),ym(t||null),wm(n||null),Ke.reconnectToRuntimeBaseUrl(),tr(e||void 0).catch(()=>{}),s&&!Ou(e,s)&&Object.keys(la()).length>0&&zm(s).catch(()=>{}),Mm();const d=()=>a?Pg(a,{reconnectActive:!0}):i?Promise.resolve():Pg();return Wl=Promise.race([d().catch(()=>{}),new Promise(u=>{window.setTimeout(u,1e4)})]).then(()=>{Ke.reconnectToRuntimeBaseUrl()}),Wl.then(()=>{window.setTimeout(()=>{Qw().catch(()=>{})},AN)}),PN({urls:c})},Du="openchamber:chunk-import-reload",xN=250,TN=3e4,IN=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function Jb(e){if(e instanceof Error)return`${e.name}
84
84
  ${e.message}
85
- ${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Bu(e){const t=Jb(e);return IN.some(s=>s.test(t))}function RN(e){return`2.6.1:${Jb(e).slice(0,500)}`}function jN(e){if(typeof window>"u"||je())return;const t=Date.now(),s=RN(e);let n=null;try{const i=window.sessionStorage.getItem(Du);if(i)try{n=JSON.parse(i)}catch{n=null}}catch{return}const a=typeof n?.timestamp=="number"?n.timestamp:0;if(!(n?.signature===s&&t-a<TN)){try{window.sessionStorage.setItem(Du,JSON.stringify({signature:s,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function ON(e,t={}){const s=t.retries??1;let n;for(let a=0;a<=s;a+=1)try{return await e()}catch(i){if(n=i,!Bu(i)||a>=s)break;await new Promise(o=>setTimeout(o,xN*(a+1)))}throw Bu(n)&&jN(n),n}const $V=e=>sk.lazy(()=>ON(e));export{Ox as $,sz as A,tz as B,ez as C,nz as D,XA as E,YA as F,rz as G,cz as H,kV as I,NR as J,IV as K,FR as L,eL as M,YE as N,JV as O,ON as P,Fz as Q,Nz as R,qr as S,Mz as T,qz as U,Lz as V,Ez as W,Nx as X,Fx as Y,Bx as Z,Dx as _,vR as a,am as a$,jx as a0,Rx as a1,Ix as a2,Tx as a3,xx as a4,zx as a5,Ax as a6,Px as a7,Sx as a8,Cx as a9,Jz as aA,Zz as aB,Kz as aC,_z as aD,Gz as aE,Hz as aF,Wz as aG,Uz as aH,D as aI,vV as aJ,Yo as aK,Rq as aL,yE as aM,Hr as aN,Ce as aO,DM as aP,tV as aQ,Xq as aR,gV as aS,Zq as aT,LV as aU,Dj as aV,Ai as aW,tr as aX,QR as aY,ls as aZ,hq as a_,vx as aa,wx as ab,yx as ac,kx as ad,bx as ae,fx as af,hx as ag,mx as ah,ux as ai,px as aj,gx as ak,dx as al,lx as am,cx as an,rx as ao,ox as ap,ix as aq,ax as ar,nx as as,sx as at,tx as au,ex as av,Xz as aw,Yz as ax,Qz as ay,$z as az,$e as b,NM as b$,ov as b0,nh as b1,lV as b2,fC as b3,cd as b4,Yr as b5,mL as b6,xq as b7,Tq as b8,ZV as b9,ui as bA,QM as bB,sr as bC,Ow as bD,jM as bE,$M as bF,wR as bG,vM as bH,AM as bI,Lm as bJ,qe as bK,XM as bL,eE as bM,Bp as bN,Fj as bO,eV as bP,jT as bQ,EV as bR,MV as bS,Qo as bT,SM as bU,Sy as bV,_A as bW,Gq as bX,Iz as bY,ps as bZ,Mq as b_,kh as ba,Yq as bb,xd as bc,kT as bd,jR as be,ct as bf,ee as bg,XN as bh,Ye as bi,CM as bj,SR as bk,Kq as bl,un as bm,_N as bn,bM as bo,bo as bp,JN as bq,$N as br,QN as bs,Dh as bt,an as bu,kA as bv,fq as bw,MM as bx,nq as by,nv as bz,qE as c,pn as c$,cE as c0,aq as c1,iq as c2,IA as c3,Ny as c4,sq as c5,ar as c6,gm as c7,zi as c8,mn as c9,sV as cA,sS as cB,$V as cC,kd as cD,tt as cE,rn as cF,mA as cG,yq as cH,CA as cI,al as cJ,Fh as cK,rq as cL,gA as cM,oq as cN,md as cO,kt as cP,Ah as cQ,$E as cR,ko as cS,cq as cT,lq as cU,gq as cV,pq as cW,eA as cX,dq as cY,uq as cZ,mq as c_,Lc as ca,Oy as cb,ca as cc,Yl as cd,UM as ce,Zl as cf,VM as cg,ss as ch,Pw as ci,JM as cj,Nq as ck,bq as cl,bd as cm,ra as cn,bn as co,ry as cp,Qn as cq,qM as cr,Bh as cs,_E as ct,CV as cu,wq as cv,FM as cw,fo as cx,RV as cy,Wc as cz,ME as d,FE as d$,kq as d0,FV as d1,ir as d2,_i as d3,Un as d4,wP as d5,yM as d6,Pg as d7,Gw as d8,Tt as d9,gR as dA,Of as dB,fM as dC,zj as dD,iS as dE,lm as dF,PM as dG,wM as dH,XL as dI,xh as dJ,PP as dK,TP as dL,AP as dM,IP as dN,CP as dO,nr as dP,mE as dQ,bE as dR,wE as dS,SE as dT,kE as dU,hE as dV,fE as dW,Mv as dX,Nv as dY,XE as dZ,BE as d_,tL as da,Xk as db,Yu as dc,WN as dd,TV as de,eq as df,HN as dg,kM as dh,GN as di,nM as dj,KN as dk,ZN as dl,aM as dm,ZA as dn,IS as dp,KL as dq,Ug as dr,aL as ds,ZL as dt,Bw as du,xw as dv,KM as dw,ZM as dx,Lw as dy,OM as dz,TE as e,NV as e$,lM as e0,dM as e1,gM as e2,pM as e3,tM as e4,iM as e5,uM as e6,rM as e7,sM as e8,oM as e9,en as eA,JA as eB,Hw as eC,Ww as eD,nE as eE,Ds as eF,Gv as eG,tq as eH,rr as eI,KE as eJ,mV as eK,OV as eL,WE as eM,RE as eN,Bq as eO,QE as eP,di as eQ,Dq as eR,Oq as eS,ly as eT,Rm as eU,YP as eV,la as eW,Qe as eX,FP as eY,xP as eZ,Ut as e_,mM as ea,cM as eb,mP as ec,hP as ed,kl as ee,qa as ef,Pd as eg,Vx as eh,qx as ei,Pz as ej,Oh as ek,jh as el,Ad as em,eM as en,RM as eo,TM as ep,IM as eq,cV as er,dR as es,lR as et,GV as eu,CR as ev,PR as ew,iz as ex,oz as ey,fz as ez,VE as f,VV as f$,im as f0,Kl as f1,$s as f2,iI as f3,OR as f4,hv as f5,GS as f6,GE as f7,sv as f8,sL as f9,Yx as fA,X as fB,Jk as fC,$k as fD,hV as fE,zV as fF,Hn as fG,Vg as fH,AR as fI,_q as fJ,LE as fK,Jq as fL,Rz as fM,KO as fN,zz as fO,PO as fP,VO as fQ,zO as fR,ru as fS,aD as fT,ou as fU,iu as fV,au as fW,sD as fX,tD as fY,eD as fZ,XO as f_,JL as fa,nS as fb,aS as fc,lE as fd,lL as fe,rL as ff,_r as fg,Qc as fh,bS as fi,Zk as fj,nL as fk,Ur as fl,wS as fm,uS as fn,OT as fo,Rs as fp,vT as fq,iL as fr,ib as fs,fL as ft,dL as fu,jL as fv,Hv as fw,KV as fx,bl as fy,Ss as fz,zE as g,xV as g$,YD as g0,UV as g1,DD as g2,OD as g3,jD as g4,ND as g5,RD as g6,Hd as g7,hb as g8,FO as g9,YO as gA,$O as gB,yb as gC,YN as gD,CS as gE,Wg as gF,DS as gG,OS as gH,ES as gI,ad as gJ,Pv as gK,GM as gL,DL as gM,PV as gN,HF as gO,Wb as gP,sI as gQ,fV as gR,$v as gS,Ec as gT,hM as gU,ZE as gV,Yv as gW,JE as gX,Qv as gY,AV as gZ,ER as g_,fb as ga,NO as gb,jO as gc,TD as gd,IO as ge,RO as gf,xO as gg,UO as gh,AD as gi,wD as gj,UD as gk,WD as gl,yD as gm,SD as gn,vD as go,OO as gp,ID as gq,QD as gr,HV as gs,kD as gt,VD as gu,wb as gv,LD as gw,GD as gx,WV as gy,HD as gz,UE as h,aV as h$,HE as h0,BL as h1,$L as h2,vP as h3,LM as h4,yV as h5,mR as h6,eR as h7,Iq as h8,aE as h9,fT as hA,mT as hB,KF as hC,_V as hD,bL as hE,$i as hF,EL as hG,PL as hH,IC as hI,SL as hJ,wL as hK,gL as hL,FL as hM,ML as hN,LL as hO,UL as hP,WL as hQ,GL as hR,zL as hS,NL as hT,AL as hU,$c as hV,OL as hW,TC as hX,jV as hY,HL as hZ,nV as h_,iE as ha,_w as hb,$w as hc,YM as hd,rE as he,oE as hf,sE as hg,tE as hh,Dw as hi,tv as hj,BV as hk,_M as hl,Bj as hm,bV as hn,Oj as ho,qV as hp,AO as hq,hL as hr,uL as hs,Nt as ht,SV as hu,oV as hv,dV as hw,rV as hx,It as hy,hT as hz,Ex as i,TL as i$,pL as i0,kC as i1,L as i2,bF as i3,zP as i4,NC as i5,HC as i6,_C as i7,LC as i8,xL as i9,jE as iA,IE as iB,PE as iC,CE as iD,vE as iE,Jv as iF,AE as iG,WM as iH,xj as iI,aa as iJ,ab as iK,Rj as iL,zM as iM,xM as iN,tT as iO,Qq as iP,Id as iQ,_g as iR,VL as iS,qL as iT,qC as iU,RL as iV,kL as iW,yL as iX,DV as iY,CL as iZ,vL as i_,NT as ia,FT as ib,BM as ic,ih as id,cr as ie,cL as ig,gt as ih,VT as ii,HM as ij,Lq as ik,Uq as il,df as im,Eq as io,qq as ip,Hq as iq,Vq as ir,Wq as is,pV as it,uV as iu,Py as iv,NE as iw,EE as ix,DE as iy,OE as iz,C as j,IL as j0,iV as j1,hA as j2,Cq as j3,Sq as j4,Aq as j5,wA as j6,vq as j7,Pq as j8,oL as j9,zq as ja,_L as jb,gE as jc,dE as jd,pE as je,EM as jf,tn as jg,nb as jh,YL as ji,QL as jj,$q as jk,wV as jl,qd as k,je as l,Lx as m,ze as n,xE as o,uE as p,Wo as q,Zv as r,yR as s,Ke as t,A as u,Rt as v,jq as w,az as x,Fq as y,Ht as z};
85
+ ${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Bu(e){const t=Jb(e);return IN.some(s=>s.test(t))}function RN(e){return`2.6.2-canary.20261104.6:${Jb(e).slice(0,500)}`}function jN(e){if(typeof window>"u"||je())return;const t=Date.now(),s=RN(e);let n=null;try{const i=window.sessionStorage.getItem(Du);if(i)try{n=JSON.parse(i)}catch{n=null}}catch{return}const a=typeof n?.timestamp=="number"?n.timestamp:0;if(!(n?.signature===s&&t-a<TN)){try{window.sessionStorage.setItem(Du,JSON.stringify({signature:s,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function ON(e,t={}){const s=t.retries??1;let n;for(let a=0;a<=s;a+=1)try{return await e()}catch(i){if(n=i,!Bu(i)||a>=s)break;await new Promise(o=>setTimeout(o,xN*(a+1)))}throw Bu(n)&&jN(n),n}const $V=e=>sk.lazy(()=>ON(e));export{Ox as $,sz as A,tz as B,ez as C,nz as D,XA as E,YA as F,rz as G,cz as H,kV as I,NR as J,IV as K,FR as L,eL as M,YE as N,JV as O,ON as P,Fz as Q,Nz as R,qr as S,Mz as T,qz as U,Lz as V,Ez as W,Nx as X,Fx as Y,Bx as Z,Dx as _,vR as a,am as a$,jx as a0,Rx as a1,Ix as a2,Tx as a3,xx as a4,zx as a5,Ax as a6,Px as a7,Sx as a8,Cx as a9,Jz as aA,Zz as aB,Kz as aC,_z as aD,Gz as aE,Hz as aF,Wz as aG,Uz as aH,D as aI,vV as aJ,Yo as aK,Rq as aL,yE as aM,Hr as aN,Ce as aO,DM as aP,tV as aQ,Xq as aR,gV as aS,Zq as aT,LV as aU,Dj as aV,Ai as aW,tr as aX,QR as aY,ls as aZ,hq as a_,vx as aa,wx as ab,yx as ac,kx as ad,bx as ae,fx as af,hx as ag,mx as ah,ux as ai,px as aj,gx as ak,dx as al,lx as am,cx as an,rx as ao,ox as ap,ix as aq,ax as ar,nx as as,sx as at,tx as au,ex as av,Xz as aw,Yz as ax,Qz as ay,$z as az,$e as b,NM as b$,ov as b0,nh as b1,lV as b2,fC as b3,cd as b4,Yr as b5,mL as b6,xq as b7,Tq as b8,ZV as b9,ui as bA,QM as bB,sr as bC,Ow as bD,jM as bE,$M as bF,wR as bG,vM as bH,AM as bI,Lm as bJ,qe as bK,XM as bL,eE as bM,Bp as bN,Fj as bO,eV as bP,jT as bQ,EV as bR,MV as bS,Qo as bT,SM as bU,Sy as bV,_A as bW,Gq as bX,Iz as bY,ps as bZ,Mq as b_,kh as ba,Yq as bb,xd as bc,kT as bd,jR as be,ct as bf,ee as bg,XN as bh,Ye as bi,CM as bj,SR as bk,Kq as bl,un as bm,_N as bn,bM as bo,bo as bp,JN as bq,$N as br,QN as bs,Dh as bt,an as bu,kA as bv,fq as bw,MM as bx,nq as by,nv as bz,qE as c,pn as c$,cE as c0,aq as c1,iq as c2,IA as c3,Ny as c4,sq as c5,ar as c6,gm as c7,zi as c8,mn as c9,sV as cA,sS as cB,$V as cC,kd as cD,tt as cE,rn as cF,mA as cG,yq as cH,CA as cI,al as cJ,Fh as cK,rq as cL,gA as cM,oq as cN,md as cO,kt as cP,Ah as cQ,$E as cR,ko as cS,cq as cT,lq as cU,gq as cV,pq as cW,eA as cX,dq as cY,uq as cZ,mq as c_,Lc as ca,Oy as cb,ca as cc,Yl as cd,UM as ce,Zl as cf,VM as cg,ss as ch,Pw as ci,JM as cj,Nq as ck,bq as cl,bd as cm,ra as cn,bn as co,ry as cp,Qn as cq,qM as cr,Bh as cs,_E as ct,CV as cu,wq as cv,FM as cw,fo as cx,RV as cy,Wc as cz,ME as d,FE as d$,kq as d0,FV as d1,ir as d2,_i as d3,Un as d4,wP as d5,yM as d6,Pg as d7,Gw as d8,Tt as d9,gR as dA,Of as dB,fM as dC,zj as dD,iS as dE,lm as dF,PM as dG,wM as dH,XL as dI,xh as dJ,PP as dK,TP as dL,AP as dM,IP as dN,CP as dO,nr as dP,mE as dQ,bE as dR,wE as dS,SE as dT,kE as dU,hE as dV,fE as dW,Mv as dX,Nv as dY,XE as dZ,BE as d_,tL as da,Xk as db,Yu as dc,WN as dd,TV as de,eq as df,HN as dg,kM as dh,GN as di,nM as dj,KN as dk,ZN as dl,aM as dm,ZA as dn,IS as dp,KL as dq,Ug as dr,aL as ds,ZL as dt,Bw as du,xw as dv,KM as dw,ZM as dx,Lw as dy,OM as dz,TE as e,NV as e$,lM as e0,dM as e1,gM as e2,pM as e3,tM as e4,iM as e5,uM as e6,rM as e7,sM as e8,oM as e9,en as eA,JA as eB,Hw as eC,Ww as eD,nE as eE,Ds as eF,Gv as eG,tq as eH,rr as eI,KE as eJ,mV as eK,OV as eL,WE as eM,RE as eN,Bq as eO,QE as eP,di as eQ,Dq as eR,Oq as eS,ly as eT,Rm as eU,YP as eV,la as eW,Qe as eX,FP as eY,xP as eZ,Ut as e_,mM as ea,cM as eb,mP as ec,hP as ed,kl as ee,qa as ef,Pd as eg,Vx as eh,qx as ei,Pz as ej,Oh as ek,jh as el,Ad as em,eM as en,RM as eo,TM as ep,IM as eq,cV as er,dR as es,lR as et,GV as eu,CR as ev,PR as ew,iz as ex,oz as ey,fz as ez,VE as f,VV as f$,im as f0,Kl as f1,$s as f2,iI as f3,OR as f4,hv as f5,GS as f6,GE as f7,sv as f8,sL as f9,Yx as fA,X as fB,Jk as fC,$k as fD,hV as fE,zV as fF,Hn as fG,Vg as fH,AR as fI,_q as fJ,LE as fK,Jq as fL,Rz as fM,KO as fN,zz as fO,PO as fP,VO as fQ,zO as fR,ru as fS,aD as fT,ou as fU,iu as fV,au as fW,sD as fX,tD as fY,eD as fZ,XO as f_,JL as fa,nS as fb,aS as fc,lE as fd,lL as fe,rL as ff,_r as fg,Qc as fh,bS as fi,Zk as fj,nL as fk,Ur as fl,wS as fm,uS as fn,OT as fo,Rs as fp,vT as fq,iL as fr,ib as fs,fL as ft,dL as fu,jL as fv,Hv as fw,KV as fx,bl as fy,Ss as fz,zE as g,xV as g$,YD as g0,UV as g1,DD as g2,OD as g3,jD as g4,ND as g5,RD as g6,Hd as g7,hb as g8,FO as g9,YO as gA,$O as gB,yb as gC,YN as gD,CS as gE,Wg as gF,DS as gG,OS as gH,ES as gI,ad as gJ,Pv as gK,GM as gL,DL as gM,PV as gN,HF as gO,Wb as gP,sI as gQ,fV as gR,$v as gS,Ec as gT,hM as gU,ZE as gV,Yv as gW,JE as gX,Qv as gY,AV as gZ,ER as g_,fb as ga,NO as gb,jO as gc,TD as gd,IO as ge,RO as gf,xO as gg,UO as gh,AD as gi,wD as gj,UD as gk,WD as gl,yD as gm,SD as gn,vD as go,OO as gp,ID as gq,QD as gr,HV as gs,kD as gt,VD as gu,wb as gv,LD as gw,GD as gx,WV as gy,HD as gz,UE as h,aV as h$,HE as h0,BL as h1,$L as h2,vP as h3,LM as h4,yV as h5,mR as h6,eR as h7,Iq as h8,aE as h9,fT as hA,mT as hB,KF as hC,_V as hD,bL as hE,$i as hF,EL as hG,PL as hH,IC as hI,SL as hJ,wL as hK,gL as hL,FL as hM,ML as hN,LL as hO,UL as hP,WL as hQ,GL as hR,zL as hS,NL as hT,AL as hU,$c as hV,OL as hW,TC as hX,jV as hY,HL as hZ,nV as h_,iE as ha,_w as hb,$w as hc,YM as hd,rE as he,oE as hf,sE as hg,tE as hh,Dw as hi,tv as hj,BV as hk,_M as hl,Bj as hm,bV as hn,Oj as ho,qV as hp,AO as hq,hL as hr,uL as hs,Nt as ht,SV as hu,oV as hv,dV as hw,rV as hx,It as hy,hT as hz,Ex as i,TL as i$,pL as i0,kC as i1,L as i2,bF as i3,zP as i4,NC as i5,HC as i6,_C as i7,LC as i8,xL as i9,jE as iA,IE as iB,PE as iC,CE as iD,vE as iE,Jv as iF,AE as iG,WM as iH,xj as iI,aa as iJ,ab as iK,Rj as iL,zM as iM,xM as iN,tT as iO,Qq as iP,Id as iQ,_g as iR,VL as iS,qL as iT,qC as iU,RL as iV,kL as iW,yL as iX,DV as iY,CL as iZ,vL as i_,NT as ia,FT as ib,BM as ic,ih as id,cr as ie,cL as ig,gt as ih,VT as ii,HM as ij,Lq as ik,Uq as il,df as im,Eq as io,qq as ip,Hq as iq,Vq as ir,Wq as is,pV as it,uV as iu,Py as iv,NE as iw,EE as ix,DE as iy,OE as iz,C as j,IL as j0,iV as j1,hA as j2,Cq as j3,Sq as j4,Aq as j5,wA as j6,vq as j7,Pq as j8,oL as j9,zq as ja,_L as jb,gE as jc,dE as jd,pE as je,EM as jf,tn as jg,nb as jh,YL as ji,QL as jj,$q as jk,wV as jl,qd as k,je as l,Lx as m,ze as n,xE as o,uE as p,Wo as q,Zv as r,yR as s,Ke as t,A as u,Rt as v,jq as w,az as x,Fq as y,Ht as z};