@openchamber/web 2.0.4 → 2.1.0

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 (264) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-C_zL-eri.js → CodeMirrorCommentWidgets-qlshRzAf.js} +1 -1
  2. package/dist/assets/{DiffView-BeN2_YYF.js → DiffView-BI_YgdKl.js} +3 -3
  3. package/dist/assets/FilesView-B_NJFLBH.js +17 -0
  4. package/dist/assets/{GitView-DLDazOo1.js → GitView-BWKg6TNS.js} +4 -4
  5. package/dist/assets/{GuestAttachDialog-C0xe_Lyy.js → GuestAttachDialog-DO4x4vIR.js} +1 -1
  6. package/dist/assets/{GuestSurfacePane-BdaurnDr.js → GuestSurfacePane-4PY11vEP.js} +1 -1
  7. package/dist/assets/JsonTreeView-u4yx65zn.js +1 -0
  8. package/dist/assets/{LinearIssuesView-BryoAHow.js → LinearIssuesView-C4gGBhU8.js} +1 -1
  9. package/dist/assets/{MarkdownImageGallery-DfuEoaGq.js → MarkdownImageGallery-fqVRCTdC.js} +1 -1
  10. package/dist/assets/MarkdownRendererImpl-Cfb5fTnq.js +39 -0
  11. package/dist/assets/OnboardingScreen-CiTV2_OT.js +1 -0
  12. package/dist/assets/PatchDiff-BrjhzXDM.js +1 -0
  13. package/dist/assets/{PierreDiffViewer-BC950e3F.js → PierreDiffViewer-CVx2e1cx.js} +5 -5
  14. package/dist/assets/{PlanView-B7Xgihqk.js → PlanView-DP9DOnI-.js} +4 -4
  15. package/dist/assets/{PluginPane-2C71F8uF.js → PluginPane-rZvoMQSi.js} +3 -3
  16. package/dist/assets/SettingsView-Dp9jubRs.js +30 -0
  17. package/dist/assets/SettingsWindow-Dst0yiV7.js +1 -0
  18. package/dist/assets/{SubmoduleDiffSummary-BSA9gnIO.js → SubmoduleDiffSummary-CixkM4fI.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-DprkVKcj.js → ToolOutputDialog-f0cS2DIf.js} +6 -6
  20. package/dist/assets/ToolPartDiffPreview-CFFIAFFY.js +8 -0
  21. package/dist/assets/{VirtualizedFileDiff-Kp8hKJdT.js → VirtualizedFileDiff-B-U_aQwV.js} +4 -4
  22. package/dist/assets/{WalkthroughView-DGnTzqIU.js → WalkthroughView-C1uB3Pl3.js} +2 -2
  23. package/dist/assets/{appThemeRegistry-BdEHBA4s.js → appThemeRegistry-DU-UKEHq.js} +1 -1
  24. package/dist/assets/{commitAndPush-LwtVa2Oc.js → commitAndPush-CtWGqrtW.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-6V1xNpO9.js → computeVirtualFileMetrics-BmhViPMt.js} +1 -1
  26. package/dist/assets/de-D4hpTCNY.js +10 -0
  27. package/dist/assets/es-Bw9m3H62.js +16 -0
  28. package/dist/assets/fileTreeStatus-CvPnAWSi.js +1 -0
  29. package/dist/assets/fr-Bhll42P0.js +14 -0
  30. package/dist/assets/index-Btd2mmYT.js +42 -0
  31. package/dist/assets/index-C-7hQnEc.css +1 -0
  32. package/dist/assets/{index-CmNPYddV.js → index-DwtCnbiK.js} +1 -1
  33. package/dist/assets/{isDiffPlainText-1bXcWCrw.js → isDiffPlainText-CPDhzF1K.js} +1 -1
  34. package/dist/assets/{isFilePlainText-CBAppvy1.js → isFilePlainText-n8k0lMTZ.js} +1 -1
  35. package/dist/assets/ja-CsHoT43d.js +16 -0
  36. package/dist/assets/ko-BBNdtFa4.js +16 -0
  37. package/dist/assets/{main-CzjTMTfW.js → main-D6rlXjug.js} +2 -2
  38. package/dist/assets/main-kYkr_urz.js +1000 -0
  39. package/dist/assets/markdownCore-CHm8ycaW.js +7 -0
  40. package/dist/assets/{miniChat-CP68IL8Q.js → miniChat-2JY8K3Qw.js} +2 -2
  41. package/dist/assets/mobile-CviaXnnU.js +2 -0
  42. package/dist/assets/nl-DszyktfH.js +16 -0
  43. package/dist/assets/openSessionFromRoute-BIlcJIf3.js +1 -0
  44. package/dist/assets/{web-components-ngpHPEDU.js → parseDiffFromFile-DeZzEah8.js} +5 -5
  45. package/dist/assets/{patchFileDiff-pqRSHLHI.js → patchFileDiff-BnEHIdM2.js} +2 -2
  46. package/dist/assets/pl-Bk9_mUXc.js +16 -0
  47. package/dist/assets/pt-BR-BIXmm3Gw.js +16 -0
  48. package/dist/assets/{renderElectronMiniChatApp-DKIilR7N.js → renderElectronMiniChatApp-DvUphkjj.js} +2 -2
  49. package/dist/assets/renderMobileApp-Cdc49X8Y.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-Cu6RUve4.js +56 -0
  51. package/dist/assets/shikiHighlight-CcVzlYit.js +1 -0
  52. package/dist/assets/space-apply-CgJ5JYPK.js +1 -0
  53. package/dist/assets/space-close-C1tL-_0t.js +1 -0
  54. package/dist/assets/{textMateThemeFromAppTheme-BSUFChBY.js → textMateThemeFromAppTheme-CAOCeVjl.js} +1 -1
  55. package/dist/assets/tr-C_13w7CX.js +7 -0
  56. package/dist/assets/uk-BZTsG-q_.js +16 -0
  57. package/dist/assets/{useAppFontEffects-Dsl_sLrj.js → useAppFontEffects-CeMgbeVa.js} +185 -177
  58. package/dist/assets/{useInlineCommentController-d5vntsQ_.js → useInlineCommentController-U97JJifS.js} +2 -2
  59. package/dist/assets/useRootScrollLock-DMBY2aTT.js +2 -0
  60. package/dist/assets/{vendor-base-ui-DnNniUWp.js → vendor-base-ui-DWgyZK2k.js} +1 -1
  61. package/dist/assets/vendor-codemirror-autocomplete-DetzHhtC.js +1 -0
  62. package/dist/assets/{vendor-codemirror-commands-B7H_j0iU.js → vendor-codemirror-commands-ConqfjLn.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-DEPs2M5t.js → vendor-codemirror-lang-angular-Dbpx8qe-.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-DhkseaMo.js → vendor-codemirror-lang-cpp-TRtQWrpl.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-O0cZX78y.js → vendor-codemirror-lang-css-DY4CGDG2.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-fMdQYcON.js → vendor-codemirror-lang-go-CLKXh6B8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-CfgK872x.js → vendor-codemirror-lang-html-CQnNjmg9.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CQj4S3zl.js → vendor-codemirror-lang-java-CokZKqls.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Cc2ZYbgX.js → vendor-codemirror-lang-javascript-Kgp6fZRE.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-BmZZv8g-.js → vendor-codemirror-lang-jinja-DZchyrN1.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-CMBS2tG9.js → vendor-codemirror-lang-json-CkdBRvqj.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-C6Eo8hVS.js → vendor-codemirror-lang-less-_k-GKz0A.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-DSTR47-H.js → vendor-codemirror-lang-liquid-DuHUMKoh.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-BPGOH9ye.js → vendor-codemirror-lang-markdown-CdG1RXm1.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-DD9udfPH.js → vendor-codemirror-lang-php-Ca15KQSA.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-HahnQaAS.js → vendor-codemirror-lang-python-B4MRHRva.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-nLTovbjv.js → vendor-codemirror-lang-rust-8fLJdxQA.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-pL2Yc72v.js → vendor-codemirror-lang-sass-CASr_yQ1.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-BVBnan19.js → vendor-codemirror-lang-sql-Dc4ER-re.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-BqGzJVm1.js → vendor-codemirror-lang-vue-fu2BqdK2.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-B0_m5DqU.js → vendor-codemirror-lang-wast-BkCOgSpV.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-Dj3voadT.js → vendor-codemirror-lang-xml-7e-kPepH.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-yu-9Z5u7.js → vendor-codemirror-lang-yaml-Cq3p_9DI.js} +1 -1
  84. package/dist/assets/vendor-codemirror-language-CZcLdzDM.js +3 -0
  85. package/dist/assets/{vendor-codemirror-language-data-B1EetJur.js → vendor-codemirror-language-data-B8HKnqZy.js} +2 -2
  86. package/dist/assets/vendor-codemirror-search-BZNojiZO.js +2 -0
  87. package/dist/assets/{vendor-codemirror-state-C9awkmn-.js → vendor-codemirror-state--21VQleR.js} +1 -1
  88. package/dist/assets/vendor-codemirror-view-8PpN-8l4.js +4 -0
  89. package/dist/assets/vendor-opencode-client-Byb4ZSqI.js +12 -0
  90. package/dist/assets/vendor-remend-DcBOpbSu.js +24 -0
  91. package/dist/assets/{vendor-replit-codemirror-vim-B2DJlAhT.js → vendor-replit-codemirror-vim-EX7OnecQ.js} +1 -1
  92. package/dist/assets/zh-CN-C62wm2Tg.js +16 -0
  93. package/dist/assets/zh-TW-BgGTiQA6.js +16 -0
  94. package/dist/index.html +4 -4
  95. package/dist/mini-chat.html +4 -4
  96. package/dist/mobile.html +4 -4
  97. package/package.json +4 -4
  98. package/server/index.js +58 -1
  99. package/server/lib/browser-control/DOCUMENTATION.md +8 -1
  100. package/server/lib/dev-tunnel/DOCUMENTATION.md +6 -0
  101. package/server/lib/dev-tunnel/runtime.js +94 -38
  102. package/server/lib/dev-tunnel/tunnel.test.js +16 -2
  103. package/server/lib/dictation/DOCUMENTATION.md +23 -10
  104. package/server/lib/dictation/audio.js +28 -0
  105. package/server/lib/dictation/local/sherpa-recognizer.js +33 -7
  106. package/server/lib/dictation/local/sherpa-recognizer.test.js +94 -0
  107. package/server/lib/dictation/local/worker-client.js +28 -10
  108. package/server/lib/dictation/local/worker-process.js +25 -1
  109. package/server/lib/dictation/stream-manager.js +160 -53
  110. package/server/lib/dictation/stream-manager.test.js +108 -7
  111. package/server/lib/enterprise-mode.d.ts +2 -0
  112. package/server/lib/enterprise-mode.js +84 -9
  113. package/server/lib/enterprise-mode.test.js +115 -0
  114. package/server/lib/fs/DOCUMENTATION.md +3 -2
  115. package/server/lib/fs/routes.js +28 -1
  116. package/server/lib/fs/routes.test.js +31 -5
  117. package/server/lib/git/DOCUMENTATION.md +1 -1
  118. package/server/lib/git/service.js +61 -2
  119. package/server/lib/git/service.test.js +141 -0
  120. package/server/lib/github/DOCUMENTATION.md +18 -0
  121. package/server/lib/github/checks-summary.js +76 -0
  122. package/server/lib/github/pr-summaries.js +282 -0
  123. package/server/lib/github/pr-summaries.test.js +209 -0
  124. package/server/lib/github/routes.js +42 -77
  125. package/server/lib/github/routes.test.js +77 -0
  126. package/server/lib/inherited-env.js +51 -0
  127. package/server/lib/inherited-env.test.js +59 -0
  128. package/server/lib/message-search/DOCUMENTATION.md +83 -0
  129. package/server/lib/message-search/indexer.js +336 -0
  130. package/server/lib/message-search/indexer.test.js +341 -0
  131. package/server/lib/message-search/routes.js +92 -0
  132. package/server/lib/message-search/runtime.js +234 -0
  133. package/server/lib/message-search/runtime.test.js +108 -0
  134. package/server/lib/message-search/sqlite.js +74 -0
  135. package/server/lib/message-search/store.js +289 -0
  136. package/server/lib/openchamber-control/DOCUMENTATION.md +6 -1
  137. package/server/lib/openchamber-control/actions.js +1 -1
  138. package/server/lib/openchamber-control/service.js +21 -2
  139. package/server/lib/openchamber-control/service.test.js +50 -0
  140. package/server/lib/openchamber-sessions/routes.js +15 -0
  141. package/server/lib/openchamber-sessions/routes.test.js +31 -0
  142. package/server/lib/opencode/DOCUMENTATION.md +43 -38
  143. package/server/lib/opencode/auth.d.ts +24 -0
  144. package/server/lib/opencode/auth.js +130 -66
  145. package/server/lib/opencode/auth.test.js +114 -70
  146. package/server/lib/opencode/compatibility.js +4 -3
  147. package/server/lib/opencode/compatibility.test.js +10 -10
  148. package/server/lib/opencode/feature-routes-runtime.js +3 -0
  149. package/server/lib/opencode/lifecycle.js +21 -12
  150. package/server/lib/opencode/lifecycle.test.js +38 -5
  151. package/server/lib/opencode/provider-source-route.test.js +55 -2
  152. package/server/lib/opencode/routes.js +17 -4
  153. package/server/lib/opencode/settings-helpers.js +6 -0
  154. package/server/lib/opencode/settings-helpers.test.js +1 -1
  155. package/server/lib/opencode/settings-registry.json +16 -0
  156. package/server/lib/opencode/settings-runtime.js +9 -0
  157. package/server/lib/opencode/shutdown-runtime.js +2 -0
  158. package/server/lib/opencode/v1-migration-topup.js +13 -3
  159. package/server/lib/opencode/v2-install.test.js +13 -13
  160. package/server/lib/quota/DOCUMENTATION.md +11 -5
  161. package/server/lib/quota/providers/claude/auth.js +19 -6
  162. package/server/lib/quota/providers/claude/auth.test.js +22 -9
  163. package/server/lib/quota/providers/claude/index.js +3 -3
  164. package/server/lib/quota/providers/claude/index.test.js +3 -2
  165. package/server/lib/quota/providers/cline-pass.js +4 -4
  166. package/server/lib/quota/providers/codex.js +3 -4
  167. package/server/lib/quota/providers/codex.test.js +1 -1
  168. package/server/lib/quota/providers/copilot.js +4 -5
  169. package/server/lib/quota/providers/copilot.test.js +1 -1
  170. package/server/lib/quota/providers/deepseek.js +3 -4
  171. package/server/lib/quota/providers/deepseek.test.js +1 -1
  172. package/server/lib/quota/providers/google/auth.js +1 -3
  173. package/server/lib/quota/providers/google/index.js +3 -2
  174. package/server/lib/quota/providers/hyper.js +4 -4
  175. package/server/lib/quota/providers/index.js +9 -2
  176. package/server/lib/quota/providers/index.test.js +5 -3
  177. package/server/lib/quota/providers/kimi.js +16 -11
  178. package/server/lib/quota/providers/kimi.test.js +81 -38
  179. package/server/lib/quota/providers/minimax-shared.js +3 -4
  180. package/server/lib/quota/providers/nanogpt.js +3 -4
  181. package/server/lib/quota/providers/neuralwatt.js +3 -4
  182. package/server/lib/quota/providers/neuralwatt.test.js +1 -1
  183. package/server/lib/quota/providers/openai.js +2 -8
  184. package/server/lib/quota/providers/opencode-go.js +5 -5
  185. package/server/lib/quota/providers/opencode-go.test.js +1 -1
  186. package/server/lib/quota/providers/openrouter.js +30 -6
  187. package/server/lib/quota/providers/openrouter.test.js +122 -1
  188. package/server/lib/quota/providers/wafer.js +3 -4
  189. package/server/lib/quota/providers/xai.js +12 -12
  190. package/server/lib/quota/providers/zai.js +3 -4
  191. package/server/lib/quota/providers/zai.test.js +1 -1
  192. package/server/lib/quota/providers/zhipuai-coding-plan.js +5 -6
  193. package/server/lib/quota/providers/zhipuai-coding-plan.test.js +1 -1
  194. package/server/lib/quota/routes.js +1 -1
  195. package/server/lib/routing/DOCUMENTATION.md +4 -0
  196. package/server/lib/routing/runtime.js +45 -4
  197. package/server/lib/routing/runtime.test.js +35 -6
  198. package/server/lib/scheduled-tasks/DOCUMENTATION.md +27 -0
  199. package/server/lib/scheduled-tasks/chats-scope.js +50 -0
  200. package/server/lib/scheduled-tasks/runtime.js +57 -23
  201. package/server/lib/scheduled-tasks/runtime.test.js +103 -1
  202. package/server/lib/scheduled-tasks/service.js +37 -29
  203. package/server/lib/scheduled-tasks/service.test.js +39 -0
  204. package/server/lib/spaces/DOCUMENTATION.md +54 -9
  205. package/server/lib/spaces/host.js +24 -3
  206. package/server/lib/spaces/journey.js +111 -11
  207. package/server/lib/spaces/journey.test.js +189 -8
  208. package/server/lib/spaces/places/docker-disk.js +151 -0
  209. package/server/lib/spaces/places/docker-disk.test.js +167 -0
  210. package/server/lib/spaces/places/docker-tools.js +11 -1
  211. package/server/lib/spaces/places/docker.js +4 -2
  212. package/server/lib/spaces/places/fake-docker.js +36 -2
  213. package/server/lib/spaces/routes.js +21 -4
  214. package/server/lib/spaces/routes.test.js +6 -2
  215. package/server/lib/spaces/space-archive.js +275 -0
  216. package/server/lib/spaces/space-archive.test.js +194 -0
  217. package/server/lib/spaces/space-opencode.js +139 -6
  218. package/server/lib/spaces/space-opencode.test.js +82 -1
  219. package/server/lib/spaces/space-records.js +3 -0
  220. package/server/lib/spaces/space-setup.js +10 -5
  221. package/server/lib/spaces/space-setup.test.js +8 -2
  222. package/server/lib/terminal/DOCUMENTATION.md +1 -0
  223. package/server/lib/terminal/runtime.js +6 -1
  224. package/server/lib/terminal/runtime.test.js +19 -0
  225. package/server/lib/tts/routes.js +2 -2
  226. package/server/lib/tts/service.js +8 -8
  227. package/dist/assets/FilesView-CN34wm_N.js +0 -17
  228. package/dist/assets/JsonTreeView-B1Xq-k2t.js +0 -1
  229. package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +0 -12
  230. package/dist/assets/OnboardingScreen-C22bGmnP.js +0 -1
  231. package/dist/assets/PatchDiff-0xd6UeFB.js +0 -1
  232. package/dist/assets/SettingsView-m_zoFiaT.js +0 -30
  233. package/dist/assets/SettingsWindow-CofS020b.js +0 -1
  234. package/dist/assets/ToolPartDiffPreview-Dq0go_fX.js +0 -8
  235. package/dist/assets/de-DlgBHUAI.js +0 -10
  236. package/dist/assets/es-BC8G41U8.js +0 -16
  237. package/dist/assets/fr-I0z3vVjy.js +0 -14
  238. package/dist/assets/index-CgR5rJq_.js +0 -41
  239. package/dist/assets/index-adyy_sEk.css +0 -1
  240. package/dist/assets/ja-BIElEsY8.js +0 -16
  241. package/dist/assets/ko-DRnnHetA.js +0 -16
  242. package/dist/assets/main-DVX34beR.js +0 -886
  243. package/dist/assets/markdownCore-Cxbkn5NR.js +0 -7
  244. package/dist/assets/mobile-BrlBrNfZ.js +0 -2
  245. package/dist/assets/nl-DzUV-kwp.js +0 -16
  246. package/dist/assets/pl-Bb-cb7k7.js +0 -16
  247. package/dist/assets/pt-BR-CyIWrTcE.js +0 -16
  248. package/dist/assets/renderMobileApp-B0z6-x58.js +0 -25
  249. package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +0 -52
  250. package/dist/assets/scheduledTasksApi-BuzWT445.js +0 -1
  251. package/dist/assets/shikiHighlight-BWGrY5YU.js +0 -1
  252. package/dist/assets/tr-DXEDSoYO.js +0 -7
  253. package/dist/assets/uk-C8hN--q_.js +0 -16
  254. package/dist/assets/useRootScrollLock-2rd5Y6gR.js +0 -2
  255. package/dist/assets/vendor-codemirror-autocomplete-DzPz9Wgq.js +0 -1
  256. package/dist/assets/vendor-codemirror-language-BgPj_McA.js +0 -3
  257. package/dist/assets/vendor-codemirror-search-BmS-GmcX.js +0 -2
  258. package/dist/assets/vendor-codemirror-view-CiLROUVV.js +0 -4
  259. package/dist/assets/vendor-opencode-client-DSZl7jSi.js +0 -12
  260. package/dist/assets/vendor-remend-BWYYytN3.js +0 -22
  261. package/dist/assets/zh-CN-CtzXdjMZ.js +0 -16
  262. package/dist/assets/zh-TW-Ds0CADSz.js +0 -16
  263. package/server/lib/opencode/credential-db.js +0 -144
  264. package/server/lib/opencode/credential-db.test.js +0 -104
@@ -0,0 +1,42 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CEam9pDc.js","assets/vendor-react-BUCujlKS.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
+ import{a as M,o as w,s as f,n as E,b as Y,d as vt,l as O,_ as H,u as Ze,r as lt,t as Md,c as ye,e as fa,j as pa,f as fr,g as ol}from"./vendor-zod-CxRSdNoV.js";import{_ as ki}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as ut,d as _n,p as kr,a as _d}from"./vendor-zustand-BAGL70zf.js";import{e as Ld,C as Fd}from"./vendor-opencode-client-Byb4ZSqI.js";import{f as Hs,R as An}from"./vendor-react-BUCujlKS.js";const nr=1,jd="openchamber-relay-v1",il=1,al=12,rr=1+al,pr=64*1024,hr=5,Ss=128,cl=0,ll=1,In=4,Ud=1+In,No=pr-hr-Ud,z={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},Nd=new Set(Object.values(z)),Bd=e=>Nd.has(e),en={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},St=globalThis.crypto.subtle,ul={name:"ECDH",namedCurve:"P-256"},dl=16,so=32,Hd=16,Bo=4,fl=8;class Lt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const $d=()=>St.generateKey(ul,!0,["deriveBits"]),zd=async e=>{const t=await St.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Wd=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Lt("invalid ECDH public key JWK");try{return await St.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},ul,!0,[])}catch{throw new Lt("invalid ECDH public key JWK")}},Gd=()=>{const e=new Uint8Array(dl);return globalThis.crypto.getRandomValues(e),e},qd=async(e,t,n)=>{if(n.length!==dl)throw new Lt("invalid handshake nonce length");const r=await St.deriveBits({name:"ECDH",public:t},e,256),s=await St.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await St.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(jd)},s,so*2*8)),i=(a,c)=>St.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(o.slice(0,so),["encrypt","decrypt"]),hostToClient:await i(o.slice(so),["encrypt","decrypt"])}},Kd=(e,t,n)=>{for(let r=fl-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Vd=(e,t)=>{let n=0n;for(let r=0;r<fl;r+=1)n=n<<8n|BigInt(e[t+r]);return n},Jd=e=>{const t=new Uint8Array(Bo);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>pr)throw new Lt("plaintext frame exceeds maximum size");n+=1n;const s=new Uint8Array(al);s.set(t,0),Kd(s,Bo,n);const o=new Uint8Array(await St.encrypt({name:"AES-GCM",iv:s},e,r)),i=new Uint8Array(rr+o.length);return i[0]=il,i.set(s,1),i.set(o,rr),i}}},Yd=e=>{let t=0n;return{async decrypt(n){if(n.length<rr+Hd)throw new Lt("encrypted frame too short");if(n[0]!==il)throw new Lt("unsupported encrypted frame version");const r=n.slice(1,rr),s=Vd(r,Bo);if(s<=t)throw new Lt("frame counter regression");let o;try{o=await St.decrypt({name:"AES-GCM",iv:r},e,n.slice(rr))}catch{throw new Lt("frame decryption failed")}return t=s,new Uint8Array(o)}}},Ur="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Qd=e=>{let t="";for(let n=0;n<e.length;n+=3){const r=e[n],s=n+1<e.length?e[n+1]:void 0,o=n+2<e.length?e[n+2]:void 0;t+=Ur[r>>2],t+=Ur[(r&3)<<4|(s??0)>>4],s!==void 0&&(t+=Ur[(s&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Ur[o&63])}return t},ha=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const n=t;if(n.v!==nr)return null;const r=n.batch===!0,s=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:nr,batch:r,flowControl:s}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:nr,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:s}:null},Xd=e=>({type:"fail",closeCode:en.ChannelFailure,reason:e}),Zd=async(e,t={})=>{const n=t.batch!==!1,r=await Wd(e),s=await $d(),o=Gd(),i={t:"hello",v:nr,clientPubJwk:await zd(s.publicKey),nonce:Qd(o)};n&&(i.batch=!0),t.flowControl!==!1&&(i.flowControl=!0);let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return ha(c)?.t==="ready"?{type:"ignore"}:Xd("plaintext frame on established channel");const l=ha(c);if(l?.t!=="ready")return{type:"ignore"};const u=await qd(s.privateKey,r,o);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:Jd(u.clientToHost),decryptor:Yd(u.hostToClient)}}}}},pl=4294967295,ef=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 ve extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Ke=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>pl)throw new ve("invalid stream id");if(n.length>No)throw new ve("tunnel payload exceeds maximum size");const s=new Uint8Array(hr+n.length);return s[0]=r?e|Ss:e,s[1]=t>>>24&255,s[2]=t>>>16&255,s[3]=t>>>8&255,s[4]=t&255,s.set(n,hr),s},tf=e=>{if(e.length<hr)throw new ve("tunnel frame too short");const t=e[0],n=(t&Ss)!==0,r=t&~Ss;if(!Bd(r))throw new ve(`unknown tunnel frame type ${r}`);const s=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:s,payload:e.slice(hr),hasMoreFragments:n}},nf=new TextEncoder,rf=new TextDecoder,Nr=e=>nf.encode(JSON.stringify(e)),Br=(e,t)=>{let n;try{n=JSON.parse(rf.decode(e))}catch{throw new ve("malformed JSON tunnel payload")}if(!t(n))throw new ve("unexpected JSON tunnel payload shape");return n},hl=(e,t=No)=>{if(t<=0||t>No)throw new ve("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},ma=(e,t,n)=>{const r=hl(n);return r.map((s,o)=>Ke(e,t,s,o<r.length-1))},sf=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,s=t.get(r);if(!n.hasMoreFragments&&!s)return n.payload;const o=s?.chunks??[],i=(s?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new ve("fragmented message exceeds maximum size");if(o.push(n.payload),n.hasMoreFragments)return t.set(r,{chunks:o,totalBytes:i}),null;t.delete(r);const a=new Uint8Array(i);let c=0;for(const l of o)a.set(l,c),c+=l.length;return a},dropStream(n){for(const r of t.keys())r.startsWith(`${n}:`)&&t.delete(r)}}},of=e=>{if(e.length===0)throw new ve("cannot encode an empty frame batch");if(e.length===1){const s=e[0],o=new Uint8Array(1+s.length);if(o[0]=cl,o.set(s,1),o.length>pr)throw new ve("frame batch exceeds maximum plaintext size");return o}let t=1;for(const s of e)t+=In+s.length;if(t>pr)throw new ve("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=ll;let r=1;for(const s of e)n[r]=s.length>>>24&255,n[r+1]=s.length>>>16&255,n[r+2]=s.length>>>8&255,n[r+3]=s.length&255,r+=In,n.set(s,r),r+=s.length;return n},af=e=>{if(e.length<1)throw new ve("empty batch plaintext");const t=e[0];if(t===cl)return[e.slice(1)];if(t!==ll)throw new ve(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+In>e.length)throw new ve("truncated batch frame length");const s=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=In,r+s>e.length)throw new ve("truncated batch frame body");n.push(e.slice(r,r+s)),r+=s}if(n.length===0)throw new ve("empty frame batch");return n},cf=new Set([z.HttpBody,z.WsText,z.WsBinary]),ml=150,lf=24*1024,uf=32,df=e=>{const t=e.windowMs??ml,n=e.maxBatchBytes??lf,r=e.maxBatchFrames??uf,s=e.now??(()=>Date.now()),o=e.setTimer??((b,S)=>setTimeout(b,S)),i=e.clearTimer??(b=>clearTimeout(b));let a=[],c=0,l=null,u=0,d=!1;const p=()=>{l!==null&&(i(l),l=null)},m=()=>{if(p(),a.length===0)return;const b=a;a=[],c=0,u=s(),e.sendBatch(of(b))};return{enqueue:b=>{if(d)return;const S=b[0]&~Ss;if(!cf.has(S)){a.push(b),m();return}const k=s();if(a.length===0&&k-u>=t){a.push(b),m();return}const P=In+b.length;if(a.length>0&&1+c+P>pr&&m(),a.push(b),c+=P,c>=n||a.length>=r){m();return}l===null&&(l=o(m,t))},flush:m,dispose(){d=!0,p(),a=[],c=0}}},ff=()=>{let e=1;return{next(){if(e>pl)throw new ve("stream id space exhausted");const t=e;return e+=2,t}}},$s=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pf=e=>$s(e)&&Object.values(e).every(t=>typeof t=="string"),hf=e=>$s(e)&&typeof e.status=="number"&&pf(e.headers),ga=e=>$s(e)&&typeof e.reason=="string",mf=e=>$s(e)&&typeof e.code=="number"&&typeof e.reason=="string",gl=/^[a-z][a-z\d+.-]*:\/\//i,Ei="http://tunnel.invalid",gf=e=>{try{const t=gl.test(e)?new URL(e):new URL(e,Ei);return`${t.pathname}${t.search}`}catch{return e}},Hr=e=>({async*[Symbol.asyncIterator](){yield e}}),yf=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)return;r&&(yield r)}}finally{t.releaseLock()}}}),wf=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Sf=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:yf(e)};if(typeof e=="string")return{body:Hr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Hr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Hr(wf(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Hr(r),contentType:n}},bf=async(e,t)=>{let n;const r=new Headers;let s="GET",o=null,i;e instanceof Request?(n=e.url,s=e.method,e.headers.forEach((d,p)=>r.set(p,d)),i=e.signal,o=e.body):n=e.toString(),t&&(t.method&&(s=t.method),t.headers&&new Headers(t.headers).forEach((d,p)=>r.set(p,d)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const a=gl.test(n)?new URL(n):new URL(n,Ei),{body:c,contentType:l}=await Sf(o);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,p)=>{u[p]=d}),{method:s.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},yl="__openchamberAmbiguousTransport",Ho=e=>(Object.defineProperty(e,yl,{value:!0,enumerable:!1,configurable:!0}),e),ya=e=>!e||typeof e!="object"?!1:e[yl]===!0,vf=["local","remote",null],Tf=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function wl(e){if(!e||typeof e!="object")return{valid:!1};const t=e,n=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,s=t.status;if(r!==null&&(typeof r!="string"||!vf.includes(r)))return{valid:!1};if(typeof s!="string"||!Tf.includes(s))return{valid:!1};if(r==="remote"||r==="local"){if(s==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok",...n}};if(s==="ok"&&r==="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,...n}};if(s==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...n}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...n}};if(s==="incompatible"||s==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:s,hostId:t.hostId,url:t.url,...n}};if(s==="missing")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...n}}}if(r===null){if(s==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...n}};if(s==="missing")return{valid:!1}}return{valid:!1}}function GT(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const n=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...n};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...n}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...n};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...n};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...n};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...n};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...n};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...n}}return null}function qT(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function KT(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function Sl(){if(kf()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=wl(t);return n.valid?n.outcome:null}function kf(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":wl(e).valid?"valid":"malformed"}const bs=/^[a-z][a-z\d+.-]*:\/\//i,Ef=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},vs=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Pf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return vs(e)},Af=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return vs(e)},If=()=>Object.keys(Gs()).length>0,xf=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},$o=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,s]of n)s!=null&&e.searchParams.set(r,String(s))},Rf=(e,t)=>{if(!t)return e;const n=new URLSearchParams;$o({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},wa=(e,t,n)=>{if(bs.test(t)){const o=new URL(t);return $o(o,n),o.toString()}const r=Ef(t);if(!e)return Rf(r,n);const s=new URL(r,`${e}/`);return $o(s,n),s.toString()},$r=(e,t=op())=>{if(!t)return e;const n=bs.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),bs.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},bl=(e,t)=>{const n=bs.test(e)?new URL(e):new URL(e,xf(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},Sa=(e,t,n)=>{if(!If())return null;const r=Af();if(!r)return null;try{const s=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${r}/`);s.searchParams.set("url",t);const o=ip(r);return o&&s.searchParams.set("oc_url_token",o),e==="ws"?(s.protocol=s.protocol==="https:"?"wss:":"ws:",bl(s.toString(),n)):s.toString()}catch{return null}},Pi=(e={})=>{const t=vs(e.apiBaseUrl),n=vs(e.realtimeBaseUrl),r=()=>t||Pf(),s=()=>n||r(),o=(a,c)=>wa(r(),a,c),i=(a,c)=>wa(s(),a,c);return{api:o,authenticatedAsset:(a,c)=>$r(o(a,c)),assetWithUrlToken:(a,c,l)=>$r(o(a,l),c),auth:o,health:a=>o("/health",a),rawFile:(a,c)=>o("/api/fs/raw",{path:a,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(a,c)=>{const l=$r(i(a,c));return Sa("sse",l,e)||l},websocket:(a,c)=>{const l=bl($r(i(a,c)),e);return Sa("ws",l,e)||l}}};let Ts=Pi();const Re=()=>Ts,Cf=e=>{Ts=e},vl=e=>(Ts=Pi(e),Ts),zo="openchamber:runtime-endpoint-changed",Wo="openchamber:runtime-endpoint-will-change";let xn="",mr="";const oo=(e,t,n)=>{try{e[t]=n}catch{}},Ai=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"}`}},Of="mobile-disconnected",Df="url:default",Tl=e=>e===""||e===Df||e===Of,kl=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},El=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Pl=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Rn=()=>xn||kl();let io="",ba=null,va,Ta;const ka=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},q=()=>{if(mr)return mr;const e=ka("__OPENCHAMBER_API_BASE_URL__"),t=ka("__OPENCHAMBER_LOCAL_ORIGIN__");if(ba===xn&&va===e&&Ta===t)return io;const n=Rn();return io=Pl(n,El())?"local":Ai(n),ba=xn,va=e,Ta=t,io},Mf=(e={})=>{if(xn||mr)return;const t=e.apiBaseUrl?.trim()||kl(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const s=El(),o=s&&(!t||Pl(t,s));xn=t,mr=e.runtimeKey?.trim()||(o?"local":Ai(t||r))},ks=e=>{const t=e.apiBaseUrl.trim(),n=Rn(),r=q(),s=e.runtimeKey?.trim()||Ai(t),o={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:s,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Wo,{detail:o})),xn=t,mr=s,typeof window<"u"){const i=window;oo(i,"__OPENCHAMBER_API_BASE_URL__",t),oo(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),oo(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}vl({apiBaseUrl:t,realtimeBaseUrl:t}),Nl(e.requestHeaders||null),Ul(e.clientToken||null),e.relay?Xf(e.relay):Zf(),qs(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zo,{detail:o}))},_f=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Wo,t),()=>window.removeEventListener(Wo,t)},Al=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(zo,t),()=>window.removeEventListener(zo,t)};let Go=null;const VT=e=>{Go=e},Er=()=>Go||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Il=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,xl=(e=Il())=>!!e,Lf=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Ut=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,on=()=>Lf()?.runtime==="electron",Ff=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},jf="right",JT=()=>{if(!on())return!1;const e=Ff();return e==="win32"||e==="linux"},YT=e=>e==="left"?"left":jf,QT=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Ce=()=>typeof Ut()?.invoke=="function",Ln=()=>on()&&Ce(),Uf=()=>{if(Ut()?.pickThemeFile)return{async pick(){const e=Ut()?.pickThemeFile;return e?{status:"picked",file:w({name:f(),size:E().nonnegative(),text:f()}).nullable().parse(await e())}:{status:"unsupported"}}}},se=async(e,t)=>{const n=Ut();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},XT=async()=>{if(!He()||!Te())return!1;const e=Rn();try{const t=Y().safeParse(await se("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===Rn()}catch{return!1}},ZT=async()=>{if(!Ln()||!Te())return null;try{const e=await se("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}},ek=async e=>{if(!Ln()||!Te())return null;try{const t=await se("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}},tk=async()=>{if(!Ln()||!Te())return null;try{const e=await se("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}},nk=async e=>{if(!Ln()||!Te())return null;try{const t=await se("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}},rk=async()=>{if(!Ln()||!Te())return null;try{const e=await se("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}},sk=async e=>{if(!Ln()||!Te())return null;try{const t=await se("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}},Ea=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}}},ao=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}}},Nf=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Wn=e=>{const t=Nf(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Te=()=>{if(typeof window>"u"||!He())return!1;if(q()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=ao(e),n=ao(Rn());if(!n&&t&&Sl()?.target==="local")return!0;if(t&&n){if(t.origin===n.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&i===a&&Wn(t.hostname)&&Wn(n.hostname)}const r=ao(window.location.origin);if(t&&r){if(t.origin===r.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&i===a&&Wn(t.hostname)&&Wn(r.hostname)}const s=Ea(e),o=Ea(window.location.origin)||window.location.origin;return s&&o&&s===o?!0:!!(r&&Wn(r.hostname))},He=()=>typeof window>"u"?!1:on(),ok=async()=>{if(!He())return!1;try{return!!await se("desktop_focus_window")}catch{return!1}},Rl=()=>He()&&Ce()&&Te(),Bf=M(w({sessionId:f().min(1),messageId:f().min(1).optional()})),ik=async()=>{if(!He()||!Te())return[];try{const e=Bf.safeParse(await se("desktop_take_pending_session_links"));return e.success?e.data.map(t=>({sessionId:t.sessionId,messageId:t.messageId??null})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},Hf=f().min(1),ak=e=>{if(!Rl())return null;try{const t=Hf.safeParse(Ut()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},ck=async()=>{if(!He())return!1;try{return await se("desktop_start_window_drag"),!0}catch{return!1}},Me=()=>xl()?!0:Er()?.runtime?.isVSCode===!0,lk=()=>{const t=Er()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Me()},uk=(e,t=He())=>e==="web"&&!t,Cl=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},dk=async e=>{if(Rl())try{const t=await Ut()?.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"}},$f=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fk=async e=>{if(Ce()&&Te())try{const t=await Ut()?.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(!$f(t))return{success:!1,error:"File selection cancelled"};const n=typeof t.path=="string"?t.path:"";return n?{success:!0,path:n,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"}},pk=async e=>({success:!0}),hk=async e=>({success:!0}),mk=async()=>Ce()?await se("desktop_check_for_updates"):null,gk=async e=>{if(!Ce())return!1;const t=Ut();let n=null,r=0,s;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("openchamber:update-progress",o=>{const i=o?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){r=0,s=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:s});return}if(c==="Progress"){const u=l?.downloaded,d=l?.total;typeof u=="number"&&(r=u),typeof d=="number"&&(s=d),e({downloaded:r,total:s});return}c==="Finished"&&e({downloaded:r,total:s})})),await se("desktop_download_and_install_update"),!0}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{if(n)try{const o=n();o instanceof Promise&&await o}catch{}}},yk=async()=>Ce()?(await se("desktop_restart"),!0):!1,wk=async()=>{if(!Ce())return!1;try{return await se("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},Sk=async()=>{if(!Ce()||!Te())return null;try{const e=await se("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}},zf=async(e,t)=>{if(!Ce()||!Te())return!1;const n=e?.trim();if(!n)return!1;try{return await se("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},bk=async e=>{if(!Ce()||!Te())return!1;const t=e?.trim();if(!t)return!1;try{return await se("desktop_reveal_path",{path:t}),!0}catch{return zf(t)}},vk=async(e,t)=>{if(!Ce()||!Te())return null;const n=e?.trim();if(!n)return null;try{const r=await se("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},Tk=async(e,t,n)=>{if(!Ce()||!Te())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await se("desktop_open_in_app",{projectPath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},kk=async(e,t,n)=>{if(!Ce()||!Te())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await se("desktop_open_file_in_app",{filePath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},Ek=async(e,t)=>{if(!Ce()||!Te())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const r=await se("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=r;return s.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(s.apps)?{apps:s.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:s.hasCache===!0,isCacheStale:s.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Pr=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",Pk=()=>{if(typeof window>"u"||!Pr()||Ol()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Ol=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Me()?"vscode":He()?"desktop":"web"},Wf="2.1.0",zr=new Uint8Array(0),Gf=new TextEncoder,qf=new TextDecoder,Ge=e=>e instanceof Error?e:new Error(String(e)),Wr=()=>new DOMException("The operation was aborted.","AbortError"),Kf=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(n){e.send(n)},close(n,r){e.close(n,r)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>t.onmessage?.({data:n.data}),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),e.onerror=()=>t.onerror?.(),t},Vf=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(n){n&&(e.binaryType=n)},onopen:null,onmessage:null,onerror:null,onclose:null,send(n){e.send(n)},close(n,r){e.close(n,r)}};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>{const r=n.data;(typeof r=="string"||r instanceof ArrayBuffer)&&t.onmessage?.({data:r})},e.onerror=()=>t.onerror?.(),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),t},Pa=0,co=1,Aa=2,Ia=3,Jf=new Set([en.AuthFailed,en.DuplicateClient,en.LimitExceeded]),Yf={[en.AuthFailed]:"relay authentication failed",[en.DuplicateClient]:"relay connection replaced by another client",[en.LimitExceeded]:"relay connection limit reached"},xa=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Ii=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,s=e.pingTimeoutMs??15e3,o=e.batchWindowMs??ml,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(R=>Kf(new WebSocket(R)));let d=!1,p=null,m={state:"idle"};const y=new Set;let b=null,S=null,k=null,P=0,F=0,_=null,Q=[],D=!1;const ke=R=>{if(!(m.state===R.state&&m.lastError===R.lastError)){m=R;for(const G of y)try{G(m)}catch{}}},ue=R=>{const G=Q;Q=[];for(const L of G)L.reject(R)},to=R=>{const G=Q;Q=[];for(const L of G)L.resolve(R)},Oe=(R,G)=>{R.dead=!0;const L=Array.from(R.streams.values());R.streams.clear();for(const U of L)try{U.fail(G)}catch{}},Nn=()=>{_!==null&&(clearTimeout(_),_=null)},Bn=()=>{d||_===null||xa()||(Nn(),et(),Hn())},Bt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Bn()},N=()=>{D||typeof window>"u"||(D=!0,window.addEventListener("online",Bn),typeof document<"u"&&document.addEventListener("visibilitychange",Bt))},et=()=>{!D||typeof window>"u"||(D=!1,window.removeEventListener("online",Bn),typeof document<"u"&&document.removeEventListener("visibilitychange",Bt))},un=()=>{if(d||_!==null)return;const R=Math.max(0,F-1),G=a*2**Math.min(R,10),L=xa()?l:c,U=Math.min(L,G);N(),_=setTimeout(()=>{_=null,et(),Hn()},U)},Lr=()=>{const R=new URL(e.relayUrl);return R.searchParams.set("v",String(nr)),R.searchParams.set("role","client"),R.searchParams.set("serverId",e.serverId),R.searchParams.set("appId","openchamber"),R.searchParams.set("appVersion",Wf),R.searchParams.set("platform",Ol()),e.grant&&R.searchParams.set("grant",e.grant),R.toString()},Hn=async()=>{if(d)return;Nn(),P+=1;const R=P;ke({state:F>0?"reconnecting":"connecting",lastError:m.lastError});let G;try{G=await Zd(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(X){if(R!==P||d)return;da(R,Ge(X),!0);return}if(R!==P||d)return;let L;try{L=u(Lr())}catch(X){da(R,Ge(X));return}S=L;let U=!1,B=null,K=null,_e=null,we=null,$=Promise.resolve(),W=null,ie=null,dt=!1,me=!1,ge=0,Se=0,be=null,ft=null,re=Date.now();const kt=()=>{be!==null&&(clearTimeout(be),be=null),B!==null&&(clearInterval(B),B=null),K!==null&&(clearTimeout(K),K=null),_e!==null&&(clearInterval(_e),_e=null),we!==null&&(clearTimeout(we),we=null),ft!==null&&(ft.dispose(),ft=null)};k=kt;function J(X,ae=!1,te=!1){if(!(U||R!==P)){U=!0,te&&(p=X),kt(),W&&(b=null,Oe(W,new Error(`relay tunnel reset: ${X.message}`))),ue(X);try{L.close()}catch{}if(S===L&&(S=null),!d){if(F+=1,te){ke({state:"error",lastError:X.message});return}ke({state:ae?"error":"reconnecting",lastError:X.message}),un()}}}const $n=()=>{try{L.send(G.helloText)}catch{}},jr=(X,ae,te)=>{ie=X,dt=ae,me=te,B!==null&&(clearInterval(B),B=null),K!==null&&(clearTimeout(K),K=null);const de=new Map,Ht=ff(),We=sf();let $t=Promise.resolve();const Et=zn=>{$t=$t.then(async()=>{if(zt.dead)return;const Dd=await X.encryptor.encrypt(zn);zt.dead||L.send(Dd)}).catch(()=>{J(new Error("relay encrypt/send failed"))})},ro=ae?df({windowMs:o,sendBatch:Et}):null;ft=ro;const zt={streams:de,assembler:We,nextStreamId:()=>Ht.next(),dead:!1,send(zn){zt.dead||(ro?ro.enqueue(zn):Et(zn))}};W=zt,b=zt,F=0,re=Date.now(),ke({state:"connected"}),to(zt),_e=setInterval(()=>{Date.now()-re<r||(zt.send(Ke(z.Ping,0,zr)),we===null&&(we=setTimeout(()=>{we=null,J(new Error("relay keepalive timeout"))},s)))},r)},dn=()=>{be!==null&&clearTimeout(be),be=null,!(!W||W.dead||ge===Se)&&(Se=ge,W.send(Ke(z.DeliveryAck,0,ef(ge))))},Od=(X,ae)=>{let te;try{te=tf(ae)}catch(We){J(Ge(We));return}if(te.frameType===z.DeliveryAck){J(new Error("unexpected downstream delivery acknowledgement"));return}if(me&&te.streamId!==0&&(ge+=ae.length,be===null&&(be=setTimeout(dn,10))),re=Date.now(),we!==null&&(clearTimeout(we),we=null),te.frameType===z.Ping){X.send(Ke(z.Pong,te.streamId,zr));return}if(te.frameType===z.Pong)return;let de=te.payload;if(te.frameType===z.WsText||te.frameType===z.WsBinary){let We;try{We=X.assembler.push(te)}catch($t){J(Ge($t));return}if(We===null)return;de=We}else if(te.hasMoreFragments){J(new Error("unexpected fragmented tunnel frame"));return}const Ht=X.streams.get(te.streamId);Ht&&Ht.handleFrame(te.frameType,de)};L.onopen=()=>{U||R!==P||($n(),B=setInterval($n,t))},L.onmessage=X=>{if(U||R!==P)return;const ae=X.data;if(typeof ae=="string"){$=$.then(async()=>{if(U||R!==P)return;const de=await G.handleText(ae);if(de.type==="established"){if(ie)return;jr(de.channel,de.batch,de.flowControl)}else de.type==="fail"&&J(new Error(`relay handshake failed: ${de.reason}`))}).catch(de=>{J(Ge(de))});return}const te=ae instanceof ArrayBuffer?new Uint8Array(ae):ae instanceof Uint8Array?ae:null;te&&($=$.then(async()=>{if(U||R!==P)return;const de=W,Ht=ie;if(!de||!Ht){J(new Error("encrypted frame before handshake completed"));return}let We;try{We=await Ht.decryptor.decrypt(te)}catch(Et){J(Ge(Et));return}let $t;try{$t=dt?af(We):[We]}catch(Et){J(Ge(Et));return}for(const Et of $t){if(U||R!==P||de.dead)return;Od(de,Et)}me&&ge-Se>=16*1024&&dn()}).catch(de=>{J(Ge(de))}))},L.onclose=X=>{const ae=Jf.has(X.code);J(new Error(Yf[X.code]??`relay socket closed (code ${X.code})`),ae,ae)},L.onerror=()=>{},K=setTimeout(()=>{K=null,J(new Error("relay handshake timeout"),!0)},n);function da(X,ae,te=!1){X!==P||d||(ue(ae),F+=1,ke({state:te?"error":"reconnecting",lastError:ae.message}),un())}},Fr=R=>d?Promise.reject(new Error("relay tunnel closed")):R?.aborted?Promise.reject(Wr()):p?Promise.reject(p):b&&!b.dead?Promise.resolve(b):new Promise((G,L)=>{let U=null;const B={resolve(K){U&&R&&R.removeEventListener("abort",U),G(K)},reject(K){U&&R&&R.removeEventListener("abort",U),L(K)}};R&&(U=()=>{Q=Q.filter(K=>K!==B),L(Wr())},R.addEventListener("abort",U,{once:!0})),Q.push(B)}),Tt=async(R,G)=>{const L=await bf(R,G),U=L.signal;if(U?.aborted)throw Wr();const B=await Fr(U),K=B.nextStreamId();return await new Promise((_e,we)=>{let $=!1,W=!1,ie=null,dt=null;const me=()=>{B.streams.delete(K),B.assembler.dropStream(K),dt&&U&&U.removeEventListener("abort",dt)},ge=re=>{if(!W){if(W=!0,me(),!$){we(re);return}try{ie?.error(re)}catch{}}},Se=re=>{B.dead||B.send(Ke(z.StreamAbort,K,Nr({reason:re})))},be=re=>Ho(new Error(re));dt=()=>{Se("aborted"),ge(Wr())},B.streams.set(K,{handleFrame(re,kt){if(re===z.HttpResponse){if($||W)return;let J;try{J=Br(kt,hf)}catch(dn){Se("malformed response head"),ge(be(Ge(dn).message));return}const $n=J.status===204||J.status===205||J.status===304;let jr=null;$n||(jr=new ReadableStream({start(dn){ie=dn},cancel(){W||(W=!0,me(),Se("response body cancelled"))}})),$=!0,_e(new Response(jr,{status:J.status,headers:J.headers})),$n&&(W=!0,me());return}if(re===z.HttpBody){if(!$||W)return;try{ie?.enqueue(kt)}catch{}return}if(re===z.StreamEnd){if(W)return;if(!$){ge(be("tunnel stream ended before response head"));return}W=!0,me();try{ie?.close()}catch{}return}if(re===z.StreamAbort){let J="stream aborted by host";try{J=Br(kt,ga).reason}catch{}ge(be(J))}},fail(re){ge(be(re.message))}}),U&&U.addEventListener("abort",dt,{once:!0});const ft={method:L.method,path:L.path,query:L.query,headers:L.headers,hasBody:L.body!==null};B.send(Ke(z.HttpRequest,K,Nr(ft))),(async()=>{try{let re=!1;if(L.body)for await(const kt of L.body){if(W||B.dead)return;for(const J of hl(kt))B.send(Ke(z.HttpBody,K,J)),re=!0}!W&&!B.dead&&(L.body&&!re&&B.send(Ke(z.HttpBody,K,zr)),B.send(Ke(z.StreamEnd,K,zr)))}catch(re){Se("request body failed"),ge(be(Ge(re).message))}})()})},no=R=>{const G=R.indexOf("?");return G===-1?{path:R,query:""}:{path:R.slice(0,G),query:R.slice(G+1)}},Rd=(R,G)=>{let L=Pa,U=null,B=0,K=!1;const _e={get readyState(){return L},onopen:null,onmessage:null,onerror:null,onclose:null,send($){if(L!==co||!U||U.dead)throw new Error("relay tunnel socket is not open");if(typeof $=="string"){for(const ie of ma(z.WsText,B,Gf.encode($)))U.send(ie);return}const W=$ instanceof ArrayBuffer?new Uint8Array($.slice(0)):(()=>{const ie=new Uint8Array($.byteLength);return ie.set(new Uint8Array($.buffer,$.byteOffset,$.byteLength)),ie})();for(const ie of ma(z.WsBinary,B,W))U.send(ie)},close($=1e3,W=""){L===Ia||L===Aa||(L===co&&U&&!U.dead&&(L=Aa,U.send(Ke(z.WsClose,B,Nr({code:$,reason:W})))),we($,W))}},we=($,W,ie=!1)=>{if(!K){if(K=!0,U&&(U.streams.delete(B),U.assembler.dropStream(B)),L=Ia,ie)try{_e.onerror?.()}catch{}try{_e.onclose?.({code:$,reason:W})}catch{}}};return(async()=>{let $;try{$=await Fr()}catch(me){we(1006,Ge(me).message,!0);return}if(K)return;U=$,B=$.nextStreamId(),$.streams.set(B,{handleFrame(me,ge){if(me===z.WsOpened){if(L===Pa){L=co;try{_e.onopen?.()}catch{}}return}if(me===z.WsText){try{_e.onmessage?.({data:qf.decode(ge)})}catch{}return}if(me===z.WsBinary){const Se=new ArrayBuffer(ge.byteLength);new Uint8Array(Se).set(ge);try{_e.onmessage?.({data:Se})}catch{}return}if(me===z.WsClose){let Se=1e3,be="";try{const ft=Br(ge,mf);Se=ft.code,be=ft.reason}catch{}we(Se,be);return}if(me===z.StreamAbort){let Se="stream aborted";try{Se=Br(ge,ga).reason}catch{}we(1006,Se,!0)}},fail(me){we(1012,me.message,!0)}});const{path:W,query:ie}=no(R),dt=G&&G.length>0?{path:W,query:ie,protocols:G}:{path:W,query:ie};$.send(Ke(z.WsOpen,B,Nr(dt)))})(),_e},Cd=()=>{if(d)return;d=!0,P+=1,Nn(),et(),k?.(),k=null;const R=b;b=null;const G=new Error("relay tunnel closed");R&&Oe(R,G),ue(G);try{S?.close()}catch{}S=null,ke({state:"idle"})};return Hn(),{fetch:Tt,openWebSocket:Rd,getStatus:()=>m,subscribeStatus(R){return y.add(R),()=>{y.delete(R)}},close:Cd}};let je=null,bt=null;const Qf=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),zs=()=>je,Ak=()=>!je||!bt?null:{relayUrl:bt.relayUrl,serverId:bt.serverId,hostEncPubJwk:{...bt.hostEncPubJwk}},Ik=()=>je!==null,Xf=e=>(je&&bt&&Qf(bt,e)||(je?.close(),bt=e,je=Ii(e)),je),xk=(e,t)=>{je!==t&&(je?.close(),bt=e,je=t)},Zf=()=>{je?.close(),je=null,bt=null};let Dl=()=>null,Ml="",Es={},nn="",gr=0,Yt=null,kn="",yr=0,rn="",Qt=null,Dt="",ls=0,us=0;const xi=1e4,ep=e=>e.toLowerCase()==="authorization",_l=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const s=n.trim(),o=r.trim();s&&o&&!ep(s)&&(t[s]=o)}return t},tp=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,s])=>t[r]===s)},Ws=e=>typeof e!="string"?"":e.trim(),np=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Ws(e)},rp=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Ll=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():rp();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},Ri=e=>{try{return new URL(e).origin}catch{return""}},Fl=()=>{kn="",yr=0,rn="",Qt=null,Dt="",ls+=1},Ar=()=>{nn="",gr=0,Fl()},jl=()=>{us+=1,Yt=null,Ar(),Ci()},Ul=e=>{const t=Ws(e);Ml=t,jl(),Dl=()=>t?{type:"bearer",token:t}:null},Nl=e=>{const t=_l(e);tp(Es,t)||(Es=t,jl())},Gs=()=>{if(Object.keys(Es).length>0)return Es;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?_l(e):{}},Bl=()=>Ml||np(),sp=(e,t)=>{const n=Ws(e);if(!n||typeof t!="number"||!Number.isFinite(t)){Ar();return}const r=nn;nn=n,gr=t,r&&r!==n&&up()},Hl=()=>!nn||gr<=Date.now()+xi?(Ar(),""):nn,$l=e=>{const t=Ri(e);return!t||rn!==t?"":!kn||yr<=Date.now()+xi?(kn="",yr=0,rn="",""):kn},op=()=>{const e=Hl();return!e&&(Bl()||typeof window<"u")&&qs().catch(()=>{}),e},ip=e=>{const t=e?$l(e):"";return!t&&e&&typeof window<"u"&&ql(e).catch(()=>{}),t},zl=async()=>{const e=await Dl(),t=e?.type==="bearer"?Ws(e.token):Bl();return t?{type:"bearer",token:t}:null},ap=w({token:f(),expiresAt:E()}),Wl=async(e,t)=>{const n=await zl(),r=new Headers;for(const[c,l]of Object.entries(Gs()))r.set(c,l);n?.type==="bearer"&&r.set("Authorization",`Bearer ${n.token}`);const s=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",o=zs(),i=o?await o.fetch(s,{method:"POST",headers:r}):await fetch(Ll(e,s),{method:"POST",headers:r,credentials:"include"});if(!i.ok)throw new Error(`Failed to mint runtime URL auth token (${i.status})`);const a=ap.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},Rk=async e=>{const t=await Wl(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Gl=e=>{if(Yt)return Yt;const t=us,r=(async()=>{let s;try{s=await Wl(e)}catch(o){throw t===us&&Ar(),o}if(t!==us)throw new Error("Runtime URL auth token response is stale");if(sp(s.token,s.expiresAt),!nn)throw new Error("Runtime URL auth token response was invalid");return nn})().finally(()=>{Yt===r&&(Yt=null)});return Yt=r,Yt},cp=e=>{const t=Ri(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Qt&&Dt===t)return Qt;const n=ls,s=(async()=>{const o=await fetch(Ll(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw n===ls&&t===Dt&&(kn="",yr=0,rn=""),new Error(`Failed to mint local runtime URL auth token (${o.status})`);const i=await o.json().catch(()=>null),a=typeof i?.token=="string"?i.token.trim():"",c=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!a||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(n!==ls||t!==Dt)throw new Error("Local runtime URL auth token response is stale");return kn=a,yr=c,rn=t,a})().finally(()=>{Qt===s&&(Qt=null,Dt="")});return Qt=s,Dt=t,Qt},qs=async e=>{const t=Hl();return t||Gl(e)},ql=async e=>{const t=Ri(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=$l(t);return n||((rn&&rn!==t||Dt&&Dt!==t)&&Fl(),cp(t))};let bn=0,sr=null,Kl=null;const qo=new Set,lp=5e3,up=()=>{for(const e of qo)try{e()}catch{}},Vl=()=>{sr!==null&&(clearTimeout(sr),sr=null)},Ci=()=>{if(Vl(),bn<=0||typeof window>"u")return;const e=gr-xi-lp,t=gr>0?Math.max(0,e-Date.now()):0;sr=setTimeout(()=>{sr=null,!(bn<=0)&&Gl(Kl).catch(()=>{}).finally(()=>{Ci()})},t)},Ck=e=>{typeof e=="string"&&e.trim()&&(Kl=e.trim()),bn+=1,Ci();let t=!1;return()=>{t||(t=!0,bn=Math.max(0,bn-1),bn===0&&Vl())}},Ok=e=>(qo.add(e),()=>{qo.delete(e)}),dp=async e=>{const t=new Headers(e);for(const[r,s]of Object.entries(Gs()))t.has(r)||t.set(r,s);if(t.has("Authorization"))return t;const n=await zl();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},Ps=ut(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),fp=15e3,pp=5*6e4;let Ko=0,lo=!1;const hp=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),mp=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!hp(t)},Jl=async()=>{if(!lo){lo=!0;try{const{runtimeFetch:e}=await ki(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>Dp);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){Ps.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=Ps.getState();n==="expired"&&r()}}catch{}finally{lo=!1}}},gp=(e,t)=>{if(t!==401||Ps.getState().state==="expired"||!mp(e))return;const n=Date.now();n-Ko<fp||(Ko=n,Jl())};let Ra=!1;const Dk=()=>{if(Ra)return;Ra=!0;let e=Date.now();const t=()=>{if(Ps.getState().state!=="ok")return;const n=Date.now();n-e<pp||(e=n,Ko=n,Jl())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},yp=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,Ca="/api/",Yl="/api/spaces/",Oi=e=>{if(!e)return null;const t=yp.exec(e);return t?t[1]:null},Oa=e=>Oi(e)!==null,wp=e=>e.startsWith(Yl),Sp=()=>xl()||Er()?.runtime?.isVSCode===!0,Di=(e,t)=>{if(Sp())return e;const n=Oi(t);return n===null||!e.startsWith(Ca)||wp(e)?e:`${Yl}${n}/${e.slice(Ca.length)}`},sn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",bp=()=>typeof window>"u"?"":window.location.origin||"",Ks=e=>{if(typeof window>"u")return!1;const t=bp();if(t&&e.origin===t)return!0;try{const n=new URL(window.location.href||t);return e.protocol===n.protocol&&e.host===n.host}catch{return!1}},Vs=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),vp=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),Ct=(e,t)=>{try{vp(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},Mi=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,s]of n)s!=null&&e.searchParams.set(r,String(s))},Ql=e=>{if(!e)return null;try{return decodeURIComponent(e)}catch{return e}},Da=e=>{const t=new URLSearchParams(e);return Ql(t.get("directory")??t.get("location[directory]"))},Ma=e=>{if(!e)return null;const t=e instanceof Headers?e.entries():Array.isArray(e)?e:Object.entries(e);for(const[n,r]of t)if(n.toLowerCase()==="x-opencode-directory")return Ql(r);return null},Tp=e=>{if(!Vs(e)){const t=e.search(/[?#]/);return t===-1?{path:e,rest:"",origin:""}:{path:e.slice(0,t),rest:e.slice(t),origin:""}}try{const t=new URL(e);return!Ks(t)&&!or(t)?null:{path:t.pathname,rest:`${t.search}${t.hash}`,origin:t.origin}}catch{return null}},kp=(e,t)=>{const n=e instanceof Request?e.url:e.toString(),r=Tp(n);if(!r||!r.path.startsWith("/api/"))return e;const s=t.directory??Da(r.rest)??(t.query?Da(new URLSearchParams(t.query instanceof URLSearchParams?t.query:Object.entries(t.query).flatMap(([a,c])=>c==null?[]:[[a,String(c)]])).toString()):null)??Ma(t.headers)??(e instanceof Request?Ma(e.headers):null),o=Di(r.path,s);if(o===r.path)return e;const i=`${r.origin}${o}${r.rest}`;return e instanceof Request?new Request(i,e):e instanceof URL?new URL(i,e):i},or=e=>{try{const t=Re().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:sn(e.pathname)}catch{return!1}},uo=e=>{if(sn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return Ks(t)&&sn(t.pathname)}catch{return!1}},Ep=(e,t)=>{try{const n=new URL(e);if(!Ks(n))return e;const r=jt(`${n.pathname}${n.search}`,t);return!Vs(r)&&(n.protocol==="http:"||n.protocol==="https:")?(Mi(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},jt=(e,t)=>e==="/health"?Re().health(t):e.startsWith("/auth/")||e==="/auth"?Re().auth(e,t):sn(e)?Re().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Ep(e,t):e,Pp=e=>{const t=e instanceof Request?e.url:e.toString();if(!Vs(t))return sn(t);try{return or(new URL(t))}catch{return!1}},Xl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Ap=(e,t)=>!Xl(t),Vo=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 n=[];let r=!1,s=!1;for(const[o,i]of t)Ap(o,i)?(n.push([o,encodeURIComponent(i)]),r=!0,o.toLowerCase()==="x-opencode-directory"&&(s=!0)):n.push([o,i]);return s&&n.push(["x-opencode-directory-encoding","uri"]),r?n:void 0},pt=async(e,t,n=!0)=>{const r=new Headers(Vo(e)??e);return t&&new Headers(Vo(t)??t).forEach((s,o)=>r.set(o,s)),n?dp(r):r},Ip=(e,t)=>{if(!t)return e;const n=new URL(e,Ei);return Mi(n,t),`${n.pathname}${n.search}`},Zl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!Vs(n))return sn(n)?Ip(n,t):null;try{const r=new URL(n);return!Ks(r)||!sn(r.pathname)?null:(Mi(r,t),`${r.pathname}${r.search}`)}catch{return null}},xp=async(e,t,n)=>{const r=zs();if(!r)return null;const s=Zl(e,n);if(s===null)return null;const o=e instanceof Request?e.headers:void 0,i=await pt(o,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(s,{...t,headers:i})},Rp=(e,t)=>{if(typeof e=="string")return jt(e,t);if(e instanceof URL)return jt(e.toString(),t);const n=jt(e.url,t);return n===e.url?e:new Request(n,e)},Cp=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Gr=new Map,Op=(e,t,n,r)=>n||e!=="GET"||t.includes("/event")||!Cp.test(t)?null:`GET ${t}\0${r.get("x-opencode-directory")??""}`,g=async(e,t={})=>{const n=kp(e,t),{query:r,directory:s,...o}=t,i=zs(),a=i?Zl(n,r):null;let c,l,u,d;if(i&&a!==null){const k=n instanceof Request?n.headers:void 0,P=await pt(k,o.headers,!0);c=n instanceof Request?()=>i.fetch(n,{...o,headers:P}):()=>i.fetch(a,{...o,headers:P}),d=P,l=a,u=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase()}else{const k=Rp(n,r),P=k instanceof Request?k.headers:void 0,F=await pt(P,o.headers,Pp(k)),_=k instanceof Request?k.url:k instanceof URL?k.toString():String(k);Ct(_,F),c=k instanceof Request?()=>fetch(new Request(k,{...o,headers:F})):()=>fetch(k,{...o,headers:F}),d=F,l=_,u=String(o.method??(k instanceof Request?k.method:"GET")).toUpperCase()}const p=c;c=()=>p().then(k=>(gp(l,k.status),k));const m=o.signal!=null||n instanceof Request,y=Op(u,l,m,d);if(!y)return c();const b=Gr.get(y);if(b)return b.then(k=>k.clone());const S=c();return Gr.set(y,S),S.then(()=>Gr.delete(y),()=>Gr.delete(y)),S.then(k=>k.clone())};let _a=!1;const eu=()=>{if(_a||typeof window>"u")return;_a=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await xp(t,n??{});if(r)return r;if(typeof t=="string"){if(!uo(t)){try{const i=new URL(t);if(or(i)){const a=await pt(void 0,n?.headers);return Ct(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const s=await pt(void 0,n?.headers),o=jt(t);return Ct(o,s),e(o,{...n,headers:s})}if(t instanceof URL){const s=t.toString();if(!uo(s)){if(or(t)){const a=await pt(void 0,n?.headers);return Ct(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const o=await pt(void 0,n?.headers),i=jt(s);return Ct(i,o),e(i,{...n,headers:o})}if(t instanceof Request){if(!uo(t.url)){try{const a=new URL(t.url);if(or(a)){const c=await pt(t.headers,n?.headers);return Ct(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const s=await pt(t.headers,n?.headers),o=jt(t.url);Ct(o,s);const i=o===t.url?t:new Request(o,t);return e(new Request(i,{...n,headers:s}))}return e(t,n)}},Dp=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:Ct,buildRuntimeFetchUrl:jt,installRuntimeFetchBridge:eu,isLatin1Safe:Xl,runtimeFetch:g,sanitizeHeadersForBrowser:Vo},Symbol.toStringTag,{value:"Module"})),En=16384,As=globalThis,Mp=e=>{if(As.Buffer)return As.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.slice(r,r+32768));return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},tu=e=>{try{if(As.Buffer)return As.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),n=atob(t),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return new TextDecoder().decode(r)}catch{return null}},_p=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:(n.hash="",n.toString().replace(/\/+$/g,""))}catch{return null}},Lp=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"?null:(n.hash="",n.toString())}catch{return null}},La=e=>typeof e=="string"&&e.length>0,Fp=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!La(t.x)||!La(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},jp=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Up=e=>{if(!e||typeof e!="object")return null;const t=e,n=jp(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=_p(t.url);return r?n===void 0?{type:t.type,url:r}:{type:t.type,url:r,priority:n}:null}if(t.type==="relay"){const r=Lp(t.relayUrl);if(!r)return null;const s=typeof t.serverId=="string"?t.serverId.trim():"";if(!s)return null;const o=Fp(t.hostEncPubJwk);if(!o)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:r,serverId:s,hostEncPubJwk:o,...i?{grant:i}:{},...n===void 0?{}:{priority:n}}}return null},_i=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const n=typeof t.pairingId=="string"?t.pairingId.trim():"",r=typeof t.secret=="string"?t.secret.trim():"";if(!n||!r)return null;const s=Array.isArray(t.candidates)?t.candidates.map(Up).filter(c=>!!c):[];if(s.length===0)return null;const o=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(o){const c=Date.parse(o);if(!Number.isFinite(c)||c<=Date.now())return null}const i=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,a=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:n,secret:r,...i?{label:i}:{},...a?{fingerprint:a}:{},...o?{expiresAt:o}:{},candidates:s}},Mk=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}),_k=e=>{const t=_i(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",Mp(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},Np=e=>{const t=e.trim();if(!t||t.length>En)return null;try{const n=new URL(t);if(n.protocol!=="openchamber:"||n.hostname!=="connect"||n.searchParams.get("v")!=="2")return null;const r=n.searchParams.get("p")||"";if(!r||r.length>En)return null;const s=tu(r);return!s||s.length>En?null:_i(JSON.parse(s))}catch{return null}},Lk=e=>{const t=e.trim();if(!t||t.length>En)return null;const n=t.indexOf("?");if(n===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,n)))return null;let r=null,s=null;for(const i of t.slice(n+1).split("&")){const a=i.indexOf("=");if(a===-1)continue;const c=i.slice(0,a),l=i.slice(a+1);c==="v"?r=l:c==="p"&&(s=l)}if(r!=="2"||!s||s.length>En)return null;const o=tu(s);if(!o||o.length>En)return null;try{return _i(JSON.parse(o))}catch{return null}},Cn=e=>typeof e=="object"&&e!==null,Bp=e=>e.trim().toLowerCase()==="authorization",Hp=e=>{if(!Cn(e))return;const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=typeof r=="string"?r.trim():"";!s||!o||/[\r\n:]/.test(s)||/[\r\n]/.test(o)||Bp(s)||(t[s]=o)}return Object.keys(t).length>0?t:void 0},$p=e=>`relay://${e}`,zp=e=>{if(!Cn(e))return null;const t=Pe(e,"relayUrl")||Pe(e,"relay_url"),n=Pe(e,"serverId")||Pe(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!Cn(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Wp=()=>{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"},Fk=async(e,t)=>{const n=Np(e);if(!n)throw new Error("invalid-connect-link");const r=await Jp().catch(()=>""),s={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:n.pairingId,secret:n.secret,clientLabel:n.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:Wp(),...r?{dedupeKey:`desktop:${r}`}:{}})},o=async S=>{if(!S.ok)return null;const k=await S.json().catch(()=>null);return(typeof k?.clientToken=="string"?k.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((S,k)=>(S.type==="relay"?1:0)-(k.type==="relay"?1:0));for(const S of a){if(S.type==="relay"){const P=Ii({relayUrl:S.relayUrl,serverId:S.serverId,hostEncPubJwk:S.hostEncPubJwk,...S.grant?{grant:S.grant}:{}});try{const F=await o(await P.fetch("/api/client-auth/pairing/redeem",s));if(F){i={relay:{relayUrl:S.relayUrl,serverId:S.serverId,hostEncPubJwk:S.hostEncPubJwk},token:F};break}}catch{}finally{P.close()}continue}const k=Ae(S.url);if(k)try{const P=await o(await fetch(`${k}/api/client-auth/pairing/redeem`,s));if(P){i={directUrl:k,token:P};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(S=>S.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),u=n.candidates.filter(S=>S.type!=="relay").map(S=>Ae(S.url)).find(S=>!!S),d=i.directUrl||u,p=d||(l?$p(l.serverId):null);if(!p)throw new Error("pairing-missing-transport");const m=t.find(S=>l?S.relay?.serverId===l.serverId:!S.relay&&Ae(S.apiUrl||S.url)===p),y=m?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),b={...m||{},id:y,label:n.label||m?.label||nu(p),url:p,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:y,hosts:m?t.map(S=>S.id===y?b:S):[b,...t]}},Gp=/^(t|.*(?:token|auth|secret|api).*)$/i,Ae=e=>{const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},jk=e=>{const t=Ae(e);if(!t)return null;try{const n=new URL(t);if((n.pathname.replace(/\/+$/,"")||"/")==="/connect"&&n.searchParams.has("t"))return{persistedUrl:n.origin,redeemUrl:n.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},nu=e=>{const t=Ae(e);if(!t)return e;try{const n=new URL(t);(n.username||n.password)&&(n.username="",n.password="");const r=Array.from(new Set(Array.from(n.searchParams.keys())));for(const s of r)Gp.test(s)&&n.searchParams.set(s,"[REDACTED]");return n.toString()}catch{return t}},qr=(e,t)=>{const n=Ae(e),r=Ae(t);if(!n||!r)return!1;try{const s=new URL(n),o=new URL(r);if(s.origin!==o.origin||o.search&&s.search!==o.search)return!1;const i=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname,a=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},Pe=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},Fa=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},qp=e=>{if(!Cn(e))return null;const t=Pe(e,"id"),n=Pe(e,"label"),r=Pe(e,"url"),s=Pe(e,"apiUrl")||Pe(e,"api_url"),o=Pe(e,"clientToken")||Pe(e,"client_token"),i=Hp(e.requestHeaders),a=zp(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...s?{apiUrl:s}:{},...o?{clientToken:o}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},ir=e=>Ae(e.apiUrl||e.url)||e.apiUrl||e.url,an=()=>Ce()?(e,t)=>se(e,t):null,Li=async()=>{const e=an();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Cn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(qp).filter(a=>!!a):[],s=Pe(t,"defaultHostId")||Pe(t,"default_host_id")||Pe(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=Pe(t,"localOrigin")||Pe(t,"local_origin");return{hosts:r,defaultHostId:s,initialHostChoiceCompleted:o,localOrigin:i}},Kp=async e=>{const t=an();if(!t)return;const n={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(n.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:n})},Vp=async()=>{const e=an();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Jp=async()=>{const e=an();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Yp=8e3,Qp=15e3,Xp=400,Zp=async(e,t,n,r)=>{const s=new AbortController,o=window.setTimeout(()=>s.abort(),n);try{return await e.fetch(t,{...r,signal:s.signal})}finally{window.clearTimeout(o)}},ja=async(e,t,n,r)=>{for(;;){const s=n-Date.now();if(s<=0)throw new Error("relay probe deadline exceeded");try{return await Zp(e,t,Math.min(Yp,s),r)}catch(o){if(e.getStatus().state==="error"||Date.now()>=n)throw o;await new Promise(i=>window.setTimeout(i,Xp))}}},eh=async(e,t)=>{const n=Ii({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),s=r+Qp;let o=!1;try{if(!(await ja(n,"/health",s)).ok)return{status:"unreachable",latencyMs:0};const a=new Headers({Accept:"application/json"});for(const[u,d]of Object.entries(t?.requestHeaders||{}))u.toLowerCase()!=="authorization"&&a.set(u,d);const c=t?.clientToken?.trim();c&&a.set("Authorization",`Bearer ${c}`);const l=await ja(n,"/auth/session",s,{headers:a});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:l.ok?(o=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...o?{tunnel:n}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{o||n.close()}},Fi=async(e,t)=>{const n=an();if(!n)return{status:"unreachable",latencyMs:0};const r=await n("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!Cn(r))return{status:"unreachable",latencyMs:0};const s=r.status,o=s==="ok"||s==="auth"||s==="update-recommended"||s==="incompatible"||s==="wrong-service"||s==="unreachable"?s:"unreachable",i=Fa(r,"latencyMs")??Fa(r,"latency_ms")??0;return{status:o,latencyMs:i}},Uk=async(e,t)=>{const n=an();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Nk=async e=>{const t=an();t&&await t("desktop_new_window_for_host",{hostId:e})},Ft="local",th=e=>({id:Ft,label:"Local",url:e||ru()}),ru=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,nh=e=>e.id===Ft?"local":`host:${e.id}`,Bk=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Ft)?.url||ru(),r=Rn(),s=Ae(n)||n,o=Ae(t)||t,i=q(),a=e.find(u=>u.relay&&nh(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&qr(r,n))return{id:Ft,label:"Local",url:s};const c=e.find(u=>r?qr(r,ir(u)):!1);if(c)return{id:c.id,label:c.label,url:Ae(ir(c))||ir(c)};if(t&&qr(t,n))return{id:Ft,label:"Local",url:s};const l=e.find(u=>t?qr(t,u.url):!1);return l?{id:l.id,label:l.label,url:Ae(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:Ft,label:"Local",url:s}:{id:"custom",label:nu(o||"Instance"),url:o}},Is=new Map;let su=0;const xs=new Map;let Jo=0,ou={byHostId:{},isProbing:!1};const Yo=new Set,Rs=()=>{ou={byHostId:Object.fromEntries(Is),isProbing:Jo>0};for(const e of Yo)try{e()}catch{}},Hk=e=>(Yo.add(e),()=>{Yo.delete(e)}),$k=()=>ou,iu=(e,t)=>{Is.set(e,t),Rs()},zk=(e,t)=>{xs.set(e,++su),iu(e,t)},rh=e=>{const t=new Set([Ft,...e]);let n=!1;for(const r of Array.from(Is.keys()))t.has(r)||(Is.delete(r),xs.delete(r),n=!0);n&&Rs()},sh=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",oh=async()=>on()?Vp().catch(()=>""):"",ih=async(e,t)=>{const n=e.id===Ft?t:e.clientToken||"",r=async()=>{const i=await eh(e.relay,{clientToken:n,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),a={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(a.via="relay"),a};if(e.relay&&!e.apiUrl)return r();const s=Ae(on()?ir(e):e.url);if(!s)return{status:"unreachable",latencyMs:0};const o=await Fi(s,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(sh(o.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:o.status,latencyMs:o.latencyMs}},ah=async e=>{if(!He())return;const t=++su;for(const n of e)xs.set(n.id,t);Jo+=1,Rs();try{const n=await oh();await Promise.all(e.map(async r=>{const s=await ih(r,n);xs.get(r.id)===t&&iu(r.id,s)}))}finally{Jo-=1,Rs()}};let Ua=!1;const ch=async()=>{if(Ua||!He())return;Ua=!0;const e=await Li().catch(()=>null);e&&(rh(e.hosts.map(t=>t.id)),await ah([th(e.localOrigin),...e.hosts]))},lh=5e3,uh=1500;let fo=!1;const dh=async e=>{if(!on()||fo)return;const t=`host:${e}`;if(q()===t){fo=!0;try{const n=await Li().catch(()=>null),r=n?.hosts.find(d=>d.id===e);if(!n||!r?.relay)return;const s=r.apiUrl?Ae(r.apiUrl):null;if(s&&s.startsWith("https://"))return;const o=await g("/api/client-auth/connection/candidates").catch(()=>null);if(!o?.ok)return;const i=await o.json().catch(()=>null);if(!i||i.serverId!==r.relay.serverId)return;const a=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const d of a){if(!d||typeof d!="object")continue;const p=d;if(p.type!=="lan"||typeof p.url!="string")continue;const m=Ae(p.url);m&&!c.includes(m)&&c.push(m)}if(c.length===0)return;const l=s&&c.includes(s)?s:c[0];l!==s&&await Kp({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await Fi(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(u.status==="unreachable"||u.status==="wrong-service"||u.status==="incompatible"||q()!==t)return;ks({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{fo=!1}}},fh=e=>{typeof window>"u"||window.setTimeout(()=>{dh(e).catch(()=>{})},lh)},ph=async e=>{if(!on())return;const t=await Li().catch(()=>null);if(!t)return;const n=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!n)return;const r=t.hosts.find(d=>d.id===n);if(!r?.relay)return;const s=`host:${r.id}`;if(q()===s)return;const o=d=>{ks({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:s})},i=()=>{ks({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:s,relay:r.relay??void 0}),fh(r.id)},a=r.apiUrl?Ae(ir(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=Fi(a,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),u=await Promise.race([l,new Promise(d=>setTimeout(()=>d(null),uh))]);if(u){if(c(u)){o(a);return}i();return}i(),l.then(d=>{c(d)&&q()===s&&o(a)})};class tn extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const Wk=e=>e instanceof tn||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),Cs=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},Ie="/api/openchamber/spaces",Fn=f().regex(/^[0-9a-f]{12}$/),Ir=w({code:f(),message:f()}),ar=w({count:E().int().min(0),paths:M(f())}),hh=w({path:f().optional(),other:f().nullable().optional(),branch:f().optional(),stillThere:ar.optional(),ignoredInTheWay:ar.optional(),filteredInTheWay:ar.optional(),tooLarge:M(f()).optional(),failed:E().int().min(0).optional()});class po extends Error{code;status;details;constructor(t,n,r,s={}){super(n),this.name="SpacesRequestError",this.code=t,this.status=r,this.details=s}}const mh=w({id:Fn,name:f(),state:f()});vt("enabled",[w({enabled:O(!1)}),w({enabled:O(!0),spaces:M(mh).nullable(),failure:Ir.optional()})]);const gh=w({id:Fn,name:f(),code:f(),message:f()});w({enabled:Y(),stopped:M(w({id:Fn,name:f()})),stillRunning:M(gh),unknown:Ir.optional()});const au=w({mode:H(["allowlist","open"]),domains:M(f())}),cu=vt("kind",[w({kind:O("model"),id:f(),provider:f(),upstream:f(),source:vt("kind",[w({kind:O("typed")}),w({kind:O("env"),name:f()})]),url:f()}),w({kind:O("domain"),id:f(),upstream:f(),url:f()})]),yh=["checking_place","creating","setting_network","bringing_code","ready"],wh=H(yh),lu=vt("state",[w({state:O("queued"),total:E().int().min(1)}),w({state:O("running"),index:E().int().min(0),total:E().int().min(1),command:f()}),w({state:O("done"),total:E().int().min(1)}),w({state:O("failed"),index:E().int().min(0),total:E().int().min(1),command:f(),exitCode:E().int().nullable(),timedOut:Y(),startedAt:f().nullable().default(null),finishedAt:f().nullable().default(null)}),w({state:O("interrupted"),total:E().int().min(1)})]),cn=w({id:Fn,name:f(),projectDirectory:f().nullable(),directory:f().nullable(),projectFolder:w({path:f().nullable(),found:Y().nullable()}).default({path:null,found:null}),state:H(["preparing","running","exited","missing","failed"]),stoppedIdle:Y().default(!1),step:wh.nullable(),failure:Ir.nullable(),network:au.nullable(),grants:M(cu),access:H(["granted","needs_access","unknown"]).nullable(),needsAccess:M(f()),damage:H(["repairable","gatekeeper_gone"]).nullable().default(null),setup:lu.nullable().default(null)}),Sh=Ze([w({id:f(),available:O(!0),hostIsolation:Y(),version:f().default("")}),w({id:f(),available:O(!1),code:f(),message:f()})]),bh=w({code:f(),message:f(),details:hh.nullable().optional().catch(null)}),xe=async(e,t,n={})=>{const r=await g(e,{...n,headers:n.body===void 0?n.headers:{"Content-Type":"application/json",...n.headers}}),s=await r.json().catch(()=>null);if(!r.ok){const i=bh.safeParse(s);throw i.success?new po(i.data.code,i.data.message,r.status,i.data.details??{}):new po("space_request_failed",`The server answered ${r.status}.`,r.status)}const o=t.safeParse(s);if(!o.success)throw new po("space_answer_malformed","The server answered in a shape this version does not know.",r.status);return o.data},Gk=async e=>(await xe(`${Ie}/places`,w({places:M(Sh)}),{signal:e})).places,vh=w({imageBytes:E().min(0).nullable(),toolsBytes:E().min(0),spacesBytes:E().min(0),freeBytes:E().min(0),freesImage:Y()});w({freedBytes:E().min(0),kept:M(w({kind:f(),reason:H(["in_use","failed"])})),disk:vh});const Th=async e=>(await xe(Ie,w({spaces:M(cn)}),{signal:e})).spaces,qk=e=>xe(Ie,cn,{method:"POST",body:JSON.stringify(e)}),Kk=async(e,t)=>(await xe(`${Ie}/${e}/grants`,w({grant:cu}),{method:"POST",body:JSON.stringify(t)})).grant,Vk=async(e,t)=>(await xe(`${Ie}/${e}/network/domains`,w({network:au}),{method:"POST",body:JSON.stringify({domain:t})})).network,kh=w({at:f(),listener:f(),host:f(),port:E(),decision:f()}),Eh=w({records:M(kh),dropped:E(),since:f()}),Jk=(e,t)=>xe(`${Ie}/${e}/journal`,Eh,{signal:t}),Ph=w({saved:E().int().min(0)}),uu=w({id:Fn,removed:Y(),failures:M(Ir),chats:Ph.nullable().default(null)}),Yk=e=>xe(`${Ie}/${e}/start`,cn,{method:"POST"}),Qk=e=>xe(`${Ie}/${e}/stop`,cn,{method:"POST"}),Xk=e=>xe(`${Ie}/${e}/restart`,cn,{method:"POST"}),Zk=e=>xe(`${Ie}/${e}/restart-opencode`,cn,{method:"POST"}),Ah=1,Ih=168;w({enabled:Y(),hours:E().int().min(Ah).max(Ih)});const eE=(e,t)=>xe(`${Ie}/${e}/setup`,cn,{method:"POST",body:JSON.stringify({commands:t})}),xh=w({setup:lu.nullable(),output:f().nullable()}),tE=(e,t)=>xe(`${Ie}/${e}/setup`,xh,{signal:t}),nE=(e,{deleteUnsavedChats:t=!1}={})=>xe(`${Ie}/${e}${t?"?unsavedChats=delete":""}`,uu,{method:"DELETE"}),Rh=w({spaceId:Fn,name:f(),directory:f()}),rE=async e=>(await xe(`${Ie}/archives`,w({archives:M(Rh)}),{signal:e})).archives,Ch=w({changedPaths:E().int().min(0),changedBytes:E().min(0),nestedRepositories:ar,unmerged:ar,changesRoute:H(["open","closed"]),lastApplied:f().nullable(),newPaths:E().int().min(0).nullable(),newPathsUndecided:Y().default(!1)}),Oh=Ze([w({status:O("applied"),branch:f()}),w({status:O("applied"),appliedPaths:E().int().min(0)}),w({status:O("nothing_to_apply")})]),Dh=w({applied:Oh,removal:uu.nullable(),kept:Ir.nullable().default(null)}),sE=(e,t)=>xe(`${Ie}/${e}/apply`,Ch,{signal:t}),oE=(e,t)=>xe(`${Ie}/${e}/apply`,Dh,{method:"POST",body:JSON.stringify(t)}),du=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,Na=/^(?:\/\/\?\/)?[A-Za-z]:$/u,Mh=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/UNC\/[^/]+\/[^/]+)$/iu,Ne=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(s,o)=>o.toUpperCase()+":");return n==="/"?"/":du.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},_h=e=>{if(e==="/"||du.test(e)||Na.test(e)||Mh.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const n=e.slice(0,t);return Na.test(n)?`${n}/`:n},Lh=e=>Ne(e)??"",Fh=w({id:f().regex(/^[0-9a-f]{12}$/),name:f().default(""),state:H(["complete","partial","stale","unknown"]),projectDirectory:f().nullable().default(null),directory:f().nullable().default(null)}),Ba=new Map,Gn=new Map,jh=(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},Ha=(e,t,n)=>{const r=e.get(t);if(!r||r.state===n)return e;const s=new Map(e);return s.set(t,{...r,state:n}),s},wr=ut((e,t)=>({spaces:Ba,journey:null,progressRevision:0,applyJourney:(n,r)=>e(s=>{const o=new Map(n.map(i=>[i.id,i]));for(const[i,a]of Gn){const c=s.journey?.get(i);a>r&&c&&o.set(i,c)}return{journey:o}}),addJourneyEntry:n=>e(r=>{const s=r.progressRevision+1;Gn.set(n.id,s);const o=new Map(r.journey??[]);return o.set(n.id,n),{journey:o,progressRevision:s}}),creationAccess:new Map,noteCreationAccess:(n,r)=>e(s=>{const o=new Map(s.creationAccess);return r?o.set(n,r):o.delete(n),{creationAccess:o}}),noteProviderGranted:(n,r)=>e(s=>{const o=s.creationAccess.get(n);if(o?.kind!=="failed")return s;const i=o.failures.filter(c=>c.provider!==r),a=new Map(s.creationAccess);return i.length>0?a.set(n,{kind:"failed",failures:i}):a.delete(n),{creationAccess:a}}),noteGrantGiven:(n,r)=>e(s=>{const o=s.journey?.get(n);if(!o)return s;const i=s.progressRevision+1;Gn.set(n,i);const a=new Map(s.journey);return a.set(n,{...o,grants:[...o.grants.filter(c=>c.id!==r.id),r],needsAccess:o.needsAccess.filter(c=>c!==r.id)}),{journey:a,progressRevision:i}}),accessDialog:null,openAccessDialog:(n,r=null)=>e({accessDialog:{spaceId:n,providerId:r}}),closeAccessDialog:()=>e({accessDialog:null}),actions:new Map,noteAction:(n,r)=>e(s=>{const o=new Map(s.actions);return r?o.set(n,r):o.delete(n),{actions:o}}),applyDialog:null,openApplyDialog:n=>e({applyDialog:n}),closeApplyDialog:()=>e({applyDialog:null}),deleteDialog:null,deleteUnsaved:null,openDeleteDialog:(n,r=null)=>e({deleteDialog:n,deleteUnsaved:r}),closeDeleteDialog:()=>e({deleteDialog:null,deleteUnsaved:null}),archivedNotice:null,noteChatsArchived:n=>e({archivedNotice:n}),setupOutputDialog:null,openSetupOutputDialog:n=>e({setupOutputDialog:n}),closeSetupOutputDialog:()=>e({setupOutputDialog:null}),actionsSheet:null,openActionsSheet:n=>e({actionsSheet:n}),closeActionsSheet:()=>e({actionsSheet:null}),noteProgress:n=>{const r=t().progressRevision+1;Gn.set(n.spaceId,r);const s=t().journey?.get(n.spaceId);if(!s)return e({progressRevision:r}),!1;const o=new Map(t().journey);return o.set(n.spaceId,jh(s,n)),e({journey:o,progressRevision:r}),!0},applyMarks:n=>e(r=>{const s=new Map(n.map(o=>[o.id,o]));return s.size===0&&r.spaces.size===0?r:{spaces:s}}),noteStream:(n,r)=>e(s=>r==="connected"?s:{spaces:Ha(s.spaces,n,"stale")}),noteReachable:n=>e(r=>({spaces:Ha(r.spaces,n,"complete")})),resetForRuntimeSwitch:()=>{Gn.clear(),Os+=1,e({spaces:Ba,journey:null,progressRevision:0,creationAccess:new Map,accessDialog:null,actions:new Map,applyDialog:null,deleteDialog:null,deleteUnsaved:null,archivedNotice:null,setupOutputDialog:null,actionsSheet:null})},forgetForSwitchOff:()=>t().resetForRuntimeSwitch()}));let Os=0;const iE=()=>Os,Uh=async()=>{const e=Os,t=wr.getState().progressRevision,n=await Th();e===Os&&wr.getState().applyJourney(n,t)},Nh=(e,t)=>{const n=Array.from(e.values());for(const r of t?.values()??[])e.has(r.id)||r.projectDirectory===null||r.directory===null||n.push({id:r.id,name:r.name,state:"complete",projectDirectory:r.projectDirectory,directory:r.directory});return n},aE=()=>{const e=Hs.c(3),t=wr(Bh),n=wr(Hh);let r;return e[0]!==n||e[1]!==t?(r=Nh(t,n),e[0]=n,e[1]=t,e[2]=r):r=e[2],r},cE=(e,t)=>{const n=Ne(t);return Array.from(e.values()).filter(r=>n!==null&&Ne(r.projectDirectory)===n)},lE=()=>{const e=Hs.c(5),t=wr($h),[n,r]=An.useState(null);let s,o;e[0]===Symbol.for("react.memo_cache_sentinel")?(s=()=>{let a=!0;return Uh().then(()=>{a&&r(null)},c=>{a&&r(c)}),()=>{a=!1}},o=[],e[0]=s,e[1]=o):(s=e[0],o=e[1]),An.useEffect(s,o);let i;return e[2]!==n||e[3]!==t?(i={journey:t,error:n},e[2]=n,e[3]=t,e[4]=i):i=e[4],i};function Bh(e){return e.spaces}function Hh(e){return e.journey}function $h(e){return e.journey}const $a=500,fu=()=>{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}},uE=()=>fu(),Ve=(e,t)=>{if(!fu())return;const n=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=n,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>$a&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-$a)},zh=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("loadAgents")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory")||r.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=zh);const dE=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();Ve(`${e}:start`,n);try{const s=await t(),o=typeof performance<"u"?performance.now():Date.now();return Ve(`${e}:end`,{durationMs:Math.round(o-r)}),s}catch(s){const o=typeof performance<"u"?performance.now():Date.now();throw Ve(`${e}:error`,{durationMs:Math.round(o-r),error:s instanceof Error?s.message:String(s)}),s}},Wh=3,Gh=3e4,qh=32e3,Kh=3600*1e3,Vh=600*1e3,Jh=200,Yh=new Set([429,502,503,504]),gt=new Map,ji=e=>JSON.stringify([q(),e]);function Qh(){const e=Date.now();for(const[t,n]of gt){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>Kh&&gt.delete(t)}}typeof setInterval<"u"&&setInterval(Qh,Vh).unref?.();function Xh(e){const t=ji(e);let n=gt.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Gh},gt.set(t,n);gt.size>Jh;){const r=gt.keys().next().value;if(!r)break;gt.delete(r)}return n}function Zh(e){e&&gt.delete(ji(e))}function em(e,t){if(!e)return;const n=Xh(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),tm(t)&&n.consecutiveErrors>=Wh&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function tm(e){return e!==void 0&&Yh.has(e)}function nm(e){const t=gt.get(ji(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,qh*4),!1):!0:!1}function rm(e){if(!(!e||!nm(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const sm="openchamber",om="auto",im=(e,t)=>e===sm&&t===om,am=lt(f().min(1),w({type:O("running")})),cm=w({id:f().min(1),sessionID:f().min(1),action:f(),resources:M(f())}),lm=w({id:f().min(1),sessionID:f().min(1),title:f()}),um=w({sessions:lt(f().min(1),w({status:f(),lastUpdateAt:E()})),pending:lt(f().min(1),w({permissions:M(cm),forms:M(lm)})).optional(),serverTime:E()});function fE(e,t){if(!(!e||!t))return e.find(n=>n.id===t)??e.find(n=>n.modelID===t)}function V(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const Pn={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}`},pE=e=>e==="completed"||e==="error",pu=e=>e.role==="user"||e.role==="assistant",hE=e=>e==="user"||e==="assistant",mE=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&pu(n))return n}},gE=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.info&&pu(n.info))return n}},yE=e=>e?.role==="assistant"&&e.time.completed===void 0,za="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",dm=14;let Wa=0,ho=0;const fm=e=>{const t=new Uint8Array(e);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let r=0;r<e;r+=1)t[r]=Math.floor(Math.random()*256);let n="";for(let r=0;r<e;r+=1)n+=za[t[r]%za.length];return n},mo=e=>{const t=Date.now();t!==Wa&&(Wa=t,ho=0),ho+=1;const n=BigInt(t)*BigInt(4096)+BigInt(ho),r=new Uint8Array(6);for(let o=0;o<6;o+=1)r[o]=Number(n>>BigInt(40-8*o)&BigInt(255));const s=Array.from(r,o=>o.toString(16).padStart(2,"0")).join("");return`${e}_${s}${fm(dm)}`},pm=w({status:O("running"),shellID:f().min(1)});function wE(e){if(e.state.status!=="completed")return;const t=pm.safeParse(e.state.metadata??{});return t.success?t.data.shellID:void 0}const hm=w({source:O("shell"),shellID:f().min(1),state:H(["completed","cancelled","error"]),exit:E().optional(),signal:f().optional(),timeout:Y().optional()}),mm=/^\s*<shell\b[^>]*>\n?([\s\S]*?)\n?<\/shell>\s*$/;function gm(e){if(e.role!=="synthetic")return;const t=hm.safeParse(e.metadata??{});if(!t.success)return;const n=e.text.match(mm);return{shellID:t.data.shellID,state:t.data.state,exit:t.data.exit,signal:t.data.signal,timeout:t.data.timeout,output:n?n[1]:e.text,endedAt:e.time.created}}function SE(e,t){for(let n=e.length-1;n>=0;n-=1){const r=gm(e[n]);if(r?.shellID===t)return r}}const bE=e=>e.state!=="completed"||e.timeout===!0||e.signal!==void 0||e.exit!==void 0&&e.exit!==0,Ui="openchamberShellCancellation",ym=w({[Ui]:w({shellID:f().min(1)})});function wm(e){return{text:[`The user stopped the background command \`${e.command}\` (shell ID: ${e.shellID}).`,"The completion notice for it that follows reports an error such as Shell.NotFoundError or says that nothing ran.","That is how the stop shows up: the command did not fail on its own, the user cancelled it.","Do not start it again just because of that notice. The command itself is fine to run later when the task or the user needs it."].join(" "),description:"Background command stopped by the user",metadata:{[Ui]:{shellID:e.shellID}}}}function Sm(e){if(e.role!=="synthetic")return;const t=ym.safeParse(e.metadata??{});return t.success?{shellID:t.data[Ui].shellID,stoppedAt:e.time.created}:void 0}function vE(e,t){for(let n=e.length-1;n>=0;n-=1){const r=Sm(e[n]);if(r?.shellID===t)return{stoppedAt:r.stoppedAt}}}const bm=w({sessionID:f().min(1)});function vm(e){if(e.status!=="running")return;const t=bm.safeParse(e.metadata);if(t.success)return{id:e.id,sessionID:t.data.sessionID,command:e.command,file:e.file,startedAt:e.time.started}}const go=e=>JSON.parse(JSON.stringify(e));function Kr(e){return V({id:e.id,parentID:e.parentID,projectID:e.projectID,directory:e.location.directory,subpath:e.subpath,title:e.title??"",agent:e.agent,model:e.model,cost:e.cost,tokens:e.tokens,outcome:e.outcome,time:V({...e.time}),metadata:e.metadata,permissions:e.permissions,revert:e.revert,fork:e.fork})}function Tm(e){return V({id:e.id,worktree:e.canonical,vcs:e.vcs,name:e.name,icon:e.icon,commands:e.commands,time:e.time,sandboxes:[...e.sandboxes]})}function km(e){return V({branch:e.branch.current,defaultBranch:e.branch.default})}function Ga(e){return!e||e.length===0?"":e.filter(t=>t.type==="text").map(t=>t.text).join(`
3
+ `)}function Em(e,t){if(!e)return;const n=e.filter(r=>r.type==="file");if(n.length!==0)return n.map((r,s)=>V({id:`${t.callID}:file:${s}`,sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name??void 0,url:r.uri}))}function Pm(e){return e.message||e.type}function Am(e,t){const n=e.time.ran??e.time.created,r=e.time.completed??n,s={sessionID:t.sessionID,messageID:t.messageID,callID:e.id};let o;switch(e.state.status){case"streaming":o={status:"pending",input:{},raw:e.state.input};break;case"running":o=V({status:"running",input:e.state.input,metadata:e.state.metadata,time:{start:n}});break;case"completed":o=V({status:"completed",input:e.state.input,output:Ga(e.state.content),metadata:e.state.metadata,time:{start:n,end:r},attachments:Em(e.state.content,s)});break;case"error":o=V({status:"error",input:e.state.input,error:Pm(e.state.error),output:Ga(e.state.content)||void 0,metadata:e.state.metadata,time:{start:n,end:r}});break}return V({id:Pn.tool(e.id),sessionID:t.sessionID,messageID:t.messageID,type:"tool",callID:e.id,tool:e.name,state:o,executed:e.executed})}function Im(e,t){const n=[];let r=0,s=0;for(const o of e)switch(o.type){case"text":{const i=r;r+=1,n.push({id:Pn.text(t.messageID,i),sessionID:t.sessionID,messageID:t.messageID,type:"text",text:o.text,time:V({start:t.created,end:t.completed})});break}case"reasoning":{const i=s;s+=1,n.push({id:Pn.reasoning(t.messageID,i),sessionID:t.sessionID,messageID:t.messageID,type:"reasoning",text:o.text,time:V({start:o.time?.created??t.created,end:o.time?.completed})});break}case"tool":n.push(Am(o,t));break}return n}function xm(e,t){return V({id:e.id,sessionID:t,role:"assistant",time:V({...e.time}),agent:e.agent,providerID:e.model.providerID,modelID:e.model.id,variant:e.model.variant,finish:e.finish,error:e.error,cost:e.cost,tokens:e.tokens,snapshot:e.snapshot,retry:e.retry,metadata:e.metadata})}function Rm(e){return e.source.type==="uri"?e.source.uri:`data:${e.mime};base64,${e.data}`}function Cm(e,t){const n=[];return e.text.length>0&&n.push({id:Pn.userText(t.messageID),sessionID:t.sessionID,messageID:t.messageID,type:"text",text:e.text,time:{start:t.created,end:t.created}}),e.files?.forEach((r,s)=>{n.push(V({id:Pn.userFile(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name,url:Rm(r)}))}),e.agents?.forEach((r,s)=>{n.push({id:Pn.userAgent(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"agent",name:r.name})}),n}function Om(e,t){const n=e.metadata;switch(e.type){case"user":return{message:V({id:e.id,sessionID:t,role:"user",time:{...e.time},metadata:n}),parts:Cm(e,{sessionID:t,messageID:e.id,created:e.time.created})};case"assistant":return{message:xm(e,t),parts:Im(e.content,{sessionID:t,messageID:e.id,created:e.time.created,completed:e.time.completed})};case"synthetic":return{message:V({id:e.id,sessionID:t,role:"synthetic",time:{...e.time},text:e.text,description:e.description,metadata:n}),parts:[]};case"system":return{message:V({id:e.id,sessionID:t,role:"system",time:{...e.time},text:e.text,description:e.description,metadata:n}),parts:[]};case"skill":return{message:V({id:e.id,sessionID:t,role:"skill",time:{...e.time},skill:e.skill,name:e.name,text:e.text,metadata:n}),parts:[]};case"shell":return{message:V({id:e.id,sessionID:t,role:"shell",time:V({...e.time}),shellID:e.shellID,command:e.command,status:e.status,exit:Dm(e.exit),output:e.output,metadata:n}),parts:[]};case"compaction":return{message:V({id:e.id,sessionID:t,role:"compaction",time:{...e.time},status:e.status,reason:e.reason,summary:e.status==="failed"?"":e.summary,error:e.status==="failed"?e.error:void 0,cost:e.status==="running"?void 0:e.cost,tokens:e.status==="running"?void 0:e.tokens,metadata:n}),parts:[]};case"agent-switched":return{message:V({id:e.id,sessionID:t,role:"agent-switched",time:{...e.time},agent:e.agent,previous:e.previous,metadata:n}),parts:[]};case"model-switched":return{message:V({id:e.id,sessionID:t,role:"model-switched",time:{...e.time},model:e.model,previous:e.previous,metadata:n}),parts:[]};case"location-switched":return{message:V({id:e.id,sessionID:t,role:"location-switched",time:{...e.time},directory:e.location.directory,previous:e.previous?.location.directory,metadata:n}),parts:[]};case"idle":return{message:V({id:e.id,sessionID:t,role:"idle",time:{...e.time},outcome:e.outcome,metadata:n}),parts:[]}}}function Dm(e){return e==="Infinity"||e==="-Infinity"||e==="NaN"?void 0:e}function qa(e,t){return e.map(n=>Om(n,t))}const hu=e=>e.type==="document";function Mm(e){const t={};for(const n of e)if(hu(n))for(const[r,s]of Object.entries(n.info)){if(s===void 0)continue;const o=t[r];t[r]=Ka(o)&&Ka(s)?{...o,...s}:s}return t}function _m(e){return e.some(t=>hu(t)&&(t.info.experimental?.policies??[]).some(n=>n.action==="provider.use"&&n.effect==="deny"))}function Ka(e){return Object.prototype.toString.call(e)==="[object Object]"}const Lm=e=>({...e,name:e.id,displayName:e.name}),Va="/api",Fm=1e4,jm=4e3,Um=100,Nm=64*1024,Bm=new Map([["InvalidRequestError",400],["InvalidCursorError",400],["FormInvalidAnswerError",400],["UnauthorizedError",401],["ForbiddenError",403],["SessionNotFoundError",404],["MessageNotFoundError",404],["PermissionNotFoundError",404],["FormNotFoundError",404],["AgentNotFoundError",404],["CommandNotFoundError",404],["SkillNotFoundError",404],["ProviderNotFoundError",404],["McpServerNotFoundError",404],["ProjectNotFoundError",404],["FileNotFoundError",404],["PtyNotFoundError",404],["ShellNotFoundError",404],["ConflictError",409],["SessionBusyError",409],["FormAlreadySettledError",409],["ServiceUnavailableError",503],["UnknownError",500]]);class ht extends Error{operation;status;tag;detail;ref;constructor(t,n,r){super(`${t} failed${r.status?` (${r.status})`:""}: ${n}`,{cause:r.cause}),this.name="OpencodeApiError",this.operation=t,this.status=r.status,this.tag=r.tag,this.detail=n,this.ref=r.ref}}const Hm=w({_tag:f(),message:f().optional(),ref:f().optional()});function $m(e,t){if(t instanceof ht)return t;if(t instanceof Fd){if(t.reason==="UnexpectedStatus"){const s=t.cause?.status;return new ht(e,"unexpected status",{status:typeof s=="number"?s:void 0,cause:t})}const r=new ht(e,t.reason==="Transport"?"transport failure":t.reason,{cause:t.cause??t});return t.reason==="Transport"&&ya(t.cause)&&Ho(r),r}const n=Hm.safeParse(t);if(n.success)return new ht(e,n.data.message??n.data._tag,{status:Bm.get(n.data._tag),tag:n.data._tag,ref:n.data.ref,cause:t});if(t instanceof Error){const r=new ht(e,t.message,{cause:t});return ya(t)&&Ho(r),r}return new ht(e,String(t),{cause:t})}const zm=e=>e.tag==="InvalidRequestError"&&e.detail.startsWith("Skill not found"),Wm=e=>e instanceof ht&&e.status===404;async function C(e,t){try{return await t()}catch(n){throw $m(e,n)}}const Gm=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ja=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(Gm.test(t)||typeof window>"u")return t;const n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(r){return console.warn("Failed to normalize OpenCode base URL:",r),t}},Ya=()=>{try{return Re().api("/api")}catch{return null}},mu=e=>{const t=typeof AbortSignal<"u"?AbortSignal:void 0;if(typeof t?.timeout=="function")return{signal:t.timeout(e),cleanup:()=>{}};const n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},qm=3e4,Km=e=>e.pathname.endsWith("/event")||e.pathname.endsWith("/log"),Vm="x-opencode-directory",Jm=e=>e.replace(/\/api\/*$/,"")||"/",yo=e=>{const t=e.requestTimeoutMs??qm;return Ld.make({baseUrl:Jm(e.baseUrl),headers:e.directory?{[Vm]:encodeURIComponent(e.directory)}:void 0,fetch:async(n,r)=>{const s=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(Km(s)||o==="POST")return g(n,r);const i=mu(t),a=r?.signal!==void 0?r.signal:n instanceof Request?n.signal:void 0,c=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let l,u=null;if(a&&c)l=AbortSignal.any([a,i.signal]);else if(a){const m=new AbortController,y=()=>m.abort(a.reason),b=()=>m.abort(i.signal.reason);a.aborted?y():i.signal.aborted?b():(a.addEventListener("abort",y,{once:!0}),i.signal.addEventListener("abort",b,{once:!0}),u=()=>{a.removeEventListener("abort",y),i.signal.removeEventListener("abort",b)}),l=m.signal}else l=i.signal;const d=()=>{u?.(),i.cleanup()};let p=!1;try{const m=await g(n,{...r,signal:l});return p=m.body!==null,m}catch(m){throw i.signal.aborted&&!a?.aborted?new Error(`OpenCode request timed out after ${t}ms`):m}finally{!p||l.aborted?d():l.addEventListener("abort",d,{once:!0})}}})},Ym=w({spaces:M(Fh).optional()}),Qm=w({reason:f().optional(),isDirectory:Y().optional()}),fn=e=>e.replace(/\\/g,"/"),Qa=400,Xa=()=>{const e=Er();return e&&e.runtime?.isDesktop&&e.files?e.files:null},Vr=f().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),Xm=w({home:Vr,chatsRoot:Vr.optional(),canonicalChatsRoot:Vr.optional(),canonicalLegacyChatsRoot:Vr.optional()}),Za=e=>V({previous:e.previous??void 0,next:e.next??void 0}),ec=e=>{const t=[],n=new Set;for(const r of e)for(const s of r)!s?.id||n.has(s.id)||(n.add(s.id),t.push(s));return t};class Zm{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;providerCatalogInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;constructor(t=Va){const r=Ya()||t;this.baseUrl=Ja(r),this.client=yo({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==q())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=Ya(),n=Ja(t||Va);this.baseUrl=n,this.client=yo({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.providerCatalogInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear()}getSdkClient(){return this.client}getScopedSdkClient(t){const n=this.normalizeCandidatePath(t)??t,r=n||"",s=this.scopedClients.get(r);if(s)return s;const o=yo({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,o),o}clientFor(t){const n=this.resolveDirectory(t);return n?this.getScopedSdkClient(n):this.client}resolveDirectory(t){return this.normalizeCandidatePath(t)??this.currentDirectory}normalizeCandidatePath(t){return Ne(t)}deriveHomeDirectory(t){const n=t.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const o=n[1],a=t.slice(o.length+(t.charAt(o.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${o}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${o}/${a[0]}`,username:a[0]}:{homeDirectory:`${o}/`,username:void 0}}const r=t.startsWith("/"),s=t.split("/").filter(Boolean);return s.length>=2&&(s[0]==="Users"||s[0]==="home")?{homeDirectory:`${r?"/":""}${s[0]}/${s[1]}`,username:s[1]}:r?s.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${s.join("/")}`,username:s[s.length-1]}:s.length>0?{homeDirectory:`/${s.join("/")}`,username:s[s.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const n=this.normalizeCandidatePath(t)??t;this.currentDirectory!==n&&Ve("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:n??null}),this.currentDirectory=n}getDirectory(){return this.currentDirectory}async withDirectory(t,n){const r=async()=>{if(t==null)return n();const o=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await n()}finally{this.currentDirectory===i&&(this.currentDirectory=o)}},s=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=s.then(()=>{},()=>{}),s}async getLocation(t){return C("location.get",()=>this.clientFor(t).location.get())}async listProjects(){return(await C("project.list",()=>this.client.project.list())).map(Tm)}async getCurrentProject(t){return(await C("location.get",()=>this.clientFor(t).location.get())).project}async getVcs(t){return C("vcs.get",()=>this.clientFor(t).vcs.get().then(n=>km(n.data)))}async getSystemInfo(){const t=new Set,n=s=>{const o=this.normalizeCandidatePath(s);o&&t.add(o)};try{const s=await this.getLocation();n(s.directory),n(s.project.directory)}catch(s){console.debug("Failed to load location info:",s)}if(!t.size)try{(await this.listSessions()).forEach(o=>n(o.directory))}catch(s){console.debug("Failed to inspect sessions for system info:",s)}if(n(this.currentDirectory),typeof window<"u")try{n(window.localStorage.getItem("lastDirectory")),n(window.localStorage.getItem("homeDirectory"))}catch{}if(!t.size&&typeof process<"u"&&typeof process.cwd=="function"&&n(process.cwd()),!t.size)return{homeDirectory:"/",username:void 0};const[r]=Array.from(t);return this.deriveHomeDirectory(r)}async probeDirectory(t){return await this.getDirectoryAvailability(t)==="available"}async getDirectoryAvailability(t){const n=this.normalizeCandidatePath(t);if(!n)return"unknown";try{const r=await g("/api/fs/directory-stat",{query:{path:n}}),s=Qm.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&s?.isDirectory===!0)return"available";const o=Cs(s?.reason);return o==="not-found"||o==="not-directory"?"missing":"unknown"}catch{return"unknown"}}async listSessionsPage(t={}){const n=t.global?void 0:this.resolveDirectory(t.directory),r=n?this.getScopedSdkClient(n):this.client,s=await C("session.list",()=>r.session.list({directory:n,limit:t.limit??Um,order:t.order,search:t.search,cursor:t.cursor,parentID:t.parentID})),o=t.global?Ym.safeParse(s).data?.spaces:void 0;return{sessions:s.data.map(Kr),cursor:Za(s.cursor),...o?{spaces:o}:{}}}async listSessions(t){return(await this.listSessionsPage({directory:t})).sessions}async createSession(t,n){const r=this.resolveDirectory(n),s=await C("session.create",()=>this.clientFor(n).session.create({id:t?.id,title:t?.title,agent:t?.agent,model:t?.model&&im(t.model.providerID,t.model.id)?void 0:t?.model,location:r?{directory:r}:void 0,metadata:t?.metadata}));return Kr(s)}async getSession(t,n){const r=await C("session.get",()=>this.clientFor(n).session.get({sessionID:t}));return Kr(r)}async deleteSession(t,n){return await C("session.remove",()=>this.clientFor(n).session.remove({sessionID:t})),!0}async renameSession(t,n,r){await C("session.update",()=>this.clientFor(r).session.update({sessionID:t,title:n}))}async moveSession(t,n,r){const s=this.normalizeCandidatePath(n)??n;await C("session.move",()=>this.client.session.move({sessionID:t,directory:s,delivery:r?.delivery}))}async switchSessionModel(t,n,r){await C("session.switchModel",()=>this.clientFor(r).session.switchModel({sessionID:t,model:n}))}async switchSessionAgent(t,n,r){await C("session.switchAgent",()=>this.clientFor(r).session.switchAgent({sessionID:t,agent:n}))}async getSessionMessages(t,n,r){const s=await C("message.list",()=>this.clientFor(r).message.list({sessionID:t,limit:n?.limit,cursor:n?.cursor,order:n?.cursor?void 0:n?.order})),o=qa(s.data,t).map(({message:a,parts:c})=>({info:a,parts:c})),i=n?.limit!==void 0&&o.length<n.limit;return{items:o,cursor:Za({...s.cursor,next:i?void 0:s.cursor.next})}}async getSessionMessage(t,n,r){const s=await C("session.message.get",()=>this.clientFor(r).session.message.get({sessionID:t,messageID:n})),[o]=qa([s],t);return{info:o.message,parts:o.parts}}shouldNormalizeToTextPlain(t){if(!t)return!1;const n=t.toLowerCase();return n.startsWith("text/")&&n!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(n)}isHeicMime(t){if(!t)return!1;const n=t.toLowerCase();return n==="image/heic"||n==="image/heif"}async convertHeicToJpeg(t){try{const n=(await ki(async()=>{const{default:d}=await import("./vendor-heic2any-CEam9pDc.js").then(p=>p.h);return{default:d}},__vite__mapDeps([0,1,2]))).default,r=t.url.indexOf(",");if(r===-1)return t;const s=t.url.substring(r+1),o=atob(s),i=new Uint8Array(o.length);for(let d=0;d<o.length;d++)i[d]=o.charCodeAt(d);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((d,p)=>{const m=new FileReader;m.onload=()=>d(m.result),m.onerror=p,m.readAsDataURL(c)});let u=t.filename;return u&&(u=u.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:u,url:l}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let n=t.url;if(t.url.startsWith("data:")){const r=t.url.indexOf(",");if(r!==-1){const s=t.url.substring(5,r),o=t.url.substring(r);n=`data:${s.replace(/^[^;,]+/,"text/plain")}${o}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toPromptFile(t){const n=await this.normalizeFilePart(t);return{uri:n.url,name:n.filename}}async applySendSelection(t,n,r,s){n.model&&(this.assertRuntimeUnchanged(s),await this.switchSessionModel(t,n.model,r)),n.agent&&(this.assertRuntimeUnchanged(s),await this.switchSessionAgent(t,n.agent,r))}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=(t.context??[]).filter(c=>c.text.trim()).map(c=>({...c,id:c.id??mo("msg")})),r=t.messageId??mo("msg"),s=await Promise.all((t.files??[]).map(c=>this.toPromptFile(c))),o=(t.agentMentions??[]).filter(c=>!!c?.name).map(c=>({name:c.name,mention:c.source?{start:c.source.start,end:c.source.end,text:c.source.value}:void 0}));if(!t.text.trim()&&s.length===0&&(t.context?.length??0)===0)throw new Error("Message must have at least one part (text or file)");rm(t.providerID);const i=async c=>{this.assertRuntimeUnchanged(t.runtimeKey),await C("session.synthetic",()=>this.clientFor(t.directory).session.synthetic({sessionID:t.id,id:c.id,text:c.text,description:c.description,metadata:c.metadata?go(c.metadata):void 0,delivery:t.delivery,resume:!1}))},a=c=>(this.assertRuntimeUnchanged(t.runtimeKey),C("session.prompt",()=>this.clientFor(t.directory).session.prompt({sessionID:t.id,id:r,text:t.text,files:s.length>0?s:void 0,agents:o.length>0?o:void 0,skills:c.length>0?c.map(l=>({id:l.id})):void 0,metadata:t.metadata,delivery:t.delivery})));try{await this.applySendSelection(t.id,{model:t.model,agent:t.agent},t.directory,t.runtimeKey);const c=await this.resolveSkillMentions(t.skills?.names??[],t.directory),l=t.skills?.instructionFor(c.unresolved)??null;for(const u of n)await i(u);l&&await i({text:l});try{await a(c.attached)}catch(u){if(c.attached.length===0||!(u instanceof ht)||!zm(u))throw u;const d=t.skills?.instructionFor(c.attached.map(p=>p.name))??null;d&&await i({text:d}),await a([])}}catch(c){throw em(t.providerID,c instanceof ht?c.status:void 0),c}return Zh(t.providerID),r}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=await Promise.all((t.files??[]).map(r=>this.toPromptFile(r)));await this.applySendSelection(t.id,{model:t.model,agent:t.agent},t.directory,t.runtimeKey);for(const r of t.context??[])r.text.trim()&&(this.assertRuntimeUnchanged(t.runtimeKey),await C("session.synthetic",()=>this.clientFor(t.directory).session.synthetic({sessionID:t.id,id:r.id,text:r.text,description:r.description,metadata:r.metadata?go(r.metadata):void 0,delivery:t.delivery,resume:!1})));this.assertRuntimeUnchanged(t.runtimeKey),await C("session.command",()=>this.clientFor(t.directory).session.command({sessionID:t.id,name:t.command,text:t.arguments??"",files:n.length>0?n:void 0,delivery:t.delivery}))}async abortSession(t,n){return(await C("session.interrupt",()=>this.clientFor(n).session.interrupt({sessionID:t}))).interrupted}async backgroundSessionWork(t,n){await C("session.background",()=>this.clientFor(n).session.background({sessionID:t}))}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??mo("msg");return await C("session.shell",()=>this.clientFor(t.directory).session.shell({sessionID:t.sessionId,id:n,command:t.command})),n}async stageRevert(t,n,r){return C("session.revert.stage",()=>this.clientFor(r?.directory).session.revert.stage({sessionID:t,messageID:n,files:r?.files}))}async commitRevert(t,n){await C("session.revert.commit",()=>this.clientFor(n).session.revert.commit({sessionID:t}))}async clearRevert(t,n){await C("session.revert.clear",()=>this.clientFor(n).session.revert.clear({sessionID:t}))}async compactSession(t,n){await C("session.compact",()=>this.clientFor(n).session.compact({sessionID:t}))}async forkSession(t,n){const r=await C("session.fork",()=>this.clientFor(n?.directory).session.fork({sessionID:t,before:n?.before}));return Kr(r)}async getActiveSessionStatuses(t){try{const n=Oa(t)&&t?this.getScopedSdkClient(t):this.client,r=am.parse(await C("session.active",()=>n.session.active())),s={};for(const o of Object.keys(r))s[o]={type:"busy"};return s}catch{return null}}async getHostSessionStatusSnapshot(){try{const t=await g("/api/sessions/status",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=um.safeParse(await t.json().catch(()=>null));return n.success?n.data:null}catch{return null}}async getWebServerSessionActivity(){try{const t=await g("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json().catch(()=>null);return!n||typeof n!="object"?null:n}catch{return null}}async generateSessionText(t,n,r){return(await C("session.generate",()=>this.clientFor(r).session.generate({sessionID:t,prompt:n}))).text}async getSessionTurnDiff(t,n){const{from:r,to:s,context:o}=n??{},i={sessionID:t,from:r,to:s,context:o};return[...await C("session.diff",()=>this.clientFor(n?.directory).session.diff(i))]}async generateText(t,n){return(await C("generate.text",()=>this.clientFor(n?.directory).generate.text({prompt:t,model:n?.model}))).text}async replyToPermission(t,n,r,s){return await C("permission.reply",()=>this.clientFor(s?.directory).permission.reply({sessionID:t,requestID:n,decision:r,message:s?.message})),!0}async createPermission(t,n,r,s){try{const o=await C("permission.create",()=>this.clientFor(s?.directory).permission.create({sessionID:t,action:n,resources:r,id:s?.id,save:s?.save,metadata:s?.metadata?go(s.metadata):void 0,source:s?.source,agent:s?.agent}));return{id:o.id,effect:o.effect}}catch{return null}}async fetchPermission(t,n,r){try{return{state:"ok",permission:await C("permission.get",()=>this.clientFor(r).permission.get({sessionID:t,requestID:n}))}}catch(s){return Wm(s)?{state:"resolved"}:{state:"unknown"}}}async listPendingPermissions(t){const n=this.uniqueDirectories(t?.directories,t?.includeGlobal),r=await Promise.all(n.map(s=>C("permission.request.list",()=>(s?this.getScopedSdkClient(s):this.client).permission.request.list().then(o=>o.data))));return ec(r)}async replyToForm(t,n,r,s){return await C("session.form.reply",()=>this.clientFor(s).session.form.reply({sessionID:t,formID:n,answer:r})),!0}async cancelForm(t,n,r){return await C("session.form.cancel",()=>this.clientFor(r).session.form.cancel({sessionID:t,formID:n})),!0}async listPendingForms(t){const n=this.uniqueDirectories(t?.directories,t?.includeGlobal),r=await Promise.all(n.map(s=>C("form.list",()=>(s?this.getScopedSdkClient(s):this.client).form.list().then(o=>o.data))));return ec(r)}async listRunningShells(t){const n=await C("shell.list",()=>this.clientFor(t).shell.list());return{directory:n.location.directory??t,shells:n.data.flatMap(r=>vm(r)??[])}}async readShellOutput(t,n,r,s=Nm){const o=this.clientFor(n);let i=r;if(i===void 0){const c=await C("shell.output",()=>o.shell.output({id:t,cursor:Number.MAX_SAFE_INTEGER}).then(l=>l.data));i=Math.max(0,c.size-s)}const a=await C("shell.output",()=>o.shell.output({id:t,cursor:i,limit:s}).then(c=>c.data));return{output:a.output,cursor:a.cursor,skipped:r===void 0&&i>0}}async stopBackgroundShell(t){const n=wm({shellID:t.shellID,command:t.command});await C("session.synthetic",()=>this.clientFor(t.sessionDirectory).session.synthetic({sessionID:t.sessionID,text:n.text,description:n.description,metadata:n.metadata,resume:!1})),await C("shell.remove",()=>this.clientFor(t.shellDirectory).shell.remove({id:t.shellID}))}uniqueDirectories(t,n=!0){const r=new Set;for(const s of t??[]){const o=this.normalizeCandidatePath(s);o&&r.add(o)}return n?[null,...r]:[...r]}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async configDeniesAnyProvider(t){const n=await C("config.get",()=>this.clientFor(this.resolveDirectory(t)).config.get());return _m(n)}async getConfig(t){const n=this.resolveDirectory(t),r=n??"",s=this.configCache.get(r);if(s&&s.expiresAt>Date.now())return Ve("opencodeClient.getConfig:cacheHit",{directory:n??null}),s.config;const o=this.configInFlight.get(r);if(o)return Ve("opencodeClient.getConfig:deduped",{directory:n??null}),o;const i=this.configCacheGeneration,a=(async()=>{Ve("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),l=await C("config.get",()=>this.clientFor(n).config.get()),u=Mm(l),d=typeof performance<"u"?performance.now():Date.now();return Ve("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(d-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:u,expiresAt:Date.now()+Fm}),u})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t,n){const r=this.resolveDirectory(t),s=r??"";let o=this.providerCatalogInFlight.get(s);if(o&&n?.fresh&&(await o.catch(()=>{}),o=this.providerCatalogInFlight.get(s)),o)return o;const i=(async()=>{const a=this.clientFor(r),c=Oa(r)?this.client:a,[l,u,d]=await Promise.all([C("provider.list",()=>c.provider.list().then(p=>p.data)),C("model.list",()=>a.model.list().then(p=>p.data)),C("model.default",()=>a.model.default().then(p=>p.data)).catch(()=>{})]);return V({providers:l,models:u,default:d?{id:d.modelID,providerID:d.providerID}:void 0})})();this.providerCatalogInFlight.set(s,i);try{return await i}finally{this.providerCatalogInFlight.get(s)===i&&this.providerCatalogInFlight.delete(s)}}async listAgents(t){const n=this.resolveDirectory(t),r=n??"",s=this.listAgentsInFlight.get(r);if(s)return s;const o=C("agent.list",()=>this.clientFor(n).agent.list().then(i=>i.data.map(Lm)));this.listAgentsInFlight.set(r,o);try{return await o}finally{this.listAgentsInFlight.get(r)===o&&this.listAgentsInFlight.delete(r)}}async listCommands(t,n){return C("command.list",()=>this.clientFor(t).command.list(void 0,{signal:n}).then(r=>r.data))}async listSkills(t){return C("skill.list",()=>this.clientFor(t).skill.list().then(n=>n.data))}async resolveSkillMentions(t,n){if(t.length===0)return{attached:[],unresolved:[]};let r;try{r=await this.listSkills(n)}catch(i){return console.warn("[opencode] Could not list skills; naming them in an instruction instead:",i),{attached:[],unresolved:[...t]}}const s=[],o=[];for(const i of t){const a=r.find(c=>c.name===i)??r.find(c=>c.id===i);a?s.some(c=>c.id===a.id)||s.push({id:a.id,name:i}):o.push(i)}return{attached:s,unresolved:o}}async listMcpServers(t){return C("mcp.list",()=>this.clientFor(t).mcp.list().then(n=>n.data))}async connectMcpServer(t,n){await C("mcp.connect",()=>this.clientFor(n).mcp.connect({server:t}))}async disconnectMcpServer(t,n){await C("mcp.disconnect",()=>this.clientFor(n).mcp.disconnect({server:t}))}async checkHealth(){return await this.probeHealth()==="healthy"}async probeHealth(){const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,n=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;Ve("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});let r;try{const s=mu(jm);r=await g(n,{signal:s.signal}).finally(s.cleanup)}catch{return"unreachable"}if(Ve("opencodeClient.checkHealth:response",{status:r.status}),r.status===502||r.status===504)return"unreachable";if(!r.ok)return"unhealthy";try{const s=await r.json();return Ve("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0?"healthy":"unhealthy"}catch{return"unhealthy"}}async createDirectory(t,n){const r=Xa();if(r?.createDirectory)try{return await r.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}if(n?.asProject){const a=await g(`${this.baseUrl}/opencode/directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,create:!0})});if(!a.ok){const l=await a.json().catch(()=>({error:"Failed to create project directory"}));throw new Error(l.error||"Failed to create project directory")}return{success:!0,path:(await a.json()).path}}const s={path:t,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},o=await g(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok){const a=await o.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await o.json()}async cloneRepository(t){const n=await g(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(r.error||"Failed to clone repository")}return await n.json()}async listLocalDirectory(t,n){const s=`${typeof t=="string"?fn(t.trim()):""}|${n?.respectGitignore?"1":"0"}`,o=Date.now(),i=this.listDirectoryCache.get(s);if(i&&i.expiresAt>o)return i.entries;const a=this.listDirectoryInFlight.get(s);if(a)return a;const l=(async()=>{const u=Xa();try{if(u){const S=await u.listDirectory(t||"",n);if(!S||!Array.isArray(S.entries))throw new tn("Directory listing returned an invalid response",{reason:"invalid-response"});const k=S.entries.map(P=>({name:P.name,path:fn(P.path),isDirectory:!!P.isDirectory,isFile:!P.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(s,{entries:k,expiresAt:Date.now()+Qa}),k}const d=new URLSearchParams;t&&t.trim().length>0&&d.set("path",t),n?.respectGitignore&&d.set("respectGitignore","true");const p=d.toString(),m=await g(`${this.baseUrl}/fs/list${p?`?${p}`:""}`);if(!m.ok){const S=await m.json().catch(()=>({})),k=typeof S.error=="string"?S.error:"Failed to list directory";throw new tn(k,{reason:Cs(S.reason),status:m.status})}const y=await m.json();if(!y||!Array.isArray(y.entries))throw new tn("Directory listing returned an invalid response",{reason:"invalid-response"});const b=y.entries;return this.listDirectoryCache.set(s,{entries:b,expiresAt:Date.now()+Qa}),b}catch(d){throw console.error("Failed to list directory contents:",d),d}})().finally(()=>{this.listDirectoryInFlight.get(s)===l&&this.listDirectoryInFlight.delete(s)});return this.listDirectoryInFlight.set(s,l),l}async searchFiles(t,n){const r=this.resolveDirectory(n?.directory),s=r?fn(r):null;try{return(await C("file.find",()=>this.clientFor(r).file.find({query:t,limit:n?.limit!==void 0&&Number.isFinite(n.limit)?n.limit:void 0,type:n?.type}))).data.map(i=>{const a=fn(i.path),c=a.split("/").filter(Boolean).pop()||a,l=fn(s?`${s}/${a}`:a);return{name:c,path:l,relativePath:a,extension:c.includes(".")?c.split(".").pop()?.toLowerCase():void 0}})}catch(o){throw console.error("Failed to search files:",o),o}}async getFilesystemHome(){const t=q();if(!t||t==="local"){const n=await Cl();if(n)return n}try{const n=await g(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const s=await n.json().catch(()=>({})),o=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to resolve home directory";throw new Error(o)}const r=await n.json();return r&&typeof r.home=="string"&&r.home.length>0?r.home:null}catch(n){return console.warn("Failed to resolve filesystem home directory:",n),null}}async getFilesystemHomeInfo(){const t=await g(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to resolve the chats root (${t.status})`);return Xm.parse(await t.json())}async setOpenCodeWorkingDirectory(t){if(!t||typeof t!="string"||!t.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",t),null;const n=`${this.baseUrl}/opencode/directory`;try{const r=await g(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),s=await r.json().catch(()=>null);if(!r.ok){const o=s??{},i=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to update OpenCode working directory";throw new Error(i)}return s&&typeof s=="object"?s:{success:!0,restarted:!1,path:t}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const it=new Zm;let wo=null,So=null,bo=null;const tc=new Set;let nc=!1;const gu=e=>{if(tc.add(e),nc||typeof window>"u")return;nc=!0;const t=()=>{for(const n of tc)n()};try{window.addEventListener("pagehide",t,{capture:!0}),window.addEventListener("beforeunload",t,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t()}),document.addEventListener("freeze",t))}catch{}},eg=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,s=new Set;let o;const i=()=>{if(o=void 0,r.size===0&&s.size===0)return;const c=Array.from(r.entries()),l=Array.from(s);r.clear(),s.clear();for(const[u,d]of c)try{n.setItem(u,JSON.stringify(d,t?.replacer))}catch(p){console.error("Failed to persist deferred storage value",p),!r.has(u)&&!s.has(u)&&r.set(u,d)}for(const u of l)try{n.removeItem(u)}catch(d){console.error("Failed to remove deferred storage value",d),r.has(u)||s.add(u)}},a=()=>{o===void 0&&(o=setTimeout(i,0))};return gu(i),{getItem:c=>{if(r.has(c))return r.get(c)??null;if(s.has(c))return null;const l=d=>{if(d===null)return null;try{return JSON.parse(d,t?.reviver)}catch{try{n.removeItem(c)}catch{}return null}},u=n.getItem(c);return u instanceof Promise?u.then(l):l(u)},setItem:(c,l)=>{r.set(c,l),s.delete(c),a()},removeItem:c=>{r.delete(c),s.add(c),a()}}},Ni=e=>eg(()=>Su(),e),tg=e=>{const t=new Map,n=new Set;let r;const s=()=>{if(r=void 0,t.size===0&&n.size===0)return;const i=Array.from(t.entries()),a=Array.from(n);t.clear(),n.clear();for(const[c,l]of i)try{e.setItem(c,l)}catch(u){console.error("Failed to persist deferred storage value",u),!t.has(c)&&!n.has(c)&&t.set(c,l)}for(const c of a)try{e.removeItem(c)}catch(l){console.error("Failed to remove deferred storage value",l),t.has(c)||n.add(c)}},o=()=>{r===void 0&&(r=setTimeout(s,0))};return gu(s),{getItem:i=>t.has(i)?t.get(i)??null:n.has(i)?null:e.getItem(i),setItem:(i,a)=>{t.set(i,a),n.delete(i),o()},removeItem:i=>{t.delete(i),n.add(i),o()},clear:()=>{t.clear(),n.clear(),r!==void 0&&(clearTimeout(r),r=void 0),e.clear()},key:i=>e.key(i),get length(){return e.length}}},yu=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},Bi=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},wu=e=>{const t=Bi(),n=new Set,r=new Set,s=l=>{if(r.has(l))return null;if(n.has(l))return t.getItem(l);try{return e.getItem(l)}catch{return null}},o=(l,u)=>{try{e.setItem(l,u),t.removeItem(l),n.delete(l),r.delete(l);return}catch{try{e.removeItem(l)}catch{}}t.setItem(l,u),n.add(l),r.delete(l)},i=l=>{try{e.removeItem(l),r.delete(l)}catch{r.add(l)}t.removeItem(l),n.delete(l)},a=()=>{const l=[];try{for(let u=0;u<e.length;u+=1){const d=e.key(u);d&&l.push(d)}}catch{}try{e.clear(),r.clear()}catch{for(const u of l)r.add(u)}t.clear(),n.clear()},c=()=>{const l=new Set;try{for(let u=0;u<e.length;u+=1){const d=e.key(u);d&&!r.has(d)&&!n.has(d)&&l.add(d)}}catch{}for(const u of n)l.add(u);return[...l]};return{getItem:s,setItem:o,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},ng=()=>{const e=yu("localStorage");return e?wu(e):Bi()},Su=()=>(wo||(wo=ng()),wo),xr=()=>(bo||(bo=tg(Su())),bo),rg=()=>{const e=yu("sessionStorage");return e?wu(e):Bi()},sg=()=>(So||(So=rg()),So),og={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.84375rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},TE={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function rc(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Jr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},vo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Jr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:vo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Jr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:vo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Jr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:vo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Jr.tool.inline})},ig=[{id:"inter",label:"Inter",description:"Modern UI sans with excellent readability at small sizes.",stack:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Inter",packageName:"@fontsource/inter",filePrefix:"inter",weights:[400,500,600]}},{id:"fixel",label:"Fixel Text",description:"Humanist geometric sans-serif with full Ukrainian support.",stack:'"Fixel Text", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Fixel Text",weights:[400,500,600],urls:{400:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Regular.woff2",500:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Medium.woff2",600:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-SemiBold.woff2"}}},{id:"geist-sans",label:"Geist Sans",description:"Crisp sans-serif with a technical interface feel.",stack:'"Geist Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Geist Sans",packageName:"@fontsource/geist-sans",filePrefix:"geist-sans",weights:[400,500,600]}},{id:"atkinson-hyperlegible",label:"Atkinson Hyperlegible",description:"Accessibility-focused sans-serif optimized for character distinction.",stack:'"Atkinson Hyperlegible", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Atkinson Hyperlegible",packageName:"@fontsource/atkinson-hyperlegible",filePrefix:"atkinson-hyperlegible",weights:[400,700]}},{id:"source-sans-3",label:"Source Sans 3",description:"Adobe sans-serif tuned for clean, readable interfaces.",stack:'"Source Sans 3", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Source Sans 3",packageName:"@fontsource/source-sans-3",filePrefix:"source-sans-3",weights:[400,500,600]}},{id:"roboto",label:"Roboto",description:"Familiar Material-style sans-serif with broad UI usage.",stack:'"Roboto", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Roboto",packageName:"@fontsource/roboto",filePrefix:"roboto",weights:[400,500,600]}},{id:"noto-sans",label:"Noto Sans",description:"Readable sans-serif with strong international coverage.",stack:'"Noto Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Noto Sans",packageName:"@fontsource/noto-sans",filePrefix:"noto-sans",weights:[400,500,600]}},{id:"dm-sans",label:"DM Sans",description:"Modern product UI sans-serif with friendly proportions.",stack:'"DM Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"DM Sans",packageName:"@fontsource/dm-sans",filePrefix:"dm-sans",weights:[400,500,600]}},{id:"manrope",label:"Manrope",description:"Polished geometric sans-serif for modern app interfaces.",stack:'"Manrope", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Manrope",packageName:"@fontsource/manrope",filePrefix:"manrope",weights:[400,500,600]}},{id:"system",label:"System",description:"Native operating system interface font.",stack:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'}],ag=[{id:"jetbrains-mono",label:"JetBrains Mono",description:"Developer-focused monospace with strong punctuation clarity.",stack:'"JetBrains Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"JetBrains Mono",packageName:"@fontsource/jetbrains-mono",filePrefix:"jetbrains-mono",weights:[400,500,600]}},{id:"fira-code",label:"Fira Code",description:"Readable coding font with ligature support.",stack:'"Fira Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Fira Code",packageName:"@fontsource/fira-code",filePrefix:"fira-code",weights:[400,500,600]}},{id:"geist-mono",label:"Geist Mono",description:"Sharp monospace pair for Geist Sans.",stack:'"Geist Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Geist Mono",packageName:"@fontsource/geist-mono",filePrefix:"geist-mono",weights:[400,500,600]}},{id:"commit-mono",label:"Commit Mono",description:"Code-oriented monospace with polished editor ergonomics.",stack:'"Commit Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Commit Mono",packageName:"@fontsource/commit-mono",filePrefix:"commit-mono",weights:[400,500,600]}},{id:"source-code-pro",label:"Source Code Pro",description:"Adobe monospace designed for source code readability.",stack:'"Source Code Pro", "SFMono-Regular", "Menlo", monospace',source:{family:"Source Code Pro",packageName:"@fontsource/source-code-pro",filePrefix:"source-code-pro",weights:[400,500,600]}},{id:"cascadia-code",label:"Cascadia Code",description:"Microsoft coding font popular in terminals and editors.",stack:'"Cascadia Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Cascadia Code",packageName:"@fontsource/cascadia-code",filePrefix:"cascadia-code",weights:[400,500,600]}},{id:"roboto-mono",label:"Roboto Mono",description:"Neutral monospace companion to Roboto.",stack:'"Roboto Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Roboto Mono",packageName:"@fontsource/roboto-mono",filePrefix:"roboto-mono",weights:[400,500,600]}},{id:"iosevka",label:"Iosevka",description:"Compact monospace for dense code and terminal layouts.",stack:'"Iosevka", "SFMono-Regular", "Menlo", monospace',source:{family:"Iosevka",packageName:"@fontsource/iosevka",filePrefix:"iosevka",weights:[400,500,600]}},{id:"system-mono",label:"System Mono",description:"Native operating system monospace font.",stack:'ui-monospace, "SFMono-Regular", "Menlo", "Cascadia Mono", "Segoe UI Mono", monospace'}],bu=e=>Object.fromEntries(e.map(t=>[t.id,t])),cg=bu(ig),lg=bu(ag),ug="system",dg="system-mono",fg=e=>typeof e=="string"&&e in cg,pg=e=>typeof e=="string"&&e in lg,Qo="openchamber.mobileKeyboardMode",hg='meta[name="viewport"]',sc="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",kE=()=>!0;function Js(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const mg=e=>Js(e)==="resize-content"?`${sc}, interactive-widget=resizes-content`:sc,gg=()=>{if(typeof window>"u")return"resize-content";try{return Js(localStorage.getItem(Qo))}catch{return"resize-content"}},vu=e=>{const t=Js(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Qo):localStorage.setItem(Qo,t)}catch{}return t},EE=e=>{const t=vu(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(hg);if(n instanceof HTMLMetaElement){const r=mg(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},To=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),yg=new Set(["starting","running","stopping"]),wg=e=>!!e?.tabs.some(t=>vn(t.purpose)&&t.lifecycle!=="exited"),Xo=512*1024,Sg=new TextEncoder,bg=new TextDecoder,ko=e=>{const t=Sg.encode(e);if(t.byteLength<=Xo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Xo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:bg.decode(r),byteLength:r.byteLength}},tt=(e,t)=>`${e}\0${t}`,pn=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},vg="terminal-store";let oc=!1,ic=0;const Tg=w({type:O("project-action"),actionId:f()}),Qn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(ic+=1,`tab-${Date.now().toString(36)}-${ic.toString(36)}`),Eo=e=>typeof e=="object"&&e!==null,vn=e=>e.type==="project-action",Yr=(e,t)=>vn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,kg=()=>Qn().replace(/^tab-/,"exec-"),ac=e=>e==="running"?"running":"exited",Eg=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),Pg=e=>{const t=new Map,n=[];for(const r of e){if(r.purpose?.type!=="project-action"){n.push(r);continue}const s=t.get(r.purpose.actionId);(!s||r.status==="running"&&s.status!=="running"||r.status===s.status&&((r.createdAt??0)>(s.createdAt??0)||r.createdAt===s.createdAt&&r.sessionId>s.sessionId))&&t.set(r.purpose.actionId,r)}return[...n,...t.values()]},Po={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},Ag=e=>e.trim()||"Action",Ig=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},ne=Lh,Ds=(e,t)=>`${e}\0${t}`,qn=(e,t,n,r)=>{e.set(Ds(t,n),r)},cc=(e,t,n,r)=>{if(!r)return!1;const s=Ds(t,n),o=e.actionMutationRevisions.get(s)??0,i=r.get(s)??0;return o>i},xg=/^Terminal(?: (\d+))?$/,lc=e=>{let t=0;for(const n of e){const r=xg.exec(n.label);if(!r)continue;const s=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(s)&&(t=Math.max(t,s))}return t===0?"Terminal":`Terminal ${t+1}`},PE=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&yg.has(e.lifecycle),Rg=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),Qr=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",purpose:{type:"terminal"},label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Ao=e=>({tabs:[e],activeTabId:e.id}),Ee=(e,t)=>e.tabs.findIndex(n=>n.id===t);let Io=null,xo=null;const Cg=e=>{if(xo&&Io?.sessions===e.sessions&&Io.nextTabId===e.nextTabId)return xo;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(s=>({id:s.id,label:s.label,iconKey:s.iconKey,createdAt:s.createdAt,purpose:s.purpose.type==="project-action"?{type:"project-action",actionId:s.purpose.actionId}:{type:"terminal"}}))}]),nextTabId:e.nextTabId};return Io={sessions:e.sessions,nextTabId:e.nextTabId},xo=t,t},Og=()=>{const e=_d(()=>sg());if(!e)return;let t=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==t)return t=r.state,e.setItem(n,r)},removeItem:n=>(t=null,e.removeItem(n))}},ds=ut()(_n(kr((e,t)=>({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=ne(n);r&&e(s=>{if(s.sessions.has(r))return s;const o=new Map(s.sessions),i=Qn(),a=Qr(i,"Terminal");return o.set(r,Ao(a)),{sessions:o,nextTabId:s.nextTabId+1}})},getDirectoryState:n=>{const r=ne(n);return t().sessions.get(r)},getActiveTab:n=>{const r=ne(n),s=t().sessions.get(r);if(!s)return;const o=s.activeTabId;return o?s.tabs.find(i=>i.id===o)??s.tabs[0]:s.tabs[0]},getBuffer:(n,r)=>t().buffers.get(tt(ne(n),r))??To,matchesActionExecution:(n,r,s)=>{const o=t().sessions.get(ne(n))?.tabs.find(i=>i.id===r);return!!(o&&vn(o.purpose)&&o.purpose.executionId===s)},captureStartedActionMutationRevisions:n=>{const r=ne(n),s=Ds(r,""),o=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(s)&&o.set(i,a);return o},createTab:n=>{const r=ne(n);if(!r)return"tab-invalid";const s=Qn();return e(o=>{const i=new Map(o.sessions),a=i.get(r),c=o.nextTabId+1,l=lc(a?.tabs??[]),u=Qr(s,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,Ao(u)),{sessions:i,nextTabId:c}}),s},reconcileServerSessions:(n,r,s)=>{const o=ne(n);o&&e(i=>{const a=i.sessions.get(o);if(!a&&r.length===0)return i;const c=[...a?.tabs??[]];let l=i.buffers,u=!1,d=null;const p=new Set,m=new Set,y=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(tt(o,c[0].id))?c[0]:null;y&&r.length>0&&(c.length=0);for(const D of Pg(r)){let ke=c.findIndex(N=>N.terminalSessionId===D.sessionId||N.id===D.sessionId);const ue=D.purpose,to=ue?.type==="project-action"&&cc(i,o,ue.actionId,s?.startedActionMutationRevisions);if(ue?.type==="project-action"){p.add(ue.actionId);const N=c.findIndex(et=>vn(et.purpose)&&et.purpose.actionId===ue.actionId);if(to){N>=0&&m.add(c[N].id);continue}ke<0&&(ke=N)}const Oe=ue?.type==="project-action"?Eg(ue,D.status):{type:"terminal"};if(ke>=0){const N=c[ke];let et=N.purpose.type==="project-action"||ue?.type==="project-action"?ac(D.status):D.status;N.lifecycle==="stopping"&&D.status==="running"&&N.purpose.type==="project-action"&&Oe.type==="project-action"&&N.purpose.executionId===Oe.executionId&&(et="stopping");const un=D.createdAt??N.createdAt,Lr=ue?.type==="project-action"&&(N.terminalSessionId!==D.sessionId||Oe.type==="project-action"&&Oe.executionId!==null&&(N.purpose.type!=="project-action"||N.purpose.executionId!==Oe.executionId));if(Lr){const Tt=tt(o,N.id);l=pn(l,no=>no===Tt)??l}const Hn=ue?.type==="project-action"&&D.status==="running"&&(N.terminalSessionId!==D.sessionId||N.lifecycle!=="running"),Fr=N.purpose.type!==Oe.type||N.purpose.type==="project-action"&&Oe.type==="project-action"&&(N.purpose.actionId!==Oe.actionId||N.purpose.executionId!==Oe.executionId);if((N.terminalSessionId!==D.sessionId||N.lifecycle!==et||N.isConnecting!==!1||N.createdAt!==un||Fr)&&(c[ke]={...N,terminalSessionId:D.sessionId,lifecycle:et,purpose:Oe,isConnecting:!1,createdAt:un},Lr&&Object.assign(c[ke],Po),u=!0),Hn){const Tt={tabId:N.id,createdAt:un,index:ke};(!d||Tt.createdAt>d.createdAt||Tt.createdAt===d.createdAt&&Tt.index>d.index)&&(d=Tt)}m.add(N.id);continue}const Nn=ue?.type==="project-action"?Ag(ue.actionId):y&&c.length===0?y.label:lc(c),Bn=ue?.type==="project-action"?"play":null,Bt={...Qr(D.sessionId,Nn),terminalSessionId:D.sessionId,lifecycle:ue?.type==="project-action"?ac(D.status):D.status,purpose:Oe,iconKey:Bn,createdAt:D.createdAt??Date.now()};if(c.push(Bt),u=!0,ue?.type==="project-action"&&D.status==="running"){const N={tabId:Bt.id,createdAt:Bt.createdAt,index:c.length-1};(!d||N.createdAt>d.createdAt||N.createdAt===d.createdAt&&N.index>d.index)&&(d=N)}m.add(Bt.id)}let b=u||!!(y&&r.length>0);const S=c.map(D=>!vn(D.purpose)||p.has(D.purpose.actionId)||m.has(D.id)||D.lifecycle==="starting"||cc(i,o,D.purpose.actionId,s?.startedActionMutationRevisions)||D.lifecycle==="exited"&&!D.isConnecting?D:(b=!0,{...D,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:D.purpose.actionId,executionId:null}})),k=a?.activeTabId??null,P=k&&S.some(D=>D.id===k)?k:S[0]?.id??null,F=P?S.find(D=>D.id===P):S[0],_=d&&!Rg(F)?d.tabId:P;if(!b&&a&&_===a.activeTabId&&S.length===a.tabs.length&&S.every((D,ke)=>D===a.tabs[ke]))return i;const Q=new Map(i.sessions);return Q.set(o,{tabs:S,activeTabId:_}),{sessions:Q,buffers:l}})},setActiveTab:(n,r)=>{const s=ne(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);return!a||a.activeTabId===r||Ee(a,r)<0?o:(i.set(s,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,s)=>{const o=ne(n),i=s.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const u=Ee(l,r);if(u<0||l.tabs[u]?.label===i)return a;const d=[...l.tabs];return d[u]={...d[u],label:i},c.set(o,{...l,tabs:d}),{sessions:c}})},moveTab:(n,r,s)=>{const o=ne(n);e(i=>{const a=i.sessions.get(o);if(!a||r===s)return i;const c=Ee(a,r),l=Ee(a,s);if(c<0||l<0)return i;const u=[...a.tabs],[d]=u.splice(c,1);u.splice(l,0,d);const p=new Map(i.sessions);return p.set(o,{...a,tabs:u}),{sessions:p}})},setTabIconKey:(n,r,s)=>{const o=ne(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const l=Ee(c,r);if(l<0)return i;const u=s?.trim()||null;if(c.tabs[l]?.iconKey===u)return i;const d=[...c.tabs];return d[l]={...d[l],iconKey:u},a.set(o,{...c,tabs:d}),{sessions:a}})},closeTab:(n,r)=>{const s=ne(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=Ee(a,r);if(c<0)return o;const l=a.tabs[c].purpose;let u=o.actionMutationRevisions,d=o.nextActionMutationRevision;l.type==="project-action"&&(u=new Map(u),qn(u,s,l.actionId,d),d+=1);const p={actionMutationRevisions:u,nextActionMutationRevision:d},m=a.tabs.filter(P=>P.id!==r),y=tt(s,r),b=o.buffers.has(y)?pn(o.buffers,P=>P===y):null;if(m.length===0){const P=Qn(),F=Qr(P,"Terminal");i.set(s,Ao(F));const _={sessions:i,nextTabId:o.nextTabId+1};return b&&(_.buffers=b),{..._,...p}}let S=a.activeTabId;a.activeTabId===r&&(S=m[Math.min(c,m.length-1)]?.id??m[0]?.id??null),i.set(s,{...a,tabs:m,activeTabId:S});const k={sessions:i};return b&&(k.buffers=b),{...k,...p}})},setTabPurpose:(n,r,s)=>{const o=ne(n);e(i=>{const a=i.sessions.get(o);if(!a)return i;const c=Ee(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(s))return i;const u=[...a.tabs],d=s.type==="project-action"&&s.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==s.executionId);u[c]={...l,purpose:s},d&&Object.assign(u[c],Po);const p=tt(o,r),m=d?pn(i.buffers,S=>S===p)??i.buffers:i.buffers,y=new Map(i.sessions);if(y.set(o,{...a,tabs:u}),s.type!=="project-action")return{sessions:y};const b=new Map(i.actionMutationRevisions);return qn(b,o,s.actionId,i.nextActionMutationRevision),{sessions:y,buffers:m,actionMutationRevisions:b,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,s)=>{const o=ne(n),i=t().sessions.get(o);if(!i||Ee(i,r)<0)return null;const a=kg();return e(c=>{const l=c.sessions.get(o);if(!l)return c;const u=Ee(l,r);if(u<0)return c;const d=[...l.tabs];d[u]={...d[u],purpose:{type:"project-action",actionId:s,executionId:a},lifecycle:"starting",terminalSessionId:null,...Po,isConnecting:!1};const p=new Map(c.sessions);p.set(o,{...l,tabs:d});const m=new Map(c.actionMutationRevisions);qn(m,o,s,c.nextActionMutationRevision);const y=tt(o,r),b=pn(c.buffers,S=>S===y)??c.buffers;return{sessions:p,buffers:b,actionMutationRevisions:m,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,s,o)=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ee(l,r);if(u<0)return a;const d=l.tabs[u];if(!Yr(d,o?.expectedExecutionId))return a;const p=s!==null&&d.terminalSessionId!==s,m=s?"running":d.terminalSessionId?"exited":d.lifecycle,y={...d,terminalSessionId:s,lifecycle:m,isConnecting:!1},b=tt(i,r),S=p&&a.buffers.has(b)?pn(a.buffers,F=>F===b):null,k=[...l.tabs];k[u]=y,c.set(i,{...l,tabs:k});const P={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(vn(d.purpose)){const F=new Map(a.actionMutationRevisions);qn(F,i,d.purpose.actionId,a.nextActionMutationRevision),P.actionMutationRevisions=F,P.nextActionMutationRevision=a.nextActionMutationRevision+1}return S&&(P.buffers=S),P})},setTabLifecycle:(n,r,s,o)=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ee(l,r);if(u<0||!Yr(l.tabs[u],o?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===s&&!d.isConnecting)return a;const p=[...l.tabs];if(p[u]={...d,lifecycle:s,isConnecting:!1},c.set(i,{...l,tabs:p}),d.purpose.type!=="project-action"||d.lifecycle===s)return{sessions:c};const m=new Map(a.actionMutationRevisions);return qn(m,i,d.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:m,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,s,o)=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ee(l,r);if(u<0||!Yr(l.tabs[u],o?.expectedExecutionId))return a;const d=[...l.tabs];return d[u]={...d[u],isConnecting:s},c.set(i,{...l,tabs:d}),{sessions:c}})},replaceBuffer:(n,r,s,o,i)=>{const a=ne(n);e(c=>{const l=c.sessions.get(a);if(!l||Ee(l,r)<0)return c;const u=tt(a,r),d=c.buffers.get(u)??To;if(d.lastSequence>o)return c;const p=ko(s),m=d.chunks[0]?.size;if(d.lastSequence===o&&d.byteLength===p.byteLength&&d.chunks.map(S=>S.data).join("")===p.text&&m?.cols===i?.cols&&m?.rows===i?.rows)return c;const y=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:p.text?[{id:y,data:p.text,byteLength:p.byteLength,...i?{size:i}:{}}]:[],byteLength:p.byteLength,lastSequence:o}),{buffers:b,nextChunkId:p.text?y+1:y}})},appendToBuffer:(n,r,s,o,i)=>{if(!s)return;const a=ne(n);e(c=>{const l=c.sessions.get(a);if(!l||Ee(l,r)<0)return c;const u=tt(a,r),d=c.buffers.get(u)??To;if(o!==void 0&&o<=d.lastSequence)return c;const p=c.nextChunkId,m=ko(s),y=i!==void 0&&i!==s?ko(i).text:void 0,b={id:p,data:m.text,...y!==void 0?{replayData:y}:{},byteLength:m.byteLength},S=[...d.chunks,b];let k=d.byteLength+b.byteLength;for(;k>Xo&&S.length>1;){const F=S.shift();if(!F)break;k-=F.byteLength}const P=new Map(c.buffers);return P.set(u,{chunks:S,byteLength:k,lastSequence:o??d.lastSequence}),{buffers:P,nextChunkId:p+1}})},setTabPreviewUrl:(n,r,s,o={})=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ee(l,r);if(u<0)return a;const d=l.tabs[u];if(!Yr(d,o.expectedExecutionId))return a;const p=o.autoOpened??d.previewAutoOpened,m=o.locked??d.previewUrlLocked;if(d.previewUrl===s&&d.previewAutoOpened===p&&d.previewUrlLocked===m)return a;const y=[...l.tabs];return y[u]={...d,previewUrl:s,previewAutoOpened:p,previewUrlLocked:m},c.set(i,{...l,tabs:y}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const s=ne(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=Ee(a,r);if(c<0)return o;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return o;const u=[...a.tabs];return u[c]={...l,previewAutoOpened:!0},i.set(s,{...a,tabs:u}),{sessions:i}})},removeDirectory:n=>{const r=ne(n);e(s=>{const o=new Map(s.sessions);o.delete(r);const i=tt(r,""),a=pn(s.buffers,d=>d.startsWith(i)),c=Ds(r,"");let l;for(const d of s.actionMutationRevisions.keys())d.startsWith(c)&&(l??=new Map(s.actionMutationRevisions),l.delete(d));const u={sessions:o};return a&&(u.buffers=a),l&&(u.actionMutationRevisions=l),u})},clearAll:()=>{e({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1})}}),{name:vg,storage:Og(),partialize:Cg,merge:(e,t)=>{if(!Eo(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let s=0;for(const a of n){if(!Array.isArray(a)||a.length!==2)continue;const[c,l]=a;if(typeof c!="string"||!Eo(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],p=new Map;for(const S of u){if(!Eo(S))continue;const k=typeof S.id=="string"?S.id:null;if(!k)continue;const P=Ig(k);P!==null&&(s=Math.max(s,P));const F=P===null?k:Qn();p.set(k,F);const _=Tg.safeParse(S.purpose).data,Q=_?{type:"project-action",actionId:_.actionId,executionId:null}:{type:"terminal"};d.push({id:F,label:typeof S.label=="string"?S.label:"Terminal",iconKey:typeof S.iconKey=="string"?S.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:Q,createdAt:typeof S.createdAt=="number"?S.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(d.length===0)continue;const m=typeof l.activeTabId=="string"?l.activeTabId:null,y=m?p.get(m)??m:null,b=y?d.some(S=>S.id===y):!1;r.set(c,{tabs:d,activeTabId:b?y:d[0].id})}const o=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,i=Math.max(t.nextTabId,o,s+1);return{...t,sessions:r,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:i,hasHydrated:!0}}})));if(typeof window<"u"&&!oc){oc=!0;const e=ds.persist,t=()=>{ds.getState().hasHydrated||ds.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const nt=20,Dg=8,uc=4096,Mg=2160*60*6e4,ee=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const s=r==="/",o=/^[A-Za-z]:\/$/.test(r);return!s&&!o&&(r=r.replace(/\/+$/,"")),r},Ot=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Mt=(e,t)=>{const n=ee(t),r=ee(e);if(!n||!r)return!1;const s=Ot(n),o=Ot(r);return o===s||o.startsWith(`${s}/`)},Kn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=ee(r);if(!o||!s||typeof s!="object")continue;const i=s,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(m=>typeof m=="string").map(m=>ee(m)).filter(m=>m.length<=uc&&Mt(m,o)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(m=>typeof m=="string").map(m=>ee(m)).filter(m=>m.length<=uc&&Mt(m,o)))).slice(-500):[],l=typeof i.selectedPath=="string"?ee(i.selectedPath):null,u=l&&Mt(l,o)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>Mg)continue;const p=n[o];if(p){const m=Array.from(new Set([...p.openPaths,...a])),y=Array.from(new Set([...p.expandedPaths,...c])),b=p.selectedPath??u??m[0]??null;n[o]={openPaths:m,selectedPath:b,expandedPaths:y,touchedAt:Math.max(p.touchedAt,d)};continue}n[o]={openPaths:a,selectedPath:u,expandedPaths:c,touchedAt:d}}return rt(n,nt)},rt=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((s,o)=>(o[1]?.touchedAt??0)-(s[1]?.touchedAt??0));const r={};for(const[s,o]of n.slice(0,t))r[s]=o;return r},hn=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},dc=ut()(_n(kr((e,t)=>({byRoot:{},activeRuntimeKey:q(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const s={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Kn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:s,byRoot:Kn(s[n]?.byRoot)}})},addOpenPath:(n,r,s)=>{const o=ee((n||"").trim()),i=ee((r||"").trim());!o||!i||!s?.allowOutsideRoot&&!Mt(i,o)||e(a=>{const c=a.byRoot[o],l=hn(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],p=l.selectedPath??i;if(c&&u&&c.selectedPath===p)return a;const m={...a.byRoot,[o]:{...l,openPaths:d,selectedPath:p}};return{byRoot:rt(m,nt)}})},removeOpenPath:(n,r)=>{const s=ee((n||"").trim()),o=ee((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=Ot(o),l=y=>Ot(y)===c,u=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!u)return i;const d=a.openPaths.filter(y=>!l(y)),p=u?d[0]??null:a.selectedPath,m={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:p,touchedAt:Date.now()}};return{byRoot:rt(m,nt)}})},removeOpenPathsByPrefix:(n,r)=>{const s=ee((n||"").trim()),o=ee((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=Ot(o),l=c.endsWith("/")?c:`${c}/`,u=y=>{const b=Ot(y);return b===c||b.startsWith(l)},d=a.openPaths.filter(y=>!u(y));if(d.length===a.openPaths.length)return i;const p=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,m={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:p,touchedAt:Date.now()}};return{byRoot:rt(m,nt)}})},removeExpandedPathsByPrefix:(n,r)=>{const s=ee((n||"").trim()),o=ee((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=Ot(o),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(p=>{const m=Ot(p);return m!==c&&!m.startsWith(l)});if(u.length===a.expandedPaths.length)return i;const d={...i.byRoot,[s]:{...a,expandedPaths:u,touchedAt:Date.now()}};return{byRoot:rt(d,nt)}})},setSelectedPath:(n,r,s)=>{const o=ee((n||"").trim()),i=r?ee(r.trim()):null;!o||i&&!s?.allowOutsideRoot&&!Mt(i,o)||e(a=>{const c=a.byRoot[o],l=hn(c),u=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&u===c.openPaths)return a;const d={...a.byRoot,[o]:{...l,openPaths:u,selectedPath:i}};return{byRoot:rt(d,nt)}})},ensureSelectedPath:n=>{const r=ee((n||"").trim());if(!r)return;const s=t().byRoot[r];if(!s||s.selectedPath)return;const o=s.openPaths[0]??null;o&&t().setSelectedPath(r,o)},toggleExpandedPath:(n,r)=>{const s=ee((n||"").trim()),o=ee((r||"").trim());!s||!o||!Mt(o,s)||e(i=>{const a=i.byRoot[s],c=hn(a),u=c.expandedPaths.includes(o)?c.expandedPaths.filter(p=>p!==o):[...c.expandedPaths,o];if(a&&a.expandedPaths===u&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:u}};return{byRoot:rt(d,nt)}})},collapseAllExpandedPaths:n=>{const r=ee((n||"").trim());r&&e(s=>{const o=s.byRoot[r];if(!o||o.expandedPaths.length===0)return s;const i={...s.byRoot,[r]:{...hn(o),expandedPaths:[]}};return{byRoot:rt(i,nt)}})},expandPath:(n,r)=>{const s=ee((n||"").trim()),o=ee((r||"").trim());!s||!o||!Mt(o,s)||e(i=>{const a=i.byRoot[s],c=hn(a);if(c.expandedPaths.includes(o)&&a)return i;const u={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,o]}};return{byRoot:rt(u,nt)}})},expandPaths:(n,r)=>{const s=ee((n||"").trim());if(!s||!r||r.length===0)return;const o=r.map(i=>ee((i||"").trim())).filter(i=>i&&Mt(i,s));o.length!==0&&e(i=>{const a=i.byRoot[s],c=hn(a),l=new Set(c.expandedPaths),u=o.filter(p=>!l.has(p));if(u.length===0)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:rt(d,nt)}})}}),{name:"files-view-tabs-store",version:3,storage:Ni(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:q(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Kn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,Dg).map(([r,s])=>[r,{byRoot:Kn(s.byRoot),updatedAt:s.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:n}},merge:(e,t)=>{const n=e&&typeof e=="object"?e:{},r=n.runtimeSnapshots&&typeof n.runtimeSnapshots=="object"?n.runtimeSnapshots:{},s=q();return{...t,activeRuntimeKey:s,runtimeSnapshots:r,byRoot:Kn(r[s]?.byRoot)}}}),{name:"files-view-tabs-store"})),Tu=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]),_g=e=>{const t=e.split("/")[0]?.split("?")[0]??"",n=t.startsWith("[")?t.slice(0,t.indexOf("]")+1):t.split(":")[0]??"";return Tu.has(n.toLowerCase())},fs="about:blank",AE=e=>{const t=e.trim();if(!t)return fs;const n=t.includes("://")?t:`${_g(t)?"http":"https"}://${t}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?fs:r.toString()}catch{return fs}},Lg=e=>{try{return Tu.has(new URL(e).hostname.toLowerCase())}catch{return!1}},IE=e=>{if(!e||e===fs)return"";try{return new URL(e).host||e}catch{return e}},Fg=new Set([-2,-7,-101,-102,-104,-109,-118,-324]),jg=(e,t)=>Fg.has(e)&&Lg(t),Ug=4e4,Rr=(e,t)=>`${e}
4
+ ${t}`,Hi=new Set,Ng=(e,t)=>{Hi.add(Rr(e,t))},xE=(e,t)=>Hi.has(Rr(e,t)),RE=(e,t)=>{Hi.delete(Rr(e,t))},ps=new Map,Bg=(e,t,n)=>{const r=ps.get(Rr(e,t));if(r)for(const s of r)s(n)},CE=(e,t)=>e.kind==="failed"||!t,OE=(e,t,n)=>{const r=Rr(e,t),s=ps.get(r)??new Set;return s.add(n),ps.set(r,s),()=>{s.delete(n),s.size===0&&ps.delete(r)}},DE=(e,{run:t,restored:n,now:r})=>{if(n||!jg(e.code,e.url))return{retry:!1,run:t};const s=t?.url===e.url?t:{url:e.url,startedAt:r};return{retry:r-s.startedAt<=Ug,run:s}},Hg=["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"],$g=/^plugin:[a-z][a-z0-9-]*$/,zg=new Set(Hg),Wg=e=>$g.test(e),Gg=e=>zg.has(e)||Wg(e),ME=e=>e.slice(7),_E=e=>`plugin:${e}`,$i=["session","repository","usage","telemetry","subagents","mcp","pinned","contextSources"],LE={session:"chat.workStatus.section.session",repository:"chat.workStatus.section.project",usage:"chat.workStatus.section.usage",telemetry:"chat.workStatus.section.telemetry",subagents:"chat.workStatus.section.subagents",mcp:"chat.workStatus.section.mcp",pinned:"chat.workStatus.section.pinned",contextSources:"chat.workStatus.section.contextBreakdown"},qg=/^ext:[a-z][a-z0-9-]*$/,FE=e=>`ext:${e}`,Kg=e=>qg.test(e),Vg=Ze([H($i),Md(["ext:",f().regex(/^[a-z][a-z0-9-]*$/)])]),ku=e=>{const t=Vg.safeParse(e);return t.success?t.data:null},Ms=e=>{const t=new Set;if(Array.isArray(e))for(const n of e){const r=ku(n);r&&t.add(r)}for(const n of $i)t.add(n);return[...t]},jE=(e,t)=>{const n=new Set(t),r=Ms(e).filter(o=>!Kg(o)||n.has(o)),s=new Set(r);for(const o of t)s.has(o)||r.push(o);return r},UE=(e,t)=>!e?.includes(t),NE=(e,t=[])=>e!=null&&$i.every(n=>e.includes(n))&&t.every(n=>e.includes(n)),BE=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),Eu=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e){const s=ku(r);s&&n.add(s)}return t||n.delete("telemetry"),[...n]},Jg=e=>Math.min(480,Math.max(200,Math.round(e))),Yg=H(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),Qg=w({widthByMode:lt(f(),E().finite().optional().catch(void 0)).catch({}),widthFractionByMode:lt(f(),E().positive().max(1).optional().catch(void 0)).catch({})}),Pu="ask",fc=e=>e==="attach"||e==="inline"||e==="ask"?e:Pu;function pc(e){return e==="vim"?"vim":"default"}const yt="all";function hc(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function mc(e){return e==="me"||e==="any"?e:"any"}function Au(e){return typeof e!="string"?yt:e.trim()||yt}function gc(e,t){const n=q();if(Tl(n))return e;const r={...e};return t===yt?delete r[n]:r[n]=t,r}function Xg(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[n,r]of Object.entries(e)){if(!n.trim()||typeof r!="string")continue;const s=Au(r);s!==yt&&(t[n]=s)}return t}function yc(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const Xr={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},Pt={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Zr=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,Zg=e=>{if(!e||typeof e!="object")return!1;const t=e;return Zr(t.completion,Xr.completion)&&Zr(t.error,Xr.error)&&Zr(t.question,Xr.question)&&Zr(t.subtask,Xr.subtask)},ey=380,ty=320,ny=1e4,Iu=12,wc=120,ry=280;let es=0;const sy=e=>ce(e),ce=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?t.startsWith("/")?"/":"":r},xu=e=>Number.isFinite(e)?Math.min(ny,Math.max(ty,Math.round(e))):ey,Sr=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},_s=e=>{const t=Sr(e);return t&&sy(t)||null},Ls=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>wc?t.slice(0,wc):t:null},zi=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,Ru=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.id=="string"?t.id.trim():"",r=typeof t.path=="string"?t.path.trim():"";return n&&r?{id:n,path:r}:null},oy=(e,t)=>(e==="file"||e==="browser")&&t||e,Cu=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return oy(e,t)},Ys=(e,t)=>t===e?e:`${e}:${t}`,Wi=e=>{const t=Sr(e.targetPath),n=e.mode==="terminal"?_s(e.targetDirectory):null,r=Cu(e.mode,t,e.dedupeKey);return{id:Ys(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Ru(e.projectPlanRef),dedupeKey:r,label:Ls(e.label),sessionTitleFallback:Ls(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:zi(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),preview:e.mode==="file"&&e.preview===!0,touchedAt:Date.now()}},Ou=(e,t,n)=>{const r=new Map;for(const i of e)r.set(i.mode,(r.get(i.mode)??0)+1);const s=[...r.entries()].filter(([,i])=>i>t);if(s.length===0)return e;const o=new Set;for(const[i,a]of s){const l=[...e.filter(u=>u.mode===i)].sort((u,d)=>u.touchedAt-d.touchedAt).filter(u=>u.id!==n);for(const u of l.slice(0,a-t))o.add(u.id)}return o.size===0?e:e.filter(i=>!o.has(i.id))},Du=e=>{if(!Array.isArray(e))return[];const t=Me(),n=[],r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s;if(typeof o.mode!="string"||!Gg(o.mode)||t&&o.mode==="browser")continue;const i=Sr(typeof o.targetPath=="string"?o.targetPath:null),a=o.mode==="terminal"?_s(o.targetDirectory):null,c=typeof o.projectPlanId=="string"&&o.projectPlanId.trim()?o.projectPlanId.trim():null,l=Ru(o.projectPlanRef);if(o.mode==="plan"&&c!==null!=(l!==null))continue;const u=Cu(o.mode,i,typeof o.dedupeKey=="string"?o.dedupeKey:null),d=Ys(o.mode,u);!d||r.has(d)||(r.add(d),n.push({id:d,mode:o.mode,targetPath:i,targetDirectory:a,projectPlanId:c,projectPlanRef:l,dedupeKey:u,label:Ls(typeof o.label=="string"?o.label:null),sessionTitleFallback:Ls(typeof o.sessionTitleFallback=="string"?o.sessionTitleFallback:null),readOnly:o.readOnly===!0,stagedDiff:o.stagedDiff===!0,diffScope:zi(o.diffScope)??(o.stagedDiff===!0?"staged":"working"),preview:o.mode==="file"&&o.preview===!0,touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return n},On=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,Wt=e=>{if(e){const t=Du(e.tabs),n=On(t,e.activeTabId);return{...e,tabs:t,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,widthByMode:{},widthFractionByMode:{},touchedAt:Date.now()}},Ro=(e,t,n,r)=>{const s=Ys("browser",n);if(e[t]?.tabs.some(o=>o.id===s)){Bg(t,s,r);return}Ng(t,s)},iy=(e,t,n)=>{const r=n?.reveal!==!1,s=Wi(t),o=s.mode==="file"&&s.targetPath?e.tabs.filter(d=>!(d.mode==="file"&&!d.targetPath)):e.tabs,i=o.findIndex(d=>d.id===s.id),a=i===-1&&s.preview?o.findIndex(d=>d.preview):-1,c=a!==-1?o.map((d,p)=>p===a?s:d):i===-1?[...o,s]:o.map((d,p)=>p===i?{...d,mode:s.mode,targetPath:s.targetPath||d.targetPath,targetDirectory:s.targetDirectory,projectPlanId:s.projectPlanId??d.projectPlanId,projectPlanRef:s.projectPlanRef??d.projectPlanRef,dedupeKey:s.dedupeKey,label:s.label,sessionTitleFallback:s.sessionTitleFallback||d.sessionTitleFallback,stagedDiff:s.stagedDiff,diffScope:s.diffScope,readOnly:s.readOnly,preview:d.preview&&s.preview,touchedAt:Date.now()}:d),l=r?s.id:e.activeTabId??s.id,u=Ou(c,Iu,l);return{...e,isOpen:r?!0:e.isOpen,tabs:u,activeTabId:On(u,l),touchedAt:Date.now()}},ay=(e,t)=>{const n=new Set(t),r=e.tabs.filter(l=>n.has(l.id)),s=e.tabs.filter(l=>!n.has(l.id));if(s.length===e.tabs.length)return e;if(!(e.activeTabId?n.has(e.activeTabId):!1))return{...e,tabs:s,activeTabId:On(s,e.activeTabId),isOpen:s.length>0?e.isOpen:!1,touchedAt:Date.now()};const i=r.find(l=>l.id===e.activeTabId)?.mode??null,a=i?s.filter(l=>l.mode===i):[],c=a.length>0?a.reduce((l,u)=>u.touchedAt>=l.touchedAt?u:l):null;if(i==="file"&&!c&&r.some(l=>l.mode==="file"&&l.targetPath)){const l=Wi({mode:"file"});return{...e,tabs:[...s,l],activeTabId:l.id,isOpen:e.isOpen,touchedAt:Date.now()}}return{...e,tabs:s,activeTabId:c?.id??On(s,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},cy=(e,t,n)=>{if(t===n)return e;const r=e.tabs.findIndex(a=>a.id===t),s=e.tabs.findIndex(a=>a.id===n);if(r===-1||s===-1)return e;const o=[...e.tabs],[i]=o.splice(r,1);return i?(o.splice(s,0,i),{...e,tabs:o,touchedAt:Date.now()}):e},ly=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),Co=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=ce(r);if(!o||!s||typeof s!="object")continue;const i=s;let a=Du(i.tabs),c=typeof i.activeTabId=="string"?i.activeTabId:null;a.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat"||i.mode==="terminal")&&(a=[Wi({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,targetDirectory:i.targetDirectory,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=a[0]?.id??null);const l=On(a,c),u=Ou(a,Iu,l),d={},p={},m=Qg.parse(s);for(const y of Yg.options){const b=m.widthByMode[y],S=m.widthFractionByMode[y];b!==void 0&&(d[y]=xu(b)),S!==void 0&&(p[y]=S)}n[o]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:On(u,l),widthByMode:d,widthFractionByMode:p,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},Gt=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((s,o)=>(o[1]?.touchedAt??0)-(s[1]?.touchedAt??0));const r={};for(const[s,o]of n.slice(0,t))r[s]=o;return r},T=ut()(_n(kr((e,t)=>({theme:"system",runOverviewKey:null,parallelComposerRequest:null,isSidebarOpen:!0,sidebarWidth:ry,contextPanelByDirectory:{},contextRailOrder:[],contextRailHiddenSurfaces:[],contextEditorTreeVisible:!0,contextEditorVisible:!0,contextEditorTreeWidth:240,notesPanelHeight:112,workStatusExpandedSections:{},messageQueueExpanded:!0,workStatusScrollTop:0,workStatusPanelEnabled:!0,workStatusPanelVisible:!1,workStatusPanelFits:!1,workStatusOverlayOpen:!1,workStatusHiddenSections:[],workStatusSectionOrder:Ms([]),workStatusHiddenSectionsExplicit:!1,isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,openGuestPageId:null,worktreesPageProjectId:null,spacesPageProjectId:null,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsProjectPath:null,settingsProvidersConnectRequested:!1,settingsProvidersClassificationRequested:!1,settingsProvidersOpenRequested:null,settingsJumpRequest:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,streamingAutoFollowEnabled:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionWorkEnabled:!0,sessionWorkAutoOpen:!0,sessionGoalEnabled:!0,sessionGoalChecker:"small-model",sessionGoalDefaultBudgetEnabled:!1,sessionGoalDefaultBudget:2e5,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",sessionRetentionOnlyArchived:!1,autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:ug,monoFont:dg,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:gg(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,diffFileListMode:"flat",diffFileTreeWidth:240,walkthroughTocWidth:224,gitChangesViewMode:"flat",toolJsonViewMode:"summary",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:yt,linearIssueListTeamIdByRuntime:{},linearIssueListPriority:"all",linearIssueFocus:null,isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,alwaysShowScrollbars:!1,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Pt.completion},error:{...Pt.error},question:{...Pt.question},subtask:{...Pt.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!0,agentControlToolEnabled:!0,agentWebToolEnabled:!0,messageSearchEnabled:!1,messageSearchReasoningEnabled:!1,browserProvider:"builtin",agentMemoryToolEnabled:!1,agentNotifyToolEnabled:!1,agentToolsCodeMode:!1,isolatedSpacesEnabled:!1,permissionDefaultMode:"ask",agentMemoryFeatureAvailable:!1,routingFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:Pu,enterToSend:!1,enterToSendConfigured:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,showSplitAssistantMessageActions:!1,allowPromptingSubagentSessions:!1,draftStartersVisible:!0,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:n=>{e({theme:n}),t().applyTheme()},toggleSidebar:()=>{e(n=>({isSidebarOpen:!n.isSidebarOpen}))},setSidebarOpen:n=>{e(r=>r.isSidebarOpen===n?r:{isSidebarOpen:n})},setSidebarWidth:n=>{e({sidebarWidth:n})},setContextRailOrder:n=>{const r=Array.isArray(n)?n.filter((s,o)=>typeof s=="string"&&s.trim()!==""&&n.indexOf(s)===o):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(n=>n.contextEditorTreeVisible&&!n.contextEditorVisible?{contextEditorTreeVisible:!1,contextEditorVisible:!0}:{contextEditorTreeVisible:!n.contextEditorTreeVisible})},toggleContextEditor:()=>{e(n=>n.contextEditorVisible&&!n.contextEditorTreeVisible?{contextEditorVisible:!1,contextEditorTreeVisible:!0}:{contextEditorVisible:!n.contextEditorVisible})},setContextEditorTreeWidth:n=>{Number.isFinite(n)&&e({contextEditorTreeWidth:Jg(n)})},openContextSurface:(n,r)=>{const s=ce((n||"").trim());if(!s)return;const o=t(),i=o.contextPanelByDirectory[s],a=i?.tabs??[],c=a.find(d=>d.id===i?.activeTabId)??null,l=()=>{if(r==="terminal"){const p=(a.find(m=>m.mode==="terminal")??null)?.targetDirectory??null;if(p){const m=ds.getState().getDirectoryState(p);if(wg(m))return}o.openContextPanelTab(s,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),o.closeContextPanel(s);return}r==="file"&&!o.contextEditorTreeVisible&&e({contextEditorTreeVisible:!0});const u=a.filter(d=>d.mode===r);if(u.length>0){l();const d=u.reduce((p,m)=>m.touchedAt>=p.touchedAt?m:p);o.setActiveContextPanelTab(s,d.id);return}r!=="chat"&&o.openContextPanelTab(s,{mode:r})},openContextPanelTab:(n,r,s)=>{const o=ce((n||"").trim());if(!o)return;const i=r.mode==="terminal"?{...r,targetDirectory:_s(r.targetDirectory)===o?null:_s(r.targetDirectory)}:r,a=i.mode==="file"&&!!i.targetPath&&s?.reveal!==!1;e(c=>{const l=c.contextPanelByDirectory[o],u=Wt(l),d={...c.contextPanelByDirectory,[o]:iy(u,i,s)};return{contextPanelByDirectory:Gt(d,20),contextEditorVisible:a||c.contextEditorVisible}})},openContextDiff:(n,r,s=!1,o=null)=>{const i=ce((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=zi(o)??(s?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r,s)=>{const o=ce((n||"").trim()),i=Sr(r);if(!o||!i)return;const a=s?.preview===!0,c=a?t().contextPanelByDirectory[o]?.tabs.find(u=>u.preview&&u.targetPath!==i)?.targetPath??null:null,l=t().contextPanelByDirectory[o]?.tabs.some(u=>u.mode==="file"&&u.targetPath===i)??!1;t().openContextPanelTab(o,{mode:"file",targetPath:i,preview:a}),c&&!l&&dc.getState().removeOpenPath(o,c),t().setPendingFileFocusPath(i),t().setPendingFileNavigation(null)},openContextFileAtLine:(n,r,s,o)=>{const i=ce((n||"").trim()),a=Sr(r),c=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1,l=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:n=>{const r=ce((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const s=ce((n||"").trim()),o=(r||"").trim();!s||!o||Me()||(Ro(t().contextPanelByDirectory,s,o,o),t().openContextPanelTab(s,{mode:"browser",targetPath:o,dedupeKey:o,label:null}))},openAgentBrowserTab:(n,r)=>{const s=ce((n||"").trim());if(!s||Me())return null;es+=1;const o=`browser:agent:${Date.now()}-${es}`;return r.trim()&&Ro(t().contextPanelByDirectory,s,o,r.trim()),t().openContextPanelTab(s,{mode:"browser",targetPath:r.trim(),dedupeKey:o,label:null},{reveal:!1}),Ys("browser",o)},openNewContextBrowserTab:n=>{const r=ce((n||"").trim());!r||Me()||(es+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${es}`,label:null}))},openContextBrowser:(n,r="",s)=>{const o=ce((n||"").trim());if(!o||Me())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";i&&Ro(t().contextPanelByDirectory,o,i,i),t().openContextPanelTab(o,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},s)},setContextPanelTabTargetPath:(n,r,s)=>{const o=ce((n||"").trim()),i=(r||"").trim();!o||!i||e(a=>{const c=a.contextPanelByDirectory[o];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[o]:ly(c,i,s)}}:a})},setActiveContextPanelTab:(n,r)=>{const s=ce((n||"").trim()),o=(r||"").trim();!s||!o||e(i=>{const a=i.contextPanelByDirectory[s],c=Wt(a),l=c.tabs.find(p=>p.id===o);if(!l)return i;const u=l.mode==="file"&&!!l.targetPath;if(c.activeTabId===o&&c.isOpen)return u?{contextEditorVisible:!0}:i;const d={...i.contextPanelByDirectory,[s]:{...c,isOpen:!0,activeTabId:o,touchedAt:Date.now(),tabs:c.tabs.map(p=>p.id===o?{...p,touchedAt:Date.now()}:p)}};return{contextPanelByDirectory:Gt(d,20),contextEditorVisible:u||i.contextEditorVisible}})},reorderContextPanelTabs:(n,r,s)=>{const o=ce((n||"").trim()),i=(r||"").trim(),a=(s||"").trim();!o||!i||!a||e(c=>{const l=c.contextPanelByDirectory[o],u=Wt(l);if(!u.tabs.some(m=>m.id===i)||!u.tabs.some(m=>m.id===a))return c;const d=cy(u,i,a);if(d.tabs===u.tabs)return c;const p={...c.contextPanelByDirectory,[o]:d};return{contextPanelByDirectory:Gt(p,20)}})},pinContextPanelTab:(n,r)=>{const s=ce((n||"").trim());s&&e(o=>{const i=o.contextPanelByDirectory[s];return i?.tabs.some(a=>a.id===r&&a.preview)?{contextPanelByDirectory:{...o.contextPanelByDirectory,[s]:{...i,tabs:i.tabs.map(a=>a.id===r?{...a,preview:!1}:a)}}}:o})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const s=ce((n||"").trim()),o=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!s||o.length===0)return;const i=o.map(a=>t().contextPanelByDirectory[s]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[s],l=Wt(c);if(!l.tabs.some(y=>o.includes(y.id)))return a;const u=ay(l,o),d=u.tabs.find(y=>y.id===u.activeTabId),p=u.isOpen&&d?.mode==="file"&&!d.targetPath,m={...a.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:Gt(m,20),contextEditorTreeVisible:p||a.contextEditorTreeVisible}});for(const a of i)a.mode==="file"&&a.targetPath&&dc.getState().removeOpenPath(s,a.targetPath)},closeContextPanel:n=>{const r=ce((n||"").trim());r&&e(s=>{const o=s.contextPanelByDirectory[r];if(!o||!o.isOpen)return s;const i={...s.contextPanelByDirectory,[r]:{...Wt(o),isOpen:!1}};return{contextPanelByDirectory:Gt(i,20)}})},toggleContextPanelExpanded:n=>{const r=ce((n||"").trim());r&&e(s=>{const o=s.contextPanelByDirectory[r],i=Wt(o),a={...s.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Gt(a,20)}})},setContextPanelWidth:(n,r,s,o)=>{const i=ce((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=Wt(c),u=xu(s),d={...l.widthFractionByMode};o!==void 0&&Number.isFinite(o)&&o>0?d[r]=Math.min(1,u/o):delete d[r];const p={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:Gt(p,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(s=>s.workStatusExpandedSections[n]===r?s:{workStatusExpandedSections:{...s.workStatusExpandedSections,[n]:r}})},setMessageQueueExpanded:n=>{e(r=>r.messageQueueExpanded===n?r:{messageQueueExpanded:n})},setWorkStatusScrollTop:n=>{e({workStatusScrollTop:Math.max(0,n)})},setWorkStatusPanelEnabled:n=>{e({workStatusPanelEnabled:n})},setWorkStatusPanelVisible:n=>{e(r=>r.workStatusPanelVisible===n?r:{workStatusPanelVisible:n})},setWorkStatusPanelFits:n=>{e(r=>r.workStatusPanelFits===n?r:n?{workStatusPanelFits:!0,workStatusOverlayOpen:!1}:{workStatusPanelFits:!1})},setWorkStatusOverlayOpen:n=>{e(r=>r.workStatusOverlayOpen===n?r:{workStatusOverlayOpen:n})},setWorkStatusSectionVisible:(n,r)=>{e(s=>{const o=s.workStatusHiddenSections,i=o.includes(n);return r===!i?s:{workStatusHiddenSectionsExplicit:!0,workStatusHiddenSections:r?o.filter(a=>a!==n):[...o,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)],workStatusHiddenSectionsExplicit:!0})},setWorkStatusSectionOrder:n=>{e({workStatusSectionOrder:Ms(n)})},setContextRailSurfaceVisible:(n,r)=>{e(s=>{const o=s.contextRailHiddenSurfaces,i=o.includes(n);return r===!i?s:{contextRailHiddenSurfaces:r?o.filter(a=>a!==n):[...o,n]}})},setContextRailHiddenSurfaces:n=>{e({contextRailHiddenSurfaces:[...new Set(n)]})},setSessionSwitcherOpen:n=>{t().isSessionSwitcherOpen!==n&&e({isSessionSwitcherOpen:n})},setSessionDropdownOpen:n=>{t().isSessionDropdownOpen!==n&&e({isSessionDropdownOpen:n})},setPendingDiffFile:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?s:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:s})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=t();return n&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),n},setIsMobile:n=>{e({isMobile:n})},toggleCommandPalette:()=>{e(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{e({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{e(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{e({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{e({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{e({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{e({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{e({isSessionCreateDialogOpen:n})},setScheduledTasksDialogOpen:n=>{e(n?{isScheduledTasksDialogOpen:!0,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,spacesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isUsageStatsPageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,spacesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isArchivePageOpen:!1})},setUsageStatsPageOpen:n=>{e(n?{isUsageStatsPageOpen:!0,isArchivePageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,spacesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isUsageStatsPageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,spacesPageProjectId:null,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,runOverviewKey:null,openGuestPageId:null}:{worktreesPageProjectId:null})},setSpacesPageProjectId:n=>{e(n?{spacesPageProjectId:n,worktreesPageProjectId:null,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,runOverviewKey:null,openGuestPageId:null}:{spacesPageProjectId:null})},setOpenGuestPage:n=>{e(n?{openGuestPageId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,spacesPageProjectId:null,runOverviewKey:null}:{openGuestPageId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.isUsageStatsPageOpen&&!n.worktreesPageProjectId&&!n.spacesPageProjectId&&!n.runOverviewKey&&!n.openGuestPageId||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,spacesPageProjectId:null,runOverviewKey:null,openGuestPageId:null})},setSettingsDialogOpen:n=>{e(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:n=>{e({isNewWorktreeDialogOpen:n})},setModelSelectorOpen:n=>{e({isModelSelectorOpen:n})},setSidebarSection:n=>{e({sidebarSection:n})},setSettingsPage:n=>{e({settingsPage:n})},setSettingsProvidersClassificationRequested:n=>{e({settingsProvidersClassificationRequested:n})},setSettingsProvidersOpenRequested:n=>{e({settingsProvidersOpenRequested:n})},requestSettingsJump:(n,r=null)=>{e({settingsJumpRequest:{page:n,itemId:r}})},clearSettingsJumpRequest:()=>{e({settingsJumpRequest:null})},setSettingsProvidersConnectRequested:n=>{e({settingsProvidersConnectRequested:n})},setSettingsProjectPath:n=>{const r=n?.trim();e({settingsProjectPath:r||null})},setSettingsProjectsSelectedId:n=>{e({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{e({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{e({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{e({showReasoningTraces:n})},setStreamingAutoFollowEnabled:n=>{e({streamingAutoFollowEnabled:n})},setSessionRecapEnabled:n=>{e({sessionRecapEnabled:n})},setSessionSuggestionEnabled:n=>{e({sessionSuggestionEnabled:n})},setSessionWorkEnabled:n=>{e({sessionWorkEnabled:n})},setSessionWorkAutoOpen:n=>{e({sessionWorkAutoOpen:n})},setSessionGoalEnabled:n=>{e({sessionGoalEnabled:n})},setSessionGoalChecker:n=>{e({sessionGoalChecker:n})},setSessionGoalDefaultBudgetEnabled:n=>{e({sessionGoalDefaultBudgetEnabled:n})},setSessionGoalDefaultBudget:n=>{e({sessionGoalDefaultBudget:n})},setCollapsibleThinkingBlocks:n=>{e({collapsibleThinkingBlocks:n})},setChatRenderMode:n=>{e({chatRenderMode:n})},setActivityRenderMode:n=>{e({activityRenderMode:n})},setShowDeletionDialog:n=>{e({showDeletionDialog:n})},setAutoDeleteEnabled:n=>{e({autoDeleteEnabled:n})},setAutoSaveEnabled:n=>{e({autoSaveEnabled:n})},setAutoDeleteAfterDays:n=>{const r=Math.max(1,Math.min(365,n));e({autoDeleteAfterDays:r})},setSessionRetentionAction:n=>{e(r=>({sessionRetentionAction:r.sessionRetentionOnlyArchived?"delete":n}))},setSessionRetentionOnlyArchived:n=>{e(r=>({sessionRetentionOnlyArchived:n,sessionRetentionAction:n?"delete":r.sessionRetentionAction}))},setAutoDeleteLastRunAt:n=>{e({autoDeleteLastRunAt:n})},setMessageLimit:n=>{const r=Math.max(10,Math.min(500,Math.round(n)));e({messageLimit:r})},setFontSize:n=>{const r=Math.max(50,Math.min(200,n));e({fontSize:r}),t().applyTypography()},setGlobalDraftStarters:n=>{e({globalDraftStarters:n})},setDraftStartersVisible:n=>{e({draftStartersVisible:n})},setTerminalFontSize:n=>{const r=Math.round(n),s=Math.max(9,Math.min(52,r));e({terminalFontSize:s})},setTerminalShell:n=>{e({terminalShell:n})},setTerminalLoginShells:n=>{e({terminalLoginShells:[...new Set(n)]})},setEditorFontSize:n=>{const r=Math.round(n),s=Math.max(9,Math.min(32,r));e({editorFontSize:s})},setUiFont:n=>{e({uiFont:n})},setMonoFont:n=>{e({monoFont:n})},setPadding:n=>{const r=Math.max(50,Math.min(200,n));e({padding:r}),t().applyPadding()},setCornerRadius:n=>{e({cornerRadius:n})},applyTypography:()=>{const{fontSize:n}=t(),r=document.documentElement,s=n/100,o=Object.entries(og);if(s===1){r.style.removeProperty("font-size");for(const[i]of o)r.style.removeProperty(rc(i));return}r.style.fontSize=`${s*100}%`;for(const[i]of o)r.style.removeProperty(rc(i))},applyPadding:()=>{const{padding:n}=t(),r=document.documentElement,s=n/100;if(s===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const o=Math.sqrt(s);r.style.setProperty("--padding-scale",o.toString());const i=1+(s-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:n=>{e({diffLayoutPreference:n})},setDiffFileLayout:(n,r)=>{e(s=>({diffFileLayout:{...s.diffFileLayout,[n]:r}}))},setDiffFileListMode:n=>{e({diffFileListMode:n})},setDiffFileTreeWidth:n=>{e({diffFileTreeWidth:Math.round(n)})},setDiffWrapLines:n=>{e({diffWrapLines:n})},setWalkthroughTocWidth:n=>{e({walkthroughTocWidth:Math.round(n)})},setGitChangesViewMode:n=>{e({gitChangesViewMode:n})},setToolJsonViewMode:n=>{e({toolJsonViewMode:n})},setLinearIssueListStatus:n=>{e({linearIssueListStatus:hc(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:mc(n)})},setLinearIssueListTeamId:n=>{const r=Au(n);e(s=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:gc(s.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=q();e(r=>({linearIssueListTeamId:Tl(n)?yt:r.linearIssueListTeamIdByRuntime[n]??yt}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:yc(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:yt,linearIssueListTeamIdByRuntime:gc(n.linearIssueListTeamIdByRuntime,yt),linearIssueListPriority:"all"}))},setLinearIssueFocus:n=>{const r=n?.trim()??"";e({linearIssueFocus:r||null})},setInputBarOffset:n=>{e({inputBarOffset:n})},setMobileKeyboardMode:n=>{e(r=>r.mobileKeyboardMode===n?r:{mobileKeyboardMode:n})},toggleFavoriteModel:(n,r)=>{e(s=>s.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:s.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...s.favoriteModels]})},reorderFavoriteModel:(n,r,s,o)=>{e(i=>{const a=i.favoriteModels.findIndex(d=>d.providerID===n&&d.modelID===r),c=i.favoriteModels.findIndex(d=>d.providerID===s&&d.modelID===o);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[u]=l.splice(a,1);return u?(l.splice(c,0,u),{favoriteModels:l}):i})},setProviderOrder:n=>{e(r=>{const s=n.filter(i=>typeof i=="string"&&i.length>0),o=r.providerOrder;return o.length===s.length&&o.every((i,a)=>i===s[a])?r:{providerOrder:s}})},toggleHiddenModel:(n,r)=>{e(s=>s.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:s.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...s.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},hideAllModels:(n,r)=>{e(s=>{const o=s.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...o]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(s=>s.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>s.collapsedModelProviders.includes(r)?{collapsedModelProviders:s.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...s.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const s=Array.from(new Set(n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)));s.length!==0&&e(o=>{const i=new Set(s),a=o.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...s]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},addRecentModel:(n,r)=>{e(s=>{const o=s.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...o].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>{if(s.recentAgents.includes(r))return s;const o=s.recentAgents;return{recentAgents:[r,...o].slice(0,5)}})},addRecentEffort:(n,r,s)=>{const o=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!o||!i)return;const a=`${o}/${i}`,c=typeof s=="string"&&s.trim().length>0?s.trim():"default";e(l=>{const u=l.recentEfforts[a]??[];if(u.includes(c))return l;const d=u;return{recentEfforts:{...l.recentEfforts,[a]:[c,...d].slice(0,5)}}})},applyTheme:()=>{const{theme:n}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(s)}else r.classList.add(n)},setRunOverviewKey:n=>{e(n?{runOverviewKey:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,spacesPageProjectId:null,openGuestPageId:null}:{runOverviewKey:null})},requestParallelComposer:(n="")=>{e(r=>({parallelComposerRequest:{id:(r.parallelComposerRequest?.id??0)+1,prompt:n},isSessionSwitcherOpen:!1}))},consumeParallelComposerRequest:n=>{t().parallelComposerRequest?.id===n&&e({parallelComposerRequest:null})},setTimelineDialogOpen:n=>{e({isTimelineDialogOpen:n})},setPromptNavigatorPanelOpen:n=>{e({isPromptNavigatorPanelOpen:n})},togglePromptNavigatorPanel:()=>{e(n=>({isPromptNavigatorPanelOpen:!n.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:n=>{e({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{e({nativeNotificationsEnabled:n})},setNotificationMode:n=>{e({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{e({showTerminalQuickKeysOnDesktop:n})},setSessionTabsEnabled:n=>{e({sessionTabsEnabled:n})},setNotifyOnSubtasks:n=>{e({notifyOnSubtasks:n})},setDockBadgeEnabled:n=>{e({dockBadgeEnabled:n})},setAlwaysShowScrollbars:n=>{e({alwaysShowScrollbars:n})},setNotifyOnCompletion:n=>{e({notifyOnCompletion:n})},setNotifyOnError:n=>{e({notifyOnError:n})},setNotifyOnQuestion:n=>{e({notifyOnQuestion:n})},setNotificationTemplates:n=>{e(r=>({notificationTemplates:typeof n=="function"?n(r.notificationTemplates):n}))},setSummarizeLastMessage:n=>{e({summarizeLastMessage:n})},setSummaryThreshold:n=>{e({summaryThreshold:n})},setSummaryLength:n=>{e({summaryLength:n})},setMaxLastMessageLength:n=>{e({maxLastMessageLength:n})},setPersistChatDraft:n=>{e({persistChatDraft:n})},setShowOpenCodeUpdateNotifications:n=>{e({showOpenCodeUpdateNotifications:n})},setAgentControlToolEnabled:n=>{e({agentControlToolEnabled:n})},setAgentWebToolEnabled:n=>{e({agentWebToolEnabled:n})},setMessageSearchEnabled:n=>{e({messageSearchEnabled:n})},setMessageSearchReasoningEnabled:n=>{e({messageSearchReasoningEnabled:n})},setBrowserProvider:n=>{e({browserProvider:n})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setIsolatedSpacesEnabled:n=>{e({isolatedSpacesEnabled:n})},setPermissionDefaultMode:n=>{e({permissionDefaultMode:n})},setAgentNotifyToolEnabled:n=>{e({agentNotifyToolEnabled:n})},setAgentToolsCodeMode:n=>{e({agentToolsCodeMode:n})},setAgentMemoryFeatureAvailable:n=>{e({agentMemoryFeatureAvailable:n})},setRoutingFeatureAvailable:n=>{e({routingFeatureAvailable:n})},setProjectContextSidebarWidth:n=>{e({projectContextSidebarWidth:n})},markAgentMemoryViewed:(n,r)=>{e(s=>({agentMemoryViewedAt:r>(s.agentMemoryViewedAt[n]??0)?{...s.agentMemoryViewedAt,[n]:r}:s.agentMemoryViewedAt}))},setProjectContextTab:n=>{e({projectContextTab:n})},setInputSpellcheckEnabled:n=>{e({inputSpellcheckEnabled:n})},setLargeTextPasteBehavior:n=>{e({largeTextPasteBehavior:fc(n)})},setEnterToSend:n=>{e({enterToSend:n})},setEnterToSendConfigured:n=>{e({enterToSendConfigured:n})},setWideChatLayoutEnabled:n=>{e({wideChatLayoutEnabled:n})},setCodeBlockLineWrap:n=>{e({codeBlockLineWrap:n})},setShowToolFileIcons:n=>{e({showToolFileIcons:n})},setShowTurnChangedFiles:n=>{e({showTurnChangedFiles:n})},setShowExpandedBashTools:n=>{e({showExpandedBashTools:n})},setShowExpandedEditTools:n=>{e({showExpandedEditTools:n})},setTimeFormatPreference:n=>{e({timeFormatPreference:n})},setWeekStartPreference:n=>{e({weekStartPreference:n})},setDesktopWindowControlsPosition:n=>{e({desktopWindowControlsPosition:n==="left"?"left":"right"})},setDesktopWindowControlsStyle:n=>{e({desktopWindowControlsStyle:n==="traffic-lights"?"traffic-lights":"classic"})},setMermaidRenderingMode:n=>{e({mermaidRenderingMode:n})},setUserMessageRenderingMode:n=>{e({userMessageRenderingMode:n})},setCollapsibleUserMessages:n=>{e({collapsibleUserMessages:n})},setStickyUserHeader:n=>{e({stickyUserHeader:n})},setPromptNavigatorEnabled:n=>{e({promptNavigatorEnabled:n})},setShowSplitAssistantMessageActions:n=>{e({showSplitAssistantMessageActions:n})},setAllowPromptingSubagentSessions:n=>{e({allowPromptingSubagentSessions:n})},setReportUsage:n=>{e({reportUsage:n})},viewPagerPage:"center",setViewPagerPage:n=>{e({viewPagerPage:n}),e({isSessionSwitcherOpen:n==="left"})},setShortcutOverride:(n,r)=>{e(s=>({shortcutOverrides:{...s.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{e(r=>{const s={...r.shortcutOverrides};return delete s[n],{shortcutOverrides:s}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:n=>{e({fileEditorKeymap:pc(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:Ni(),version:21,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<21&&n.workStatusHiddenSectionsExplicit!==!0&&(n.workStatusHiddenSections=Array.isArray(n.workStatusHiddenSections)?n.workStatusHiddenSections.filter(r=>r!=="telemetry"):[],n.workStatusHiddenSectionsExplicit=!1),t<16&&(delete n.activeMainTab,delete n.activeSurface),t<17&&delete n.expandedEditorToolbar,t<18&&delete n.shortcutOverrides,t<14){const r=n.contextPanelByDirectory;if(r&&typeof r=="object")for(const s of Object.values(r)){if(!s||typeof s!="object")continue;const o=s,i=o.widthByMode;if(i&&typeof i=="object"){const l=i;l.preview!==void 0&&(l.browser===void 0&&(l.browser=l.preview),delete l.preview)}if(!Array.isArray(o.tabs))continue;const a=new Set,c=[];for(const l of o.tabs){if(!l||typeof l!="object")continue;const u=l;if(u.mode!=="preview"){typeof u.id=="string"&&a.add(u.id),c.push(u);continue}const d=typeof u.targetPath=="string"?u.targetPath:"",p=typeof u.dedupeKey=="string"&&u.dedupeKey.trim()?u.dedupeKey.trim():d||"browser",m=p==="browser"?"browser":`browser:${p}`;a.has(m)||(a.add(m),c.push({...u,mode:"browser",id:m,dedupeKey:p}))}if(o.tabs=c,typeof o.activeTabId=="string"&&o.activeTabId.startsWith("preview")){const l=c.find(u=>typeof u.id=="string");o.activeTabId=l&&typeof l.id=="string"?l.id:null}}}if(t<13&&typeof n.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const s=localStorage.getItem("openchamber:files:auto-save-enabled");s!==null&&(r=s!=="false",localStorage.removeItem("openchamber:files:auto-save-enabled"))}}catch{r=!0}n.autoSaveEnabled=r}if(t<12&&(n.desktopWindowControlsPosition==="auto"||n.desktopWindowControlsPosition==null)&&(n.desktopWindowControlsPosition="right"),t<11&&n.terminalFontSize===13&&(n.terminalFontSize=14),t<10&&delete n.diffViewMode,t<9&&((!n.workStatusExpandedSections||typeof n.workStatusExpandedSections!="object")&&(n.workStatusExpandedSections={}),(typeof n.workStatusScrollTop!="number"||!Number.isFinite(n.workStatusScrollTop))&&(n.workStatusScrollTop=0),typeof n.workStatusPanelEnabled!="boolean"&&(n.workStatusPanelEnabled=!0),Array.isArray(n.workStatusHiddenSections)||(n.workStatusHiddenSections=[]),(typeof n.notesPanelHeight!="number"||!Number.isFinite(n.notesPanelHeight))&&(n.notesPanelHeight=112)),t<1&&Zg(n.notificationTemplates)&&(n.notificationTemplates={completion:{...Pt.completion},error:{...Pt.error},question:{...Pt.question},subtask:{...Pt.subtask}}),t<3){const r=new Set([90,120,180,220]),s=n.memoryLimitHistorical,o=n.memoryLimitActiveSession;typeof s=="number"&&!r.has(s)?n.messageLimit=s:typeof o=="number"&&!r.has(o)&&(n.messageLimit=o),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if(delete n.isRightSidebarOpen,delete n.rightSidebarWidth,delete n.rightSidebarTab,n.contextPanelByDirectory=Co(n.contextPanelByDirectory),t<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,s={};for(const[o,i]of Object.entries(r))typeof o=="string"&&typeof i=="string"&&(s[o]=i);n.shortcutOverrides=s}return t<6&&(n.contextPanelByDirectory=Co(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=Co(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=hc(n.linearIssueListStatus),n.linearIssueListAssignee=mc(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=Xg(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=yc(n.linearIssueListPriority),n.fileEditorKeymap=pc(n.fileEditorKeymap),n.largeTextPasteBehavior=fc(n.largeTextPasteBehavior),n.toolJsonViewMode!=="summary"&&n.toolJsonViewMode!=="formatted"&&n.toolJsonViewMode!=="raw"&&(n.toolJsonViewMode="summary"),typeof n.autoSaveEnabled!="boolean"&&(n.autoSaveEnabled=!0),n.contextRailHiddenSurfaces=Array.isArray(n.contextRailHiddenSurfaces)?n.contextRailHiddenSurfaces.filter(r=>typeof r=="string"&&r.trim()!==""):[],n.contextRailOrder=Array.isArray(n.contextRailOrder)?n.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""):[],n},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextRailHiddenSurfaces:e.contextRailHiddenSurfaces,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorVisible:e.contextEditorVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,notesPanelHeight:e.notesPanelHeight,workStatusExpandedSections:e.workStatusExpandedSections,messageQueueExpanded:e.messageQueueExpanded,workStatusScrollTop:e.workStatusScrollTop,workStatusPanelEnabled:e.workStatusPanelEnabled,workStatusHiddenSections:e.workStatusHiddenSections,workStatusSectionOrder:e.workStatusSectionOrder,workStatusHiddenSectionsExplicit:e.workStatusHiddenSectionsExplicit,isSessionSwitcherOpen:e.isSessionSwitcherOpen,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,streamingAutoFollowEnabled:e.streamingAutoFollowEnabled,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,sessionWorkEnabled:e.sessionWorkEnabled,sessionWorkAutoOpen:e.sessionWorkAutoOpen,sessionGoalEnabled:e.sessionGoalEnabled,sessionGoalChecker:e.sessionGoalChecker,sessionGoalDefaultBudgetEnabled:e.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:e.sessionGoalDefaultBudget,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,chatRenderMode:e.chatRenderMode,activityRenderMode:e.activityRenderMode,showDeletionDialog:e.showDeletionDialog,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,sessionRetentionOnlyArchived:e.sessionRetentionOnlyArchived,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,providerOrder:e.providerOrder,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,diffWrapLines:e.diffWrapLines,diffFileListMode:e.diffFileListMode,diffFileTreeWidth:e.diffFileTreeWidth,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,toolJsonViewMode:e.toolJsonViewMode,linearIssueListStatus:e.linearIssueListStatus,linearIssueListAssignee:e.linearIssueListAssignee,linearIssueListTeamIdByRuntime:e.linearIssueListTeamIdByRuntime,linearIssueListPriority:e.linearIssueListPriority,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,sessionTabsEnabled:e.sessionTabsEnabled,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,alwaysShowScrollbars:e.alwaysShowScrollbars,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,agentControlToolEnabled:e.agentControlToolEnabled,agentWebToolEnabled:e.agentWebToolEnabled,messageSearchEnabled:e.messageSearchEnabled,messageSearchReasoningEnabled:e.messageSearchReasoningEnabled,browserProvider:e.browserProvider,agentMemoryToolEnabled:e.agentMemoryToolEnabled,agentNotifyToolEnabled:e.agentNotifyToolEnabled,agentToolsCodeMode:e.agentToolsCodeMode,isolatedSpacesEnabled:e.isolatedSpacesEnabled,permissionDefaultMode:e.permissionDefaultMode,agentMemoryViewedAt:e.agentMemoryViewedAt,projectContextSidebarWidth:e.projectContextSidebarWidth,inputSpellcheckEnabled:e.inputSpellcheckEnabled,largeTextPasteBehavior:e.largeTextPasteBehavior,enterToSend:e.enterToSend,enterToSendConfigured:e.enterToSendConfigured,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,inputBarOffset:e.inputBarOffset,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,allowPromptingSubagentSessions:e.allowPromptingSubagentSessions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),uy=e=>{if(!e||typeof e!="object")return null;const t={};return typeof e.showReasoningTraces=="boolean"&&(t.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&(t.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),Object.keys(t).length>0?t:null},dy=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},fy=e=>{const t=T.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},py=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=dy(t);return uy(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},hy=768,my=800,gy=()=>{if(typeof window>"u")return!1;const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches||window.matchMedia("(hover: none)").matches:!1,t=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return e||t>0},yy=()=>{if(typeof window>"u")return!1;const e=new URLSearchParams(window.location.search).get("surface");return e==="mobile"||e==="desktop"},Mu=()=>{if(typeof window>"u")return!1;const e=Math.min(window.innerWidth||Number.POSITIVE_INFINITY,window.screen?.width||Number.POSITIVE_INFINITY);return Number.isFinite(e)&&e<=hy&&gy()},_u=()=>{if(typeof window>"u")return"desktop";const e=window.__OPENCHAMBER_SURFACE__;if(e==="mobile"||e==="desktop")return e;const t=new URLSearchParams(window.location.search).get("surface");return t==="mobile"||t==="desktop"?t:Pr()?"mobile":He()||Me()?"desktop":Mu()?"mobile":"desktop"},HE=()=>{const e=_u();return typeof window<"u"&&(window.__OPENCHAMBER_SURFACE__=e),e},wy=()=>_u()==="mobile",$E=()=>{if(typeof window>"u")return()=>{};if(Pr()||He()||Me())return()=>{};if(yy())return()=>{};let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null;const n=window.__OPENCHAMBER_SURFACE__,r=Mu()?"mobile":"desktop";n&&n!==r&&(window.__OPENCHAMBER_SURFACE__=void 0,window.location.reload())},my)};return window.addEventListener("resize",t),()=>{e&&clearTimeout(e),window.removeEventListener("resize",t)}},Lu="surface",Gi=()=>{try{if(Me())return"vscode";if(He())return"desktop";if(Pr()||wy())return"mobile"}catch{}return"web"},Sy=()=>Gi()==="mobile"?"timeline":"projects",by=(e,t)=>{const n=e??{};return t<2&&(n.projectSortOrder="manual"),t<3&&n.projectSortOrder==="recent"&&(n.projectSortOrder="manual"),t<4&&delete n.displayMode,t<6&&delete n.sessionGroupingMode,t<7&&delete n.stickyZoneHeaders,t<8&&(n.showRecentSection=!1),t<9&&!n.worktreeSortOrder&&(n.worktreeSortOrder="manual"),n},Zo=ut()(kr(e=>({animatedActivityIndicators:!1,setAnimatedActivityIndicators:t=>e({animatedActivityIndicators:t}),projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sidebarViewMode:Sy(),setSidebarViewMode:t=>e({sidebarViewMode:t}),showRecentSection:!1,showArchivedSessions:!1,projectSortOrder:"manual",worktreeSortOrder:"manual",setShowRecentSection:t=>e({showRecentSection:t}),setShowArchivedSessions:t=>e({showArchivedSessions:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection})),toggleArchivedSessions:()=>e(t=>({showArchivedSessions:!t.showArchivedSessions})),setProjectSortOrder:t=>e({projectSortOrder:t}),setWorktreeSortOrder:t=>e({worktreeSortOrder:t})}),{name:"session-display-mode",version:9,migrate:by})),Fu="directoryTreeShowHidden",ei="directory-show-hidden-change",ti=()=>{if(typeof window>"u")return!0;try{const e=xr().getItem(Fu);return e===null?!0:e==="true"}catch{return!0}},vy=()=>{typeof window>"u"||window.dispatchEvent(new Event(ei))},Ty=()=>ti(),ky=(e,t={})=>{if(!(typeof window>"u")){try{xr().setItem(Fu,e?"true":"false"),vy()}catch{}t.persist!==!1&&wt({directoryShowHidden:e})}},zE=()=>{const e=Hs.c(2),[t,n]=An.useState(ti);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(ti())};return window.addEventListener("storage",o),window.addEventListener(ei,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(ei,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),An.useEffect(r,s),t},ju=[{name:"explore",icon:"compass-3",labelKey:"chat.draftPresets.explore.label",command:"/explore"},{name:"catch-up",icon:"history",labelKey:"chat.draftPresets.catchup.label",command:"/catch-up"},{name:"weigh",icon:"scales-3",labelKey:"chat.draftPresets.weigh.label",command:"/weigh"},{name:"plan-feature",icon:"survey",labelKey:"chat.draftPresets.plan.label",command:"/plan-feature"},{name:"craft-goal",icon:"target",labelKey:"chat.draftPresets.craftGoal.label",command:"/craft-goal"},{name:"schedule-task",icon:"calendar-schedule",labelKey:"chat.draftPresets.scheduleTask.label",command:"/schedule-task"},{name:"debug",icon:"bug",labelKey:"chat.draftPresets.debug.label",command:"/debug"},{name:"review",icon:"search-eye",labelKey:"chat.draftPresets.review.label",command:"/workspace-review"}],Ey=new Map(ju.map(e=>[e.name,e])),WE=e=>Ey.get(e),GE=ju.map(e=>({type:"command",name:e.name})),qE="terminal-box",KE="book-open",VE=e=>`${e.type}:${e.name}`,JE=(e,t)=>e.type===t.type&&e.name===t.name,YE=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Py=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const s=r,o=s.type==="command"||s.type==="skill"?s.type:null,i=typeof s.name=="string"?s.name.trim():"";if(!o||!i)continue;const a=`${o}:${i}`;n.has(a)||(n.add(a),t.push({type:o,name:i}))}return t},Uu="filesViewShowGitignored",ni="files-view-show-gitignored-change",ri=()=>{if(typeof window>"u")return!1;try{return xr().getItem(Uu)==="true"}catch{return!1}},Ay=()=>{typeof window>"u"||window.dispatchEvent(new Event(ni))},Iy=()=>ri(),xy=(e,t={})=>{if(!(typeof window>"u")){try{xr().setItem(Uu,e?"true":"false"),Ay()}catch{}t.persist!==!1&&wt({filesViewShowGitignored:e})}},QE=()=>{const e=Hs.c(2),[t,n]=An.useState(ri);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(ri())};return window.addEventListener("storage",o),window.addEventListener(ni,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(ni,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),An.useEffect(r,s),t},Nu="session",Bu=40,Ry=1,Cy=100,Hu=e=>e==="global"||e==="session",qi=e=>e!=null&&Number.isInteger(e)&&e>=Ry&&e<=Cy,Oy=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Ki=e=>e==="auto"||typeof e=="string"&&Oy.includes(e),Tn="openchamber-input-history.v1",Dy=8,My=50,_y=[40,25,10,5,1],Oo=Object.freeze([]);let mt=null,Sc=0;const cr=(e=Nu,t=Bu)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),$u=()=>(Sc+=1,Date.now()*1e3+Sc),zu=e=>JSON.stringify([e]),si=(e,t,n)=>JSON.stringify([e,t,n]),Vi=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},Ly=()=>{const e=Vi(),t=Je?JSON.stringify(ms(Je.base)):mt;if(!e)return t;try{return e.getItem(Tn)??(Je?null:mt)}catch{return t}},bc=lt(f(),ye()),Fy=w({key:f().min(1),source:Ze([O("file-url"),O("vscode-file")]),filename:f().min(1),mimeType:f().min(1),size:E().finite().nonnegative(),reference:f().min(1)}),jy=w({text:f(),attachmentKeys:M(f()),restorableAttachments:M(Fy),submittedAt:E().finite().nonnegative()}),Uy=w({touchedAt:E().finite().nonnegative(),entries:M(ye())}),Ny=(e,t)=>{try{const n=JSON.parse(e),s=(t===1?fa([f().trim().min(1)]):fa([f().trim().min(1),f().trim().min(1),f().trim().min(1)])).safeParse(n);if(!s.success)return null;if(t===3){const o=Ne(s.data[1]);if(!o||o!==s.data[1])return null}return s.data}catch{return null}},vc=(e,t)=>{const n=[];for(const[r,s]of Object.entries(e)){if(!Ny(r,t))continue;const o=Uy.safeParse(s);if(!o.success)continue;const i=o.data.entries.map(a=>jy.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:o.data.touchedAt,entries:i}])}return Object.fromEntries(n)},By=()=>{const e=Ly();if(e===null)return cr();try{const t=JSON.parse(e),n=w({version:O(1),entryLimit:E().int().optional(),scope:Ze([O("global"),O("session")]).optional(),global:bc.default({}),session:bc.default({})}).safeParse(t);return n.success?{entryLimit:qi(n.data.entryLimit)?n.data.entryLimit:Bu,scope:n.data.scope??Nu,globalBuckets:vc(n.data.global,1),sessionBuckets:vc(n.data.session,3)}:cr()}catch{const t=Vi();if(t)try{t.removeItem(Tn)}catch{}return mt=null,cr()}};let Je=null,hs=cr();const Tc=(e,t,n)=>{const r={...e};for(const s of new Set([...Object.keys(t),...Object.keys(n)])){if(JSON.stringify(t[s])===JSON.stringify(n[s]))continue;const o=n[s];if(!o){delete r[s];continue}const i=new Set((t[s]?.entries??[]).map(u=>JSON.stringify(u))),a=new Set(o.entries.map(u=>JSON.stringify(u))),c=(e[s]?.entries??[]).filter(u=>{const d=JSON.stringify(u);return!i.has(d)||a.has(d)}),l=new Set(c.map(u=>JSON.stringify(u)));for(const u of o.entries){const d=JSON.stringify(u);!i.has(d)&&!l.has(d)&&c.push(u)}c.sort((u,d)=>u.submittedAt-d.submittedAt),r[s]={touchedAt:Math.max(o.touchedAt,e[s]?.touchedAt??0),entries:c}}return r},Xn=()=>{const e=By();if(hs=e,!Je)return e;const{base:t,value:n}=Je;return oi({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:Tc(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:Tc(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},Wu=(e,t)=>e.slice(Math.max(0,e.length-t)),kc=(e,t,n)=>{const r=Object.entries(e).map(([s,o])=>[s,{touchedAt:o.touchedAt,entries:Wu(o.entries,n)}]).sort((s,o)=>o[1].touchedAt-s[1].touchedAt).slice(0,t);return Object.fromEntries(r)},oi=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:kc(e.globalBuckets,Dy,t),sessionBuckets:kc(e.sessionBuckets,My,t)}),ms=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Ec=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Zn=e=>{const t=oi(e),n=JSON.stringify(ms(t));Je={base:hs,value:t};const r=Vi();if(!r)return mt=n,t;try{return r.setItem(Tn,n),Je=null,mt=n,t}catch(i){if(!(i instanceof Error)||!Ec(i))return mt=n,t}try{r.removeItem(Tn)}catch{}for(const i of _y){const a=oi(t,i),c=JSON.stringify(ms(a));try{return r.setItem(Tn,c),Je=null,mt=c,a}catch(l){if(!(l instanceof Error)||!Ec(l))return Je={base:hs,value:a},mt=c,a}}const s=cr(t.scope,t.entryLimit),o=JSON.stringify(ms(s));try{r.setItem(Tn,o),Je=null}catch{Je={base:hs,value:s}}return mt=o,s},Hy=(e,t,n)=>{const r=e.trim(),s=Ne(t),o=n.trim();return!r||!s||!o?null:{runtimeKey:r,directory:s,sessionId:o}},Gu=e=>e.source==="vscode"&&e.vscodeSource==="file"?Ne(e.vscodePath??null):e.dataUrl.trim()||null,$y=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),ii=e=>{const t=Gu(e),n=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),n].join("|")},zy=e=>{const t=Gu(e);return!t||!$y(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:ii(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:ii(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},Wy=(e,t)=>({text:e,attachmentKeys:t.map(ii),restorableAttachments:t.map(zy).filter(n=>n!==null)}),Gy=(e,t)=>e.length===t.length&&e.every((n,r)=>{const s=t[r];return s!==void 0&&n.key===s.key&&n.source===s.source&&n.filename===s.filename&&n.mimeType===s.mimeType&&n.size===s.size&&n.reference===s.reference}),qy=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&Gy(e.restorableAttachments,t.restorableAttachments),Pc=(e,t,n,r)=>{const s=e?[...e.entries]:[];for(const o of t){const i=s.at(-1);qy(i,o)||s.push({text:o.text,attachmentKeys:[...o.attachmentKeys],restorableAttachments:o.restorableAttachments.map(a=>({...a})),submittedAt:$u()})}return{touchedAt:n,entries:Wu(s,r)}},Ky=Zn(Xn()),er=ut(e=>({...Ky,applyEntryLimit:t=>{qi(t)&&e(n=>{const r=Xn();if(r.entryLimit===t)return{...n,...r};const s=Zn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},applyScope:t=>{Hu(t)&&e(n=>{const r=Xn();if(r.scope===t)return{...n,...r};const s=Zn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const s=Xn(),o=$u(),i=zu(t.runtimeKey),a=si(t.runtimeKey,t.directory,t.sessionId),c=Zn({entryLimit:s.entryLimit,scope:s.scope,globalBuckets:{...s.globalBuckets,[i]:Pc(s.globalBuckets[i],n,o,s.entryLimit)},sessionBuckets:{...s.sessionBuckets,[a]:Pc(s.sessionBuckets[a],n,o,s.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=Xn(),s=si(t.runtimeKey,t.directory,t.sessionId);if(!(s in r.sessionBuckets))return{...n,...r};const o={...r.sessionBuckets};delete o[s];const i=Zn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:o});return{...n,...i}})}})),XE=(e,t)=>t?e.scope==="session"?e.sessionBuckets[si(t.runtimeKey,t.directory,t.sessionId)]?.entries??Oo:e.globalBuckets[zu(t.runtimeKey)]?.entries??Oo:Oo,Vy=w({text:f(),prefix:f(),suffix:f(),start:E()}),Ac=32,Jy=200,Yy="[data-chat-quote-root]";function ZE(e,t){return e.querySelector(`[data-message-id="${CSS.escape(t)}"]`)?.querySelector(Yy)??null}function Ic(e,t,n){const r=e.ownerDocument.createRange();return r.setStart(e,0),r.setEnd(t,n),r.toString().length}function eP(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))return null;const n=e.textContent??"",r=Ic(e,t.startContainer,t.startOffset),s=Ic(e,t.endContainer,t.endOffset),o=n.slice(r,s);return o.trim()?{text:o,prefix:n.slice(Math.max(0,r-Ac),r),suffix:n.slice(s,s+Ac),start:r}:null}function Qy(e,t){if(!t.text)return null;const n=[];for(let s=e.indexOf(t.text);s!==-1&&n.length<Jy;s=e.indexOf(t.text,s+1))n.push(s);if(n.length<=1)return n[0]??null;if(!t.prefix&&!t.suffix)return null;const r=n.filter(s=>s>=t.prefix.length&&e.startsWith(t.prefix,s-t.prefix.length)&&e.startsWith(t.suffix,s+t.text.length));return r.length===0?null:r.reduce((s,o)=>Math.abs(o-t.start)<Math.abs(s-t.start)?o:s)}function qu(e,t){for(let n=e.firstChild;n;n=n.nextSibling)n.nodeType===3?t.push(n):qu(n,t);return t}function tP(e,t){const n=Qy(e.textContent??"",t);if(n===null)return null;const r=n+t.text.length,s=e.ownerDocument.createRange();let o=0,i=!1;for(const a of qu(e,[])){const c=a.data.length;if(!i&&n<o+c&&(s.setStart(a,n-o),i=!0),i&&r<=o+c)return s.setEnd(a,r-o),s;o+=c}return null}function nP(e){return{text:e.trim(),prefix:"",suffix:"",start:0}}const Xy=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Zy=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
5
+ `).replace(/^\n+|\n+$/g,"");if(!t||!n||!r)return null;const s=Math.max(1,Math.floor(e.startLine));return{terminalId:t,terminalLabel:n,startLine:s,endLine:Math.max(s,Math.floor(e.endLine)),text:r}},ew=(e,t)=>{const n=t.map(Zy).filter(o=>o!==null);if(n.length===0)return e;const s=["<terminal_context>",...n.flatMap((o,i)=>[`- ${o.terminalLabel} lines ${o.startLine}-${o.endLine}:`,...o.text.split(`
6
+ `).map((a,c)=>` ${o.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
7
+ `);return e.trim()?`${e.trim()}
8
+
9
+ ${s}`:s},rP=e=>{const t=Xy.exec(e);if(!t)return{visibleText:e,contexts:[]};const n=[];let r=null;for(const s of(t[1]??"").split(`
10
+ `)){const o=/^- (.+) lines (\d+)-(\d+):$/.exec(s);if(o){r&&n.push(r),r={terminalLabel:o[1],startLine:Number(o[2]),endLine:Number(o[3]),text:""};continue}const i=/^\s{2}\d+ \| ?(.*)$/.exec(s);r&&i&&(r.text+=`${r.text?`
11
+ `:""}${i[1]}`)}return r&&n.push(r),{visibleText:e.slice(0,t.index).trimEnd(),contexts:n}},Ji="openchamberContext",Yi="opencodeComment";function tw(e){switch(e.kind){case"code-comment":{const t=`lines ${e.startLine}-${e.endLine}`,n=e.source==="diff"&&e.side?` (${e.side})`:"";return`Comment on \`${e.fileLabel}\` ${t}${n}:
12
+ \`\`\`${e.language}
13
+ ${e.code}
14
+ \`\`\`
15
+
16
+ ${e.text}`}case"terminal":return ew("",[{terminalId:e.terminalId,terminalLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,text:e.output}]);case"browser-annotation":return e.text?`${e.prompt}
17
+
18
+ ${e.text}`:e.prompt;case"pr-comment":return`Attached GitHub PR comment (${e.label}):
19
+
20
+ ${e.body}${e.text?`
21
+
22
+ ${e.text}`:""}`;case"file-quote":{const t=e.startLine!=null&&e.endLine!=null?` lines ${e.startLine}-${e.endLine}`:"",n=e.quote.split(`
23
+ `).map(r=>`> ${r}`).join(`
24
+ `);return`Comment on this fragment of \`${e.fileLabel}\`${t}:
25
+ ${n}${e.text?`
26
+
27
+ ${e.text}`:""}`}case"chat-quote":return`Comment on this fragment of an earlier message in this conversation:
28
+ ${e.quote.split(`
29
+ `).map(n=>`> ${n}`).join(`
30
+ `)}${e.text?`
31
+
32
+ ${e.text}`:""}`;case"pr-check":return`Attached failed GitHub PR check (${e.label}):
33
+ \`\`\`
34
+ ${e.output}
35
+ \`\`\`${e.text?`
36
+
37
+ ${e.text}`:""}`;case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return""}}function sP(e,t){const n=t??tw(e),r={[Ji]:e};return e.kind==="code-comment"&&(r[Yi]={path:e.fileLabel,selection:{startLine:e.startLine,endLine:e.endLine,startChar:0,endChar:0},comment:e.text,preview:e.code,origin:e.source==="diff"?"review":"file"}),{text:n,metadata:r}}function oP(e){switch(e.source){case"terminal":return{kind:"terminal",terminalId:e.terminalId??"",terminalLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,output:e.code};case"preview-annotation":return{kind:"browser-annotation",pageUrl:e.fileLabel,prompt:e.code,text:e.text};case"pr-comment":return{kind:"pr-comment",label:e.fileLabel,body:e.code,text:e.text};case"pr-check":return{kind:"pr-check",label:e.fileLabel,output:e.code,text:e.text};case"file-quote":{const t={kind:"file-quote",fileLabel:e.fileLabel,quote:e.code,text:e.text};return e.startLine>0&&e.endLine>0&&(t.startLine=e.startLine,t.endLine=e.endLine),t}case"chat-quote":{const t={kind:"chat-quote",quote:e.code,text:e.text};return e.fileLabel&&(t.messageId=e.fileLabel),e.anchor&&(t.anchor=e.anchor),t}case"diff":case"file":case"plan":{const t={kind:"code-comment",source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,language:e.language,code:e.code,text:e.text};return e.source==="diff"&&e.side&&(t.side=e.side),t}}}const Ku=vt("kind",[w({kind:O("code-comment"),source:H(["diff","file","plan"]),fileLabel:f(),startLine:E(),endLine:E(),side:H(["original","modified"]).optional(),language:f(),code:f(),text:f()}),w({kind:O("terminal"),terminalId:f(),terminalLabel:f(),startLine:E(),endLine:E(),output:f()}),w({kind:O("browser-annotation"),pageUrl:f(),prompt:f(),text:f()}),w({kind:O("pr-comment"),label:f(),body:f(),text:f()}),w({kind:O("pr-check"),label:f(),output:f(),text:f()}),w({kind:O("file-quote"),fileLabel:f(),startLine:E().optional(),endLine:E().optional(),quote:f(),text:f()}),w({kind:O("chat-quote"),messageId:f().optional(),anchor:Vy.optional(),quote:f(),text:f()}),w({kind:O("github-issue"),number:E().int().positive(),title:f(),url:f()}),w({kind:O("github-pr"),number:E().int().positive(),title:f(),url:f()}),w({kind:O("linear-issue"),identifier:f().min(1),title:f(),url:f()}),w({kind:O("guest-issue"),providerId:f().min(1),id:f().min(1),title:f(),url:f(),data:pa().optional()}),w({kind:O("guest-pr"),providerId:f().min(1),id:f().min(1),title:f(),url:f(),data:pa().optional()})]),Vu=w({path:f(),selection:w({startLine:E().finite(),endLine:E().finite(),startChar:E().finite().optional(),endChar:E().finite().optional()}).optional(),comment:f(),preview:f().optional(),origin:H(["file","review"]).optional()}),nw=w({[Ji]:Ku,[Yi]:Vu.optional()});function iP(e){if(e.type!==void 0&&e.type!=="text")return null;const t=Ku.safeParse(e.metadata?.[Ji]);if(t.success)return t.data;const n=Vu.safeParse(e.metadata?.[Yi]);if(n.success){const r=n.data;return r.selection?{kind:"code-comment",source:r.origin==="review"?"diff":"file",fileLabel:r.path,startLine:r.selection.startLine,endLine:r.selection.endLine,language:"",code:r.preview??"",text:r.comment}:{kind:"file-quote",fileLabel:r.path,quote:r.preview??"",text:r.comment}}return null}function aP(e){switch(e.kind){case"code-comment":{const t={source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,code:e.code,language:e.language,text:e.text};return e.side&&(t.side=e.side),t}case"terminal":return{source:"terminal",fileLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,code:e.output,language:"",text:"",terminalId:e.terminalId};case"browser-annotation":return{source:"preview-annotation",fileLabel:e.pageUrl,startLine:0,endLine:0,code:e.prompt,language:"",text:e.text};case"pr-comment":return{source:"pr-comment",fileLabel:e.label,startLine:0,endLine:0,code:e.body,language:"",text:e.text};case"pr-check":return{source:"pr-check",fileLabel:e.label,startLine:0,endLine:0,code:e.output,language:"",text:e.text};case"file-quote":return{source:"file-quote",fileLabel:e.fileLabel,startLine:e.startLine??0,endLine:e.endLine??0,code:e.quote,language:"",text:e.text};case"chat-quote":return{source:"chat-quote",fileLabel:e.messageId??"",startLine:0,endLine:0,code:e.quote,language:"",text:e.text,anchor:e.anchor};case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return null}}function rw(e){switch(e.kind){case"code-comment":return e.text.trim()||e.code.trim()||e.fileLabel;case"chat-quote":case"file-quote":return e.text.trim()||e.quote;case"browser-annotation":return e.text.trim()||e.prompt.trim()||e.pageUrl;case"pr-comment":return e.text.trim()||e.body.trim()||e.label;case"pr-check":return e.text.trim()||e.label.trim()||e.output;case"terminal":return e.output.trim()||e.terminalLabel;case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return e.title.trim()||e.url}}function sw(e){let t=e.content.trim()||e.contextPreview?.trim()||"";if(!t){for(const r of e.context??[])if(r.kind!=="instruction"&&(t=(r.kind==="context"?rw(r.metadata.openchamberContext):r.text).trim(),t))break}t||=e.attachments?.[0]?.filename??"";const n=t.split(`
38
+ `,1)[0];return n.slice(0,100)+(t.length>n.length||n.length>100?"...":"")}const Ju="queue",ow=e=>e==="steer"||e==="queue",iw=(e,t)=>e==="immediate"?"steer":ow(e)?e:t===!1?"steer":t===!0?"queue":Ju,Rt=()=>!Me(),xc=50,ai=(e,t,n=q())=>{const r=Ne(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},$e=e=>`${e.runtimeKey}
39
+ ${e.directory}
40
+ ${e.sessionId}`,Xt=e=>{const[t,n,...r]=e.split(`
41
+ `);return ai(r.join(`
42
+ `),n,t)},aw=w({providerID:f().min(1),modelID:f().min(1),agent:f().optional(),variant:f().optional()}),cw=w({id:f(),filename:f(),mimeType:f(),size:E(),source:H(["local","server","vscode"]),serverPath:f().optional(),dataUrl:f().optional()}),lw=vt("kind",[w({kind:O("context"),text:f(),metadata:nw,instructions:f().optional()}),w({kind:O("instruction"),text:f()}),w({kind:O("synthetic"),text:f()})]),Qi=w({id:f().min(1),createdAt:E(),content:f(),text:f(),agentMention:f().optional(),attachments:M(cw),context:M(lw).optional(),contextPreview:f().optional(),sendConfig:aw}),Xi=w({sessionId:f().min(1),directory:f(),items:M(Qi),sendingId:f().nullable()}),Rc=w({revision:E(),sessions:M(Xi)}),lr=w({revision:E(),session:Xi}),uw=lr.extend({item:Qi}),dw=lr.extend({items:M(Qi)}),fw=e=>{const t=e.indexOf(",");if(!e.startsWith("data:")||t===-1)return null;const n=e.slice(5,t),r=e.slice(t+1);try{if(n.endsWith(";base64")){const i=atob(r),a=new ArrayBuffer(i.length),c=new Uint8Array(a);for(let l=0;l<i.length;l+=1)c[l]=i.charCodeAt(l);return a}const s=new TextEncoder().encode(decodeURIComponent(r)),o=new ArrayBuffer(s.byteLength);return new Uint8Array(o).set(s),o}catch{return null}},pw=e=>{const t=e.dataUrl??"",n=t?fw(t):null,r={id:e.id,file:new File(n?[n]:[],e.filename,{type:e.mimeType}),dataUrl:t,mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source};return e.serverPath&&(r.serverPath=e.serverPath),r},ts=e=>{const t={id:e.id,content:e.content,text:e.text,createdAt:e.createdAt,sendConfig:{...e.sendConfig}};return e.agentMention&&(t.agentMention=e.agentMention),e.attachments.length>0&&(t.attachments=e.attachments.map(pw)),e.context&&(t.context=e.context),e.contextPreview&&(t.contextPreview=e.contextPreview),t},hw=e=>{const t={id:e.id,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source,dataUrl:e.dataUrl};return e.serverPath&&(t.serverPath=e.serverPath),t},Cc=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(s=>!!s.dataUrl).map(hw),context:e.context??[],sendConfig:t};e.agentMention&&(n.agentMention=e.agentMention);const r=sw({content:"",context:e.context});return r&&(n.contextPreview=r),n},qt=async(e,t,n)=>{const r=await g(t,n);if(!r.ok){const o=new Error(`Message queue request failed (${r.status})`);throw o.status=r.status,o}const s=e.safeParse(await r.json());if(!s.success)throw new Error("Invalid message queue response");return s.data},At=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},It=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,Do=new Set,Oc=new Map,st=new Map,ns=new Map;let Mo=0;const Dc=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),mw=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:Dc(n.queuedMessages??{}),quarantinedLegacyMessages:Dc({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:iw(n.followUpBehavior,n.queueModeEnabled??null)}},ot=(e,t)=>{const{[t]:n,...r}=e;return r},rs=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(s=>s.id!==n);return r.length===0?{queuedMessages:ot(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},gw=(e,t,n,r)=>{let s=e.queuedMessages,o=e.sendingIds;for(const i of new Set([...Object.keys(s),...Object.keys(o)])){const a=Xt(i);a?.runtimeKey!==t||a.sessionId!==n||(st.get(i)??-1)>r||(st.set(i,r),s=ot(s,i),o=ot(o,i))}return{queuedMessages:s,sendingIds:o}},ci=ut()(_n(kr((e,t)=>{let n=null,r=!1;const s=(a,c,l)=>{if(l!==q()||(ns.get(l)??-1)>c)return;const u=ai(a.sessionId,a.directory,l);if(!u){if(a.items.length>0)return;e(p=>gw(p,l,a.sessionId,c));return}const d=$e(u);(st.get(d)??-1)>c||(st.set(d,c),e(p=>{const m=a.items.map(ts),y=m.length>0?{...p.queuedMessages,[d]:m}:ot(p.queuedMessages,d),b=a.sendingId?{...p.sendingIds,[d]:[a.sendingId]}:ot(p.sendingIds,d);return{queuedMessages:y,sendingIds:b}}))},o=async a=>{try{const c=await qt(Rc,"/api/message-queue"),l=c.sessions.find(u=>u.sessionId===a.sessionId)??{sessionId:a.sessionId,directory:a.directory,items:[],sendingId:null};s(l,c.revision,a.runtimeKey)}catch{}},i=async(a,c,l)=>{try{const u=await qt(lr,c,l);s(u.session,u.revision,a.runtimeKey)}catch(u){console.warn("[queue] server update failed:",u),await o(a)}};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:Ju,sendingIds:{},addToQueue:async(a,c)=>{const l=$e(a),u=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,d={id:u,content:c.content,text:c.text??c.content,createdAt:Date.now(),sendConfig:c.sendConfig};if(c.agentMention&&(d.agentMention=c.agentMention),c.attachments&&c.attachments.length>0&&(d.attachments=c.attachments),c.context&&c.context.length>0&&(d.context=c.context),e(y=>{const b=y.queuedMessages[l]??[],S={...y.queuedMessages,[l]:[...b,d].slice(-20)},k=Object.keys(S);if(k.length>xc){k.sort((P,F)=>(S[P]?.[0]?.createdAt??0)-(S[F]?.[0]?.createdAt??0));for(const P of k.slice(0,k.length-xc))delete S[P]}return{queuedMessages:S}}),!Rt())return;if(!c.sendConfig)throw e(y=>rs(y,l,u)),new Error("A queued message needs a provider and model to be delivered later.");const p=Hy(a.runtimeKey,a.directory,a.sessionId),m=Wy(c.content,c.attachments??[]);try{const y=await qt(lr,`${It(a.sessionId)}/items`,At("POST",{directory:a.directory,item:Cc(c,c.sendConfig)}));e(b=>rs(b,l,u)),s(y.session,y.revision,a.runtimeKey),p&&er.getState().appendSubmissions(p,[m])}catch(y){throw e(b=>rs(b,l,u)),y}},removeFromQueue:(a,c)=>{const l=$e(a);e(u=>rs(u,l,c)),Rt()&&i(a,`${It(a.sessionId)}/items/${encodeURIComponent(c)}`,At("DELETE"))},reorderQueue:(a,c,l)=>{if(c===l)return;const u=$e(a),d=t().queuedMessages[u];if(!d)return;const p=d.findIndex(S=>S.id===c),m=d.findIndex(S=>S.id===l);if(p===-1||m===-1)return;const y=d.slice(),[b]=y.splice(p,1);if(y.splice(m,0,b),e(S=>({queuedMessages:{...S.queuedMessages,[u]:y}})),Rt()){const S=y.map(k=>k.id);i(a,`${It(a.sessionId)}/order`,At("PUT",{itemIds:S}))}},popToInput:async(a,c)=>{const[l]=await t().takeForSend(a,c);return l??null},takeForSend:async(a,c)=>{const l=$e(a);if(Rt())try{if(c){const b=await qt(uw,`${It(a.sessionId)}/items/${encodeURIComponent(c)}/take`,At("POST"));return s(b.session,b.revision,a.runtimeKey),[ts(b.item)]}const y=await qt(dw,`${It(a.sessionId)}/take`,At("POST"));return s(y.session,y.revision,a.runtimeKey),y.items.map(ts)}catch(y){throw await o(a),y}const u=t(),d=u.sendingIds[l]??[],p=(u.queuedMessages[l]??[]).filter(y=>(c?y.id===c:!0)&&!d.includes(y.id));if(p.length===0)return[];const m=new Set(p.map(y=>y.id));return e(y=>{const b=(y.queuedMessages[l]??[]).filter(S=>!m.has(S.id));return b.length===0?{queuedMessages:ot(y.queuedMessages,l)}:{queuedMessages:{...y.queuedMessages,[l]:b}}}),p},clearQueue:a=>{const c=$e(a);e(l=>{const u=l.sendingIds[c]??[],d=(l.queuedMessages[c]??[]).filter(p=>u.includes(p.id));return d.length>0?{queuedMessages:{...l.queuedMessages,[c]:d}}:{queuedMessages:ot(l.queuedMessages,c)}}),Rt()&&i(a,It(a.sessionId),At("DELETE"))},forgetQueue:a=>{const c=$e(a);st.delete(c),e(l=>({queuedMessages:ot(l.queuedMessages,c),sendingIds:ot(l.sendingIds,c)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(a,c)=>{const l=$e(a);e(u=>{const d=u.sendingIds[l]??[];return d.includes(c)?u:{sendingIds:{...u.sendingIds,[l]:[...d,c]}}})},clearSending:(a,c)=>{const l=$e(a);e(u=>{const d=u.sendingIds[l];if(!d||!d.includes(c))return u;const p=d.filter(m=>m!==c);return p.length===0?{sendingIds:ot(u.sendingIds,l)}:{sendingIds:{...u.sendingIds,[l]:p}}})},getSendableQueue:a=>{const c=$e(a),l=t(),u=l.queuedMessages[c]??[],d=l.sendingIds[c];return!d||d.length===0?u:u.filter(p=>!d.includes(p.id))},setFollowUpBehavior:a=>{e({followUpBehavior:a}),wt({followUpBehavior:a})},getQueueForTarget:a=>t().queuedMessages[$e(a)]??[],hydrate:()=>{if(!Rt())return Promise.resolve();const a=q();if(n?.runtimeKey===a)return n.promise;const c=++Mo,l=()=>c===Mo&&a===q(),u=(async()=>{let m=Oc.get(a);for(m||(m={items:Object.entries(t().queuedMessages).flatMap(([b,S])=>{const k=Xt(b);return!k||k.runtimeKey!==a?[]:S.map(P=>({target:k,message:P}))}),pending:null},Oc.set(a,m));m.pending||m.items.length>0;){if(!l())return;if(m.pending){await m.pending;continue}const y=m.items.shift();if(!y?.message.sendConfig)continue;const{target:b,message:S}=y,k=qt(lr,`${It(b.sessionId)}/items`,At("POST",{directory:b.directory,item:Cc(S,y.message.sendConfig)})).then(()=>{}).catch(F=>{console.warn("[queue] failed to migrate a locally queued message to the server:",F)});m.pending=k;const P=m;k.then(()=>{P.pending===k&&(P.pending=null)}),await k}if(l())do{r=!1;let y;try{y=await qt(Rc,"/api/message-queue",{signal:AbortSignal.timeout(15e3)})}catch(b){if(!l())return;if(r)continue;throw b}if(!l())return;Do.add(a),!((ns.get(a)??-1)>y.revision)&&(ns.set(a,y.revision),e(b=>{const S=_=>(st.get(_)??-1)>y.revision,k=_=>Xt(_)?.runtimeKey!==a||S(_),P={},F={};for(const[_,Q]of Object.entries(b.queuedMessages))k(_)&&(P[_]=Q);for(const[_,Q]of Object.entries(b.sendingIds))k(_)&&(F[_]=Q);for(const _ of y.sessions){const Q=ai(_.sessionId,_.directory,a);if(!Q)continue;const D=$e(Q);S(D)||(st.set(D,y.revision),_.items.length>0&&(P[D]=_.items.map(ts)),_.sendingId&&(F[D]=[_.sendingId]))}return{queuedMessages:P,sendingIds:F}}))}while(r&&l())})(),d={runtimeKey:a,promise:u};n=d;const p=()=>{n===d&&(n=null)};return u.then(p,p),u},resync:()=>(n?.runtimeKey===q()&&(r=!0),t().hydrate()),applyServerSession:s,setServerHold:async(a,c)=>{if(!Rt())return;const l=await g(`${It(a)}/hold`,At("PUT",{held:c}));if(!l.ok)throw new Error(`Message queue hold request failed (${l.status})`)},resetForRuntimeSwitch:a=>{if(Mo+=1,n=null,r=!1,a){ns.delete(a);for(const c of st.keys())Xt(c)?.runtimeKey===a&&st.delete(c)}!a||!Do.has(a)||e(c=>{const l={},u={};for(const[d,p]of Object.entries(c.queuedMessages))Xt(d)?.runtimeKey===a?st.delete(d):l[d]=p;for(const[d,p]of Object.entries(c.sendingIds))Xt(d)?.runtimeKey!==a&&(u[d]=p);return{queuedMessages:l,sendingIds:u}})}}},{name:"message-queue-store",version:3,storage:Ni(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=Xt(t)?.runtimeKey;return!n||!Do.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:mw}),{name:"message-queue-store"})),yw=w({type:O("openchamber:message-queue.updated"),properties:w({revision:E(),session:Xi})}),cP=(e,t)=>{if(!Rt())return;const n=yw.safeParse(e);if(!n.success)return;const{session:r,revision:s}=n.data.properties;ci.getState().applyServerSession(r,s,t)},ww=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const n=new TextEncoder().encode(t);let r="";for(const o of n)r+=String.fromCharCode(o);return`path_${typeof btoa=="function"?btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},j=e=>t=>{const n=e.safeParse(t);return n.success?n.data:void 0},jn=E().refine(Number.isFinite),Be=f().transform(e=>e.trim()),he=Be.pipe(f().min(1)),Nt=lt(f(),ye()),A=j(Y()),ze=j(f().min(1)),Sn=j(Be),mn=j(he),Mc=e=>j(f().max(e)),Vn=e=>j(Be.transform(t=>t.slice(0,e))),Z=e=>j(Be.pipe(H(e))),Kt=j(jn),Sw=(e,t)=>j(jn.transform(n=>Math.max(e,Math.min(t,Math.round(n))))),_o=e=>j(jn.transform(t=>Math.max(e,Math.round(t)))),bw=j(jn.positive().transform(Math.floor)),vw=j(Ze([fr(),jn])),Tw=j(Ze([fr(),Be.transform(e=>e.length>0?e:null)])),kw=j(Ze([fr(),Be])),Zi=M(ye()).transform(e=>e.filter(t=>f().min(1).safeParse(t).success)),ss=j(Zi.transform(e=>Array.from(new Set(e.map(String))))),Lo=j(Zi.transform(e=>e.map(String))),Ew=Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=M(ye()).safeParse(r);s.success&&(t[n]=s.data.filter(o=>f().safeParse(o).success).map(String))}return t}),Fo=j(Ew.pipe(lt(f(),M(f())).refine(e=>Object.keys(e).length>0))),Pw=w({providerID:he,modelID:he}),jo=e=>j(M(ye()).transform(t=>{const n=[],r=new Set;for(const s of t){const o=Pw.safeParse(s);if(!o.success)continue;const i=`${o.data.providerID}/${o.data.modelID}`;if(!r.has(i)&&(r.add(i),n.push(o.data),n.length>=e))break}return n})),Aw=j(Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){if(!n)continue;const s=Zi.safeParse(r);if(!s.success)continue;const o=Array.from(new Set(s.data.map(String)));o.length>0&&(t[n]=o.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),Iw=j(Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=he.safeParse(r);!s||!o.success||(t[s]=o.data)}return t})),os={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."}},xw=w({title:f().catch(""),message:f().catch("")}),Rw=j(Nt.transform(e=>{const t=i=>{const a=xw.safeParse(e[i]);return a.success?a.data:void 0},n=t("completion"),r=t("error"),s=t("question"),o=t("subtask");if(!(!n&&!r&&!s&&!o))return{completion:n??os.completion,error:r??os.error,question:s??os.question,subtask:o??os.subtask}}).pipe(ol(e=>e!==void 0))),_c=Nt.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{const r=f().safeParse(n);return r.success?[[t,r.data]]:[]}))),Cw=w({id:ye().transform(e=>String(e??"")),label:ye().transform(e=>String(e??"")),models:M(ye()).transform(e=>e.filter(t=>f().safeParse(t).success).map(String)).catch([]),order:E().catch(0)}),Ow=j(Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=Nt.safeParse(r);if(!s.success)continue;const o={},i=M(ye()).safeParse(s.data.customGroups);i.success&&(o.customGroups=i.data.flatMap(l=>{const u=Cw.safeParse(l);return u.success?[u.data]:[]}));const a=_c.safeParse(s.data.modelAssignments);a.success&&(o.modelAssignments=a.data);const c=_c.safeParse(s.data.renamedGroups);c.success&&(o.renamedGroups=c.data),Object.keys(o).length>0&&(t[n]=o)}return t}).refine(e=>Object.keys(e).length>0)),Dw=w({id:he,name:he,hostname:he.transform(e=>e.toLowerCase())}),Mw=j(M(ye()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=Dw.safeParse(s);o.success&&(n.has(o.data.id)||r.has(o.data.hostname)||(n.add(o.data.id),r.add(o.data.hostname),t.push(o.data)))}return t})),_w=j(Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=he.safeParse(r);!s||!o.success||(t[s]=o.data)}return t}).refine(e=>Object.keys(e).length>0)),Lw=w({id:he,label:he,source:he,subpath:Be.optional().catch(void 0),gitIdentityId:Be.optional().catch(void 0)}),Fw=j(M(ye()).transform(e=>{const t=[],n=new Set;for(const r of e){const s=Lw.safeParse(r);if(!s.success||n.has(s.data.id))continue;n.add(s.data.id);const o={id:s.data.id,label:s.data.label,source:s.data.source};s.data.subpath&&(o.subpath=s.data.subpath),s.data.gitIdentityId&&(o.gitIdentityId=s.data.gitIdentityId),t.push(o)}return t})),jw=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Uo=jn.nonnegative(),Uw=w({path:he,label:he.optional().catch(void 0),icon:he.optional().catch(void 0),iconImage:Ze([fr(),w({mime:he,updatedAt:Uo.transform(Math.round).pipe(E().positive()),source:H(["custom","auto"])})]).optional().catch(void 0),color:he.optional().catch(void 0),iconBackground:Ze([fr(),Be.pipe(f().regex(jw)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:Uo.optional().catch(void 0),lastOpenedAt:Uo.optional().catch(void 0),sidebarCollapsed:Y().optional().catch(void 0),defaultModel:he.optional().catch(void 0),defaultAgent:he.optional().catch(void 0),defaultVariant:he.optional().catch(void 0)}),Nw=j(M(ye()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=Uw.safeParse(s);if(!o.success)continue;const i=Ne(o.data.path);if(!i)continue;const a=ww(i);if(!a||n.has(a)||r.has(i))continue;n.add(a),r.add(i);const c={id:a,path:i};o.data.label&&(c.label=o.data.label),o.data.icon&&(c.icon=o.data.icon),o.data.iconImage!==void 0&&(c.iconImage=o.data.iconImage),o.data.color&&(c.color=o.data.color),o.data.iconBackground!==void 0&&(c.iconBackground=o.data.iconBackground),o.data.addedAt!==void 0&&(c.addedAt=o.data.addedAt),o.data.lastOpenedAt!==void 0&&(c.lastOpenedAt=o.data.lastOpenedAt),o.data.defaultModel&&(c.defaultModel=o.data.defaultModel),o.data.defaultAgent&&(c.defaultAgent=o.data.defaultAgent),o.data.defaultVariant&&(c.defaultVariant=o.data.defaultVariant),o.data.sidebarCollapsed!==void 0&&(c.sidebarCollapsed=o.data.sidebarCollapsed),t.push(c)}return t}).refine(e=>e.length>0)),Bw=H(["steer","queue"]),Hw=(e,t)=>{const n=Bw.safeParse(e);if(n.success)return n.data;if(e==="immediate")return"steer";const r=Y().safeParse(t.queueModeEnabled);if(r.success)return r.data?"queue":"steer"},$w=j(Be.pipe(H(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),zw=j(Be.pipe(H(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),Ww=j(Be.transform(e=>e.replace(/\s+/g," ").slice(0,64))),Gw=e=>j(M(ye()).transform(t=>{const n=[];for(const r of t){const s=Be.transform(o=>o.toLowerCase()).safeParse(r);s.success&&e(s.data)&&!n.includes(s.data)&&n.push(s.data)}return n})),ea=e=>j(ol(e)),br=(e,t)=>(n,r)=>{const s=e(n,r);return s===void 0?void 0:t(s)},h=e=>e,v=(e,t,n={})=>({read:()=>T.getState()[e],write:t,autoSave:n.autoSave??!0}),Vt=e=>t=>{T.setState({[e]:t})},Lc=()=>globalThis.window?.__zustand_config_store__??null,Jt=e=>({read:()=>Lc()?.getState()[e],write:t=>{Lc()?.setState({[e]:t})},autoSave:!1}),Jn=e=>({read:()=>Zo.getState()[e],write:t=>{Zo.setState({[e]:t})},autoSave:!1}),qw=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],Kw=ea(Ki),Vw=ea(fg),Jw=ea(pg),Yw=j(f().refine(Hu)),Qw=j(E().refine(qi)),Xw=br(Sn,e=>Js(e,void 0)),Zw=br(j(M(ye())),Py),eS=br(j(M(ye())),e=>Eu(e)),tS=Z(["ask","attach","inline"]),nS=Z(["default","vim"]),rS=(e,t)=>{let n=e;const r=(s,o)=>{if(n.some(c=>c.type==="command"&&c.name===s))return;const i=n.findIndex(c=>c.type==="command"&&c.name===o),a=i>=0?i+1:n.length;n=[...n.slice(0,a),{type:"command",name:s},...n.slice(a)]};return t.draftStartersCraftGoalAdded!==!0&&r("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==!0&&r("schedule-task","craft-goal"),n},Cr={themeId:h({scope:"profile",perSurface:!0,parse:ze}),useSystemTheme:h({scope:"profile",perSurface:!0,parse:A}),themeVariant:h({scope:"profile",derived:!0,parse:Z(["light","dark"])}),lightThemeId:h({scope:"profile",perSurface:!0,parse:ze}),darkThemeId:h({scope:"profile",perSurface:!0,parse:ze}),lastDirectory:h({scope:"instance",adopt:"bootstrap-only",parse:ze}),homeDirectory:h({scope:"instance",parse:ze}),opencodeBinary:h({scope:"instance",parse:Sn}),projects:h({scope:"instance",parse:Nw}),activeProjectId:h({scope:"instance",adopt:"bootstrap-only",parse:ze}),securityScopedBookmarks:h({scope:"instance",surfaces:["desktop"],parse:Lo}),pinnedDirectories:h({scope:"instance",parse:ss}),desktopLanAccessEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopKeepAwakeEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopMinimizeToTrayEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopMacMenuBarEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopUiPassword:h({scope:"instance",secret:!0,surfaces:["desktop"],parse:Sn}),hasDesktopUiPassword:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessActive:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessBlockedReason:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:Sn}),githubClientId:h({scope:"instance",parse:mn}),githubScopes:h({scope:"instance",parse:mn}),skillCatalogs:h({scope:"instance",parse:Fw}),defaultGitIdentityId:h({scope:"instance",parse:Sn}),permissionAutoAccept:h({scope:"instance",parse:j(w({sessions:lt(f().min(1),Ze([Y(),H(["ask","safety","auto"])])).catch({}),revision:E().int().nonnegative().catch(0)}))}),permissionDefaultMode:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:j(H(["ask","safety","auto"])),ui:v("permissionDefaultMode",e=>T.getState().setPermissionDefaultMode(e))}),messageSearchEnabled:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:A,ui:v("messageSearchEnabled",e=>T.getState().setMessageSearchEnabled(e))}),messageSearchReasoningEnabled:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:A,ui:v("messageSearchReasoningEnabled",e=>T.getState().setMessageSearchReasoningEnabled(e))}),agentControlToolEnabled:h({scope:"instance",parse:A,ui:v("agentControlToolEnabled",e=>T.getState().setAgentControlToolEnabled(e))}),agentWebToolEnabled:h({scope:"instance",parse:A,ui:v("agentWebToolEnabled",e=>T.getState().setAgentWebToolEnabled(e))}),browserProvider:h({scope:"instance",parse:ze,ui:v("browserProvider",e=>T.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:h({scope:"instance",parse:A,ui:v("agentNotifyToolEnabled",e=>T.getState().setAgentNotifyToolEnabled(e))}),agentToolsCodeMode:h({scope:"instance",parse:A,ui:v("agentToolsCodeMode",e=>T.getState().setAgentToolsCodeMode(e))}),agentMemoryToolEnabled:h({scope:"instance",parse:A,ui:v("agentMemoryToolEnabled",e=>T.getState().setAgentMemoryToolEnabled(e))}),isolatedSpacesEnabled:h({scope:"instance",parse:A,ui:v("isolatedSpacesEnabled",e=>T.getState().setIsolatedSpacesEnabled(e))}),isolatedSpacesIdleStop:h({scope:"instance",parse:j(w({enabled:Y(),hours:E().int().min(1).max(168)}).strict())}),agentMemoryFeatureAvailable:h({scope:"instance",computed:!0,parse:A,ui:v("agentMemoryFeatureAvailable",e=>T.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),routingFeatureAvailable:h({scope:"instance",computed:!0,parse:A,ui:v("routingFeatureAvailable",e=>T.getState().setRoutingFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:h({scope:"instance",parse:Vn(128)}),autoDeleteEnabled:h({scope:"instance",parse:A,ui:v("autoDeleteEnabled",e=>T.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:h({scope:"instance",parse:Sw(1,365),ui:v("autoDeleteAfterDays",e=>T.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:h({scope:"instance",parse:A,ui:v("sessionRetentionOnlyArchived",e=>T.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionAction:h({scope:"instance",parse:Z(["archive","delete"]),ui:v("sessionRetentionAction",e=>T.getState().setSessionRetentionAction(e))}),terminalShell:h({scope:"instance",parse:Kw,ui:v("terminalShell",e=>T.getState().setTerminalShell(e))}),terminalLoginShells:h({scope:"instance",parse:Gw(Ki),ui:v("terminalLoginShells",e=>T.getState().setTerminalLoginShells(e))}),openInAppId:h({scope:"instance",parse:mn}),dictationEnabled:h({scope:"profile",parse:A,ui:Jt("dictationEnabled")}),sttProvider:h({scope:"instance",parse:$w,ui:Jt("sttProvider")}),sttServerUrl:h({scope:"instance",parse:Vn(2048),ui:Jt("sttServerUrl")}),sttModel:h({scope:"instance",parse:Vn(256),ui:Jt("sttModel")}),sttLocalModel:h({scope:"instance",parse:Vn(256),ui:Jt("sttLocalModel")}),sttLanguage:h({scope:"profile",parse:Vn(64),ui:Jt("sttLanguage")}),tunnelProvider:h({scope:"instance",parse:br(mn,e=>e.toLowerCase())}),tunnelMode:h({scope:"instance",parse:j(f().transform(e=>e.trim().toLowerCase()).pipe(H(["quick","managed-remote","managed-local"])))}),tunnelBootstrapTtlMs:h({scope:"instance",parse:vw}),tunnelSessionTtlMs:h({scope:"instance",parse:Kt}),managedLocalTunnelConfigPath:h({scope:"instance",parse:Tw}),managedRemoteTunnelHostname:h({scope:"instance",parse:Sn}),managedRemoteTunnelToken:h({scope:"instance",secret:!0,parse:kw}),hasManagedRemoteTunnelToken:h({scope:"instance",computed:!0,parse:A}),managedRemoteTunnelPresets:h({scope:"instance",parse:Mw}),managedRemoteTunnelSelectedPresetId:h({scope:"instance",parse:mn}),managedRemoteTunnelPresetTokens:h({scope:"instance",secret:!0,parse:_w}),sidebarProjectDisplayMode:h({scope:"profile",parse:Z(["all","single"]),ui:Jn("projectDisplayMode")}),sidebarViewMode:h({scope:"profile",perSurface:!0,parse:Z(["projects","timeline"]),ui:Jn("sidebarViewMode")}),sidebarProjectSortOrder:h({scope:"profile",parse:Z(["manual","a-z","z-a","date-added","recent"]),ui:Jn("projectSortOrder")}),sidebarWorktreeSortOrder:h({scope:"profile",parse:Z(["recent","manual","a-z"]),ui:Jn("worktreeSortOrder")}),sidebarShowRecentSection:h({scope:"profile",perSurface:!0,parse:A,ui:Jn("showRecentSection")}),workStatusSectionOrder:h({scope:"profile",parse:br(Lo,Ms),ui:v("workStatusSectionOrder",e=>T.getState().setWorkStatusSectionOrder(e))}),workStatusPanelEnabled:h({scope:"profile",parse:A,ui:v("workStatusPanelEnabled",e=>T.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:h({scope:"profile",parse:eS,ui:{read:()=>T.getState().workStatusHiddenSections,write:(e,t)=>{const n=t.workStatusHiddenSectionsExplicit===!0;T.setState({workStatusHiddenSections:Eu(e,n),workStatusHiddenSectionsExplicit:n})},autoSave:!0}}),workStatusHiddenSectionsExplicit:h({scope:"profile",parse:A,ui:v("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:h({scope:"profile",parse:A,ui:v("showReasoningTraces",e=>T.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:v("streamingAutoFollowEnabled",e=>T.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:h({scope:"profile",parse:A,ui:v("collapsibleThinkingBlocks",e=>T.getState().setCollapsibleThinkingBlocks(e))}),showTextJustificationActivity:h({scope:"profile",parse:A}),chatRenderMode:h({scope:"profile",parse:Z(["sorted","live"]),ui:v("chatRenderMode",e=>T.getState().setChatRenderMode(e))}),activityRenderMode:h({scope:"profile",parse:Z(["collapsed","summary"]),ui:v("activityRenderMode",e=>T.getState().setActivityRenderMode(e))}),mermaidRenderingMode:h({scope:"profile",parse:Z(["svg","ascii"]),ui:v("mermaidRenderingMode",e=>T.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:h({scope:"profile",parse:Z(["markdown","plain"]),ui:v("userMessageRenderingMode",e=>T.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:h({scope:"profile",parse:A,ui:v("collapsibleUserMessages",e=>T.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:h({scope:"profile",perSurface:!0,parse:A,ui:v("stickyUserHeader",e=>T.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:v("promptNavigatorEnabled",e=>T.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:v("wideChatLayoutEnabled",e=>T.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:h({scope:"profile",parse:A,ui:v("showSplitAssistantMessageActions",e=>T.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:h({scope:"profile",parse:A,ui:v("showToolFileIcons",e=>T.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:h({scope:"profile",parse:A,ui:v("codeBlockLineWrap",e=>T.getState().setCodeBlockLineWrap(e))}),showTurnChangedFiles:h({scope:"profile",parse:A,ui:v("showTurnChangedFiles",e=>T.getState().setShowTurnChangedFiles(e))}),showExpandedBashTools:h({scope:"profile",parse:A,ui:v("showExpandedBashTools",e=>T.getState().setShowExpandedBashTools(e))}),showExpandedEditTools:h({scope:"profile",parse:A,ui:v("showExpandedEditTools",e=>T.getState().setShowExpandedEditTools(e))}),toolJsonViewMode:h({scope:"profile",parse:Z(["summary","formatted","raw"]),ui:v("toolJsonViewMode",e=>T.getState().setToolJsonViewMode(e))}),timeFormatPreference:h({scope:"profile",parse:Z(["auto","12h","24h"]),ui:v("timeFormatPreference",e=>T.getState().setTimeFormatPreference(e))}),weekStartPreference:h({scope:"profile",parse:Z(["auto","sunday","monday"]),ui:v("weekStartPreference",e=>T.getState().setWeekStartPreference(e))}),messageStreamTransport:h({scope:"profile",parse:Z(["auto","ws","sse"]),ui:Jt("settingsMessageStreamTransport")}),diffLayoutPreference:h({scope:"profile",parse:Z(["dynamic","inline","side-by-side"]),ui:v("diffLayoutPreference",e=>T.getState().setDiffLayoutPreference(e))}),diffWrapLines:h({scope:"profile",parse:A,ui:v("diffWrapLines",e=>T.getState().setDiffWrapLines(e))}),gitChangesViewMode:h({scope:"profile",parse:Z(["flat","tree"]),ui:v("gitChangesViewMode",e=>T.getState().setGitChangesViewMode(e))}),gitmojiEnabled:h({scope:"profile",parse:A}),defaultFileViewerPreview:h({scope:"profile",parse:A}),directoryShowHidden:h({scope:"profile",parse:A,ui:{read:Ty,write:e=>ky(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:h({scope:"profile",parse:A,ui:{read:Iy,write:e=>xy(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:h({scope:"profile",parse:nS,ui:v("fileEditorKeymap",e=>T.getState().setFileEditorKeymap(e))}),autoSaveEnabled:h({scope:"profile",parse:A,ui:v("autoSaveEnabled",e=>T.getState().setAutoSaveEnabled(e))}),autoCreateWorktree:h({scope:"profile",parse:A}),sessionTabsEnabled:h({scope:"profile",surfaces:["web","desktop","vscode"],parse:A,ui:v("sessionTabsEnabled",e=>T.getState().setSessionTabsEnabled(e))}),allowPromptingSubagentSessions:h({scope:"profile",parse:A,ui:v("allowPromptingSubagentSessions",e=>T.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:h({scope:"profile",parse:A,ui:v("inputSpellcheckEnabled",e=>T.getState().setInputSpellcheckEnabled(e))}),enterToSend:h({scope:"profile",parse:A,ui:v("enterToSend",e=>T.getState().setEnterToSend(e))}),enterToSendConfigured:h({scope:"profile",parse:A,ui:v("enterToSendConfigured",e=>T.getState().setEnterToSendConfigured(e))}),persistChatDraft:h({scope:"profile",parse:A,ui:v("persistChatDraft",e=>T.getState().setPersistChatDraft(e))}),largeTextPasteBehavior:h({scope:"profile",parse:tS,ui:v("largeTextPasteBehavior",e=>T.getState().setLargeTextPasteBehavior(e))}),followUpBehavior:h({scope:"profile",parse:Hw,ui:{read:()=>ci.getState().followUpBehavior,write:e=>ci.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:h({scope:"profile",parse:A}),inputHistoryScope:h({scope:"profile",parse:Yw,ui:{read:()=>er.getState().scope,write:e=>er.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:h({scope:"profile",parse:Qw,ui:{read:()=>er.getState().entryLimit,write:e=>er.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:h({scope:"profile",parse:Zw,ui:{read:()=>T.getState().globalDraftStarters??void 0,write:(e,t)=>T.getState().setGlobalDraftStarters(rS(e,t)),autoSave:!1}}),draftStartersVisible:h({scope:"profile",parse:A,ui:v("draftStartersVisible",e=>T.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:h({scope:"profile",parse:A}),draftStartersScheduleTaskAdded:h({scope:"profile",parse:A}),fontSize:h({scope:"profile",perSurface:!0,parse:Kt,ui:v("fontSize",e=>T.getState().setFontSize(e))}),terminalFontSize:h({scope:"profile",perSurface:!0,parse:Kt,ui:v("terminalFontSize",e=>T.getState().setTerminalFontSize(e))}),editorFontSize:h({scope:"profile",perSurface:!0,parse:Kt,ui:v("editorFontSize",e=>T.getState().setEditorFontSize(e))}),uiFont:h({scope:"profile",parse:Vw,ui:v("uiFont",e=>T.getState().setUiFont(e))}),monoFont:h({scope:"profile",parse:Jw,ui:v("monoFont",e=>T.getState().setMonoFont(e))}),padding:h({scope:"profile",perSurface:!0,parse:Kt,ui:v("padding",e=>T.getState().setPadding(e))}),cornerRadius:h({scope:"profile",perSurface:!0,parse:Kt,ui:v("cornerRadius",e=>T.getState().setCornerRadius(e))}),shortcutOverrides:h({scope:"profile",parse:Iw,ui:v("shortcutOverrides",Vt("shortcutOverrides"))}),defaultModel:h({scope:"profile",parse:ze}),defaultVariant:h({scope:"profile",parse:ze}),defaultAgent:h({scope:"profile",parse:ze}),smallModelUseDefault:h({scope:"profile",parse:A}),smallModelOverride:h({scope:"profile",parse:ze}),walkthroughModelOverride:h({scope:"profile",parse:ze}),zenModel:h({scope:"profile",parse:mn}),favoriteModels:h({scope:"profile",parse:jo(64),ui:v("favoriteModels",Vt("favoriteModels"),{autoSave:!1})}),hiddenModels:h({scope:"profile",parse:jo(1024),ui:v("hiddenModels",Vt("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:h({scope:"profile",parse:ss,ui:v("collapsedModelProviders",Vt("collapsedModelProviders"),{autoSave:!1})}),recentModels:h({scope:"profile",parse:jo(16),ui:v("recentModels",Vt("recentModels"),{autoSave:!1})}),recentAgents:h({scope:"profile",parse:ss,ui:v("recentAgents",Vt("recentAgents"),{autoSave:!1})}),recentEfforts:h({scope:"profile",parse:Aw,ui:v("recentEfforts",Vt("recentEfforts"),{autoSave:!1})}),providerOrder:h({scope:"profile",parse:ss,ui:v("providerOrder",e=>T.getState().setProviderOrder(e))}),sessionRecapEnabled:h({scope:"profile",parse:A,ui:v("sessionRecapEnabled",e=>T.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:h({scope:"profile",parse:A,ui:v("sessionSuggestionEnabled",e=>T.getState().setSessionSuggestionEnabled(e))}),sessionWorkEnabled:h({scope:"profile",parse:A,ui:v("sessionWorkEnabled",e=>T.getState().setSessionWorkEnabled(e))}),sessionWorkAutoOpen:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:A,ui:v("sessionWorkAutoOpen",e=>T.getState().setSessionWorkAutoOpen(e))}),sessionGoalEnabled:h({scope:"profile",parse:A,ui:v("sessionGoalEnabled",e=>T.getState().setSessionGoalEnabled(e))}),sessionGoalChecker:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:Z(["classifier","small-model"]),ui:v("sessionGoalChecker",e=>T.getState().setSessionGoalChecker(e))}),sessionGoalDefaultBudgetEnabled:h({scope:"profile",parse:A,ui:v("sessionGoalDefaultBudgetEnabled",e=>T.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:h({scope:"profile",parse:bw,ui:v("sessionGoalDefaultBudget",e=>T.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:h({scope:"profile",parse:A,ui:v("summarizeLastMessage",e=>T.getState().setSummarizeLastMessage(e))}),summaryThreshold:h({scope:"profile",parse:_o(0),ui:v("summaryThreshold",e=>T.getState().setSummaryThreshold(e))}),summaryLength:h({scope:"profile",parse:_o(10),ui:v("summaryLength",e=>T.getState().setSummaryLength(e))}),maxLastMessageLength:h({scope:"profile",parse:_o(10),ui:v("maxLastMessageLength",e=>T.getState().setMaxLastMessageLength(e))}),showDeletionDialog:h({scope:"profile",parse:A,ui:v("showDeletionDialog",e=>T.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:h({scope:"profile",parse:A,ui:v("nativeNotificationsEnabled",e=>T.getState().setNativeNotificationsEnabled(e))}),notificationMode:h({scope:"profile",parse:Z(["always","hidden-only"]),ui:v("notificationMode",e=>T.getState().setNotificationMode(e))}),notifyOnSubtasks:h({scope:"profile",parse:A,ui:v("notifyOnSubtasks",e=>T.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:h({scope:"profile",parse:A,ui:v("notifyOnCompletion",e=>T.getState().setNotifyOnCompletion(e))}),notifyOnError:h({scope:"profile",parse:A,ui:v("notifyOnError",e=>T.getState().setNotifyOnError(e))}),notifyOnQuestion:h({scope:"profile",parse:A,ui:v("notifyOnQuestion",e=>T.getState().setNotifyOnQuestion(e))}),notificationTemplates:h({scope:"profile",parse:Rw,ui:v("notificationTemplates",e=>T.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:h({scope:"profile",parse:A,ui:v("showOpenCodeUpdateNotifications",e=>T.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:h({scope:"profile",parse:A,ui:v("reportUsage",e=>T.getState().setReportUsage(e))}),usageDisplayMode:h({scope:"profile",parse:Z(["usage","remaining"])}),usageDropdownProviders:h({scope:"profile",parse:Lo}),usageSelectedModels:h({scope:"profile",parse:Fo}),usageCollapsedFamilies:h({scope:"profile",parse:Fo}),usageExpandedFamilies:h({scope:"profile",parse:Fo}),usageModelGroups:h({scope:"profile",parse:Ow}),globalBehaviorPrompt:h({scope:"profile",parse:Mc(1024*1024)}),responseStyleEnabled:h({scope:"profile",parse:A}),responseStylePreset:h({scope:"profile",parse:Z(qw)}),responseStyleCustomInstructions:h({scope:"profile",parse:Mc(5e4)}),pwaAppName:h({scope:"instance",surfaces:["web"],parse:Ww}),pwaOrientation:h({scope:"instance",surfaces:["web"],parse:Z(["system","portrait","landscape"])}),mobileKeyboardMode:h({scope:"device",surfaces:["mobile"],parse:Xw,ui:v("mobileKeyboardMode",e=>T.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:h({scope:"device",surfaces:["desktop"],parse:zw,ui:v("desktopWindowControlsPosition",e=>T.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:h({scope:"device",surfaces:["desktop"],parse:Z(["classic","traffic-lights"]),ui:v("desktopWindowControlsStyle",e=>T.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:h({scope:"device",surfaces:["mobile","web"],parse:Kt,ui:v("inputBarOffset",e=>T.getState().setInputBarOffset(e))})},sS=e=>Object.prototype.hasOwnProperty.call(Cr,e),Or=Object.keys(Cr).filter(sS),Yu=e=>Cr[e].scope==="device",Dr=e=>Cr[e],oS=e=>!Cr[e].computed&&!Yu(e),iS=lt(f(),ye()),aS=e=>{const t=iS.safeParse(e);if(!t.success)return null;const n=t.data,r={};for(const s of Or){const i=Dr(s).parse(n[s],n);i!==void 0&&Object.assign(r,{[s]:i})}return r},cS=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),lS=e=>{for(const t of Or){const n=Dr(t);if(!n.ui)continue;const r=e[t];r!==void 0&&(cS(n.ui.read(),r)||n.ui.write(r,e))}},uS=Or.filter(e=>Dr(e).ui?.autoSave===!0),lP=()=>{const e={};for(const t of uS){const r=Dr(t).ui?.read();r!==void 0&&Object.assign(e,{[t]:r})}return e},dS=Or.filter(e=>{const t=Dr(e);return t.scope!=="device"&&!t.secret&&!t.computed}),fS=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},Fc="openchamber.settingsMirror.v2.index",pS="openchamber.deviceSeeded.v1:",hS=e=>`${pS}${encodeURIComponent(e)}`,mS=(e,t)=>{const n=hS(t);let r=!1;try{r=localStorage.getItem(n)===null,r&&localStorage.setItem(n,String(Date.now()))}catch{r=!1}if(r)return e;const s={};for(const o of Or)e[o]===void 0||Yu(o)||Object.assign(s,{[o]:e[o]});return s},gS="openchamber.settingsMirror.v2:",yS=5,jc=e=>`${gS}${encodeURIComponent(e)}`,gn=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},wS=(e,t)=>{const n={};for(const o of dS)e[o]!==void 0&&Object.assign(n,{[o]:e[o]});localStorage.setItem(jc(t),JSON.stringify(n));let r=[];try{const o=JSON.parse(localStorage.getItem(Fc)??"[]");Array.isArray(o)&&(r=o.filter(i=>typeof i=="string"))}catch{r=[]}const s=[t,...r.filter(o=>o!==t)].slice(0,yS);for(const o of r)s.includes(o)||localStorage.removeItem(jc(o));localStorage.setItem(Fc,JSON.stringify(s))},SS=e=>{if(!(typeof window>"u")){if(wS(e,q()),gn("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),fS(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(n=>n.sidebarCollapsed===!0).map(n=>n.id).filter(n=>typeof n=="string"&&n.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"),gn("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(vu(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.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),gn("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),gn("sttModel",typeof e.sttModel=="string"?e.sttModel:null),gn("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),gn("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null)}},li=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let ui="idle",is=null;const di=new Set,uP=()=>ui,dP=e=>(di.add(e),()=>di.delete(e)),fP=e=>{Xs(),Ye(e)},Ye=e=>{is&&(clearTimeout(is),is=null);const t=e==="saved"?"idle":e;t!==ui&&(ui=t,di.forEach(n=>n())),t==="error"&&(is=setTimeout(()=>Ye("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},Qu=()=>{const e=T.persist;if(e&&typeof e=="object")return e},Xu=()=>Er()?.settings??null,Zu=()=>`/api/config/settings?${Lu}=${Gi()}`,bS=e=>{lS(e)},Fs=e=>aS(e);class vS{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const n=this.mutations.at(-1),r=n?[...this.operations].some(s=>s.revision>=n.revision):!0;n&&!r?(n.revision=this.revision,n.changes={...n.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const n={revision:t};return this.operations.add(n),n}reconcile(t,n){let r=t;for(const s of this.mutations)s.revision<=n.revision||(r={...r,...s.changes});return r}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const n=Math.min(...[...this.operations].map(({revision:r})=>r));this.mutations=this.mutations.filter(r=>r.revision>n)}reset(){this.mutations=[],this.operations.clear()}}let ta=0,_t=null,Dn={},fi=!1;const pP=()=>fi,pi=e=>{fi=!0;try{bS(e)}finally{fi=!1}};let Zt=null,Xe=null,at=null,De=null,ur=[],Uc=!1,js=0,gs=[];const Ue=new vS,TS=2e3,kS=200,na=()=>({runtimeKey:q(),generation:ta}),Qs=e=>Object.keys(e),ed=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),ys=e=>{Dn={...Dn,...e}},ES=e=>{const t={...Dn};for(const n of e)delete t[n];Dn=t},PS=e=>{const t={};for(const n of Qs(e))ed(e[n],Dn[n])||Object.assign(t,{[n]:e[n]});return t},vr=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,td=e=>{let t=null;for(const n of gs)vr(n.context,e)&&(t={...t??{},...n.changes});return Xe&&at&&vr(at,e)&&(t={...t??{},...Xe}),t},Nc=(e,t)=>{const n=td(t);return e&&n?{...e,...n}:e},le=e=>e.generation===ta&&e.runtimeKey===q(),Yn=()=>{Xe&&(De&&(clearTimeout(De),De=null),Us({keepalive:!0}))},Xs=()=>{if(!(Uc||typeof window>"u")){Uc=!0,_f(e=>{e.runtimeKey!==e.previousRuntimeKey&&(De&&clearTimeout(De),Xe&&Us())}),Al(e=>{e.runtimeKey!==e.previousRuntimeKey&&(ta+=1,Ue.reset(),js=0,_t=null,Zt=null,Dn={},Ye("saved"))});try{window.addEventListener("pagehide",Yn,{capture:!0}),window.addEventListener("beforeunload",Yn,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Yn()}),document.addEventListener("freeze",Yn)),Pr()&&ki(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||Yn()})).catch(()=>{})}catch{}}},nd=async(e=na())=>{if(Xs(),_t&&vr(_t.context,e)&&Date.now()-_t.at<TS)return Nc(_t.value,e);if(Zt&&vr(Zt.context,e))return Zt.promise;const t=Ue.begin(),n=td(e),r=o=>{if(!le(e)||!o)return null;const i=Nc(Ue.reconcile({...o,...n},t),e);_t={value:i,at:Date.now(),context:e};const a={};for(const c of Qs(o))ed(o[c],i?.[c])&&Object.assign(a,{[c]:o[c]});return ys(a),i},s={context:e,promise:(async()=>{const o=Xu();if(o)try{const i=await o.load();if(!le(e))return null;const a=Fs(i.settings);return r(a)}catch(i){if(!le(e))return null;console.warn("Failed to load shared settings from runtime settings API:",i)}if(!le(e))return null;try{const i=await g(Zu(),{method:"GET",headers:{Accept:"application/json"}});if(!le(e)||!i.ok)return null;const a=await i.json().catch(()=>null);if(!le(e))return null;const c=Fs(a);return r(c)}catch(i){return le(e)&&console.warn("Failed to load shared settings from server:",i),null}})()};return Zt=s,s.promise.finally(()=>{Ue.finish(t),Zt===s&&(Zt=null)}),s.promise},hP=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;Xs();const r=na(),s=Ue.begin(),o=[Qu(),Zo.persist],i=u=>!u?.hasHydrated||u.hasHydrated()||!u.onFinishHydration?Promise.resolve():new Promise(d=>{let p=!1;const m=()=>{p||(p=!0,d())},y=u.onFinishHydration(()=>{y?.(),m()});u.hasHydrated?.()&&m()}),a=()=>Promise.all(o.map(i)).then(()=>{}),c=u=>!Xe||!at||!le(at)?u:{...u,...Xe},l=async u=>{if(!le(r))return;let d=c(Ue.reconcile(u,s));if(await a(),!!le(r)){d=mS(c(Ue.reconcile(u,s)),r.runtimeKey);try{SS(d)}catch(p){console.warn("persistToLocalStorage failed:",p)}try{pi(d)}catch(p){console.warn("applyDesktopUiPreferences failed:",p)}li(d,t,n)}};try{const u=await nd(r);u&&le(r)?await l(u):le(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(u){le(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",u)}finally{Ue.finish(s)}};async function Us({keepalive:e=!1}={}){let t=!1;const n=Xe,r=at,s=js,o=ur;Xe=null,at=null,js=0,De=null,ur=[];try{if(!n||!r||Object.keys(n).length===0||!le(r)){t=!0,Ye("saved");return}const i=Ue.begin(s),a={context:r,changes:{...n}};gs.push(a),ys(n);const c=()=>ES(Qs(n));try{const l=Xu();if(l)try{const u=Fs(await l.save(n));if(!le(r))return;if(u){ys(u);const d=Ue.reconcile(u,i);pi(d),li(d,!1),_t=null}u||c(),t=!!u,Ye(u?"saved":"error");return}catch(u){if(!le(r))return;console.warn("Failed to update settings via runtime settings API:",u)}if(!le(r))return;try{const u=await g(Zu(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:e});if(!le(r))return;if(!u.ok){console.warn("Failed to update shared settings via API:",u.status,u.statusText),c(),Ye("error");return}const d=Fs(await u.json().catch(()=>null));if(!le(r))return;if(d){ys(d);const p=Ue.reconcile(d,i);pi(p),li(p,!1),t=!0,Ye("saved"),_t=null}else c(),Ye("error")}catch(u){le(r)&&(console.warn("Failed to update shared settings via API:",u),c(),Ye("error"))}}finally{gs=gs.filter(l=>l!==a),Ue.finish(i)}}finally{o.forEach(i=>i({ok:t}))}}const mP=()=>nd(),wt=async e=>{if(typeof window>"u")return{ok:!1};Xs();const t=na();at&&!vr(at,t)&&(De&&clearTimeout(De),Us());const n={};for(const i of Qs(e))oS(i)&&Object.assign(n,{[i]:e[i]});const r=Ue.record(n),s=PS({...Xe??{},...n});if(Object.keys(s).length===0){Xe=null,at=null,De&&(clearTimeout(De),De=null);const i=ur;return ur=[],i.forEach(a=>a({ok:!0})),Ye("saved"),{ok:!0}}Xe=s,at=t,js=r,Ye("saving"),De&&clearTimeout(De);const o=new Promise(i=>{ur.push(i)});return De=setTimeout(()=>{Us()},kS),o},gP=async()=>{if(typeof window>"u")return;const e=Qu();try{const t=await py();if(!t)return;const n=()=>fy(t);if(e?.hasHydrated?.()){n();return}if(n(),e?.onFinishHydration){const r=e.onFinishHydration(()=>{r?.(),n()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},AS=3e4,IS=40,xS=60,RS=(e,t,n,r,s,o,i)=>{const a=t.trim(),c=n.trim().toLowerCase();return JSON.stringify([e,a,c,r,s,o,i])},Bc=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},CS=ut()(_n((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,s=xS,o){if(!n||n.trim().length===0)return[];const i=n.trim(),a=q(),c=typeof r=="string"?r.trim():"",l=!!o?.includeHidden,u=o?.respectGitignore??!0,d=o?.type==="directory"?"directory":"file",p=RS(a,i,c,s,l,u,d),m=Date.now(),y=t().cache[p];if(y&&m-y.timestamp<AS)return y.files;const b=t().inFlight[p];if(b)return b;const S=it.searchFiles(c,{directory:i,limit:s,type:d}).then(k=>(e(P=>{if(P.inFlight[p]!==S)return P;const F={...P.cache,[p]:{files:k,timestamp:Date.now()}},_=P.cacheKeys.filter(Q=>Q!==p);for(_.push(p);_.length>IS;){const Q=_.shift();Q&&delete F[Q]}return{cache:F,cacheKeys:_}}),k)).finally(()=>{e(k=>{if(k.inFlight[p]!==S)return k;const P={...k.inFlight};return delete P[p],{inFlight:P}})});return e(k=>({inFlight:{...k.inFlight,[p]:S}})),S},invalidateDirectory(n){if(!n||n.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const r=n.trim();e(s=>{const o={...s.cache},i=s.cacheKeys.filter(l=>Bc(l,r)?(delete o[l],!1):!0),a=Object.entries(s.inFlight).filter(([l])=>!Bc(l,r)),c=Object.fromEntries(a);return{cache:o,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),OS=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},hi="openchamber_stream_perf",DS=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(hi)==="1"}catch{return!1}};let rd=DS(),sd=!1;const ln=()=>rd||sd,od=()=>{ln()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},Hc=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),id=()=>{if(!ln()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},ad=e=>Array.from(e.entries()).map(([t,n])=>({metric:t,count:n.count,avg:n.count>0?Number((n.total/n.count).toFixed(3)):0,max:Number(n.max.toFixed(3)),total:Number(n.total.toFixed(3)),last:Number(n.last.toFixed(3))})).sort((t,n)=>n.total-t.total||n.count-t.count),ra=(e,t)=>{const n=id();if(!n)return;const r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},MS=e=>{if(rd=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(hi,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(hi),od()}catch{}},yP=e=>{if(sd=e,!(typeof window>"u")){if(e){id();return}od()}},_S=()=>{typeof window>"u"||(ln()&&(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()}))},LS=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!ln()||!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:ad(e.counters)}},wP=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!ln()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,n=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:n,durationMs:t?Math.max(0,Date.now()-t):0,entries:ad(e.counters)}},SP=(e,t=1)=>{ra(e,t)},bP=(e,t)=>{ra(e,t)},vP=e=>{!ln()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},TP=(e,t)=>{if(!ln())return t();const n=Hc();try{return t()}finally{ra(e,Hc()-n)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:MS,reset:_S,getSnapshot:LS});var FS={};let ct=null,$c=0;const Qe=xr(),zc=Qe.getItem("lastDirectory"),jS=typeof zc=="string"&&zc.length>0,as=e=>{try{CS.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Mn=e=>Ne(e)??"",US=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},ws=(e,t)=>{const n=US(e,t);return Mn(n)},NS=()=>{const e=Qe.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Mn(e);return t.length>0?t:null},BS=()=>{const e=Qe.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Mn(e);return t.length>0?t:null},HS=()=>{if(typeof process>"u")return null;const e=FS,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const r=Mn(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=Mn(n);return r.length>0?r:null}return null},sa=()=>{if(typeof window<"u"){if(ct)return ct;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ct=t,Qe.setItem("homeDirectory",t),t;const n=NS();if(n&&!Me())return ct=n,n}const e=HS();return e||"/"},$S=e=>{const t=Ne(e);return t&&t!=="/"?t:null},zS=e=>(ct=e,typeof window<"u"&&Qe.setItem("homeDirectory",e),wt({homeDirectory:e}),e),mi=async()=>{const e=r=>{const s=$S(r);return s?zS(s):null};try{const r=await it.getFilesystemHome(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await it.getSystemInfo(),s=e(r?.homeDirectory);if(s)return s}catch(r){console.warn("Failed to get home directory from system info:",r)}try{const r=await Cl(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=sa(),n=e(t);return n||t},WS=()=>{if(!Me())return null;const e=Il()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Mn(e);return t.length>0?t:null},Tr=WS()||sa(),Ns=(()=>{const e=BS();return e&&!Me()?ws(e,Tr):Tr})();Ns&&it.setDirectory(Ns);const GS=!!(Tr&&Tr!=="/"),gi=ut()(_n((e,t)=>({currentDirectory:Ns,directoryHistory:[Ns],historyIndex:0,homeDirectory:Tr,hasPersistedDirectory:jS,isHomeReady:GS,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const s=ct||t().homeDirectory||Qe.getItem("homeDirectory"),o=ws(n,s);OS()&&console.log("[DirectoryStore] setDirectory called with path:",o),it.setDirectory(o),as(),e(i=>{const a=i.directoryHistory[i.historyIndex]===o,c=a?i.directoryHistory:[...i.directoryHistory.slice(0,i.historyIndex+1),o];return Qe.setItem("lastDirectory",o),wt({lastDirectory:o}),{currentDirectory:o,directoryHistory:c,historyIndex:a?i.historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const n=t();if(n.historyIndex>0){const r=n.historyIndex-1,s=n.directoryHistory[r];it.setDirectory(s),as(),Qe.setItem("lastDirectory",s),wt({lastDirectory:s}),e({currentDirectory:s,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const n=t();if(n.historyIndex<n.directoryHistory.length-1){const r=n.historyIndex+1,s=n.directoryHistory[r];it.setDirectory(s),as(),Qe.setItem("lastDirectory",s),wt({lastDirectory:s}),e({currentDirectory:s,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=t(),s=ct||t().homeDirectory||sa();if(n===s)return;const o=_h(n);o&&r(o)},goHome:async()=>{const n=ct||t().homeDirectory||await mi();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),s=n;ct=s;const o=r.homeDirectory!==s,i=Qe.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!o&&!c){r.isHomeReady||e({isHomeReady:!0});return}const l=typeof s=="string"&&s!==""&&s!=="/",u=r.currentDirectory?ws(r.currentDirectory,s):r.currentDirectory,d=r.directoryHistory.map(b=>ws(b,s)),p=d.some((b,S)=>b!==r.directoryHistory[S]),m=!!(u&&u!==r.currentDirectory),y={homeDirectory:s,hasPersistedDirectory:a,isHomeReady:l};if(c?(y.currentDirectory=s,y.directoryHistory=[s],y.historyIndex=0,y.isSwitchingDirectory=!1):(m||p)&&(y.currentDirectory=u,y.directoryHistory=d,y.historyIndex=Math.min(r.historyIndex,d.length-1),y.isSwitchingDirectory=!1),e(()=>y),(c||m)&&l){const b=c?s:u;it.setDirectory(b),as(),Qe.setItem("lastDirectory",b),wt({lastDirectory:b})}wt({homeDirectory:s})}}),{name:"directory-store"}));typeof window<"u"&&(mi().then(e=>{gi.getState().synchronizeHomeDirectory(e)}),Al(()=>{ct=null;const e=++$c;mi().then(t=>{e===$c&&gi.getState().synchronizeHomeDirectory(t)})}));const qS=(e,t)=>{const n=zs();return n?n.openWebSocket(gf(e),t):Vf(new WebSocket(e))},cd=1,Wc=512*1024,KS=0,yn=1,VS=15e3,oa=new TextEncoder,ld=new TextDecoder,ia=H(["interactive","command"]),ud=H(["running","exited","error"]),JS=H(["node","bun"]),aa=vt("type",[w({type:O("terminal")}),w({type:O("project-action"),actionId:f(),executionId:f()})]),YS=w({sessionId:f(),cols:E(),rows:E(),status:ud,mode:ia.optional(),purpose:aa.optional()}),QS=w({sessionId:f(),cwd:f(),status:H(["running","exited"]),createdAt:E().nullable().optional().transform(e=>e??null),mode:ia.optional(),purpose:aa.optional()}),Gc={mode:ia.optional(),purpose:aa.optional()},XS=vt("t",[w({t:O("hello")}),w({t:O("pong")}),w({t:O("error"),s:f().optional(),message:f().optional(),code:f().optional(),fatal:Y().optional()}),w({t:O("snapshot"),s:f(),q:E().int().nonnegative().default(0),history:f().default(""),status:ud,cols:E().int().positive().optional(),rows:E().int().positive().optional(),exitCode:E().nullish().transform(e=>e??void 0),signal:E().nullable().optional(),runtime:JS.optional(),ptyBackend:f().optional(),...Gc}),w({t:O("output"),s:f(),q:E().int().nonnegative(),d:f(),r:f().optional()}),w({t:O("exit"),s:f(),q:E().int().nonnegative(),exitCode:E().nullish().transform(e=>e??void 0),signal:E().nullable().optional()}),w({t:O("restarted"),s:f(),q:E().int().nonnegative(),history:f().default(""),...Gc})]),ZS=e=>{const t=oa.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=cd,n.set(t,1),n},eb=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):oa.encode(e);t[0]===cd&&(t=t.subarray(1));try{return XS.safeParse(JSON.parse(ld.decode(t))).data??null}catch{return null}};class tb extends Error{code;constructor(t,n){super(t),this.name="TerminalRequestError",this.code=n}}const kP=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,nb=w({error:f().optional(),code:f().optional()}),Zs=async(e,t)=>{const n=nb.safeParse(await e.json().catch(()=>null)).data;return new tb(n?.error??t,n?.code??null)},rb=e=>{const t=oa.encode(e);if(t.byteLength<=Wc)return e;let n=t.byteLength-Wc;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return ld.decode(t.subarray(n))},sb=w({sessions:M(ye())});class ob{constructor(t=dd()){this.dependencies=t}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,n){this.cancelIdleClose();const r={handlers:n,lastSequence:-1},s=this.subscribers.get(t)??new Set,o=s.size===0;s.add(r),this.subscribers.set(t,s);const i=this.projections.get(t);i&&(r.lastSequence=i.sequence,n.onEvent({type:"snapshot",sequence:i.sequence,data:i.history,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}));const a=this.socket?.readyState===yn;return this.ensureConnected().then(()=>{const c=this.subscribers.get(t);o&&a&&c===s&&c.size>0&&this.send({t:"attach",v:3,s:t})}).catch(c=>{s.has(r)&&(n.onError?.(c,!1),this.scheduleReconnect())}),()=>{const c=this.subscribers.get(t);if(c?.delete(r),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===yn){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,n){if(n&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n}))))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,n,r){const s=this.projections.get(t);s&&this.projections.set(t,{...s,cols:n,rows:r})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===yn)return;if(this.opening)return await this.opening,this.socket?.readyState===yn?void 0:this.ensureConnected();const t=this.generation,n=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((r,s)=>{let o=!1,i=!1,a=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,u=()=>{a||i||!l()||(a=!0,this.dependencies.clearUrlAuthToken?.())},d=m=>{o||(o=!0,clearTimeout(p),m?s(m):r())},p=setTimeout(()=>{u(),c?.close(),d(new Error("Terminal connection timed out"))},1e4);try{const m=this.dependencies.openSocket();c=m,m.binaryType="arraybuffer",this.socket=m,m.onopen=()=>{if(!l()){m.close(),d(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const y of this.subscribers.keys())this.send({t:"attach",v:3,s:y});this.startKeepalive(),d()},m.onmessage=y=>{this.handleMessage(y.data)},m.onerror=()=>{const y=l();y&&u(),d(new Error("Terminal WebSocket failed")),y&&this.subscribers.size>0&&this.scheduleReconnect()},m.onclose=()=>{const y=l();y&&(this.stopKeepalive(),u()),this.socket===m&&(this.socket=null),d(new Error("Terminal WebSocket closed")),y&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(m){d(m instanceof Error?m:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=n;try{await n}finally{this.opening===n&&(this.opening=null)}}handleMessage(t){const n=eb(t);if(!n||n.t==="hello"||n.t==="pong")return;if(n.t==="error"){const o=new Error(n.message??"Terminal error");o.code=n.code;const i=n.s?[n.s]:[...this.subscribers.keys()];for(const a of i)for(const c of this.subscribers.get(a)??[])c.handlers.onError?.(o,n.fatal===!0);return}if(!n.s)return;const r=this.subscribers.get(n.s);if(!r)return;if(n.t==="snapshot"){const o={sequence:n.q??0,history:n.history??"",cols:n.cols,rows:n.rows,status:n.status,mode:n.mode,purpose:n.purpose,exitCode:n.exitCode,signal:n.signal??null,runtime:n.runtime,ptyBackend:n.ptyBackend};this.projections.set(n.s,o);for(const i of r)i.lastSequence=o.sequence,i.handlers.onEvent({type:"snapshot",sequence:o.sequence,data: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});return}const s=this.projections.get(n.s);s&&n.q>s.sequence&&(n.t==="output"?this.projections.set(n.s,{...s,sequence:n.q,history:rb(s.history+(n.r??n.d))}):n.t==="exit"?this.projections.set(n.s,{...s,sequence:n.q,status:"exited",exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&this.projections.set(n.s,{...s,sequence:n.q,history:n.history??"",status:"running",mode:n.mode??s.mode,purpose:n.purpose??s.purpose,exitCode:void 0,signal:null}));for(const o of r)n.q<=o.lastSequence||(o.lastSequence=n.q,n.t==="output"?o.handlers.onEvent({type:"data",sequence:n.q,data:n.d,replayData:n.r}):n.t==="exit"?o.handlers.onEvent({type:"exit",sequence:n.q,exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&o.handlers.onEvent({type:"snapshot",sequence:n.q,data:n.history??"",status:"running",mode:n.mode??s?.mode,purpose:n.purpose??s?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==yn)return!1;try{return this.socket.send(ZS(t)),!0}catch{return!1}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const n=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 s of this.subscribers.values())for(const o of s)o.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const r=()=>{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",r),typeof document<"u"&&document.addEventListener("visibilitychange",r),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",r),typeof document<"u"&&document.removeEventListener("visibilitychange",r)},this.reconnectTimer=setTimeout(r,n)}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())},VS))}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===KS||t.readyState===yn)&&t.close()}}const ib="",Bs=new Map;function dd(e){return{refreshAuth:qs,openSocket:()=>qS(Re().websocket(Di("/api/terminal/ws",e))),clearUrlAuthToken:Ar}}function Mr(e){const t=Oi(e)??ib,n=Bs.get(t);if(n)return n;const r=new ob(dd(e));return Bs.set(t,r),r}async function ab(e){const t=await g("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),directory:e.cwd});if(!t.ok)throw await Zs(t,"Failed to create terminal session");const n=await t.json().catch(()=>null),r=YS.safeParse(n).data;if(!r)throw new Error("Failed to create terminal session");return r}async function cb(e){const t=await g(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`,{directory:e});if(!t.ok)throw await Zs(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=sb.safeParse(n).data?.sessions;if(!Array.isArray(r))throw new Error("Failed to list terminal sessions");const s=[];for(const o of r){const i=QS.safeParse(o).data;i&&s.push(i)}return s}async function lb(e,t){e.length!==0&&await Un("/api/terminal/touch","POST",{sessionIds:e},t)}async function ub(){const e=await g("/api/terminal/shells");if(!e.ok)throw await Zs(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&Ki(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function db(e,t,n,r){return Mr(r).subscribe(e,{onEvent:t,onError:n})}async function fb(e,t,n){await Mr(n).write(e,t)}async function Un(e,t,n,r){const s={method:t,directory:r};n!==void 0&&(s.headers={"Content-Type":"application/json"},s.body=JSON.stringify(n));const o=await g(e,s);if(!o.ok)throw await Zs(o,"Terminal command failed");return o}async function pb(e,t,n,r){await Un(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n},r),Mr(r).noteResize(e,t,n)}async function hb(e,t,n){await Un(`/api/terminal/${e}/appearance`,"POST",t,n)}async function mb(e,t){await Un(`/api/terminal/${e}`,"DELETE",void 0,t),Mr(t).forget(e)}async function gb(e,t){return(await Un(`/api/terminal/${e}/restart`,"POST",t,t.cwd)).json()}async function yb(e){const n=await(await Un("/api/terminal/force-kill","POST",e,e.cwd)).json().catch(()=>null),r=Mr(e.cwd);if(Array.isArray(n?.killedSessionIds))for(const s of n.killedSessionIds)typeof s=="string"&&r.forget(s);else e.sessionId&&r.forget(e.sessionId)}function EP(){for(const e of Bs.values())e.dispose();Bs.clear()}const wb=()=>({async listShells(){return ub()},async listSessions(e){return cb(e)},async touchSessions(e,t){await lb(e,t)},async createSession(e){return ab(e)},connect(e,t,n){const r=db(e,t.onEvent,t.onError,n);return{close:()=>r()}},async sendInput(e,t,n){await fb(e,t,n)},async resize(e){await pb(e.sessionId,e.cols,e.rows,e.directory)},async updateAppearance(e,t,n){await hb(e,t,n)},async close(e,t){await mb(e,t)},async restartSession(e,t){return gb(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 yb(e)}}),yi=new Set,Sb=e=>(yi.add(e),()=>{yi.delete(e)}),bb=e=>{for(const t of yi)t(e)},wi=new Set,vb=(e,t)=>JSON.stringify([t,Ne(e)]);function PP(e){return wi.add(e),()=>{wi.delete(e)}}function Tb(e,t){const n=vb(e,t);for(const r of wi)r(n)}class kb extends Error{reason;constructor(t,n){super(t),this.name="GitPathUnavailableError",this.reason=n}}const Eb=w({error:f(),code:H(["path_not_found","nested_repository","untracked_directory"])}),fd=w({headCommit:f().nullable(),indexCommit:f().nullable(),worktreeCommit:f().nullable(),hasTrackedChanges:Y(),hasUntrackedFiles:Y(),hasConflict:Y()}),I="/api/git",pd=w({diff:f()}),Pb=w({files:M(w({path:f(),status:f()}))}),Ab=w({error:f()}),Ib=w({files:M(w({path:f(),previousPath:f().optional(),changeType:f(),insertions:E(),deletions:E(),isBinary:Y()}))}),qc=w({hash:f(),date:f(),message:f(),refs:f(),body:f(),author_name:f(),author_email:f(),filesChanged:E(),insertions:E(),deletions:E(),parents:M(f())}),xb=w({all:M(qc),latest:qc.nullable(),total:E()}),Rb=w({diff:f(),submodule:fd.nullable().default(null)}),Cb=w({original:f(),modified:f(),path:f(),isBinary:Y().optional(),submodule:fd.nullable().default(null)});async function hd(e,t){const n=Eb.safeParse(await e.json().catch(()=>null));return n.success&&(e.status===404||e.status===422)?new kb(n.data.error,n.data.code):new Error(`${t}: ${e.statusText}`)}async function eo(e,t){const n=Ab.safeParse(await e.json().catch(()=>null));return new Error(n.success?n.data.error:`${t}: ${e.statusText}`)}const Ob=1200,Db=5e3,Si=new Map,tr=new Map,md=new Map,Kc=new Map,cs=new Map,gd=e=>e.trim(),ca=(e,t)=>JSON.stringify([e,gd(t)]),yd=(e,t,n)=>JSON.stringify([e,gd(t),n??"full"]),bi=(e,t)=>md.get(ca(e,t))??0,wd=(e,t)=>{const n=ca(e,t);md.set(n,bi(e,t)+1);for(const r of[void 0,"light"]){const s=yd(e,t,r);Si.delete(s),tr.delete(s)}};Sb(e=>{wd(q(),e)});const _r=e=>{bb(e)},oe=async(e,t)=>{const n=await t.json();return _r(e),n};function x(e,t,n){const r={...n};return t&&(r.directory=t),Re().api(Di(e,t),r)}async function Mb(e){const t=ca(q(),e),n=Date.now(),r=Kc.get(t);if(r&&r.expiresAt>n)return r.value;const s=cs.get(t);if(s)return s;const o=(async()=>{const i=await g(x(`${I}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return Kc.set(t,{value:c,expiresAt:Date.now()+Db}),c})();cs.set(t,o);try{return await o}finally{cs.get(t)===o&&cs.delete(t)}}class _b extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function AP(e){const t=await g("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new _b;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const n=await t.json();if(!Array.isArray(n?.repositories))throw new Error("Unexpected git directories response");return n.repositories.map(r=>Ne(r?.path??null)).filter(r=>r!==null)}async function Lb(e,t){const n=t?.mode,r=q();t?.fresh&&wd(r,e);const s=yd(r,e,n),o=Date.now(),i=Si.get(s);if(i&&i.expiresAt>o)return i.value;const a=tr.get(s);if(a)return a;const c=(async()=>{const l=bi(r,e),u=await g(x(`${I}/status`,e,n?{mode:n}:void 0));if(!u.ok)throw new Error(`Failed to get git status: ${u.statusText}`);const d=await u.json();return bi(r,e)===l&&Si.set(s,{value:d,expiresAt:Date.now()+Ob}),d})();tr.set(s,c);try{return await c}finally{tr.get(s)===c&&tr.delete(s)}}async function IP(e){const t=await g(x(`${I}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function xP(e){const t=await g(x(`${I}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function RP(e,t){const n=await g(x(`${I}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!n.ok)throw new Error(`Failed to get git commit summaries: ${n.statusText}`);const r=await n.json().catch(()=>({}));return{commits:Array.isArray(r.commits)?r.commits.map(s=>({sha:typeof s.sha=="string"?s.sha:"",short:typeof s.short=="string"?s.short:"",subject:typeof s.subject=="string"?s.subject:""})).filter(s=>s.sha&&s.short):[]}}async function Fb(e,t){const{path:n,staged:r,contextLines:s}=t;if(!n)throw new Error("path is required to fetch git diff");const o=await g(x(`${I}/diff`,e,{path:n,staged:r?"true":void 0,context:s}));if(!o.ok)throw await hd(o,"Failed to get git diff");return Rb.parse(await o.json())}async function jb(e,t){const{base:n,head:r,path:s,contextLines:o,includeWorkingTree:i}=t;if(!n||!r)throw new Error("base and head are required to fetch git range diff");const a=await g(x(`${I}/range-diff`,e,{base:n,head:r,path:s||void 0,context:o,includeWorkingTree:i}));if(!a.ok)throw await eo(a,"Failed to get git range diff");return pd.parse(await a.json())}async function Ub(e,t){const n=await g(x(`${I}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!n.ok)throw await eo(n,"Failed to get commit diff");return pd.parse(await n.json())}async function Nb(e,t){const{base:n,head:r,includeWorkingTree:s}=t;if(!n||!r)throw new Error("base and head are required to fetch git range files");const o=await g(x(`${I}/range-files`,e,{base:n,head:r,includeWorkingTree:s}));if(!o.ok)throw await eo(o,"Failed to get git range files");return Pb.parse(await o.json()).files}async function Bb(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await g(x(`${I}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function Hb(e,t){const{path:n,staged:r}=t;if(!n)throw new Error("path is required to fetch git file diff");const s=await g(x(`${I}/file-diff`,e,{path:n,staged:r?"true":void 0}));if(!s.ok)throw await hd(s,"Failed to get git file diff");return Cb.parse(await s.json())}async function $b(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await g(x(`${I}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to revert git changes")}_r(e)}async function zb(e,t){await Sd(e,[t])}async function Sd(e,t){const n=t.map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to stage git changes");const r=await g(x(`${I}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to stage git changes")}_r(e)}async function Wb(e,t){await bd(e,[t])}async function bd(e,t){const n=t.map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to unstage git changes");const r=await g(x(`${I}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to unstage git changes")}_r(e)}async function Gb(e,t,n){await la(e,t,n,"stage")}async function qb(e,t,n){await la(e,t,n,"unstage")}async function Kb(e,t,n){await la(e,t,n,"discard")}async function la(e,t,n,r){if(!t)throw new Error("path is required to apply a git hunk");if(typeof n!="string"||!n.trim())throw new Error("patch is required to apply a git hunk");const s=await g(x(`${I}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:n,action:r})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error||"Failed to apply git hunk")}_r(e)}async function Vb(e){if(!e)return!1;const t=await g(x(`${I}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function Jb(e){const t=await g(x(`${I}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function Yb(e,t){const n=await g(x(`${I}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!n.ok)throw new Error(`Failed to get branch push status: ${n.statusText}`);return n.json()}async function Qb(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await g(x(`${I}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete branch")}return oe(e,n)}async function Xb(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await g(x(`${I}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete remote branch")}return oe(e,n)}async function Zb(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await g(x(`${I}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to remove remote")}return oe(e,r)}async function ev(e,t,n){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);const s=await g(x(`${I}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));console.error("[git-generation][browser] http error",{status:s.status,statusText:s.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 o=await s.json();if(!o?.message||typeof o.message!="object")throw new Error("Malformed commit generation response");const i=typeof o.message.subject=="string"&&o.message.subject.trim().length>0?o.message.subject.trim():"",a=Array.isArray(o.message.highlights)?o.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:i,highlights:a}}}async function tv(e,t){const{base:n,head:r,context:s,zenModel:o,providerId:i,modelId:a}=t;if(!n||!r)throw new Error("base and head are required");const c={base:n,head:r};s?.trim()&&(c.context=s.trim()),o&&(c.zenModel=o),i&&(c.providerId=i),a&&(c.modelId=a);const l=await g(x(`${I}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const m=await l.json().catch(()=>({error:l.statusText}));throw new Error(m.error||"Failed to generate PR description")}const u=await l.json().catch(()=>null),d=typeof u?.title=="string"?u.title:"",p=typeof u?.body=="string"?u.body:"";if(!d&&!p)throw new Error("Malformed PR description response");return{title:d,body:p}}async function Vc(e){const t=await g(x(`${I}/worktrees`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list worktrees")}return t.json()}async function Jc(e,t){const n=await g(x(`${I}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to validate worktree")}return n.json()}async function nv(e){const t=await g(x(`${I}/worktrees/bootstrap-status`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to get worktree bootstrap status")}return t.json()}async function rv(e,t){const n=await g(x(`${I}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to preview worktree")}return n.json()}async function Yc(e,t){const n=await g(x(`${I}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to create worktree")}return n.json()}async function Qc(e,t){const n=await g(x(`${I}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete worktree")}return n.json()}const sv=w({ref:f(),commit:f().min(1),head:f().min(1)});async function ov(e,t){const n=await g(x(`${I}/worktrees/snapshot`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to snapshot worktree")}return sv.parse(await n.json())}async function iv(e,t,n={}){const r=await g(x(`${I}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create commit")}return oe(e,r)}async function av(e,t={}){const n=q(),r=await g(x(`${I}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to push")}const s=await oe(e,r);return s.success&&Tb(e,n),s}async function cv(e,t={}){const n=await g(x(`${I}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to pull")}return oe(e,n)}async function lv(e,t={}){const n=await g(x(`${I}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to fetch")}return oe(e,n)}async function uv(e){const t=await g(x(`${I}/stashes`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list stashes")}return t.json()}async function dv(e,t){const n=await g(x(`${I}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to count stash files")}return n.json()}async function vd(e,t={}){const n=await g(x(`${I}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to stash changes")}return oe(e,n)}const ua=async(e,t,n)=>{const r=await g(x(`${I}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||`Failed to ${t}`)}return oe(e,r)},fv=(e,t)=>ua(e,"stash/apply",t),Td=(e,t)=>ua(e,"stash/pop",t),pv=(e,t)=>ua(e,"stash/drop",t);async function hv(e,t){const n=await g(x(`${I}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout branch")}return oe(e,n)}async function mv(e,t,n){const r=await g(x(`${I}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create branch")}return oe(e,r)}async function gv(e,t,n){const r=await g(x(`${I}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to rename branch")}return oe(e,r)}async function yv(e,t={}){const n=await g(x(`${I}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(`Failed to get git log: ${r.error||n.statusText}`)}return xb.parse(await n.json())}async function wv(e,t){const n=await g(x(`${I}/commit-files`,e,{hash:t}));if(!n.ok)throw await eo(n,"Failed to get commit files");return Ib.parse(await n.json())}async function CP(e,t,n,r){const s=await g(x(`${I}/commit-file-diff`,e,{hash:t,path:n,binary:r?"true":void 0}));if(!s.ok)throw new Error(`Failed to get commit file diff: ${s.statusText}`);return s.json()}async function Sv(){const e=await g(x(`${I}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function bv(e){const t=await g(x(`${I}/identities`,void 0),{method:"POST",headers:{"Content-Type":"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 create git identity")}return t.json()}async function vv(e,t){const n=await g(x(`${I}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to update git identity")}return n.json()}async function Tv(e){const t=await g(x(`${I}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to delete git identity")}}async function kv(e){if(!e)return null;const t=await g(x(`${I}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function Ev(e){if(!e)return!1;const t=await g(x(`${I}/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 OP(){const e=await g(x(`${I}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function Pv(e,t){const n=await g(x(`${I}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to set git identity")}return n.json()}async function DP(){const e=await g(x(`${I}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function MP(e,t){if(!e)return null;const n=await g(x(`${I}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function Av(e){const t=await g(x(`${I}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function Iv(e,t){const n=await g(x(`${I}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to rebase")}return oe(e,n)}async function xv(e){const t=await g(x(`${I}/rebase/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort rebase")}return oe(e,t)}async function Rv(e,t){const n=await g(x(`${I}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to merge")}return oe(e,n)}async function Cv(e,t){const n=await g(x(`${I}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout commit")}return oe(e,n)}async function Ov(e,t){const n=await g(x(`${I}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to cherry-pick")}return oe(e,n)}async function Dv(e,t){const n=await g(x(`${I}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to revert commit")}return oe(e,n)}async function Mv(e,t,n,r){const s=await g(x(`${I}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:n,force:r})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error||"Failed to reset")}return oe(e,s)}async function _v(e){const t=await g(x(`${I}/merge/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort merge")}return oe(e,t)}async function Lv(e){const t=await g(x(`${I}/rebase/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue rebase")}return oe(e,t)}async function Fv(e){const t=await g(x(`${I}/merge/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue merge")}return oe(e,t)}async function jv(e,t){return await vd(e,{message:t?.message}),{success:!0}}async function Uv(e){return await Td(e,{ref:"stash@{0}"}),{success:!0}}async function Nv(e){const t=await g(x(`${I}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function Bv(e,t){const n=await g(`${I}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw new Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function Hv(e){const t=await g(`${I}/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 $v=()=>({checkIsGitRepository:Mb,getGitStatus:Lb,getGitDiff:Fb,getGitFileDiff:Hb,getGitRangeDiff:jb,getGitRangeFiles:Nb,getBranchBase:Bb,revertGitFile:$b,stageGitFile:zb,stageGitFiles:Sd,unstageGitFile:Wb,unstageGitFiles:bd,stageGitHunk:Gb,unstageGitHunk:qb,revertGitHunk:Kb,isLinkedWorktree:Vb,getGitBranches:Jb,getGitUnpushedBranchCounts:Yb,deleteGitBranch:Qb,deleteRemoteBranch:Xb,removeRemote:Zb,generateCommitMessage:ev,generatePullRequestDescription:tv,listGitWorktrees:Vc,validateGitWorktree:Jc,createGitWorktree:Yc,deleteGitWorktree:Qc,validateWorktreeDirectory:Bv,canonicalizeWorktreeState:Hv,createGitCommit(e,t,n){return iv(e,t,n)},gitPush:av,gitPull:cv,gitFetch:lv,listGitStashes:uv,countGitStashFiles:dv,stashGitChanges:vd,applyGitStash:fv,popGitStash:Td,dropGitStash:pv,checkoutBranch:hv,createBranch:mv,renameBranch:gv,getGitLog(e,t){return yv(e,t)},getCommitFiles:wv,getGitCommitDiff:Ub,getCurrentGitIdentity:kv,hasLocalIdentity:Ev,setGitIdentity:Pv,getGitIdentities:Sv,createGitIdentity:bv,updateGitIdentity:vv,deleteGitIdentity:Tv,getRemotes:Av,rebase:Iv,abortRebase:xv,continueRebase:Lv,merge:Rv,abortMerge:_v,continueMerge:Fv,checkoutCommit:Cv,cherryPick:Ov,revertCommit:Dv,resetToCommit:Mv,stash:jv,stashPop:Uv,getConflictDetails:Nv,worktree:{list:Vc,validate:Jc,bootstrapStatus:nv,preview:rv,create:Yc,remove:Qc,snapshot:ov}});let Xc=null;const zv=()=>window.Capacitor,Wv=e=>e.getPlatform?.()!=="android"||!e.registerPlugin?null:(Xc??=e.registerPlugin("FileShare"),Xc),Gv=async e=>{const t=new Uint8Array(await e.arrayBuffer());let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(n)},qv=async e=>{const t=zv(),n=t?Wv(t):null;if(n){await n.share({fileName:e.name,mimeType:e.type||"application/octet-stream",data:await Gv(e)});return}if(!navigator.canShare?.({files:[e]}))throw new Error("File sharing is unavailable in this mobile runtime");await navigator.share({files:[e]})},pe=e=>e.replace(/\\/g,"/"),Kv=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new tn("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:pe(t?.directory||t?.path||e),entries:t.entries.filter(r=>!!(r&&typeof r.name=="string"&&typeof r.path=="string")).map(r=>({name:r.name,path:pe(r.path),isDirectory:!!r.isDirectory}))}},qe=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},Vv=({getDirectory:e})=>({async listDirectory(t,n){const r=pe(t),s=new URLSearchParams;r&&s.set("path",r),n?.respectGitignore&&s.set("respectGitignore","true");const o=await g("/api/fs/list",{query:s,headers:qe(e)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new tn(a.error||"Failed to list directory",{reason:Cs(a.reason),status:o.status})}const i=await o.json();return Kv(r,i)},async search(t){const n=new URLSearchParams,r=pe(t.directory);r&&n.set("directory",r),n.set("query",t.query),n.set("dirs","false"),n.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&n.set("limit",String(t.maxResults));const s=await g("/api/find/file",{query:n,headers:qe(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to search files")}const o=await s.json();return(Array.isArray(o)?o:[]).map(a=>({path:pe(`${r}/${a}`),preview:[pe(a)]}))},async createDirectory(t){const n=pe(t),r=await g("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...qe(e)},body:JSON.stringify({path:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create directory")}const s=await r.json();return{success:!!s?.success,path:typeof s?.path=="string"?pe(s.path):n}},async statFile(t,n){const r=pe(t),s=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&s.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&s.set("outsideFileGrant",n.outsideFileGrant);const o=await g("/api/fs/stat",{query:s,signal:AbortSignal.timeout(3e4),headers:qe(e,n?.directory)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to stat file")}const i=await o.json().catch(()=>({}));return{path:typeof i.path=="string"?pe(i.path):r,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,n){const r=pe(t),s=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&s.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&s.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&s.set("optional","true");const o=await g("/api/fs/read",{query:s,signal:AbortSignal.timeout(3e4),cache:n?.optional||n?.fresh?"no-store":"default",headers:qe(e,n?.directory)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await o.text(),path:r}},async writeFile(t,n){const r=pe(t),s=await g("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...qe(e)},body:JSON.stringify({path:r,content:n})});if(!s.ok){const i=await s.json().catch(()=>({error:s.statusText}));throw new Error(i.error||"Failed to write file")}const o=await s.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?pe(o.path):r}},async uploadFile(t,n,r){const s=pe(t),o=await g("/api/fs/upload",{method:"POST",query:{path:s,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...qe(e,r?.directory)},body:n});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new tn(a.error||"Failed to upload file",{reason:Cs(a.reason),status:o.status})}const i=await o.json().catch(()=>({}));return{success:!!i.success,path:i.path?pe(i.path):s}},async delete(t){const n=pe(t),r=await g("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...qe(e)},body:JSON.stringify({path:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete file")}return{success:!!(await r.json().catch(()=>({}))).success}},async rename(t,n){const r=await g("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...qe(e)},body:JSON.stringify({oldPath:t,newPath:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rename file")}const s=await r.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?pe(s.path):n}},async revealPath(t){const n=await g("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...qe(e)},body:JSON.stringify({path:pe(t)})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(t){const n=pe(t),r=await g("/api/fs/raw",{query:{path:n,download:!0},headers:qe(e)});if(!r.ok)throw new Error(`Download failed (${r.status})`);const s=await r.blob(),o=n.split("/").pop()||"file";if(window.Capacitor?.isNativePlatform?.()===!0){await qv(new File([s],o,{type:s.type||"application/octet-stream"}));return}const a=URL.createObjectURL(s),c=document.createElement("a");c.href=a,c.download=o,document.body.appendChild(c),c.click(),document.body.removeChild(c),setTimeout(()=>URL.revokeObjectURL(a),100)}}),Jv="/api/config/settings",Zc=()=>`${Jv}?${Lu}=${Gi()}`,Yv="/api/config/reload",el=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},Qv=()=>({async load(){const e=await g(Zc(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:el(await e.json()),source:"web"}},async save(e){const t=await g(Zc(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to save settings")}return el(await t.json())},async restartOpenCode(){const e=await g(Yv,{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}}}),Xv=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),Zv=1500,vi=5e3,eT="openchamber-notification-claim:",dr=new Map,tT=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),nT=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim()).join("|")},rT=e=>{for(const[t,n]of dr)e-n>vi&&dr.delete(t)},sT=e=>{const t=nT(e);if(!t)return!0;const n=Date.now();rT(n);const r=dr.get(t)??0;if(n-r<vi)return!1;try{if(typeof window<"u"&&window.localStorage){const s=`${eT}${t}`,o=Number(window.localStorage.getItem(s)??"0");if(Number.isFinite(o)&&n-o<vi)return dr.set(t,o),!1;Number.isFinite(o)&&o>0&&window.localStorage.removeItem(s),window.localStorage.setItem(s,String(n))}}catch{}return dr.set(t,n),!0},kd=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(n=>{setTimeout(()=>n(null),Zv)})])??e}catch{return e}},oT=async e=>{const t=await kd();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(n){return console.warn("Failed to send notification via service worker",n),!1}},iT=async()=>{const e=await kd();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},aT=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(!tT()&&await iT()||!sT(e))return!0;try{return await oT(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},cT=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,requireHidden:e?.requireHidden}}),!0}catch(n){return console.warn("Failed to send native notification (desktop)",n),!1}},lT=()=>({async notifyAgentCompletion(e){return await cT(e)||await aT(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),wn=async(e,t)=>{try{const n=await g(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},uT=()=>({async getVapidPublicKey(){return wn("/api/push/vapid-public-key")},async subscribe(e){return wn("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return wn("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return wn("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return wn("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return wn("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),dT=w({state:H(["success","failure","pending","unknown"]),total:E(),success:E(),failure:E(),pending:E(),inProgress:E().optional(),queued:E().optional(),startedAt:f().optional()}),fT=vt("connected",[w({connected:O(!1)}),w({connected:O(!0),fetchedAt:E(),summaries:M(w({owner:f(),repo:f(),number:E(),state:H(["open","closed","merged"]),draft:Y(),title:f(),headSha:f().optional(),mergeable:Y().nullable(),mergeableState:f().nullable(),checks:dT.nullable()})),issueSummaries:M(w({owner:f(),repo:f(),number:E(),title:f(),state:H(["open","completed","not_planned"])}))})]),fe=async e=>await e.json().catch(()=>null),pT=({urls:e})=>({async authStatus(){const t=await g("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await fe(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to load GitHub status");return n},async authStart(){const t=await g("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),n=await fe(t);if(!t.ok||!n||!("deviceCode"in n))throw new Error(n?.error||t.statusText||"Failed to start GitHub auth");return n},async authComplete(t){const n=await g("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to complete GitHub auth");return r},async authDisconnect(){const t=await g("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),n=await fe(t);if(!t.ok)throw new Error(n?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!n?.removed}},async authActivate(t){const n=await g("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to activate GitHub account");return r},async authSetGhCliDisabled(t){const n=await g("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update gh CLI setting");return{disabled:!!r.disabled}},async me(){const t=await g("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),n=await fe(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to fetch GitHub user");return n},async prStatus(t,n,r,s){const o=new URLSearchParams({directory:t,branch:n,...r?{remote:r}:{},...s?.force?{force:"true"}:{}}),i=await g(`/api/github/pr/status?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await fe(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prSummaries(t,n=[]){const r=await g("/api/github/pr/summaries",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({refs:t,issueRefs:n})}),s=await r.json().catch(()=>null);if(!r.ok){const o=w({error:f()}).safeParse(s);throw new Error(o.success&&o.data.error||r.statusText||"Failed to load PR summaries")}return fT.parse(s)},async prCreate(t){const n=await g("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to create PR");return r},async prUpdate(t){const n=await g("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update PR");return r},async prMerge(t){const n=await g("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to merge PR");return r},async prReady(t){const n=await g("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to mark PR ready");return r},async repoUpstream(t){const n=await g(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),r=await fe(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to detect upstream repo");return r},async repoBranches(t,n){const r=await g(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(n)}`,{method:"GET",headers:{Accept:"application/json"}}),s=await fe(r);if(!r.ok||!s)throw new Error(s?.error||r.statusText||"Failed to fetch repo branches");return s.branches??[]},async prsList(t,n){const r=n?.page??1,s=new URLSearchParams({directory:t,page:String(r)});n?.query&&s.set("query",n.query);const o=await g(`/api/github/pulls/list?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await fe(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load pull requests");return i},async prContext(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.includeDiff&&s.set("diff","1"),r?.includeCheckDetails&&s.set("checkDetails","1"),r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/pulls/context",s),{method:"GET",headers:{Accept:"application/json"}}),i=await fe(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load pull request context");return i},async issuesList(t,n){const r=n?.page??1,s=new URLSearchParams({directory:t,page:String(r)});n?.query&&s.set("query",n.query);const o=await g(`/api/github/issues/list?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await fe(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issues");return i},async issueGet(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/issues/get",s),{method:"GET",headers:{Accept:"application/json"}}),i=await fe(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issue");return i},async issueComments(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/issues/comments",s),{method:"GET",headers:{Accept:"application/json"}}),i=await fe(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issue comments");return i}});async function Le(e){try{return await e.json()}catch{return null}}function Fe(e,t){return e?.error?.trim()||t}function Ed(e){return Number.isFinite(e)?e??null:null}function Pd(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function Ad(e){const t=e?.id?.trim();return t?{id:t,name:e?.name?.trim()||null,displayName:e?.displayName?.trim()||null,email:e?.email?.trim()||null,avatarUrl:e?.avatarUrl?.trim()||null}:null}function hT(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function mT(e){const t=e?.id?.trim();if(!t)return null;const n=e?.authorizedAt;return{id:t,name:e?.name?.trim()||null,urlKey:e?.urlKey?.trim()||null,current:e?.current===!0,user:Ad(e?.user),authorizedAt:Ed(n)}}function tl(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(mT).filter(n=>n!=null):[];return{connected:e.connected,user:Ad(e.user),organization:hT(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function gT(e){const t=e?.authorizationUrl?.trim(),n=e?.expiresIn,r=e?.scope?.trim();return!t||!Number.isFinite(n)||n==null||!r?null:{authorizationUrl:t,expiresIn:n,scope:r}}function yT(e){const t=e?.id?.trim()||null,n=e?.name?.trim()||null,r=e?.type?.trim()||null;return!t&&!n&&!r?null:{id:t,name:n,type:r}}function wT(e){const t=e?.id?.trim(),n=e?.name?.trim();if(!t||!n)return null;const r=e?.position;return{id:t,name:n,type:e?.type?.trim()||null,position:Ed(r)??0}}function ST(e){const t=e?.name?.trim()||null,n=e?.displayName?.trim()||null,r=e?.avatarUrl?.trim()||null;return!t&&!n&&!r?null:{name:t,displayName:n,avatarUrl:r}}function bT(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();return!t||!n||!r?null:{id:t,key:n,name:r}}function vT(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function TT(e){const t=e?.trim();if(!t)return null;const n=t.startsWith("#")?t.slice(1):t;return/^[0-9A-Fa-f]{6}$/.test(n)?`#${n.toLowerCase()}`:null}function kT(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:TT(e.color)}}function ET(e){return Array.isArray(e)?e.map(kT).filter(t=>t!=null):[]}function Id(e){if(!e)return null;const t=e?.id?.trim(),n=e?.identifier?.trim(),r=e?.title?.trim(),s=e?.url?.trim();return!t||!n||!r||!s?null:{id:t,identifier:n,title:r,url:s,state:yT(e.state),assignee:ST(e.assignee),team:bT(e.team),priority:vT(e.priority),labels:ET(e.labels)}}function PT(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:Pd(n)??"",createdAt:e?.createdAt?.trim()||null,user:e?.user?{name:e.user.name?.trim()||null,displayName:e.user.displayName?.trim()||null,avatarUrl:e.user.avatarUrl?.trim()||null}:null}}function xd(e){const t=Id(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map(PT).filter(s=>s!=null):[],r=e?.description;return{...t,description:Pd(r),comments:n}}function AT(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(Id).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function IT(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:xd(e.issue)}}function xT(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(wT).filter(n=>n!=null):[]}}function RT(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:xd(e.issue)}}function CT(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();if(!t||!n||!r)return null;const s=e?.projectPath?.trim()||null;return{id:t,key:n,name:r,projectPath:s}}function nl(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};const t=Array.isArray(e.teams)?e.teams.map(CT).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const OT=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function DT(e){return OT.find(t=>t===e)??null}function rl(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function MT(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};if(e.posted===!0)return{connected:!0,posted:!0,commentId:e.commentId?.trim()||null};const t=DT(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const _T=()=>({async authStatus(){const e=await g("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await Le(e),n=tl(t);if(!e.ok||!n)throw new Error(Fe(t,e.statusText||"Failed to load Linear status"));return n},async authStart(e){const t=await g("/api/linear/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{origin:e}:{})}),n=await Le(t),r=gT(n);if(!t.ok||!r)throw new Error(Fe(n,t.statusText||"Failed to start Linear auth"));return r},async authDisconnect(){const e=await g("/api/linear/auth",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Le(e);if(!e.ok)throw new Error(Fe(t,e.statusText||"Failed to disconnect Linear"));return{removed:t?.removed===!0}},async authActivate(e){const t=await g("/api/linear/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({organizationId:e})}),n=await Le(t),r=tl(n);if(!t.ok||!r)throw new Error(Fe(n,t.statusText||"Failed to switch Linear workspace"));return r},async issuesList(e){const t=new URLSearchParams,n=e?.query?.trim(),r=e?.cursor?.trim(),s=e?.status?.trim(),o=e?.assignee?.trim(),i=e?.teamId?.trim(),a=e?.priority?.trim();n&&t.set("query",n),r&&t.set("cursor",r),s&&t.set("status",s),o&&t.set("assignee",o),i&&t.set("teamId",i),a&&t.set("priority",a);const c=t.toString(),l=c?`?${c}`:"",u=await g(`/api/linear/issues/list${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await Le(u),p=AT(d);if(!u.ok||!p)throw new Error(Fe(d,u.statusText||"Failed to load Linear issues"));return p},async issueGet(e){const t=new URLSearchParams({id:e}),n=await g(`/api/linear/issues/get?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Le(n),s=IT(r);if(!n.ok||!s)throw new Error(Fe(r,n.statusText||"Failed to load Linear issue"));return s},async issueStates(e){const t=new URLSearchParams({teamId:e}),n=await g(`/api/linear/issues/states?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Le(n),s=xT(r);if(!n.ok||!s)throw new Error(Fe(r,n.statusText||"Failed to load Linear workflow states"));return s},async issueUpdate(e){const t=await g("/api/linear/issues/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:e.id,stateId:e.stateId})}),n=await Le(t),r=RT(n);if(!t.ok||!r)throw new Error(Fe(n,t.statusText||"Failed to update Linear issue"));return r},async mappingGet(){const e=await g("/api/linear/mapping",{method:"GET",headers:{Accept:"application/json"}}),t=await Le(e),n=nl(t);if(!e.ok||!n)throw new Error(Fe(t,e.statusText||"Failed to load Linear mapping"));return n},async mappingSet(e){const t=await g("/api/linear/mapping",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({defaultProjectPath:e.defaultProjectPath,teamProjectPaths:e.teamProjectPaths})}),n=await Le(t),r=nl(n);if(!t.ok||!r)throw new Error(Fe(n,t.statusText||"Failed to save Linear mapping"));return r},async sessionStatusPost(e){const t=await g("/api/linear/session-status",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({kind:e.kind,sessionId:e.sessionId,issueIdentifier:e.issueIdentifier,sessionOrigin:e.sessionOrigin})}),n=await Le(t),r=MT(n);if(!t.ok||!r)throw new Error(Fe(n,t.statusText||"Failed to post Linear session status"));return r},async preferencesGet(){const e=await g("/api/linear/preferences",{method:"GET",headers:{Accept:"application/json"}}),t=await Le(e),n=rl(t);if(!e.ok||!n)throw new Error(Fe(t,e.statusText||"Failed to load Linear preferences"));return n},async preferencesSet(e){const t=await g("/api/linear/preferences",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({sessionComments:e.sessionComments})}),n=await Le(t),r=rl(n);if(!t.ok||!r)throw new Error(Fe(n,t.statusText||"Failed to save Linear preferences"));return r}}),xt=async e=>await e.json().catch(()=>null),LT=()=>({async listClients(){const e=await g("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await xt(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 g("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),n=await xt(t);if(!t.ok||!n?.client||typeof n.token!="string")throw new Error(n?.error||t.statusText||"Failed to create remote client token");return n},async createPairingSession(e={}){const t=await g("/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}:{}})}),n=await xt(t);if(!t.ok||typeof n?.pairing?.secret!="string"||!n?.server)throw new Error(n?.error||t.statusText||"Failed to create pairing session");return n},async listPendingPairings(){const e=await g("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await xt(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 g("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await xt(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 g(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await xt(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to cancel pairing");return{cancelled:n.cancelled===!0}},async revokeClient(e){const t=await g(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await xt(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to revoke remote client");return n},async purgeRevokedClients(){const e=await g("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await xt(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),FT=()=>({api:(...e)=>Re().api(...e),authenticatedAsset:(...e)=>Re().authenticatedAsset(...e),assetWithUrlToken:(...e)=>Re().assetWithUrlToken(...e),auth:(...e)=>Re().auth(...e),health:(...e)=>Re().health(...e),rawFile:(...e)=>Re().rawFile(...e),sse:(...e)=>Re().sse(...e),websocket:(...e)=>Re().websocket(...e)}),jT=(e={})=>{const t=e.urls??Pi();Cf(t);const n=FT();return{themeFiles:Uf(),runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:wb(),git:$v(),files:Vv({getDirectory:()=>gi.getState().currentDirectory}),settings:Qv(),permissions:Xv(),notifications:lT(),github:pT({urls:n}),linear:_T(),push:uT(),clientAuth:LT()}},UT=3e3,sl=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},NT=()=>{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__)}};let Ti=Promise.resolve();const _P=()=>Ti,LP=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:s,relayHostId:o,relay:i}=e??NT(),a=e?null:Sl(),c=o||(a?.target==="remote"?a.hostId:""),l=vl({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return Mf({apiBaseUrl:t,runtimeKey:sl(t,r)?"local":c?`host:${c}`:null}),Ul(n||null),Nl(s||null),i&&ks({apiBaseUrl:t,clientToken:n||null,requestHeaders:s||null,runtimeKey:o?`host:${o}`:null,relay:i}),it.reconnectToRuntimeBaseUrl(),qs(t||void 0).catch(()=>{}),r&&!sl(t,r)&&Object.keys(Gs()).length>0&&ql(r).catch(()=>{}),eu(),Ti=i?Promise.resolve():Promise.race([ph(o||void 0).catch(()=>{}),new Promise(u=>{window.setTimeout(u,1e4)})]).then(()=>{it.reconnectToRuntimeBaseUrl()}),Ti.then(()=>{window.setTimeout(()=>{ch().catch(()=>{})},UT)}),jT({urls:l})};export{Bl as $,dc as A,Er as B,Al as C,Ps as D,VT as E,it as F,kb as G,gP as H,hP as I,He as J,Te as K,Tk as L,Of as M,zf as N,ds as O,kP as P,Oi as Q,Me as R,SP as S,Ln as T,Li as U,ru as V,Bk as W,th as X,Ft as Y,nu as Z,se as _,q as a,iP as a$,ck as a0,uk as a1,zE as a2,QE as a3,CS as a4,AE as a5,Ni as a6,IE as a7,Lg as a8,fs as a9,kf as aA,Sl as aB,GT as aC,yP as aD,EE as aE,qT as aF,ik as aG,KT as aH,wk as aI,XT as aJ,yk as aK,mk as aL,gk as aM,on as aN,fP as aO,mP as aP,Vk as aQ,Uh as aR,Jk as aS,Kk as aT,sE as aU,tE as aV,pk as aW,hk as aX,Wk as aY,ht as aZ,_h as a_,sy as aa,xE as ab,RE as ac,OE as ad,DE as ae,CE as af,Wg as ag,ME as ah,Jg as ai,Ak as aj,Gs as ak,lk as al,Re as am,PE as an,Lh as ao,vP as ap,Rl as aq,dk as ar,LS as as,wP as at,_S as au,qr as av,ir as aw,sg as ax,Ve as ay,uE as az,Ol as b,dv as b$,_f as b0,$m as b1,fk as b2,zs as b3,qs as b4,qS as b5,yg as b6,lg as b7,dg as b8,EP as b9,ya as bA,aP as bB,mo as bC,Pn as bD,V as bE,go as bF,nv as bG,Py as bH,vm as bI,Ga as bJ,Pm as bK,Em as bL,Cm as bM,Ar as bN,wh as bO,yw as bP,cP as bQ,_v as bR,xv as bS,fv as bT,Hv as bU,Mb as bV,hv as bW,Cv as bX,Ov as bY,Fv as bZ,Lv as b_,ci as ba,JT as bb,YT as bc,QT as bd,_E as be,xl as bf,Il as bg,mn as bh,ww as bi,OS as bj,fE as bk,dE as bl,sm as bm,om as bn,im as bo,Su as bp,Vy as bq,pE as br,bb as bs,yE as bt,mE as bu,wy as bv,ai as bw,Rt as bx,Hy as by,er as bz,LP as c,TE as c$,mv as c0,iv as c1,bv as c2,Yc as c3,Qb as c4,Tv as c5,Qc as c6,Xb as c7,DP as c8,pv as c9,Vb as cA,uv as cB,Rv as cC,Td as cD,rv as cE,Iv as cF,Zb as cG,gv as cH,Mv as cI,IP as cJ,xP as cK,Dv as cL,$b as cM,Kb as cN,Pv as cO,zb as cP,Sd as cQ,Gb as cR,jv as cS,vd as cT,Uv as cU,Wb as cV,bd as cW,qb as cX,vv as cY,Bv as cZ,Ce as c_,Bb as ca,CP as cb,wv as cc,Nv as cd,kv as ce,Jb as cf,Ub as cg,RP as ch,Fb as ci,Hb as cj,Sv as ck,yv as cl,jb as cm,Nb as cn,Lb as co,Yb as cp,OP as cq,MP as cr,Av as cs,ov as ct,Jc as cu,Vc as cv,lv as cw,cv as cx,av as cy,Ev as cz,xr as d,tP as d$,og as d0,Tl as d1,lP as d2,pP as d3,uS as d4,Pk as d5,Hk as d6,$k as d7,Ae as d8,Kp as d9,qv as dA,vk as dB,bk as dC,pu as dD,gE as dE,sw as dF,$e as dG,WE as dH,qE as dI,YE as dJ,KE as dK,GE as dL,VE as dM,ju as dN,JE as dO,tn as dP,sP as dQ,oP as dR,qk as dS,po as dT,eE as dU,Gk as dV,Wy as dW,XE as dX,Ji as dY,TP as dZ,ZE as d_,rh as da,ah as db,nh as dc,Fi as dd,eh as de,zk as df,jk as dg,Nk as dh,Uk as di,Vp as dj,fh as dk,Dk as dl,AP as dm,_b as dn,Sb as dp,nP as dq,rP as dr,Jr as ds,bE as dt,wE as du,vo as dv,SE as dw,vE as dx,bP as dy,eP as dz,Rn as e,hE as e0,FE as e1,jE as e2,NE as e3,Kg as e4,LE as e5,UE as e6,BE as e7,rE as e8,Wm as e9,nk as eA,sk as eB,iE as eC,nE as eD,Zk as eE,Xk as eF,Qk as eG,Yk as eH,oE as eI,Gg as eJ,Rk as eK,vb as eL,PP as eM,Ek as eN,Di as eO,Ck as eP,Ok as eQ,kk as eR,Fk as eS,yt as eT,Xt as ea,cg as eb,ug as ec,dP as ed,uP as ee,Jp as ef,$p as eg,Mk as eh,_k as ei,Sk as ej,xy as ek,ok as el,ak as em,qi as en,kE as eo,ig as ep,ag as eq,Ki as er,Cy as es,Ry as et,ky as eu,Js as ev,ZT as ew,tk as ex,rk as ey,ek as ez,Ik as f,_P as g,g as h,Pr as i,xk as j,Ii as k,Ct as l,Lk as m,gi as n,Ne as o,Np as p,lE as q,HE as r,ks as s,cE as t,T as u,Zo as v,$E as w,aE as x,wr as y,wt as z};