@openchamber/web 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/bin/lib/DOCUMENTATION.md +1 -1
  2. package/bin/lib/commands-connect-url.js +6 -5
  3. package/bin/lib/commands-tunnel.js +24 -5
  4. package/dist/assets/{CodeMirrorCommentWidgets-CmKmyb9T.js → CodeMirrorCommentWidgets-C_zL-eri.js} +1 -1
  5. package/dist/assets/{DiffView-8-PFpZ2p.js → DiffView-BeN2_YYF.js} +3 -3
  6. package/dist/assets/FilesView-CN34wm_N.js +17 -0
  7. package/dist/assets/{GitView-DNUSu00w.js → GitView-DLDazOo1.js} +4 -4
  8. package/dist/assets/{GuestAttachDialog-Cv6QzjHC.js → GuestAttachDialog-C0xe_Lyy.js} +1 -1
  9. package/dist/assets/{GuestSurfacePane-Bt3jB_Ye.js → GuestSurfacePane-BdaurnDr.js} +1 -1
  10. package/dist/assets/{JsonTreeView-BlyHTRhM.js → JsonTreeView-B1Xq-k2t.js} +1 -1
  11. package/dist/assets/LinearIssuesView-BryoAHow.js +1 -0
  12. package/dist/assets/{MarkdownImageGallery-2UXJF-5B.js → MarkdownImageGallery-DfuEoaGq.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +12 -0
  14. package/dist/assets/OnboardingScreen-C22bGmnP.js +1 -0
  15. package/dist/assets/{PatchDiff-ByvnbG5T.js → PatchDiff-0xd6UeFB.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BXieg0mH.js → PierreDiffViewer-BC950e3F.js} +3 -3
  17. package/dist/assets/PlanView-B7Xgihqk.js +5 -0
  18. package/dist/assets/PluginPane-2C71F8uF.js +3 -0
  19. package/dist/assets/SettingsView-m_zoFiaT.js +30 -0
  20. package/dist/assets/{SettingsWindow-BIz224xs.js → SettingsWindow-CofS020b.js} +1 -1
  21. package/dist/assets/{SubmoduleDiffSummary-CXKmlps9.js → SubmoduleDiffSummary-BSA9gnIO.js} +1 -1
  22. package/dist/assets/{ToolOutputDialog-BsgAK8xu.js → ToolOutputDialog-DprkVKcj.js} +7 -7
  23. package/dist/assets/{ToolPartDiffPreview-vdPObXOf.js → ToolPartDiffPreview-Dq0go_fX.js} +2 -2
  24. package/dist/assets/{VirtualizedFileDiff-BkFNKWS5.js → VirtualizedFileDiff-Kp8hKJdT.js} +1 -1
  25. package/dist/assets/WalkthroughView-DGnTzqIU.js +4 -0
  26. package/dist/assets/{appThemeRegistry-aHUNHoqP.js → appThemeRegistry-BdEHBA4s.js} +1 -1
  27. package/dist/assets/{commitAndPush-Bon9r94r.js → commitAndPush-LwtVa2Oc.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-DKqr_1AQ.js → computeVirtualFileMetrics-6V1xNpO9.js} +2 -2
  29. package/dist/assets/de-DlgBHUAI.js +10 -0
  30. package/dist/assets/es-BC8G41U8.js +16 -0
  31. package/dist/assets/fr-I0z3vVjy.js +14 -0
  32. package/dist/assets/index-CgR5rJq_.js +41 -0
  33. package/dist/assets/{index-DpFttslC.js → index-CmNPYddV.js} +1 -1
  34. package/dist/assets/index-adyy_sEk.css +1 -0
  35. package/dist/assets/{isDiffPlainText-kzAgpIgi.js → isDiffPlainText-1bXcWCrw.js} +1 -1
  36. package/dist/assets/{isFilePlainText-Uj6y-jzz.js → isFilePlainText-CBAppvy1.js} +1 -1
  37. package/dist/assets/ja-BIElEsY8.js +16 -0
  38. package/dist/assets/ko-DRnnHetA.js +16 -0
  39. package/dist/assets/{main-CbfMxn-I.js → main-CzjTMTfW.js} +2 -2
  40. package/dist/assets/main-DVX34beR.js +886 -0
  41. package/dist/assets/markdownCore-Cxbkn5NR.js +7 -0
  42. package/dist/assets/{miniChat-CiAKBC10.js → miniChat-CP68IL8Q.js} +2 -2
  43. package/dist/assets/{mobile-CsT4sJwC.js → mobile-BrlBrNfZ.js} +2 -2
  44. package/dist/assets/nl-DzUV-kwp.js +16 -0
  45. package/dist/assets/{patchFileDiff-DeaE08W0.js → patchFileDiff-pqRSHLHI.js} +2 -2
  46. package/dist/assets/pl-Bb-cb7k7.js +16 -0
  47. package/dist/assets/pt-BR-CyIWrTcE.js +16 -0
  48. package/dist/assets/renderElectronMiniChatApp-DKIilR7N.js +2 -0
  49. package/dist/assets/renderMobileApp-B0z6-x58.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +52 -0
  51. package/dist/assets/{scheduledTasksApi-BZCNJ588.js → scheduledTasksApi-BuzWT445.js} +1 -1
  52. package/dist/assets/{shikiHighlight-BSUEa3yF.js → shikiHighlight-BWGrY5YU.js} +1 -1
  53. package/dist/assets/{textMateThemeFromAppTheme-CsATFZIV.js → textMateThemeFromAppTheme-BSUFChBY.js} +1 -1
  54. package/dist/assets/tr-DXEDSoYO.js +7 -0
  55. package/dist/assets/uk-C8hN--q_.js +16 -0
  56. package/dist/assets/useAppFontEffects-Dsl_sLrj.js +7366 -0
  57. package/dist/assets/useInlineCommentController-d5vntsQ_.js +2 -0
  58. package/dist/assets/{useRootScrollLock-Cp1eFoM2.js → useRootScrollLock-2rd5Y6gR.js} +2 -2
  59. package/dist/assets/{vendor-base-ui-CsXYnR5c.js → vendor-base-ui-DnNniUWp.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-language-data-BwwommM0.js → vendor-codemirror-language-data-B1EetJur.js} +2 -2
  61. package/dist/assets/vendor-opencode-client-DSZl7jSi.js +12 -0
  62. package/dist/assets/{vendor-tanstack-react-virtual-ClYN8CzB.js → vendor-tanstack-react-virtual--0sBrLRh.js} +1 -1
  63. package/dist/assets/{vendor-tanstack-virtual-core-BewVQryB.js → vendor-tanstack-virtual-core-BoA4iGMw.js} +1 -1
  64. package/dist/assets/{vendor-zod-BSoePkpP.js → vendor-zod-CxRSdNoV.js} +4 -4
  65. package/dist/assets/{web-components-D3Yjr4Zx.js → web-components-ngpHPEDU.js} +1 -1
  66. package/dist/assets/zh-CN-CtzXdjMZ.js +16 -0
  67. package/dist/assets/zh-TW-Ds0CADSz.js +16 -0
  68. package/dist/index.html +5 -5
  69. package/dist/mini-chat.html +5 -5
  70. package/dist/mobile.html +5 -5
  71. package/package.json +5 -5
  72. package/server/index.js +82 -4
  73. package/server/lib/agent-tool/DOCUMENTATION.md +8 -1
  74. package/server/lib/agent-tool/runtime.js +13 -4
  75. package/server/lib/agent-tool/runtime.test.js +15 -0
  76. package/server/lib/context-obligatory/DOCUMENTATION.md +10 -7
  77. package/server/lib/context-obligatory/runtime.js +2 -1
  78. package/server/lib/context-obligatory/runtime.test.js +76 -30
  79. package/server/lib/dictation/DOCUMENTATION.md +4 -1
  80. package/server/lib/dictation/openai-compatible-session.js +7 -0
  81. package/server/lib/enterprise-mode.d.ts +30 -0
  82. package/server/lib/enterprise-mode.js +253 -0
  83. package/server/lib/enterprise-mode.test.js +247 -0
  84. package/server/lib/event-stream/translate-v2.js +6 -0
  85. package/server/lib/event-stream/translate-v2.test.js +6 -0
  86. package/server/lib/git/DOCUMENTATION.md +2 -1
  87. package/server/lib/git/routes.js +44 -1
  88. package/server/lib/git/routes.test.js +98 -1
  89. package/server/lib/git/service.js +146 -11
  90. package/server/lib/git/service.test.js +195 -0
  91. package/server/lib/github/routes.js +9 -19
  92. package/server/lib/github/routes.test.js +112 -0
  93. package/server/lib/guests/DOCUMENTATION.md +4 -2
  94. package/server/lib/guests/background.test.js +1 -1
  95. package/server/lib/guests/catalog.js +56 -2
  96. package/server/lib/guests/catalog.test.js +24 -1
  97. package/server/lib/guests/clone-network.test.js +52 -0
  98. package/server/lib/guests/clone.js +30 -4
  99. package/server/lib/guests/enterprise.js +68 -0
  100. package/server/lib/guests/enterprise.test.js +106 -0
  101. package/server/lib/guests/grant-scope.js +8 -2
  102. package/server/lib/guests/grant-scope.test.js +9 -0
  103. package/server/lib/guests/html-styles.js +16 -2
  104. package/server/lib/guests/html-styles.test.js +53 -4
  105. package/server/lib/guests/install.js +10 -0
  106. package/server/lib/guests/persist.js +1 -0
  107. package/server/lib/guests/routes.js +40 -5
  108. package/server/lib/guests/updates.js +9 -2
  109. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  110. package/server/lib/notifications/runtime.js +22 -8
  111. package/server/lib/notifications/trigger-runtime.test.js +45 -0
  112. package/server/lib/openchamber-sessions/session-metadata-store.js +27 -0
  113. package/server/lib/openchamber-sessions/session-metadata-store.test.js +18 -0
  114. package/server/lib/opencode/DOCUMENTATION.md +13 -9
  115. package/server/lib/opencode/auth-state-runtime.js +2 -2
  116. package/server/lib/opencode/config-paths.test.js +1 -0
  117. package/server/lib/opencode/env-runtime.js +26 -3
  118. package/server/lib/opencode/env-runtime.test.js +57 -0
  119. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  120. package/server/lib/opencode/hmr-state-runtime.js +4 -3
  121. package/server/lib/opencode/lifecycle.js +10 -5
  122. package/server/lib/opencode/lifecycle.test.js +6 -2
  123. package/server/lib/opencode/managed-config-file.js +2 -1
  124. package/server/lib/opencode/managed-config-file.test.js +18 -0
  125. package/server/lib/opencode/npm-registry-config.d.ts +1 -0
  126. package/server/lib/opencode/npm-registry-config.js +123 -0
  127. package/server/lib/opencode/npm-registry-config.test.js +167 -0
  128. package/server/lib/opencode/npm-registry.js +5 -6
  129. package/server/lib/opencode/npm-registry.test.js +30 -0
  130. package/server/lib/opencode/openchamber-routes.js +8 -0
  131. package/server/lib/opencode/project-icon-routes.js +2 -2
  132. package/server/lib/opencode/project-icon-routes.test.js +44 -0
  133. package/server/lib/opencode/provider-source-route.test.js +32 -0
  134. package/server/lib/opencode/routes.js +17 -2
  135. package/server/lib/opencode/settings-helpers.js +26 -3
  136. package/server/lib/opencode/settings-helpers.test.js +12 -5
  137. package/server/lib/opencode/settings-registry.json +35 -1
  138. package/server/lib/opencode/settings-runtime.js +1 -0
  139. package/server/lib/opencode/shutdown-runtime.js +2 -0
  140. package/server/lib/opencode/static-routes-runtime.js +9 -1
  141. package/server/lib/opencode/static-routes-runtime.test.js +58 -1
  142. package/server/lib/package-manager.js +4 -1
  143. package/server/lib/package-manager.test.js +24 -0
  144. package/server/lib/permission-auto-accept/DOCUMENTATION.md +23 -15
  145. package/server/lib/permission-auto-accept/modes.js +26 -0
  146. package/server/lib/permission-auto-accept/runtime.js +146 -40
  147. package/server/lib/permission-auto-accept/runtime.test.js +93 -9
  148. package/server/lib/quota/DOCUMENTATION.md +6 -0
  149. package/server/lib/quota/providers/zhipuai-coding-plan.js +74 -30
  150. package/server/lib/quota/providers/zhipuai-coding-plan.test.js +124 -0
  151. package/server/lib/relay/DOCUMENTATION.md +1 -1
  152. package/server/lib/relay/service.js +32 -12
  153. package/server/lib/relay/service.test.js +30 -0
  154. package/server/lib/routing/DOCUMENTATION.md +150 -41
  155. package/server/lib/routing/classifier.js +156 -0
  156. package/server/lib/routing/defaults.js +27 -0
  157. package/server/lib/routing/jev.js +5 -17
  158. package/server/lib/routing/routes.http.test.js +9 -0
  159. package/server/lib/routing/routes.js +27 -1
  160. package/server/lib/routing/runtime.js +199 -33
  161. package/server/lib/routing/runtime.test.js +299 -15
  162. package/server/lib/routing/store.js +57 -0
  163. package/server/lib/routing/store.test.js +37 -0
  164. package/server/lib/session-assist/DOCUMENTATION.md +17 -7
  165. package/server/lib/session-assist/context.js +42 -2
  166. package/server/lib/session-assist/context.test.js +38 -1
  167. package/server/lib/session-assist/runtime.js +57 -13
  168. package/server/lib/session-assist/runtime.test.js +45 -0
  169. package/server/lib/session-goal/DOCUMENTATION.md +47 -22
  170. package/server/lib/session-goal/audit.js +112 -0
  171. package/server/lib/session-goal/audit.test.js +58 -0
  172. package/server/lib/session-goal/runtime.js +113 -134
  173. package/server/lib/session-goal/runtime.test.js +146 -13
  174. package/server/lib/session-lineage.js +52 -0
  175. package/server/lib/session-lineage.test.js +45 -0
  176. package/server/lib/session-work/DOCUMENTATION.md +108 -0
  177. package/server/lib/session-work/questions.js +126 -0
  178. package/server/lib/session-work/runtime.js +278 -0
  179. package/server/lib/session-work/runtime.test.js +255 -0
  180. package/server/lib/session-work/state.js +48 -0
  181. package/server/lib/session-work/state.test.js +34 -0
  182. package/server/lib/small-model/DOCUMENTATION.md +14 -7
  183. package/server/lib/small-model/client.js +7 -4
  184. package/server/lib/small-model/index.js +11 -21
  185. package/server/lib/small-model/index.test.js +13 -26
  186. package/server/lib/spaces/DOCUMENTATION.md +79 -25
  187. package/server/lib/spaces/gatekeeper-channel.js +63 -11
  188. package/server/lib/spaces/gatekeeper-channel.test.js +34 -4
  189. package/server/lib/spaces/gatekeeper-program.cjs +64 -13
  190. package/server/lib/spaces/gatekeeper-program.test.js +115 -3
  191. package/server/lib/spaces/host.js +58 -13
  192. package/server/lib/spaces/host.test.js +34 -1
  193. package/server/lib/spaces/idle-stop.js +98 -0
  194. package/server/lib/spaces/idle-stop.test.js +130 -0
  195. package/server/lib/spaces/journey.js +427 -17
  196. package/server/lib/spaces/journey.test.js +592 -5
  197. package/server/lib/spaces/layout.js +27 -6
  198. package/server/lib/spaces/manager.test.js +1 -1
  199. package/server/lib/spaces/places/contract-suite.js +4 -2
  200. package/server/lib/spaces/places/docker-live-support.js +27 -4
  201. package/server/lib/spaces/places/docker.js +32 -5
  202. package/server/lib/spaces/places/docker.test.js +38 -8
  203. package/server/lib/spaces/places/escape-suite.js +32 -0
  204. package/server/lib/spaces/places/fake-docker.js +3 -1
  205. package/server/lib/spaces/places/grants.docker.live.test.js +197 -0
  206. package/server/lib/spaces/places/memory-place.js +3 -3
  207. package/server/lib/spaces/places/sessions.docker.live.test.js +4 -2
  208. package/server/lib/spaces/routes.js +49 -1
  209. package/server/lib/spaces/routes.test.js +31 -3
  210. package/server/lib/spaces/space-opencode.js +52 -0
  211. package/server/lib/spaces/space-opencode.test.js +41 -0
  212. package/server/lib/spaces/space-records.js +90 -2
  213. package/server/lib/spaces/space-records.test.js +58 -1
  214. package/server/lib/spaces/space-server.js +13 -1
  215. package/server/lib/spaces/space-server.test.js +13 -0
  216. package/server/lib/spaces/space-setup.js +173 -0
  217. package/server/lib/spaces/space-setup.test.js +174 -0
  218. package/server/lib/tts/DOCUMENTATION.md +3 -0
  219. package/server/lib/tts/base-url.js +8 -0
  220. package/server/lib/tts/routes.js +13 -1
  221. package/server/lib/tts/routes.test.js +26 -0
  222. package/server/lib/tunnels/DOCUMENTATION.md +2 -0
  223. package/server/lib/tunnels/routes.js +14 -0
  224. package/server/lib/tunnels/routes.test.js +26 -0
  225. package/server/lib/walkthrough/index.js +11 -7
  226. package/server/lib/walkthrough/jobs.test.js +8 -0
  227. package/server/lib/walkthrough/languages.js +1 -0
  228. package/server/lib/walkthrough/routes.js +7 -1
  229. package/dist/assets/FilesView-0Ie20mEk.js +0 -17
  230. package/dist/assets/LinearIssuesView-CSl2MUfA.js +0 -1
  231. package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +0 -12
  232. package/dist/assets/OnboardingScreen-CIdXJpfc.js +0 -1
  233. package/dist/assets/PlanView-DEIi3Q7M.js +0 -5
  234. package/dist/assets/PluginPane-BEPUWVho.js +0 -3
  235. package/dist/assets/SettingsView-CiNh-RbW.js +0 -30
  236. package/dist/assets/WalkthroughView-6oE-MuDL.js +0 -4
  237. package/dist/assets/de-CgAJ51z7.js +0 -10
  238. package/dist/assets/es-zGi_ravM.js +0 -16
  239. package/dist/assets/fr-CPfogrWx.js +0 -14
  240. package/dist/assets/index-CHfphYL3.js +0 -41
  241. package/dist/assets/index-DvMJ3w6V.css +0 -1
  242. package/dist/assets/ja-DMk6wd-U.js +0 -16
  243. package/dist/assets/ko-BFpzJ8jc.js +0 -16
  244. package/dist/assets/main-anyZFMIs.js +0 -896
  245. package/dist/assets/markdownCore-CmM47cAE.js +0 -7
  246. package/dist/assets/pl-VdRPcZrB.js +0 -16
  247. package/dist/assets/pt-BR-BRys_lOW.js +0 -16
  248. package/dist/assets/renderElectronMiniChatApp-C5677jy0.js +0 -2
  249. package/dist/assets/renderMobileApp-D4dBBAqQ.js +0 -25
  250. package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +0 -27
  251. package/dist/assets/tr-CA9ckNnm.js +0 -7
  252. package/dist/assets/uk-byjR-y8D.js +0 -16
  253. package/dist/assets/useAppFontEffects-BWQZ5DeI.js +0 -7341
  254. package/dist/assets/useInlineCommentController-DlFyVfBu.js +0 -2
  255. package/dist/assets/vendor-opencode-client-DYdsLbCM.js +0 -12
  256. package/dist/assets/zh-CN-DRabgxdG.js +0 -16
  257. package/dist/assets/zh-TW-rbY5c9UK.js +0 -16
@@ -0,0 +1,41 @@
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{s as f,o as S,n as x,b as he,d as jt,l as D,a as j,_ as J,u as ct,r as lt,t as kd,c as ye,e as oa,j as ia,f as lr,g as Qc}from"./vendor-zod-CxRSdNoV.js";import{_ as gi}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as ut,d as Mn,p as Sr,a as Ed}from"./vendor-zustand-BAGL70zf.js";import{e as Pd,C as Ad}from"./vendor-opencode-client-DSZl7jSi.js";import{f as yi,R as fs}from"./vendor-react-BUCujlKS.js";const er=1,Id="openchamber-relay-v1",Xc=1,Zc=12,tr=1+Zc,ur=64*1024,dr=5,ps=128,el=0,tl=1,An=4,xd=1+An,Do=ur-dr-xd,$={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},Rd=new Set(Object.values($)),Cd=e=>Rd.has(e),en={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},St=globalThis.crypto.subtle,nl={name:"ECDH",namedCurve:"P-256"},rl=16,Xs=32,Od=16,Mo=4,sl=8;class _t extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Dd=()=>St.generateKey(nl,!0,["deriveBits"]),Md=async e=>{const t=await St.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},_d=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new _t("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},nl,!0,[])}catch{throw new _t("invalid ECDH public key JWK")}},Ld=()=>{const e=new Uint8Array(rl);return globalThis.crypto.getRandomValues(e),e},Fd=async(e,t,n)=>{if(n.length!==rl)throw new _t("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(Id)},s,Xs*2*8)),i=(a,c)=>St.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(o.slice(0,Xs),["encrypt","decrypt"]),hostToClient:await i(o.slice(Xs),["encrypt","decrypt"])}},jd=(e,t,n)=>{for(let r=sl-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Ud=(e,t)=>{let n=0n;for(let r=0;r<sl;r+=1)n=n<<8n|BigInt(e[t+r]);return n},Nd=e=>{const t=new Uint8Array(Mo);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>ur)throw new _t("plaintext frame exceeds maximum size");n+=1n;const s=new Uint8Array(Zc);s.set(t,0),jd(s,Mo,n);const o=new Uint8Array(await St.encrypt({name:"AES-GCM",iv:s},e,r)),i=new Uint8Array(tr+o.length);return i[0]=Xc,i.set(s,1),i.set(o,tr),i}}},Bd=e=>{let t=0n;return{async decrypt(n){if(n.length<tr+Od)throw new _t("encrypted frame too short");if(n[0]!==Xc)throw new _t("unsupported encrypted frame version");const r=n.slice(1,tr),s=Ud(r,Mo);if(s<=t)throw new _t("frame counter regression");let o;try{o=await St.decrypt({name:"AES-GCM",iv:r},e,n.slice(tr))}catch{throw new _t("frame decryption failed")}return t=s,new Uint8Array(o)}}},Mr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Hd=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+=Mr[r>>2],t+=Mr[(r&3)<<4|(s??0)>>4],s!==void 0&&(t+=Mr[(s&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Mr[o&63])}return t},aa=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!==er)return null;const r=n.batch===!0,s=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:er,batch:r,flowControl:s}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:er,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:s}:null},$d=e=>({type:"fail",closeCode:en.ChannelFailure,reason:e}),zd=async(e,t={})=>{const n=t.batch!==!1,r=await _d(e),s=await Dd(),o=Ld(),i={t:"hello",v:er,clientPubJwk:await Md(s.publicKey),nonce:Hd(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 aa(c)?.t==="ready"?{type:"ignore"}:$d("plaintext frame on established channel");const l=aa(c);if(l?.t!=="ready")return{type:"ignore"};const u=await Fd(s.privateKey,r,o);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:Nd(u.clientToHost),decryptor:Bd(u.hostToClient)}}}}},ol=4294967295,Wd=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 qe=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>ol)throw new ve("invalid stream id");if(n.length>Do)throw new ve("tunnel payload exceeds maximum size");const s=new Uint8Array(dr+n.length);return s[0]=r?e|ps:e,s[1]=t>>>24&255,s[2]=t>>>16&255,s[3]=t>>>8&255,s[4]=t&255,s.set(n,dr),s},Gd=e=>{if(e.length<dr)throw new ve("tunnel frame too short");const t=e[0],n=(t&ps)!==0,r=t&~ps;if(!Cd(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(dr),hasMoreFragments:n}},qd=new TextEncoder,Kd=new TextDecoder,_r=e=>qd.encode(JSON.stringify(e)),Lr=(e,t)=>{let n;try{n=JSON.parse(Kd.decode(e))}catch{throw new ve("malformed JSON tunnel payload")}if(!t(n))throw new ve("unexpected JSON tunnel payload shape");return n},il=(e,t=Do)=>{if(t<=0||t>Do)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},ca=(e,t,n)=>{const r=il(n);return r.map((s,o)=>qe(e,t,s,o<r.length-1))},Vd=(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)}}},Jd=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]=el,o.set(s,1),o.length>ur)throw new ve("frame batch exceeds maximum plaintext size");return o}let t=1;for(const s of e)t+=An+s.length;if(t>ur)throw new ve("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=tl;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+=An,n.set(s,r),r+=s.length;return n},Yd=e=>{if(e.length<1)throw new ve("empty batch plaintext");const t=e[0];if(t===el)return[e.slice(1)];if(t!==tl)throw new ve(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+An>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+=An,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},Qd=new Set([$.HttpBody,$.WsText,$.WsBinary]),al=150,Xd=24*1024,Zd=32,ef=e=>{const t=e.windowMs??al,n=e.maxBatchBytes??Xd,r=e.maxBatchFrames??Zd,s=e.now??(()=>Date.now()),o=e.setTimer??((b,w)=>setTimeout(b,w)),i=e.clearTimer??(b=>clearTimeout(b));let a=[],c=0,l=null,u=0,d=!1;const h=()=>{l!==null&&(i(l),l=null)},m=()=>{if(h(),a.length===0)return;const b=a;a=[],c=0,u=s(),e.sendBatch(Jd(b))};return{enqueue:b=>{if(d)return;const w=b[0]&~ps;if(!Qd.has(w)){a.push(b),m();return}const k=s();if(a.length===0&&k-u>=t){a.push(b),m();return}const E=An+b.length;if(a.length>0&&1+c+E>ur&&m(),a.push(b),c+=E,c>=n||a.length>=r){m();return}l===null&&(l=o(m,t))},flush:m,dispose(){d=!0,h(),a=[],c=0}}},tf=()=>{let e=1;return{next(){if(e>ol)throw new ve("stream id space exhausted");const t=e;return e+=2,t}}},Fs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nf=e=>Fs(e)&&Object.values(e).every(t=>typeof t=="string"),rf=e=>Fs(e)&&typeof e.status=="number"&&nf(e.headers),la=e=>Fs(e)&&typeof e.reason=="string",sf=e=>Fs(e)&&typeof e.code=="number"&&typeof e.reason=="string",cl=/^[a-z][a-z\d+.-]*:\/\//i,wi="http://tunnel.invalid",of=e=>{try{const t=cl.test(e)?new URL(e):new URL(e,wi);return`${t.pathname}${t.search}`}catch{return e}},Fr=e=>({async*[Symbol.asyncIterator](){yield e}}),af=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()}}}),cf=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},lf=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:af(e)};if(typeof e=="string")return{body:Fr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Fr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Fr(cf(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Fr(r),contentType:n}},uf=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,h)=>r.set(h,d)),i=e.signal,o=e.body):n=e.toString(),t&&(t.method&&(s=t.method),t.headers&&new Headers(t.headers).forEach((d,h)=>r.set(h,d)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const a=cl.test(n)?new URL(n):new URL(n,wi),{body:c,contentType:l}=await lf(o);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,h)=>{u[h]=d}),{method:s.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},ll="__openchamberAmbiguousTransport",_o=e=>(Object.defineProperty(e,ll,{value:!0,enumerable:!1,configurable:!0}),e),ua=e=>!e||typeof e!="object"?!1:e[ll]===!0,df=["local","remote",null],ff=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function ul(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"||!df.includes(r)))return{valid:!1};if(typeof s!="string"||!ff.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 cT(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 lT(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function uT(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function dl(){if(pf()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=ul(t);return n.valid?n.outcome:null}function pf(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":ul(e).valid?"valid":"malformed"}const hs=/^[a-z][a-z\d+.-]*:\/\//i,hf=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},ms=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),mf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return ms(e)},gf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return ms(e)},yf=()=>Object.keys(Ns()).length>0,wf=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Lo=(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))},Sf=(e,t)=>{if(!t)return e;const n=new URLSearchParams;Lo({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},da=(e,t,n)=>{if(hs.test(t)){const o=new URL(t);return Lo(o,n),o.toString()}const r=hf(t);if(!e)return Sf(r,n);const s=new URL(r,`${e}/`);return Lo(s,n),s.toString()},jr=(e,t=Vf())=>{if(!t)return e;const n=hs.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),hs.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},fl=(e,t)=>{const n=hs.test(e)?new URL(e):new URL(e,wf(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},fa=(e,t,n)=>{if(!yf())return null;const r=gf();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=Jf(r);return o&&s.searchParams.set("oc_url_token",o),e==="ws"?(s.protocol=s.protocol==="https:"?"wss:":"ws:",fl(s.toString(),n)):s.toString()}catch{return null}},Si=(e={})=>{const t=ms(e.apiBaseUrl),n=ms(e.realtimeBaseUrl),r=()=>t||mf(),s=()=>n||r(),o=(a,c)=>da(r(),a,c),i=(a,c)=>da(s(),a,c);return{api:o,authenticatedAsset:(a,c)=>jr(o(a,c)),assetWithUrlToken:(a,c,l)=>jr(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=jr(i(a,c));return fa("sse",l,e)||l},websocket:(a,c)=>{const l=fl(jr(i(a,c)),e);return fa("ws",l,e)||l}}};let gs=Si();const Ae=()=>gs,bf=e=>{gs=e},pl=e=>(gs=Si(e),gs),Fo="openchamber:runtime-endpoint-changed",jo="openchamber:runtime-endpoint-will-change";let In="",fr="";const Zs=(e,t,n)=>{try{e[t]=n}catch{}},bi=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"}`}},vf="mobile-disconnected",Tf="url:default",hl=e=>e===""||e===Tf||e===vf,ml=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},gl=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},yl=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},xn=()=>In||ml();let eo="",pa=null,ha,ma;const ga=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},G=()=>{if(fr)return fr;const e=ga("__OPENCHAMBER_API_BASE_URL__"),t=ga("__OPENCHAMBER_LOCAL_ORIGIN__");if(pa===In&&ha===e&&ma===t)return eo;const n=xn();return eo=yl(n,gl())?"local":bi(n),pa=In,ha=e,ma=t,eo},kf=(e={})=>{if(In||fr)return;const t=e.apiBaseUrl?.trim()||ml(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const s=gl(),o=s&&(!t||yl(t,s));In=t,fr=e.runtimeKey?.trim()||(o?"local":bi(t||r))},ys=e=>{const t=e.apiBaseUrl.trim(),n=xn(),r=G(),s=e.runtimeKey?.trim()||bi(t),o={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:s,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(jo,{detail:o})),In=t,fr=s,typeof window<"u"){const i=window;Zs(i,"__OPENCHAMBER_API_BASE_URL__",t),Zs(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Zs(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}pl({apiBaseUrl:t,realtimeBaseUrl:t}),Ol(e.requestHeaders||null),Cl(e.clientToken||null),e.relay?Hf(e.relay):$f(),Bs(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fo,{detail:o}))},Ef=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(jo,t),()=>window.removeEventListener(jo,t)},wl=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Fo,t),()=>window.removeEventListener(Fo,t)};let Uo=null;const dT=e=>{Uo=e},br=()=>Uo||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Sl=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,bl=(e=Sl())=>!!e,Pf=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Ut=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,on=()=>Pf()?.runtime==="electron",Af=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},If="right",fT=()=>{if(!on())return!1;const e=Af();return e==="win32"||e==="linux"},pT=e=>e==="left"?"left":If,hT=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Ie=()=>typeof Ut()?.invoke=="function",_n=()=>on()&&Ie(),xf=()=>{if(Ut()?.pickThemeFile)return{async pick(){const e=Ut()?.pickThemeFile;return e?{status:"picked",file:S({name:f(),size:x().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??{})},mT=async()=>{if(!$e()||!Pe())return!1;const e=xn();try{const t=he().safeParse(await se("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===xn()}catch{return!1}},gT=async()=>{if(!_n()||!Pe())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}},yT=async e=>{if(!_n()||!Pe())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}},wT=async()=>{if(!_n()||!Pe())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}},ST=async e=>{if(!_n()||!Pe())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}},bT=async()=>{if(!_n()||!Pe())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}},vT=async e=>{if(!_n()||!Pe())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}},ya=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}}},to=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}}},Rf=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),$n=e=>{const t=Rf(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Pe=()=>{if(typeof window>"u"||!$e())return!1;if(G()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=to(e),n=to(xn());if(!n&&t&&dl()?.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&&$n(t.hostname)&&$n(n.hostname)}const r=to(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&&$n(t.hostname)&&$n(r.hostname)}const s=ya(e),o=ya(window.location.origin)||window.location.origin;return s&&o&&s===o?!0:!!(r&&$n(r.hostname))},$e=()=>typeof window>"u"?!1:on(),TT=async()=>{if(!$e())return!1;try{return!!await se("desktop_focus_window")}catch{return!1}},vl=()=>$e()&&Ie()&&Pe(),Cf=f().min(1),kT=e=>{if(!vl())return null;try{const t=Cf.safeParse(Ut()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},ET=async()=>{if(!$e())return!1;try{return await se("desktop_start_window_drag"),!0}catch{return!1}},Oe=()=>bl()?!0:br()?.runtime?.isVSCode===!0,PT=()=>{const t=br()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Oe()},AT=(e,t=$e())=>e==="web"&&!t,Tl=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},IT=async e=>{if(vl())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"}},Of=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),xT=async e=>{if(Ie()&&Pe())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(!Of(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"}},RT=async e=>({success:!0}),CT=async e=>({success:!0}),OT=async()=>Ie()?await se("desktop_check_for_updates"):null,DT=async e=>{if(!Ie())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{}}},MT=async()=>Ie()?(await se("desktop_restart"),!0):!1,_T=async()=>{if(!Ie())return!1;try{return await se("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},LT=async()=>{if(!Ie()||!Pe())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}},Df=async(e,t)=>{if(!Ie()||!Pe())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}},FT=async e=>{if(!Ie()||!Pe())return!1;const t=e?.trim();if(!t)return!1;try{return await se("desktop_reveal_path",{path:t}),!0}catch{return Df(t)}},jT=async(e,t)=>{if(!Ie()||!Pe())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}},UT=async(e,t,n)=>{if(!Ie()||!Pe())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}},NT=async(e,t,n)=>{if(!Ie()||!Pe())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}},BT=async(e,t)=>{if(!Ie()||!Pe())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}}},vr=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",HT=()=>{if(typeof window>"u"||!vr()||kl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},kl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Oe()?"vscode":$e()?"desktop":"web"},Mf="2.0.4",Ur=new Uint8Array(0),_f=new TextEncoder,Lf=new TextDecoder,We=e=>e instanceof Error?e:new Error(String(e)),Nr=()=>new DOMException("The operation was aborted.","AbortError"),Ff=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},jf=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},wa=0,no=1,Sa=2,ba=3,Uf=new Set([en.AuthFailed,en.DuplicateClient,en.LimitExceeded]),Nf={[en.AuthFailed]:"relay authentication failed",[en.DuplicateClient]:"relay connection replaced by another client",[en.LimitExceeded]:"relay connection limit reached"},va=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},vi=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,s=e.pingTimeoutMs??15e3,o=e.batchWindowMs??al,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(R=>Ff(new WebSocket(R)));let d=!1,h=null,m={state:"idle"};const y=new Set;let b=null,w=null,k=null,E=0,L=0,M=null,Y=[],C=!1;const Te=R=>{if(!(m.state===R.state&&m.lastError===R.lastError)){m=R;for(const W of y)try{W(m)}catch{}}},ce=R=>{const W=Y;Y=[];for(const _ of W)_.reject(R)},Js=R=>{const W=Y;Y=[];for(const _ of W)_.resolve(R)},xe=(R,W)=>{R.dead=!0;const _=Array.from(R.streams.values());R.streams.clear();for(const U of _)try{U.fail(W)}catch{}},jn=()=>{M!==null&&(clearTimeout(M),M=null)},Un=()=>{d||M===null||va()||(jn(),Ze(),Nn())},Bt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Un()},N=()=>{C||typeof window>"u"||(C=!0,window.addEventListener("online",Un),typeof document<"u"&&document.addEventListener("visibilitychange",Bt))},Ze=()=>{!C||typeof window>"u"||(C=!1,window.removeEventListener("online",Un),typeof document<"u"&&document.removeEventListener("visibilitychange",Bt))},un=()=>{if(d||M!==null)return;const R=Math.max(0,L-1),W=a*2**Math.min(R,10),_=va()?l:c,U=Math.min(_,W);N(),M=setTimeout(()=>{M=null,Ze(),Nn()},U)},Cr=()=>{const R=new URL(e.relayUrl);return R.searchParams.set("v",String(er)),R.searchParams.set("role","client"),R.searchParams.set("serverId",e.serverId),R.searchParams.set("appId","openchamber"),R.searchParams.set("appVersion",Mf),R.searchParams.set("platform",kl()),e.grant&&R.searchParams.set("grant",e.grant),R.toString()},Nn=async()=>{if(d)return;jn(),E+=1;const R=E;Te({state:L>0?"reconnecting":"connecting",lastError:m.lastError});let W;try{W=await zd(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(Q){if(R!==E||d)return;sa(R,We(Q),!0);return}if(R!==E||d)return;let _;try{_=u(Cr())}catch(Q){sa(R,We(Q));return}w=_;let U=!1,B=null,q=null,De=null,we=null,H=Promise.resolve(),z=null,oe=null,dt=!1,me=!1,ge=0,Se=0,be=null,ft=null,te=Date.now();const Tt=()=>{be!==null&&(clearTimeout(be),be=null),B!==null&&(clearInterval(B),B=null),q!==null&&(clearTimeout(q),q=null),De!==null&&(clearInterval(De),De=null),we!==null&&(clearTimeout(we),we=null),ft!==null&&(ft.dispose(),ft=null)};k=Tt;function V(Q,ie=!1,ee=!1){if(!(U||R!==E)){U=!0,ee&&(h=Q),Tt(),z&&(b=null,xe(z,new Error(`relay tunnel reset: ${Q.message}`))),ce(Q);try{_.close()}catch{}if(w===_&&(w=null),!d){if(L+=1,ee){Te({state:"error",lastError:Q.message});return}Te({state:ie?"error":"reconnecting",lastError:Q.message}),un()}}}const Bn=()=>{try{_.send(W.helloText)}catch{}},Dr=(Q,ie,ee)=>{oe=Q,dt=ie,me=ee,B!==null&&(clearInterval(B),B=null),q!==null&&(clearTimeout(q),q=null);const le=new Map,Ht=tf(),ze=Vd();let $t=Promise.resolve();const kt=Hn=>{$t=$t.then(async()=>{if(zt.dead)return;const Td=await Q.encryptor.encrypt(Hn);zt.dead||_.send(Td)}).catch(()=>{V(new Error("relay encrypt/send failed"))})},Qs=ie?ef({windowMs:o,sendBatch:kt}):null;ft=Qs;const zt={streams:le,assembler:ze,nextStreamId:()=>Ht.next(),dead:!1,send(Hn){zt.dead||(Qs?Qs.enqueue(Hn):kt(Hn))}};z=zt,b=zt,L=0,te=Date.now(),Te({state:"connected"}),Js(zt),De=setInterval(()=>{Date.now()-te<r||(zt.send(qe($.Ping,0,Ur)),we===null&&(we=setTimeout(()=>{we=null,V(new Error("relay keepalive timeout"))},s)))},r)},dn=()=>{be!==null&&clearTimeout(be),be=null,!(!z||z.dead||ge===Se)&&(Se=ge,z.send(qe($.DeliveryAck,0,Wd(ge))))},vd=(Q,ie)=>{let ee;try{ee=Gd(ie)}catch(ze){V(We(ze));return}if(ee.frameType===$.DeliveryAck){V(new Error("unexpected downstream delivery acknowledgement"));return}if(me&&ee.streamId!==0&&(ge+=ie.length,be===null&&(be=setTimeout(dn,10))),te=Date.now(),we!==null&&(clearTimeout(we),we=null),ee.frameType===$.Ping){Q.send(qe($.Pong,ee.streamId,Ur));return}if(ee.frameType===$.Pong)return;let le=ee.payload;if(ee.frameType===$.WsText||ee.frameType===$.WsBinary){let ze;try{ze=Q.assembler.push(ee)}catch($t){V(We($t));return}if(ze===null)return;le=ze}else if(ee.hasMoreFragments){V(new Error("unexpected fragmented tunnel frame"));return}const Ht=Q.streams.get(ee.streamId);Ht&&Ht.handleFrame(ee.frameType,le)};_.onopen=()=>{U||R!==E||(Bn(),B=setInterval(Bn,t))},_.onmessage=Q=>{if(U||R!==E)return;const ie=Q.data;if(typeof ie=="string"){H=H.then(async()=>{if(U||R!==E)return;const le=await W.handleText(ie);if(le.type==="established"){if(oe)return;Dr(le.channel,le.batch,le.flowControl)}else le.type==="fail"&&V(new Error(`relay handshake failed: ${le.reason}`))}).catch(le=>{V(We(le))});return}const ee=ie instanceof ArrayBuffer?new Uint8Array(ie):ie instanceof Uint8Array?ie:null;ee&&(H=H.then(async()=>{if(U||R!==E)return;const le=z,Ht=oe;if(!le||!Ht){V(new Error("encrypted frame before handshake completed"));return}let ze;try{ze=await Ht.decryptor.decrypt(ee)}catch(kt){V(We(kt));return}let $t;try{$t=dt?Yd(ze):[ze]}catch(kt){V(We(kt));return}for(const kt of $t){if(U||R!==E||le.dead)return;vd(le,kt)}me&&ge-Se>=16*1024&&dn()}).catch(le=>{V(We(le))}))},_.onclose=Q=>{const ie=Uf.has(Q.code);V(new Error(Nf[Q.code]??`relay socket closed (code ${Q.code})`),ie,ie)},_.onerror=()=>{},q=setTimeout(()=>{q=null,V(new Error("relay handshake timeout"),!0)},n);function sa(Q,ie,ee=!1){Q!==E||d||(ce(ie),L+=1,Te({state:ee?"error":"reconnecting",lastError:ie.message}),un())}},Or=R=>d?Promise.reject(new Error("relay tunnel closed")):R?.aborted?Promise.reject(Nr()):h?Promise.reject(h):b&&!b.dead?Promise.resolve(b):new Promise((W,_)=>{let U=null;const B={resolve(q){U&&R&&R.removeEventListener("abort",U),W(q)},reject(q){U&&R&&R.removeEventListener("abort",U),_(q)}};R&&(U=()=>{Y=Y.filter(q=>q!==B),_(Nr())},R.addEventListener("abort",U,{once:!0})),Y.push(B)}),vt=async(R,W)=>{const _=await uf(R,W),U=_.signal;if(U?.aborted)throw Nr();const B=await Or(U),q=B.nextStreamId();return await new Promise((De,we)=>{let H=!1,z=!1,oe=null,dt=null;const me=()=>{B.streams.delete(q),B.assembler.dropStream(q),dt&&U&&U.removeEventListener("abort",dt)},ge=te=>{if(!z){if(z=!0,me(),!H){we(te);return}try{oe?.error(te)}catch{}}},Se=te=>{B.dead||B.send(qe($.StreamAbort,q,_r({reason:te})))},be=te=>_o(new Error(te));dt=()=>{Se("aborted"),ge(Nr())},B.streams.set(q,{handleFrame(te,Tt){if(te===$.HttpResponse){if(H||z)return;let V;try{V=Lr(Tt,rf)}catch(dn){Se("malformed response head"),ge(be(We(dn).message));return}const Bn=V.status===204||V.status===205||V.status===304;let Dr=null;Bn||(Dr=new ReadableStream({start(dn){oe=dn},cancel(){z||(z=!0,me(),Se("response body cancelled"))}})),H=!0,De(new Response(Dr,{status:V.status,headers:V.headers})),Bn&&(z=!0,me());return}if(te===$.HttpBody){if(!H||z)return;try{oe?.enqueue(Tt)}catch{}return}if(te===$.StreamEnd){if(z)return;if(!H){ge(be("tunnel stream ended before response head"));return}z=!0,me();try{oe?.close()}catch{}return}if(te===$.StreamAbort){let V="stream aborted by host";try{V=Lr(Tt,la).reason}catch{}ge(be(V))}},fail(te){ge(be(te.message))}}),U&&U.addEventListener("abort",dt,{once:!0});const ft={method:_.method,path:_.path,query:_.query,headers:_.headers,hasBody:_.body!==null};B.send(qe($.HttpRequest,q,_r(ft))),(async()=>{try{let te=!1;if(_.body)for await(const Tt of _.body){if(z||B.dead)return;for(const V of il(Tt))B.send(qe($.HttpBody,q,V)),te=!0}!z&&!B.dead&&(_.body&&!te&&B.send(qe($.HttpBody,q,Ur)),B.send(qe($.StreamEnd,q,Ur)))}catch(te){Se("request body failed"),ge(be(We(te).message))}})()})},Ys=R=>{const W=R.indexOf("?");return W===-1?{path:R,query:""}:{path:R.slice(0,W),query:R.slice(W+1)}},Sd=(R,W)=>{let _=wa,U=null,B=0,q=!1;const De={get readyState(){return _},onopen:null,onmessage:null,onerror:null,onclose:null,send(H){if(_!==no||!U||U.dead)throw new Error("relay tunnel socket is not open");if(typeof H=="string"){for(const oe of ca($.WsText,B,_f.encode(H)))U.send(oe);return}const z=H instanceof ArrayBuffer?new Uint8Array(H.slice(0)):(()=>{const oe=new Uint8Array(H.byteLength);return oe.set(new Uint8Array(H.buffer,H.byteOffset,H.byteLength)),oe})();for(const oe of ca($.WsBinary,B,z))U.send(oe)},close(H=1e3,z=""){_===ba||_===Sa||(_===no&&U&&!U.dead&&(_=Sa,U.send(qe($.WsClose,B,_r({code:H,reason:z})))),we(H,z))}},we=(H,z,oe=!1)=>{if(!q){if(q=!0,U&&(U.streams.delete(B),U.assembler.dropStream(B)),_=ba,oe)try{De.onerror?.()}catch{}try{De.onclose?.({code:H,reason:z})}catch{}}};return(async()=>{let H;try{H=await Or()}catch(me){we(1006,We(me).message,!0);return}if(q)return;U=H,B=H.nextStreamId(),H.streams.set(B,{handleFrame(me,ge){if(me===$.WsOpened){if(_===wa){_=no;try{De.onopen?.()}catch{}}return}if(me===$.WsText){try{De.onmessage?.({data:Lf.decode(ge)})}catch{}return}if(me===$.WsBinary){const Se=new ArrayBuffer(ge.byteLength);new Uint8Array(Se).set(ge);try{De.onmessage?.({data:Se})}catch{}return}if(me===$.WsClose){let Se=1e3,be="";try{const ft=Lr(ge,sf);Se=ft.code,be=ft.reason}catch{}we(Se,be);return}if(me===$.StreamAbort){let Se="stream aborted";try{Se=Lr(ge,la).reason}catch{}we(1006,Se,!0)}},fail(me){we(1012,me.message,!0)}});const{path:z,query:oe}=Ys(R),dt=W&&W.length>0?{path:z,query:oe,protocols:W}:{path:z,query:oe};H.send(qe($.WsOpen,B,_r(dt)))})(),De},bd=()=>{if(d)return;d=!0,E+=1,jn(),Ze(),k?.(),k=null;const R=b;b=null;const W=new Error("relay tunnel closed");R&&xe(R,W),ce(W);try{w?.close()}catch{}w=null,Te({state:"idle"})};return Nn(),{fetch:vt,openWebSocket:Sd,getStatus:()=>m,subscribeStatus(R){return y.add(R),()=>{y.delete(R)}},close:bd}};let Le=null,bt=null;const Bf=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),js=()=>Le,$T=()=>!Le||!bt?null:{relayUrl:bt.relayUrl,serverId:bt.serverId,hostEncPubJwk:{...bt.hostEncPubJwk}},zT=()=>Le!==null,Hf=e=>(Le&&bt&&Bf(bt,e)||(Le?.close(),bt=e,Le=vi(e)),Le),WT=(e,t)=>{Le!==t&&(Le?.close(),bt=e,Le=t)},$f=()=>{Le?.close(),Le=null,bt=null};let El=()=>null,Pl="",ws={},nn="",pr=0,Yt=null,kn="",hr=0,rn="",Qt=null,Ot="",ss=0,os=0;const Ti=1e4,zf=e=>e.toLowerCase()==="authorization",Al=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const s=n.trim(),o=r.trim();s&&o&&!zf(s)&&(t[s]=o)}return t},Wf=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,s])=>t[r]===s)},Us=e=>typeof e!="string"?"":e.trim(),Gf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Us(e)},qf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Il=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():qf();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},ki=e=>{try{return new URL(e).origin}catch{return""}},xl=()=>{kn="",hr=0,rn="",Qt=null,Ot="",ss+=1},Tr=()=>{nn="",pr=0,xl()},Rl=()=>{os+=1,Yt=null,Tr(),Ei()},Cl=e=>{const t=Us(e);Pl=t,Rl(),El=()=>t?{type:"bearer",token:t}:null},Ol=e=>{const t=Al(e);Wf(ws,t)||(ws=t,Rl())},Ns=()=>{if(Object.keys(ws).length>0)return ws;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Al(e):{}},Dl=()=>Pl||Gf(),Kf=(e,t)=>{const n=Us(e);if(!n||typeof t!="number"||!Number.isFinite(t)){Tr();return}const r=nn;nn=n,pr=t,r&&r!==n&&Zf()},Ml=()=>!nn||pr<=Date.now()+Ti?(Tr(),""):nn,_l=e=>{const t=ki(e);return!t||rn!==t?"":!kn||hr<=Date.now()+Ti?(kn="",hr=0,rn="",""):kn},Vf=()=>{const e=Ml();return!e&&(Dl()||typeof window<"u")&&Bs().catch(()=>{}),e},Jf=e=>{const t=e?_l(e):"";return!t&&e&&typeof window<"u"&&Ul(e).catch(()=>{}),t},Ll=async()=>{const e=await El(),t=e?.type==="bearer"?Us(e.token):Dl();return t?{type:"bearer",token:t}:null},Yf=S({token:f(),expiresAt:x()}),Fl=async(e,t)=>{const n=await Ll(),r=new Headers;for(const[c,l]of Object.entries(Ns()))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=js(),i=o?await o.fetch(s,{method:"POST",headers:r}):await fetch(Il(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=Yf.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},GT=async e=>{const t=await Fl(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},jl=e=>{if(Yt)return Yt;const t=os,r=(async()=>{let s;try{s=await Fl(e)}catch(o){throw t===os&&Tr(),o}if(t!==os)throw new Error("Runtime URL auth token response is stale");if(Kf(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},Qf=e=>{const t=ki(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Qt&&Ot===t)return Qt;const n=ss,s=(async()=>{const o=await fetch(Il(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw n===ss&&t===Ot&&(kn="",hr=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!==ss||t!==Ot)throw new Error("Local runtime URL auth token response is stale");return kn=a,hr=c,rn=t,a})().finally(()=>{Qt===s&&(Qt=null,Ot="")});return Qt=s,Ot=t,Qt},Bs=async e=>{const t=Ml();return t||jl(e)},Ul=async e=>{const t=ki(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=_l(t);return n||((rn&&rn!==t||Ot&&Ot!==t)&&xl(),Qf(t))};let bn=0,nr=null,Nl=null;const No=new Set,Xf=5e3,Zf=()=>{for(const e of No)try{e()}catch{}},Bl=()=>{nr!==null&&(clearTimeout(nr),nr=null)},Ei=()=>{if(Bl(),bn<=0||typeof window>"u")return;const e=pr-Ti-Xf,t=pr>0?Math.max(0,e-Date.now()):0;nr=setTimeout(()=>{nr=null,!(bn<=0)&&jl(Nl).catch(()=>{}).finally(()=>{Ei()})},t)},qT=e=>{typeof e=="string"&&e.trim()&&(Nl=e.trim()),bn+=1,Ei();let t=!1;return()=>{t||(t=!0,bn=Math.max(0,bn-1),bn===0&&Bl())}},KT=e=>(No.add(e),()=>{No.delete(e)}),ep=async e=>{const t=new Headers(e);for(const[r,s]of Object.entries(Ns()))t.has(r)||t.set(r,s);if(t.has("Authorization"))return t;const n=await Ll();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},Ss=ut(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),tp=15e3,np=5*6e4;let Bo=0,ro=!1;const rp=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),sp=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!rp(t)},Hl=async()=>{if(!ro){ro=!0;try{const{runtimeFetch:e}=await gi(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>vp);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){Ss.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=Ss.getState();n==="expired"&&r()}}catch{}finally{ro=!1}}},op=(e,t)=>{if(t!==401||Ss.getState().state==="expired"||!sp(e))return;const n=Date.now();n-Bo<tp||(Bo=n,Hl())};let Ta=!1;const VT=()=>{if(Ta)return;Ta=!0;let e=Date.now();const t=()=>{if(Ss.getState().state!=="ok")return;const n=Date.now();n-e<np||(e=n,Bo=n,Hl())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},ip=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,ka="/api/",$l="/api/spaces/",Pi=e=>{if(!e)return null;const t=ip.exec(e);return t?t[1]:null},Ea=e=>Pi(e)!==null,ap=e=>e.startsWith($l),cp=()=>bl()||br()?.runtime?.isVSCode===!0,Ai=(e,t)=>{if(cp())return e;const n=Pi(t);return n===null||!e.startsWith(ka)||ap(e)?e:`${$l}${n}/${e.slice(ka.length)}`},sn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",lp=()=>typeof window>"u"?"":window.location.origin||"",Hs=e=>{if(typeof window>"u")return!1;const t=lp();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}},$s=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),up=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),Rt=(e,t)=>{try{up(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},Ii=(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))},zl=e=>{if(!e)return null;try{return decodeURIComponent(e)}catch{return e}},Pa=e=>{const t=new URLSearchParams(e);return zl(t.get("directory")??t.get("location[directory]"))},Aa=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 zl(r);return null},dp=e=>{if(!$s(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!Hs(t)&&!rr(t)?null:{path:t.pathname,rest:`${t.search}${t.hash}`,origin:t.origin}}catch{return null}},fp=(e,t)=>{const n=e instanceof Request?e.url:e.toString(),r=dp(n);if(!r||!r.path.startsWith("/api/"))return e;const s=t.directory??Pa(r.rest)??(t.query?Pa(new URLSearchParams(t.query instanceof URLSearchParams?t.query:Object.entries(t.query).flatMap(([a,c])=>c==null?[]:[[a,String(c)]])).toString()):null)??Aa(t.headers)??(e instanceof Request?Aa(e.headers):null),o=Ai(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},rr=e=>{try{const t=Ae().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}},so=e=>{if(sn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return Hs(t)&&sn(t.pathname)}catch{return!1}},pp=(e,t)=>{try{const n=new URL(e);if(!Hs(n))return e;const r=Ft(`${n.pathname}${n.search}`,t);return!$s(r)&&(n.protocol==="http:"||n.protocol==="https:")?(Ii(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},Ft=(e,t)=>e==="/health"?Ae().health(t):e.startsWith("/auth/")||e==="/auth"?Ae().auth(e,t):sn(e)?Ae().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?pp(e,t):e,hp=e=>{const t=e instanceof Request?e.url:e.toString();if(!$s(t))return sn(t);try{return rr(new URL(t))}catch{return!1}},Wl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},mp=(e,t)=>!Wl(t),Ho=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)mp(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(Ho(e)??e);return t&&new Headers(Ho(t)??t).forEach((s,o)=>r.set(o,s)),n?ep(r):r},gp=(e,t)=>{if(!t)return e;const n=new URL(e,wi);return Ii(n,t),`${n.pathname}${n.search}`},Gl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!$s(n))return sn(n)?gp(n,t):null;try{const r=new URL(n);return!Hs(r)||!sn(r.pathname)?null:(Ii(r,t),`${r.pathname}${r.search}`)}catch{return null}},yp=async(e,t,n)=>{const r=js();if(!r)return null;const s=Gl(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})},wp=(e,t)=>{if(typeof e=="string")return Ft(e,t);if(e instanceof URL)return Ft(e.toString(),t);const n=Ft(e.url,t);return n===e.url?e:new Request(n,e)},Sp=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Br=new Map,bp=(e,t,n,r)=>n||e!=="GET"||t.includes("/event")||!Sp.test(t)?null:`GET ${t}\0${r.get("x-opencode-directory")??""}`,g=async(e,t={})=>{const n=fp(e,t),{query:r,directory:s,...o}=t,i=js(),a=i?Gl(n,r):null;let c,l,u,d;if(i&&a!==null){const k=n instanceof Request?n.headers:void 0,E=await pt(k,o.headers,!0);c=n instanceof Request?()=>i.fetch(n,{...o,headers:E}):()=>i.fetch(a,{...o,headers:E}),d=E,l=a,u=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase()}else{const k=wp(n,r),E=k instanceof Request?k.headers:void 0,L=await pt(E,o.headers,hp(k)),M=k instanceof Request?k.url:k instanceof URL?k.toString():String(k);Rt(M,L),c=k instanceof Request?()=>fetch(new Request(k,{...o,headers:L})):()=>fetch(k,{...o,headers:L}),d=L,l=M,u=String(o.method??(k instanceof Request?k.method:"GET")).toUpperCase()}const h=c;c=()=>h().then(k=>(op(l,k.status),k));const m=o.signal!=null||n instanceof Request,y=bp(u,l,m,d);if(!y)return c();const b=Br.get(y);if(b)return b.then(k=>k.clone());const w=c();return Br.set(y,w),w.then(()=>Br.delete(y),()=>Br.delete(y)),w.then(k=>k.clone())};let Ia=!1;const ql=()=>{if(Ia||typeof window>"u")return;Ia=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await yp(t,n??{});if(r)return r;if(typeof t=="string"){if(!so(t)){try{const i=new URL(t);if(rr(i)){const a=await pt(void 0,n?.headers);return Rt(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const s=await pt(void 0,n?.headers),o=Ft(t);return Rt(o,s),e(o,{...n,headers:s})}if(t instanceof URL){const s=t.toString();if(!so(s)){if(rr(t)){const a=await pt(void 0,n?.headers);return Rt(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const o=await pt(void 0,n?.headers),i=Ft(s);return Rt(i,o),e(i,{...n,headers:o})}if(t instanceof Request){if(!so(t.url)){try{const a=new URL(t.url);if(rr(a)){const c=await pt(t.headers,n?.headers);return Rt(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const s=await pt(t.headers,n?.headers),o=Ft(t.url);Rt(o,s);const i=o===t.url?t:new Request(o,t);return e(new Request(i,{...n,headers:s}))}return e(t,n)}},vp=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:Rt,buildRuntimeFetchUrl:Ft,installRuntimeFetchBridge:ql,isLatin1Safe:Wl,runtimeFetch:g,sanitizeHeadersForBrowser:Ho},Symbol.toStringTag,{value:"Module"})),En=16384,bs=globalThis,Tp=e=>{if(bs.Buffer)return bs.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,"")},Kl=e=>{try{if(bs.Buffer)return bs.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}},kp=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}},Ep=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}},xa=e=>typeof e=="string"&&e.length>0,Pp=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!xa(t.x)||!xa(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Ap=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ip=e=>{if(!e||typeof e!="object")return null;const t=e,n=Ap(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=kp(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=Ep(t.relayUrl);if(!r)return null;const s=typeof t.serverId=="string"?t.serverId.trim():"";if(!s)return null;const o=Pp(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},xi=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(Ip).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}},JT=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}),YT=e=>{const t=xi(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",Tp(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},xp=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=Kl(r);return!s||s.length>En?null:xi(JSON.parse(s))}catch{return null}},QT=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=Kl(s);if(!o||o.length>En)return null;try{return xi(JSON.parse(o))}catch{return null}},Rn=e=>typeof e=="object"&&e!==null,Rp=e=>e.trim().toLowerCase()==="authorization",Cp=e=>{if(!Rn(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)||Rp(s)||(t[s]=o)}return Object.keys(t).length>0?t:void 0},Op=e=>`relay://${e}`,Dp=e=>{if(!Rn(e))return null;const t=ke(e,"relayUrl")||ke(e,"relay_url"),n=ke(e,"serverId")||ke(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!Rn(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Mp=()=>{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"},XT=async(e,t)=>{const n=xp(e);if(!n)throw new Error("invalid-connect-link");const r=await Up().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:Mp(),...r?{dedupeKey:`desktop:${r}`}:{}})},o=async w=>{if(!w.ok)return null;const k=await w.json().catch(()=>null);return(typeof k?.clientToken=="string"?k.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((w,k)=>(w.type==="relay"?1:0)-(k.type==="relay"?1:0));for(const w of a){if(w.type==="relay"){const E=vi({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const L=await o(await E.fetch("/api/client-auth/pairing/redeem",s));if(L){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:L};break}}catch{}finally{E.close()}continue}const k=Ee(w.url);if(k)try{const E=await o(await fetch(`${k}/api/client-auth/pairing/redeem`,s));if(E){i={directUrl:k,token:E};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(w=>w.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),u=n.candidates.filter(w=>w.type!=="relay").map(w=>Ee(w.url)).find(w=>!!w),d=i.directUrl||u,h=d||(l?Op(l.serverId):null);if(!h)throw new Error("pairing-missing-transport");const m=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&Ee(w.apiUrl||w.url)===h),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||Vl(h),url:h,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:y,hosts:m?t.map(w=>w.id===y?b:w):[b,...t]}},_p=/^(t|.*(?:token|auth|secret|api).*)$/i,Ee=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}},ZT=e=>{const t=Ee(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"}},Vl=e=>{const t=Ee(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)_p.test(s)&&n.searchParams.set(s,"[REDACTED]");return n.toString()}catch{return t}},Hr=(e,t)=>{const n=Ee(e),r=Ee(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}},ke=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},Ra=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},Lp=e=>{if(!Rn(e))return null;const t=ke(e,"id"),n=ke(e,"label"),r=ke(e,"url"),s=ke(e,"apiUrl")||ke(e,"api_url"),o=ke(e,"clientToken")||ke(e,"client_token"),i=Cp(e.requestHeaders),a=Dp(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}:{}}},sr=e=>Ee(e.apiUrl||e.url)||e.apiUrl||e.url,an=()=>Ie()?(e,t)=>se(e,t):null,Ri=async()=>{const e=an();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Rn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(Lp).filter(a=>!!a):[],s=ke(t,"defaultHostId")||ke(t,"default_host_id")||ke(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=ke(t,"localOrigin")||ke(t,"local_origin");return{hosts:r,defaultHostId:s,initialHostChoiceCompleted:o,localOrigin:i}},Fp=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})},jp=async()=>{const e=an();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Up=async()=>{const e=an();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Np=8e3,Bp=15e3,Hp=400,$p=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)}},Ca=async(e,t,n,r)=>{for(;;){const s=n-Date.now();if(s<=0)throw new Error("relay probe deadline exceeded");try{return await $p(e,t,Math.min(Np,s),r)}catch(o){if(e.getStatus().state==="error"||Date.now()>=n)throw o;await new Promise(i=>window.setTimeout(i,Hp))}}},zp=async(e,t)=>{const n=vi({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),s=r+Bp;let o=!1;try{if(!(await Ca(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 Ca(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()}},Ci=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(!Rn(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=Ra(r,"latencyMs")??Ra(r,"latency_ms")??0;return{status:o,latencyMs:i}},ek=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})},tk=async e=>{const t=an();t&&await t("desktop_new_window_for_host",{hostId:e})},Lt="local",Wp=e=>({id:Lt,label:"Local",url:e||Jl()}),Jl=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,Gp=e=>e.id===Lt?"local":`host:${e.id}`,nk=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Lt)?.url||Jl(),r=xn(),s=Ee(n)||n,o=Ee(t)||t,i=G(),a=e.find(u=>u.relay&&Gp(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Hr(r,n))return{id:Lt,label:"Local",url:s};const c=e.find(u=>r?Hr(r,sr(u)):!1);if(c)return{id:c.id,label:c.label,url:Ee(sr(c))||sr(c)};if(t&&Hr(t,n))return{id:Lt,label:"Local",url:s};const l=e.find(u=>t?Hr(t,u.url):!1);return l?{id:l.id,label:l.label,url:Ee(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:Lt,label:"Local",url:s}:{id:"custom",label:Vl(o||"Instance"),url:o}},vs=new Map;let Yl=0;const Ts=new Map;let $o=0,Ql={byHostId:{},isProbing:!1};const zo=new Set,ks=()=>{Ql={byHostId:Object.fromEntries(vs),isProbing:$o>0};for(const e of zo)try{e()}catch{}},rk=e=>(zo.add(e),()=>{zo.delete(e)}),sk=()=>Ql,Xl=(e,t)=>{vs.set(e,t),ks()},ok=(e,t)=>{Ts.set(e,++Yl),Xl(e,t)},qp=e=>{const t=new Set([Lt,...e]);let n=!1;for(const r of Array.from(vs.keys()))t.has(r)||(vs.delete(r),Ts.delete(r),n=!0);n&&ks()},Kp=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",Vp=async()=>on()?jp().catch(()=>""):"",Jp=async(e,t)=>{const n=e.id===Lt?t:e.clientToken||"",r=async()=>{const i=await zp(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=Ee(on()?sr(e):e.url);if(!s)return{status:"unreachable",latencyMs:0};const o=await Ci(s,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Kp(o.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:o.status,latencyMs:o.latencyMs}},Yp=async e=>{if(!$e())return;const t=++Yl;for(const n of e)Ts.set(n.id,t);$o+=1,ks();try{const n=await Vp();await Promise.all(e.map(async r=>{const s=await Jp(r,n);Ts.get(r.id)===t&&Xl(r.id,s)}))}finally{$o-=1,ks()}};let Oa=!1;const Qp=async()=>{if(Oa||!$e())return;Oa=!0;const e=await Ri().catch(()=>null);e&&(qp(e.hosts.map(t=>t.id)),await Yp([Wp(e.localOrigin),...e.hosts]))},Xp=5e3,Zp=1500;let oo=!1;const eh=async e=>{if(!on()||oo)return;const t=`host:${e}`;if(G()===t){oo=!0;try{const n=await Ri().catch(()=>null),r=n?.hosts.find(d=>d.id===e);if(!n||!r?.relay)return;const s=r.apiUrl?Ee(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 h=d;if(h.type!=="lan"||typeof h.url!="string")continue;const m=Ee(h.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 Fp({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await Ci(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"||G()!==t)return;ys({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{oo=!1}}},th=e=>{typeof window>"u"||window.setTimeout(()=>{eh(e).catch(()=>{})},Xp)},nh=async e=>{if(!on())return;const t=await Ri().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(G()===s)return;const o=d=>{ys({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:s})},i=()=>{ys({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:s,relay:r.relay??void 0}),th(r.id)},a=r.apiUrl?Ee(sr(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=Ci(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),Zp))]);if(u){if(c(u)){o(a);return}i();return}i(),l.then(d=>{c(d)&&G()===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 ik=e=>e instanceof tn||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),Es=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},Ue="/api/openchamber/spaces",kr=f().regex(/^[0-9a-f]{12}$/),zs=S({code:f(),message:f()});class io extends Error{code;status;constructor(t,n,r){super(n),this.name="SpacesRequestError",this.code=t,this.status=r}}const rh=S({id:kr,name:f(),state:f()});jt("enabled",[S({enabled:D(!1)}),S({enabled:D(!0),spaces:j(rh).nullable(),failure:zs.optional()})]);const sh=S({id:kr,name:f(),code:f(),message:f()});S({enabled:he(),stopped:j(S({id:kr,name:f()})),stillRunning:j(sh),unknown:zs.optional()});const Zl=S({mode:J(["allowlist","open"]),domains:j(f())}),eu=jt("kind",[S({kind:D("model"),id:f(),provider:f(),upstream:f(),source:jt("kind",[S({kind:D("typed")}),S({kind:D("env"),name:f()})]),url:f()}),S({kind:D("domain"),id:f(),upstream:f(),url:f()})]),oh=["checking_place","creating","setting_network","bringing_code","ready"],ih=J(oh),tu=jt("state",[S({state:D("queued"),total:x().int().min(1)}),S({state:D("running"),index:x().int().min(0),total:x().int().min(1),command:f()}),S({state:D("done"),total:x().int().min(1)}),S({state:D("failed"),index:x().int().min(0),total:x().int().min(1),command:f(),exitCode:x().int().nullable(),timedOut:he()}),S({state:D("interrupted"),total:x().int().min(1)})]),cn=S({id:kr,name:f(),projectDirectory:f().nullable(),directory:f().nullable(),state:J(["preparing","running","exited","missing","failed"]),stoppedIdle:he().default(!1),step:ih.nullable(),failure:zs.nullable(),network:Zl.nullable(),grants:j(eu),access:J(["granted","needs_access","unknown"]).nullable(),needsAccess:j(f()),damage:J(["repairable","gatekeeper_gone"]).nullable().default(null),setup:tu.nullable().default(null)}),ah=ct([S({id:f(),available:D(!0),hostIsolation:he()}),S({id:f(),available:D(!1),code:f(),message:f()})]),ch=S({code:f(),message:f()}),Ne=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=ch.safeParse(s);throw i.success?new io(i.data.code,i.data.message,r.status):new io("space_request_failed",`The server answered ${r.status}.`,r.status)}const o=t.safeParse(s);if(!o.success)throw new io("space_answer_malformed","The server answered in a shape this version does not know.",r.status);return o.data},ak=async e=>(await Ne(`${Ue}/places`,S({places:j(ah)}),{signal:e})).places,lh=async e=>(await Ne(Ue,S({spaces:j(cn)}),{signal:e})).spaces,ck=e=>Ne(Ue,cn,{method:"POST",body:JSON.stringify(e)}),lk=async(e,t)=>(await Ne(`${Ue}/${e}/grants`,S({grant:eu}),{method:"POST",body:JSON.stringify(t)})).grant,uk=async(e,t)=>(await Ne(`${Ue}/${e}/network/domains`,S({network:Zl}),{method:"POST",body:JSON.stringify({domain:t})})).network,uh=S({at:f(),listener:f(),host:f(),port:x(),decision:f()}),dh=S({records:j(uh),dropped:x(),since:f()}),dk=(e,t)=>Ne(`${Ue}/${e}/journal`,dh,{signal:t}),fh=S({id:kr,removed:he(),failures:j(zs)}),fk=e=>Ne(`${Ue}/${e}/start`,cn,{method:"POST"}),pk=e=>Ne(`${Ue}/${e}/stop`,cn,{method:"POST"}),hk=e=>Ne(`${Ue}/${e}/restart`,cn,{method:"POST"}),mk=e=>Ne(`${Ue}/${e}/restart-opencode`,cn,{method:"POST"}),ph=1,hh=168;S({enabled:he(),hours:x().int().min(ph).max(hh)});const gk=(e,t)=>Ne(`${Ue}/${e}/setup`,cn,{method:"POST",body:JSON.stringify({commands:t})}),mh=S({setup:tu.nullable(),output:f().nullable()}),yk=(e,t)=>Ne(`${Ue}/${e}/setup`,mh,{signal:t}),wk=e=>Ne(`${Ue}/${e}`,fh,{method:"DELETE"}),gh=S({id:f().regex(/^[0-9a-f]{12}$/),name:f().default(""),state:J(["complete","partial","stale","unknown"]),projectDirectory:f().nullable().default(null),directory:f().nullable().default(null)}),Da=new Map,zn=new Map,yh=(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},Ma=(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},Ps=ut((e,t)=>({spaces:Da,journey:null,progressRevision:0,applyJourney:(n,r)=>e(s=>{const o=new Map(n.map(i=>[i.id,i]));for(const[i,a]of zn){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;zn.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;zn.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}}),deleteDialog:null,openDeleteDialog:n=>e({deleteDialog:n}),closeDeleteDialog:()=>e({deleteDialog:null}),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;zn.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,yh(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:Ma(s.spaces,n,"stale")}),noteReachable:n=>e(r=>({spaces:Ma(r.spaces,n,"complete")})),resetForRuntimeSwitch:()=>{zn.clear(),As+=1,e({spaces:Da,journey:null,progressRevision:0,creationAccess:new Map,accessDialog:null,actions:new Map,deleteDialog:null,setupOutputDialog:null,actionsSheet:null})},forgetForSwitchOff:()=>t().resetForRuntimeSwitch()}));let As=0;const Sk=()=>As,bk=async()=>{const e=As,t=Ps.getState().progressRevision,n=await lh();e===As&&Ps.getState().applyJourney(n,t)},wh=(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},vk=()=>{const e=yi.c(3),t=Ps(Sh),n=Ps(bh);let r;return e[0]!==n||e[1]!==t?(r=wh(t,n),e[0]=n,e[1]=t,e[2]=r):r=e[2],r};function Sh(e){return e.spaces}function bh(e){return e.journey}const _a=500,nu=()=>{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}},Tk=()=>nu(),Ke=(e,t)=>{if(!nu())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)},vh=()=>{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__=vh);const kk=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();Ke(`${e}:start`,n);try{const s=await t(),o=typeof performance<"u"?performance.now():Date.now();return Ke(`${e}:end`,{durationMs:Math.round(o-r)}),s}catch(s){const o=typeof performance<"u"?performance.now():Date.now();throw Ke(`${e}:error`,{durationMs:Math.round(o-r),error:s instanceof Error?s.message:String(s)}),s}},Th=3,kh=3e4,Eh=32e3,Ph=3600*1e3,Ah=600*1e3,Ih=200,xh=new Set([429,502,503,504]),gt=new Map,Oi=e=>JSON.stringify([G(),e]);function Rh(){const e=Date.now();for(const[t,n]of gt){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>Ph&&gt.delete(t)}}typeof setInterval<"u"&&setInterval(Rh,Ah).unref?.();function Ch(e){const t=Oi(e);let n=gt.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:kh},gt.set(t,n);gt.size>Ih;){const r=gt.keys().next().value;if(!r)break;gt.delete(r)}return n}function Oh(e){e&&gt.delete(Oi(e))}function Dh(e,t){if(!e)return;const n=Ch(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Mh(t)&&n.consecutiveErrors>=Th&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Mh(e){return e!==void 0&&xh.has(e)}function _h(e){const t=gt.get(Oi(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Eh*4),!1):!0:!1}function Lh(e){if(!(!e||!_h(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const ru=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,La=/^(?:\/\/\?\/)?[A-Za-z]:$/u,Fh=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/UNC\/[^/]+\/[^/]+)$/iu,Xe=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==="/"?"/":ru.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},jh=e=>{if(e==="/"||ru.test(e)||La.test(e)||Fh.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const n=e.slice(0,t);return La.test(n)?`${n}/`:n},Uh=e=>Xe(e)??"",Nh="openchamber",Bh="auto",Hh=(e,t)=>e===Nh&&t===Bh,$h=lt(f().min(1),S({type:D("running")})),zh=S({id:f().min(1),sessionID:f().min(1),action:f(),resources:j(f())}),Wh=S({id:f().min(1),sessionID:f().min(1),title:f()}),Gh=S({sessions:lt(f().min(1),S({status:f(),lastUpdateAt:x()})),pending:lt(f().min(1),S({permissions:j(zh),forms:j(Wh)})).optional(),serverTime:x()});function Ek(e,t){if(!(!e||!t))return e.find(n=>n.id===t)??e.find(n=>n.modelID===t)}function K(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}`},Pk=e=>e==="completed"||e==="error",su=e=>e.role==="user"||e.role==="assistant",Ak=e=>e==="user"||e==="assistant",Ik=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&su(n))return n}},xk=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.info&&su(n.info))return n}},Rk=e=>e?.role==="assistant"&&e.time.completed===void 0,Fa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",qh=14;let ja=0,ao=0;const Kh=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+=Fa[t[r]%Fa.length];return n},co=e=>{const t=Date.now();t!==ja&&(ja=t,ao=0),ao+=1;const n=BigInt(t)*BigInt(4096)+BigInt(ao),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}${Kh(qh)}`},lo=e=>JSON.parse(JSON.stringify(e));function $r(e){return K({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:K({...e.time}),metadata:e.metadata,permissions:e.permissions,revert:e.revert,fork:e.fork})}function Vh(e){return K({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 Jh(e){return K({branch:e.branch.current,defaultBranch:e.branch.default})}function Ua(e){return!e||e.length===0?"":e.filter(t=>t.type==="text").map(t=>t.text).join(`
3
+ `)}function Yh(e,t){if(!e)return;const n=e.filter(r=>r.type==="file");if(n.length!==0)return n.map((r,s)=>K({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 Qh(e){return e.message||e.type}function Xh(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=K({status:"running",input:e.state.input,metadata:e.state.metadata,time:{start:n}});break;case"completed":o=K({status:"completed",input:e.state.input,output:Ua(e.state.content),metadata:e.state.metadata,time:{start:n,end:r},attachments:Yh(e.state.content,s)});break;case"error":o=K({status:"error",input:e.state.input,error:Qh(e.state.error),output:Ua(e.state.content)||void 0,metadata:e.state.metadata,time:{start:n,end:r}});break}return K({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 Zh(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:K({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:K({start:o.time?.created??t.created,end:o.time?.completed})});break}case"tool":n.push(Xh(o,t));break}return n}function em(e,t){return K({id:e.id,sessionID:t,role:"assistant",time:K({...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 tm(e){return e.source.type==="uri"?e.source.uri:`data:${e.mime};base64,${e.data}`}function nm(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(K({id:Pn.userFile(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name,url:tm(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 rm(e,t){const n=e.metadata;switch(e.type){case"user":return{message:K({id:e.id,sessionID:t,role:"user",time:{...e.time},metadata:n}),parts:nm(e,{sessionID:t,messageID:e.id,created:e.time.created})};case"assistant":return{message:em(e,t),parts:Zh(e.content,{sessionID:t,messageID:e.id,created:e.time.created,completed:e.time.completed})};case"synthetic":return{message:K({id:e.id,sessionID:t,role:"synthetic",time:{...e.time},text:e.text,description:e.description,metadata:n}),parts:[]};case"system":return{message:K({id:e.id,sessionID:t,role:"system",time:{...e.time},text:e.text,description:e.description,metadata:n}),parts:[]};case"skill":return{message:K({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:K({id:e.id,sessionID:t,role:"shell",time:K({...e.time}),shellID:e.shellID,command:e.command,status:e.status,exit:sm(e.exit),output:e.output,metadata:n}),parts:[]};case"compaction":return{message:K({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:K({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:K({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:K({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:K({id:e.id,sessionID:t,role:"idle",time:{...e.time},outcome:e.outcome,metadata:n}),parts:[]}}}function sm(e){return e==="Infinity"||e==="-Infinity"||e==="NaN"?void 0:e}function Na(e,t){return e.map(n=>rm(n,t))}const ou=e=>e.type==="document";function om(e){const t={};for(const n of e)if(ou(n))for(const[r,s]of Object.entries(n.info)){if(s===void 0)continue;const o=t[r];t[r]=Ba(o)&&Ba(s)?{...o,...s}:s}return t}function im(e){return e.some(t=>ou(t)&&(t.info.experimental?.policies??[]).some(n=>n.action==="provider.use"&&n.effect==="deny"))}function Ba(e){return Object.prototype.toString.call(e)==="[object Object]"}const am=e=>({...e,name:e.id,displayName:e.name}),Ha="/api",cm=1e4,lm=4e3,um=100,dm=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 fm=S({_tag:f(),message:f().optional(),ref:f().optional()});function pm(e,t){if(t instanceof ht)return t;if(t instanceof Ad){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"&&ua(t.cause)&&_o(r),r}const n=fm.safeParse(t);if(n.success)return new ht(e,n.data.message??n.data._tag,{status:dm.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 ua(t)&&_o(r),r}return new ht(e,String(t),{cause:t})}const hm=e=>e.tag==="InvalidRequestError"&&e.detail.startsWith("Skill not found"),mm=e=>e instanceof ht&&e.status===404;async function O(e,t){try{return await t()}catch(n){throw pm(e,n)}}const gm=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,$a=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}},za=()=>{try{return Ae().api("/api")}catch{return null}},iu=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)}},ym=3e4,wm=e=>e.pathname.endsWith("/event")||e.pathname.endsWith("/log"),Sm="x-opencode-directory",bm=e=>e.replace(/\/api\/*$/,"")||"/",uo=e=>{const t=e.requestTimeoutMs??ym;return Pd.make({baseUrl:bm(e.baseUrl),headers:e.directory?{[Sm]: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(wm(s)||o==="POST")return g(n,r);const i=iu(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 h=!1;try{const m=await g(n,{...r,signal:l});return h=m.body!==null,m}catch(m){throw i.signal.aborted&&!a?.aborted?new Error(`OpenCode request timed out after ${t}ms`):m}finally{!h||l.aborted?d():l.addEventListener("abort",d,{once:!0})}}})},vm=S({spaces:j(gh).optional()}),Tm=S({reason:f().optional(),isDirectory:he().optional()}),fn=e=>e.replace(/\\/g,"/"),Wa=400,Ga=()=>{const e=br();return e&&e.runtime?.isDesktop&&e.files?e.files:null},zr=f().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),km=S({home:zr,chatsRoot:zr.optional(),canonicalChatsRoot:zr.optional(),canonicalLegacyChatsRoot:zr.optional()}),qa=e=>K({previous:e.previous??void 0,next:e.next??void 0}),Ka=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 Em{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=Ha){const r=za()||t;this.baseUrl=$a(r),this.client=uo({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==G())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=za(),n=$a(t||Ha);this.baseUrl=n,this.client=uo({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=uo({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 Xe(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&&Ke("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 O("location.get",()=>this.clientFor(t).location.get())}async listProjects(){return(await O("project.list",()=>this.client.project.list())).map(Vh)}async getCurrentProject(t){return(await O("location.get",()=>this.clientFor(t).location.get())).project}async getVcs(t){return O("vcs.get",()=>this.clientFor(t).vcs.get().then(n=>Jh(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=Tm.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&s?.isDirectory===!0)return"available";const o=Es(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 O("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?vm.safeParse(s).data?.spaces:void 0;return{sessions:s.data.map($r),cursor:qa(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 O("session.create",()=>this.clientFor(n).session.create({id:t?.id,title:t?.title,agent:t?.agent,model:t?.model&&Hh(t.model.providerID,t.model.id)?void 0:t?.model,location:r?{directory:r}:void 0,metadata:t?.metadata}));return $r(s)}async getSession(t,n){const r=await O("session.get",()=>this.clientFor(n).session.get({sessionID:t}));return $r(r)}async deleteSession(t,n){return await O("session.remove",()=>this.clientFor(n).session.remove({sessionID:t})),!0}async renameSession(t,n,r){await O("session.update",()=>this.clientFor(r).session.update({sessionID:t,title:n}))}async moveSession(t,n,r){const s=this.normalizeCandidatePath(n)??n;await O("session.move",()=>this.client.session.move({sessionID:t,directory:s,delivery:r?.delivery}))}async switchSessionModel(t,n,r){await O("session.switchModel",()=>this.clientFor(r).session.switchModel({sessionID:t,model:n}))}async switchSessionAgent(t,n,r){await O("session.switchAgent",()=>this.clientFor(r).session.switchAgent({sessionID:t,agent:n}))}async getSessionMessages(t,n,r){const s=await O("message.list",()=>this.clientFor(r).message.list({sessionID:t,limit:n?.limit,cursor:n?.cursor,order:n?.cursor?void 0:n?.order})),o=Na(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:qa({...s.cursor,next:i?void 0:s.cursor.next})}}async getSessionMessage(t,n,r){const s=await O("session.message.get",()=>this.clientFor(r).session.message.get({sessionID:t,messageID:n})),[o]=Na([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 gi(async()=>{const{default:d}=await import("./vendor-heic2any-CEam9pDc.js").then(h=>h.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,h)=>{const m=new FileReader;m.onload=()=>d(m.result),m.onerror=h,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??co("msg")})),r=t.messageId??co("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)");Lh(t.providerID);const i=async c=>{this.assertRuntimeUnchanged(t.runtimeKey),await O("session.synthetic",()=>this.clientFor(t.directory).session.synthetic({sessionID:t.id,id:c.id,text:c.text,description:c.description,metadata:c.metadata?lo(c.metadata):void 0,delivery:t.delivery,resume:!1}))},a=c=>(this.assertRuntimeUnchanged(t.runtimeKey),O("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)||!hm(u))throw u;const d=t.skills?.instructionFor(c.attached.map(h=>h.name))??null;d&&await i({text:d}),await a([])}}catch(c){throw Dh(t.providerID,c instanceof ht?c.status:void 0),c}return Oh(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 O("session.synthetic",()=>this.clientFor(t.directory).session.synthetic({sessionID:t.id,id:r.id,text:r.text,description:r.description,metadata:r.metadata?lo(r.metadata):void 0,delivery:t.delivery,resume:!1})));this.assertRuntimeUnchanged(t.runtimeKey),await O("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 O("session.interrupt",()=>this.clientFor(n).session.interrupt({sessionID:t}))).interrupted}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??co("msg");return await O("session.shell",()=>this.clientFor(t.directory).session.shell({sessionID:t.sessionId,id:n,command:t.command})),n}async stageRevert(t,n,r){return O("session.revert.stage",()=>this.clientFor(r?.directory).session.revert.stage({sessionID:t,messageID:n,files:r?.files}))}async commitRevert(t,n){await O("session.revert.commit",()=>this.clientFor(n).session.revert.commit({sessionID:t}))}async clearRevert(t,n){await O("session.revert.clear",()=>this.clientFor(n).session.revert.clear({sessionID:t}))}async compactSession(t,n){await O("session.compact",()=>this.clientFor(n).session.compact({sessionID:t}))}async forkSession(t,n){const r=await O("session.fork",()=>this.clientFor(n?.directory).session.fork({sessionID:t,before:n?.before}));return $r(r)}async getActiveSessionStatuses(t){try{const n=Ea(t)&&t?this.getScopedSdkClient(t):this.client,r=$h.parse(await O("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=Gh.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 O("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 O("session.diff",()=>this.clientFor(n?.directory).session.diff(i))]}async generateText(t,n){return(await O("generate.text",()=>this.clientFor(n?.directory).generate.text({prompt:t,model:n?.model}))).text}async replyToPermission(t,n,r,s){return await O("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 O("permission.create",()=>this.clientFor(s?.directory).permission.create({sessionID:t,action:n,resources:r,id:s?.id,save:s?.save,metadata:s?.metadata?lo(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 O("permission.get",()=>this.clientFor(r).permission.get({sessionID:t,requestID:n}))}}catch(s){return mm(s)?{state:"resolved"}:{state:"unknown"}}}async listPendingPermissions(t){const n=this.uniqueDirectories(t?.directories,t?.includeGlobal),r=await Promise.all(n.map(s=>O("permission.request.list",()=>(s?this.getScopedSdkClient(s):this.client).permission.request.list().then(o=>o.data))));return Ka(r)}async replyToForm(t,n,r,s){return await O("session.form.reply",()=>this.clientFor(s).session.form.reply({sessionID:t,formID:n,answer:r})),!0}async cancelForm(t,n,r){return await O("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=>O("form.list",()=>(s?this.getScopedSdkClient(s):this.client).form.list().then(o=>o.data))));return Ka(r)}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 O("config.get",()=>this.clientFor(this.resolveDirectory(t)).config.get());return im(n)}async getConfig(t){const n=this.resolveDirectory(t),r=n??"",s=this.configCache.get(r);if(s&&s.expiresAt>Date.now())return Ke("opencodeClient.getConfig:cacheHit",{directory:n??null}),s.config;const o=this.configInFlight.get(r);if(o)return Ke("opencodeClient.getConfig:deduped",{directory:n??null}),o;const i=this.configCacheGeneration,a=(async()=>{Ke("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),l=await O("config.get",()=>this.clientFor(n).config.get()),u=om(l),d=typeof performance<"u"?performance.now():Date.now();return Ke("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(d-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:u,expiresAt:Date.now()+cm}),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){const n=this.resolveDirectory(t),r=n??"",s=this.providerCatalogInFlight.get(r);if(s)return s;const o=(async()=>{const i=this.clientFor(n),a=Ea(n)?this.client:i,[c,l,u]=await Promise.all([O("provider.list",()=>a.provider.list().then(d=>d.data)),O("model.list",()=>i.model.list().then(d=>d.data)),O("model.default",()=>i.model.default().then(d=>d.data)).catch(()=>{})]);return K({providers:c,models:l,default:u?{id:u.modelID,providerID:u.providerID}:void 0})})();this.providerCatalogInFlight.set(r,o);try{return await o}finally{this.providerCatalogInFlight.get(r)===o&&this.providerCatalogInFlight.delete(r)}}async listAgents(t){const n=this.resolveDirectory(t),r=n??"",s=this.listAgentsInFlight.get(r);if(s)return s;const o=O("agent.list",()=>this.clientFor(n).agent.list().then(i=>i.data.map(am)));this.listAgentsInFlight.set(r,o);try{return await o}finally{this.listAgentsInFlight.get(r)===o&&this.listAgentsInFlight.delete(r)}}async listCommands(t,n){return O("command.list",()=>this.clientFor(t).command.list(void 0,{signal:n}).then(r=>r.data))}async listSkills(t){return O("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 O("mcp.list",()=>this.clientFor(t).mcp.list().then(n=>n.data))}async connectMcpServer(t,n){await O("mcp.connect",()=>this.clientFor(n).mcp.connect({server:t}))}async disconnectMcpServer(t,n){await O("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`;Ke("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});let r;try{const s=iu(lm);r=await g(n,{signal:s.signal}).finally(s.cleanup)}catch{return"unreachable"}if(Ke("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 Ke("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0?"healthy":"unhealthy"}catch{return"unhealthy"}}async createDirectory(t,n){const r=Ga();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=Ga();try{if(u){const w=await u.listDirectory(t||"",n);if(!w||!Array.isArray(w.entries))throw new tn("Directory listing returned an invalid response",{reason:"invalid-response"});const k=w.entries.map(E=>({name:E.name,path:fn(E.path),isDirectory:!!E.isDirectory,isFile:!E.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(s,{entries:k,expiresAt:Date.now()+Wa}),k}const d=new URLSearchParams;t&&t.trim().length>0&&d.set("path",t),n?.respectGitignore&&d.set("respectGitignore","true");const h=d.toString(),m=await g(`${this.baseUrl}/fs/list${h?`?${h}`:""}`);if(!m.ok){const w=await m.json().catch(()=>({})),k=typeof w.error=="string"?w.error:"Failed to list directory";throw new tn(k,{reason:Es(w.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()+Wa}),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 O("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=G();if(!t||t==="local"){const n=await Tl();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 km.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 ot=new Em;let fo=null,po=null,ho=null;const Va=new Set;let Ja=!1;const au=e=>{if(Va.add(e),Ja||typeof window>"u")return;Ja=!0;const t=()=>{for(const n of Va)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{}},Pm=(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(h){console.error("Failed to persist deferred storage value",h),!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 au(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()}}},Di=e=>Pm(()=>uu(),e),Am=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 au(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}}},cu=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},Mi=()=>{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}}},lu=e=>{const t=Mi(),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}}},Im=()=>{const e=cu("localStorage");return e?lu(e):Mi()},uu=()=>(fo||(fo=Im()),fo),Er=()=>(ho||(ho=Am(uu())),ho),xm=()=>{const e=cu("sessionStorage");return e?lu(e):Mi()},Rm=()=>(po||(po=xm()),po),Cm={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.84375rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},Ck={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function Ya(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Wr={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)"}}},mo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Wr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:mo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Wr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:mo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Wr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:mo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Wr.tool.inline})},Om=[{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'}],Dm=[{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'}],du=e=>Object.fromEntries(e.map(t=>[t.id,t])),Mm=du(Om),_m=du(Dm),Lm="system",Fm="system-mono",jm=e=>typeof e=="string"&&e in Mm,Um=e=>typeof e=="string"&&e in _m,Wo="openchamber.mobileKeyboardMode",Nm='meta[name="viewport"]',Qa="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Ok=()=>!0;function Ws(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const Bm=e=>Ws(e)==="resize-content"?`${Qa}, interactive-widget=resizes-content`:Qa,Hm=()=>{if(typeof window>"u")return"resize-content";try{return Ws(localStorage.getItem(Wo))}catch{return"resize-content"}},fu=e=>{const t=Ws(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Wo):localStorage.setItem(Wo,t)}catch{}return t},Dk=e=>{const t=fu(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(Nm);if(n instanceof HTMLMetaElement){const r=Bm(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},go=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),$m=new Set(["starting","running","stopping"]),zm=e=>!!e?.tabs.some(t=>vn(t.purpose)&&t.lifecycle!=="exited"),Go=512*1024,Wm=new TextEncoder,Gm=new TextDecoder,yo=e=>{const t=Wm.encode(e);if(t.byteLength<=Go)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Go;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Gm.decode(r),byteLength:r.byteLength}},et=(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},qm="terminal-store";let Xa=!1,Za=0;const Km=S({type:D("project-action"),actionId:f()}),Jn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Za+=1,`tab-${Date.now().toString(36)}-${Za.toString(36)}`),wo=e=>typeof e=="object"&&e!==null,vn=e=>e.type==="project-action",Gr=(e,t)=>vn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,Vm=()=>Jn().replace(/^tab-/,"exec-"),ec=e=>e==="running"?"running":"exited",Jm=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),Ym=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()]},So={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},Qm=e=>e.trim()||"Action",Xm=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},ne=Uh,Is=(e,t)=>`${e}\0${t}`,Wn=(e,t,n,r)=>{e.set(Is(t,n),r)},tc=(e,t,n,r)=>{if(!r)return!1;const s=Is(t,n),o=e.actionMutationRevisions.get(s)??0,i=r.get(s)??0;return o>i},Zm=/^Terminal(?: (\d+))?$/,nc=e=>{let t=0;for(const n of e){const r=Zm.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}`},Mk=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&$m.has(e.lifecycle),eg=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}),bo=e=>({tabs:[e],activeTabId:e.id}),Re=(e,t)=>e.tabs.findIndex(n=>n.id===t);let vo=null,To=null;const tg=e=>{if(To&&vo?.sessions===e.sessions&&vo.nextTabId===e.nextTabId)return To;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 vo={sessions:e.sessions,nextTabId:e.nextTabId},To=t,t},ng=()=>{const e=Ed(()=>Rm());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))}},is=ut()(Mn(Sr((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=Jn(),a=qr(i,"Terminal");return o.set(r,bo(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(et(ne(n),r))??go,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=Is(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=Jn();return e(o=>{const i=new Map(o.sessions),a=i.get(r),c=o.nextTabId+1,l=nc(a?.tabs??[]),u=qr(s,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,bo(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 h=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(et(o,c[0].id))?c[0]:null;y&&r.length>0&&(c.length=0);for(const C of Ym(r)){let Te=c.findIndex(N=>N.terminalSessionId===C.sessionId||N.id===C.sessionId);const ce=C.purpose,Js=ce?.type==="project-action"&&tc(i,o,ce.actionId,s?.startedActionMutationRevisions);if(ce?.type==="project-action"){h.add(ce.actionId);const N=c.findIndex(Ze=>vn(Ze.purpose)&&Ze.purpose.actionId===ce.actionId);if(Js){N>=0&&m.add(c[N].id);continue}Te<0&&(Te=N)}const xe=ce?.type==="project-action"?Jm(ce,C.status):{type:"terminal"};if(Te>=0){const N=c[Te];let Ze=N.purpose.type==="project-action"||ce?.type==="project-action"?ec(C.status):C.status;N.lifecycle==="stopping"&&C.status==="running"&&N.purpose.type==="project-action"&&xe.type==="project-action"&&N.purpose.executionId===xe.executionId&&(Ze="stopping");const un=C.createdAt??N.createdAt,Cr=ce?.type==="project-action"&&(N.terminalSessionId!==C.sessionId||xe.type==="project-action"&&xe.executionId!==null&&(N.purpose.type!=="project-action"||N.purpose.executionId!==xe.executionId));if(Cr){const vt=et(o,N.id);l=pn(l,Ys=>Ys===vt)??l}const Nn=ce?.type==="project-action"&&C.status==="running"&&(N.terminalSessionId!==C.sessionId||N.lifecycle!=="running"),Or=N.purpose.type!==xe.type||N.purpose.type==="project-action"&&xe.type==="project-action"&&(N.purpose.actionId!==xe.actionId||N.purpose.executionId!==xe.executionId);if((N.terminalSessionId!==C.sessionId||N.lifecycle!==Ze||N.isConnecting!==!1||N.createdAt!==un||Or)&&(c[Te]={...N,terminalSessionId:C.sessionId,lifecycle:Ze,purpose:xe,isConnecting:!1,createdAt:un},Cr&&Object.assign(c[Te],So),u=!0),Nn){const vt={tabId:N.id,createdAt:un,index:Te};(!d||vt.createdAt>d.createdAt||vt.createdAt===d.createdAt&&vt.index>d.index)&&(d=vt)}m.add(N.id);continue}const jn=ce?.type==="project-action"?Qm(ce.actionId):y&&c.length===0?y.label:nc(c),Un=ce?.type==="project-action"?"play":null,Bt={...qr(C.sessionId,jn),terminalSessionId:C.sessionId,lifecycle:ce?.type==="project-action"?ec(C.status):C.status,purpose:xe,iconKey:Un,createdAt:C.createdAt??Date.now()};if(c.push(Bt),u=!0,ce?.type==="project-action"&&C.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 w=c.map(C=>!vn(C.purpose)||h.has(C.purpose.actionId)||m.has(C.id)||C.lifecycle==="starting"||tc(i,o,C.purpose.actionId,s?.startedActionMutationRevisions)||C.lifecycle==="exited"&&!C.isConnecting?C:(b=!0,{...C,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:C.purpose.actionId,executionId:null}})),k=a?.activeTabId??null,E=k&&w.some(C=>C.id===k)?k:w[0]?.id??null,L=E?w.find(C=>C.id===E):w[0],M=d&&!eg(L)?d.tabId:E;if(!b&&a&&M===a.activeTabId&&w.length===a.tabs.length&&w.every((C,Te)=>C===a.tabs[Te]))return i;const Y=new Map(i.sessions);return Y.set(o,{tabs:w,activeTabId:M}),{sessions:Y,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||Re(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=Re(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}})},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=Re(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=Re(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),Wn(u,s,l.actionId,d),d+=1);const h={actionMutationRevisions:u,nextActionMutationRevision:d},m=a.tabs.filter(E=>E.id!==r),y=et(s,r),b=o.buffers.has(y)?pn(o.buffers,E=>E===y):null;if(m.length===0){const E=Jn(),L=qr(E,"Terminal");i.set(s,bo(L));const M={sessions:i,nextTabId:o.nextTabId+1};return b&&(M.buffers=b),{...M,...h}}let w=a.activeTabId;a.activeTabId===r&&(w=m[Math.min(c,m.length-1)]?.id??m[0]?.id??null),i.set(s,{...a,tabs:m,activeTabId:w});const k={sessions:i};return b&&(k.buffers=b),{...k,...h}})},setTabPurpose:(n,r,s)=>{const o=ne(n);e(i=>{const a=i.sessions.get(o);if(!a)return i;const c=Re(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],So);const h=et(o,r),m=d?pn(i.buffers,w=>w===h)??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 Wn(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||Re(i,r)<0)return null;const a=Vm();return e(c=>{const l=c.sessions.get(o);if(!l)return c;const u=Re(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,...So,isConnecting:!1};const h=new Map(c.sessions);h.set(o,{...l,tabs:d});const m=new Map(c.actionMutationRevisions);Wn(m,o,s,c.nextActionMutationRevision);const y=et(o,r),b=pn(c.buffers,w=>w===y)??c.buffers;return{sessions:h,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=Re(l,r);if(u<0)return a;const d=l.tabs[u];if(!Gr(d,o?.expectedExecutionId))return a;const h=s!==null&&d.terminalSessionId!==s,m=s?"running":d.terminalSessionId?"exited":d.lifecycle,y={...d,terminalSessionId:s,lifecycle:m,isConnecting:!1},b=et(i,r),w=h&&a.buffers.has(b)?pn(a.buffers,L=>L===b):null,k=[...l.tabs];k[u]=y,c.set(i,{...l,tabs:k});const E={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(vn(d.purpose)){const L=new Map(a.actionMutationRevisions);Wn(L,i,d.purpose.actionId,a.nextActionMutationRevision),E.actionMutationRevisions=L,E.nextActionMutationRevision=a.nextActionMutationRevision+1}return w&&(E.buffers=w),E})},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=Re(l,r);if(u<0||!Gr(l.tabs[u],o?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===s&&!d.isConnecting)return a;const h=[...l.tabs];if(h[u]={...d,lifecycle:s,isConnecting:!1},c.set(i,{...l,tabs:h}),d.purpose.type!=="project-action"||d.lifecycle===s)return{sessions:c};const m=new Map(a.actionMutationRevisions);return Wn(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=Re(l,r);if(u<0||!Gr(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||Re(l,r)<0)return c;const u=et(a,r),d=c.buffers.get(u)??go;if(d.lastSequence>o)return c;const h=yo(s),m=d.chunks[0]?.size;if(d.lastSequence===o&&d.byteLength===h.byteLength&&d.chunks.map(w=>w.data).join("")===h.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:h.text?[{id:y,data:h.text,byteLength:h.byteLength,...i?{size:i}:{}}]:[],byteLength:h.byteLength,lastSequence:o}),{buffers:b,nextChunkId:h.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||Re(l,r)<0)return c;const u=et(a,r),d=c.buffers.get(u)??go;if(o!==void 0&&o<=d.lastSequence)return c;const h=c.nextChunkId,m=yo(s),y=i!==void 0&&i!==s?yo(i).text:void 0,b={id:h,data:m.text,...y!==void 0?{replayData:y}:{},byteLength:m.byteLength},w=[...d.chunks,b];let k=d.byteLength+b.byteLength;for(;k>Go&&w.length>1;){const L=w.shift();if(!L)break;k-=L.byteLength}const E=new Map(c.buffers);return E.set(u,{chunks:w,byteLength:k,lastSequence:o??d.lastSequence}),{buffers:E,nextChunkId:h+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=Re(l,r);if(u<0)return a;const d=l.tabs[u];if(!Gr(d,o.expectedExecutionId))return a;const h=o.autoOpened??d.previewAutoOpened,m=o.locked??d.previewUrlLocked;if(d.previewUrl===s&&d.previewAutoOpened===h&&d.previewUrlLocked===m)return a;const y=[...l.tabs];return y[u]={...d,previewUrl:s,previewAutoOpened:h,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=Re(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=et(r,""),a=pn(s.buffers,d=>d.startsWith(i)),c=Is(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:qm,storage:ng(),partialize:tg,merge:(e,t)=>{if(!wo(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"||!wo(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],h=new Map;for(const w of u){if(!wo(w))continue;const k=typeof w.id=="string"?w.id:null;if(!k)continue;const E=Xm(k);E!==null&&(s=Math.max(s,E));const L=E===null?k:Jn();h.set(k,L);const M=Km.safeParse(w.purpose).data,Y=M?{type:"project-action",actionId:M.actionId,executionId:null}:{type:"terminal"};d.push({id:L,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:Y,createdAt:typeof w.createdAt=="number"?w.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?h.get(m)??m:null,b=y?d.some(w=>w.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"&&!Xa){Xa=!0;const e=is.persist,t=()=>{is.getState().hasHydrated||is.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const tt=20,rg=8,rc=4096,sg=2160*60*6e4,Z=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},Ct=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Dt=(e,t)=>{const n=Z(t),r=Z(e);if(!n||!r)return!1;const s=Ct(n),o=Ct(r);return o===s||o.startsWith(`${s}/`)},Gn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=Z(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=>Z(m)).filter(m=>m.length<=rc&&Dt(m,o)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(m=>typeof m=="string").map(m=>Z(m)).filter(m=>m.length<=rc&&Dt(m,o)))).slice(-500):[],l=typeof i.selectedPath=="string"?Z(i.selectedPath):null,u=l&&Dt(l,o)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>sg)continue;const h=n[o];if(h){const m=Array.from(new Set([...h.openPaths,...a])),y=Array.from(new Set([...h.expandedPaths,...c])),b=h.selectedPath??u??m[0]??null;n[o]={openPaths:m,selectedPath:b,expandedPaths:y,touchedAt:Math.max(h.touchedAt,d)};continue}n[o]={openPaths:a,selectedPath:u,expandedPaths:c,touchedAt:d}}return nt(n,tt)},nt=(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()},og=ut()(Mn(Sr((e,t)=>({byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const s={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Gn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:s,byRoot:Gn(s[n]?.byRoot)}})},addOpenPath:(n,r,s)=>{const o=Z((n||"").trim()),i=Z((r||"").trim());!o||!i||!s?.allowOutsideRoot&&!Dt(i,o)||e(a=>{const c=a.byRoot[o],l=hn(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],h=l.selectedPath??i;if(c&&u&&c.selectedPath===h)return a;const m={...a.byRoot,[o]:{...l,openPaths:d,selectedPath:h}};return{byRoot:nt(m,tt)}})},removeOpenPath:(n,r)=>{const s=Z((n||"").trim()),o=Z((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=Ct(o),l=y=>Ct(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)),h=u?d[0]??null:a.selectedPath,m={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:h,touchedAt:Date.now()}};return{byRoot:nt(m,tt)}})},removeOpenPathsByPrefix:(n,r)=>{const s=Z((n||"").trim()),o=Z((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=Ct(o),l=c.endsWith("/")?c:`${c}/`,u=y=>{const b=Ct(y);return b===c||b.startsWith(l)},d=a.openPaths.filter(y=>!u(y));if(d.length===a.openPaths.length)return i;const h=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,m={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:h,touchedAt:Date.now()}};return{byRoot:nt(m,tt)}})},removeExpandedPathsByPrefix:(n,r)=>{const s=Z((n||"").trim()),o=Z((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=Ct(o),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(h=>{const m=Ct(h);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:nt(d,tt)}})},setSelectedPath:(n,r,s)=>{const o=Z((n||"").trim()),i=r?Z(r.trim()):null;!o||i&&!s?.allowOutsideRoot&&!Dt(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:nt(d,tt)}})},ensureSelectedPath:n=>{const r=Z((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=Z((n||"").trim()),o=Z((r||"").trim());!s||!o||!Dt(o,s)||e(i=>{const a=i.byRoot[s],c=hn(a),u=c.expandedPaths.includes(o)?c.expandedPaths.filter(h=>h!==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:nt(d,tt)}})},collapseAllExpandedPaths:n=>{const r=Z((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:nt(i,tt)}})},expandPath:(n,r)=>{const s=Z((n||"").trim()),o=Z((r||"").trim());!s||!o||!Dt(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:nt(u,tt)}})},expandPaths:(n,r)=>{const s=Z((n||"").trim());if(!s||!r||r.length===0)return;const o=r.map(i=>Z((i||"").trim())).filter(i=>i&&Dt(i,s));o.length!==0&&e(i=>{const a=i.byRoot[s],c=hn(a),l=new Set(c.expandedPaths),u=o.filter(h=>!l.has(h));if(u.length===0)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:nt(d,tt)}})}}),{name:"files-view-tabs-store",version:3,storage:Di(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Gn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,rg).map(([r,s])=>[r,{byRoot:Gn(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=G();return{...t,activeRuntimeKey:s,runtimeSnapshots:r,byRoot:Gn(r[s]?.byRoot)}}}),{name:"files-view-tabs-store"})),ig=["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"],ag=/^plugin:[a-z][a-z0-9-]*$/,cg=new Set(ig),lg=e=>ag.test(e),ug=e=>cg.has(e)||lg(e),_k=e=>e.slice(7),Lk=e=>`plugin:${e}`,_i=["session","repository","usage","telemetry","subagents","mcp","pinned","contextSources"],Fk={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"},dg=/^ext:[a-z][a-z0-9-]*$/,jk=e=>`ext:${e}`,fg=e=>dg.test(e),pg=ct([J(_i),kd(["ext:",f().regex(/^[a-z][a-z0-9-]*$/)])]),pu=e=>{const t=pg.safeParse(e);return t.success?t.data:null},xs=e=>{const t=new Set;if(Array.isArray(e))for(const n of e){const r=pu(n);r&&t.add(r)}for(const n of _i)t.add(n);return[...t]},Uk=(e,t)=>{const n=new Set(t),r=xs(e).filter(o=>!fg(o)||n.has(o)),s=new Set(r);for(const o of t)s.has(o)||r.push(o);return r},Nk=(e,t)=>!e?.includes(t),Bk=(e,t=[])=>e!=null&&_i.every(n=>e.includes(n))&&t.every(n=>e.includes(n)),Hk=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),hu=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e){const s=pu(r);s&&n.add(s)}return t||n.delete("telemetry"),[...n]},hg=e=>Math.min(480,Math.max(200,Math.round(e))),mg=J(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),gg=S({widthByMode:lt(f(),x().finite().optional().catch(void 0)).catch({}),widthFractionByMode:lt(f(),x().positive().max(1).optional().catch(void 0)).catch({})}),mu="ask",sc=e=>e==="attach"||e==="inline"||e==="ask"?e:mu;function oc(e){return e==="vim"?"vim":"default"}const yt="all";function ic(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function ac(e){return e==="me"||e==="any"?e:"any"}function gu(e){return typeof e!="string"?yt:e.trim()||yt}function cc(e,t){const n=G();if(hl(n))return e;const r={...e};return t===yt?delete r[n]:r[n]=t,r}function yg(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=gu(r);s!==yt&&(t[n]=s)}return t}function lc(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const Kr={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}"}},Et={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Vr=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,wg=e=>{if(!e||typeof e!="object")return!1;const t=e;return Vr(t.completion,Kr.completion)&&Vr(t.error,Kr.error)&&Vr(t.question,Kr.question)&&Vr(t.subtask,Kr.subtask)},Sg=380,bg=320,vg=1e4,yu=12,uc=120,Tg=280;let Jr=0;const kg=e=>de(e),de=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},wu=e=>Number.isFinite(e)?Math.min(vg,Math.max(bg,Math.round(e))):Sg,mr=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Rs=e=>{const t=mr(e);return t&&kg(t)||null},Cs=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>uc?t.slice(0,uc):t:null},Li=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,Su=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},Eg=(e,t)=>(e==="file"||e==="browser")&&t||e,bu=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return Eg(e,t)},Fi=(e,t)=>t===e?e:`${e}:${t}`,ji=e=>{const t=mr(e.targetPath),n=e.mode==="terminal"?Rs(e.targetDirectory):null,r=bu(e.mode,t,e.dedupeKey);return{id:Fi(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Su(e.projectPlanRef),dedupeKey:r,label:Cs(e.label),sessionTitleFallback:Cs(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:Li(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},vu=(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))},Tu=e=>{if(!Array.isArray(e))return[];const t=Oe(),n=[],r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s;if(typeof o.mode!="string"||!ug(o.mode)||t&&o.mode==="browser")continue;const i=mr(typeof o.targetPath=="string"?o.targetPath:null),a=o.mode==="terminal"?Rs(o.targetDirectory):null,c=typeof o.projectPlanId=="string"&&o.projectPlanId.trim()?o.projectPlanId.trim():null,l=Su(o.projectPlanRef);if(o.mode==="plan"&&c!==null!=(l!==null))continue;const u=bu(o.mode,i,typeof o.dedupeKey=="string"?o.dedupeKey:null),d=Fi(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:Cs(typeof o.label=="string"?o.label:null),sessionTitleFallback:Cs(typeof o.sessionTitleFallback=="string"?o.sessionTitleFallback:null),readOnly:o.readOnly===!0,stagedDiff:o.stagedDiff===!0,diffScope:Li(o.diffScope)??(o.stagedDiff===!0?"staged":"working"),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return n},Cn=(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=Tu(e.tabs),n=Cn(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()}},Pg=(e,t,n)=>{const r=n?.reveal!==!1,s=ji(t),o=s.mode==="file"&&s.targetPath?e.tabs.filter(u=>!(u.mode==="file"&&!u.targetPath)):e.tabs,i=o.findIndex(u=>u.id===s.id),a=i===-1?[...o,s]:o.map((u,d)=>d===i?{...u,mode:s.mode,targetPath:s.targetPath||u.targetPath,targetDirectory:s.targetDirectory,projectPlanId:s.projectPlanId??u.projectPlanId,projectPlanRef:s.projectPlanRef??u.projectPlanRef,dedupeKey:s.dedupeKey,label:s.label,sessionTitleFallback:s.sessionTitleFallback||u.sessionTitleFallback,stagedDiff:s.stagedDiff,diffScope:s.diffScope,readOnly:s.readOnly,touchedAt:Date.now()}:u),c=r?s.id:e.activeTabId??s.id,l=vu(a,yu,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:Cn(l,c),touchedAt:Date.now()}},Ag=(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:Cn(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=ji({mode:"file"});return{...e,tabs:[...s,l],activeTabId:l.id,isOpen:e.isOpen,touchedAt:Date.now()}}return{...e,tabs:s,activeTabId:c?.id??Cn(s,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},Ig=(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},xg=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),ko=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=de(r);if(!o||!s||typeof s!="object")continue;const i=s;let a=Tu(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=[ji({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=Cn(a,c),u=vu(a,yu,l),d={},h={},m=gg.parse(s);for(const y of mg.options){const b=m.widthByMode[y],w=m.widthFractionByMode[y];b!==void 0&&(d[y]=wu(b)),w!==void 0&&(h[y]=w)}n[o]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:Cn(u,l),widthByMode:d,widthFractionByMode:h,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()(Mn(Sr((e,t)=>({theme:"system",runOverviewKey:null,parallelComposerRequest:null,isSidebarOpen:!0,sidebarWidth:Tg,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:xs([]),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,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:Lm,monoFont:Fm,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Hm(),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:{...Et.completion},error:{...Et.error},question:{...Et.question},subtask:{...Et.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!0,agentControlToolEnabled:!0,agentWebToolEnabled:!0,browserProvider:"builtin",agentMemoryToolEnabled:!1,agentNotifyToolEnabled:!1,agentToolsCodeMode:!1,isolatedSpacesEnabled:!1,permissionDefaultMode:"ask",agentMemoryFeatureAvailable:!1,routingFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:mu,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:hg(n)})},openContextSurface:(n,r)=>{const s=de((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 h=(a.find(m=>m.mode==="terminal")??null)?.targetDirectory??null;if(h){const m=is.getState().getDirectoryState(h);if(zm(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((h,m)=>m.touchedAt>=h.touchedAt?m:h);o.setActiveContextPanelTab(s,d.id);return}r!=="chat"&&o.openContextPanelTab(s,{mode:r})},openContextPanelTab:(n,r,s)=>{const o=de((n||"").trim());if(!o)return;const i=r.mode==="terminal"?{...r,targetDirectory:Rs(r.targetDirectory)===o?null:Rs(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]:Pg(u,i,s)};return{contextPanelByDirectory:Gt(d,20),contextEditorVisible:a||c.contextEditorVisible}})},openContextDiff:(n,r,s=!1,o=null)=>{const i=de((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=Li(o)??(s?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const s=de((n||"").trim()),o=mr(r);!s||!o||(t().openContextPanelTab(s,{mode:"file",targetPath:o}),t().setPendingFileFocusPath(o),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,s,o)=>{const i=de((n||"").trim()),a=mr(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=de((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const s=de((n||"").trim()),o=(r||"").trim();!s||!o||Oe()||t().openContextPanelTab(s,{mode:"browser",targetPath:o,dedupeKey:o,label:null})},openAgentBrowserTab:(n,r)=>{const s=de((n||"").trim());if(!s||Oe())return null;Jr+=1;const o=`browser:agent:${Date.now()}-${Jr}`;return t().openContextPanelTab(s,{mode:"browser",targetPath:r.trim(),dedupeKey:o,label:null},{reveal:!1}),Fi("browser",o)},openNewContextBrowserTab:n=>{const r=de((n||"").trim());!r||Oe()||(Jr+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${Jr}`,label:null}))},openContextBrowser:(n,r="",s)=>{const o=de((n||"").trim());if(!o||Oe())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(o,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},s)},setContextPanelTabTargetPath:(n,r,s)=>{const o=de((n||"").trim()),i=(r||"").trim();!o||!i||e(a=>{const c=a.contextPanelByDirectory[o];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[o]:xg(c,i,s)}}:a})},setActiveContextPanelTab:(n,r)=>{const s=de((n||"").trim()),o=(r||"").trim();!s||!o||e(i=>{const a=i.contextPanelByDirectory[s],c=Wt(a),l=c.tabs.find(h=>h.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(h=>h.id===o?{...h,touchedAt:Date.now()}:h)}};return{contextPanelByDirectory:Gt(d,20),contextEditorVisible:u||i.contextEditorVisible}})},reorderContextPanelTabs:(n,r,s)=>{const o=de((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=Ig(u,i,a);if(d.tabs===u.tabs)return c;const h={...c.contextPanelByDirectory,[o]:d};return{contextPanelByDirectory:Gt(h,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const s=de((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=Ag(l,o),d=u.tabs.find(y=>y.id===u.activeTabId),h=u.isOpen&&d?.mode==="file"&&!d.targetPath,m={...a.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:Gt(m,20),contextEditorTreeVisible:h||a.contextEditorTreeVisible}});for(const a of i)a.mode==="file"&&a.targetPath&&og.getState().removeOpenPath(s,a.targetPath)},closeContextPanel:n=>{const r=de((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=de((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=de((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=Wt(c),u=wu(s),d={...l.widthFractionByMode};o!==void 0&&Number.isFinite(o)&&o>0?d[r]=Math.min(1,u/o):delete d[r];const h={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:Gt(h,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:xs(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,runOverviewKey:null,openGuestPageId:null}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isUsageStatsPageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isArchivePageOpen:!1})},setUsageStatsPageOpen:n=>{e(n?{isUsageStatsPageOpen:!0,isArchivePageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isUsageStatsPageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,runOverviewKey:null,openGuestPageId:null}:{worktreesPageProjectId:null})},setOpenGuestPage:n=>{e(n?{openGuestPageId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,runOverviewKey:null}:{openGuestPageId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.isUsageStatsPageOpen&&!n.worktreesPageProjectId&&!n.runOverviewKey&&!n.openGuestPageId||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId: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(Cm);if(s===1){r.style.removeProperty("font-size");for(const[i]of o)r.style.removeProperty(Ya(i));return}r.style.fontSize=`${s*100}%`;for(const[i]of o)r.style.removeProperty(Ya(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:ic(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:ac(n)})},setLinearIssueListTeamId:n=>{const r=gu(n);e(s=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:cc(s.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=G();e(r=>({linearIssueListTeamId:hl(n)?yt:r.linearIssueListTeamIdByRuntime[n]??yt}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:lc(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:yt,linearIssueListTeamIdByRuntime:cc(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,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})},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:sc(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:oc(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:Di(),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:"",h=typeof u.dedupeKey=="string"&&u.dedupeKey.trim()?u.dedupeKey.trim():d||"browser",m=h==="browser"?"browser":`browser:${h}`;a.has(m)||(a.add(m),c.push({...u,mode:"browser",id:m,dedupeKey:h}))}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&&wg(n.notificationTemplates)&&(n.notificationTemplates={completion:{...Et.completion},error:{...Et.error},question:{...Et.question},subtask:{...Et.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=ko(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=ko(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=ko(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=ic(n.linearIssueListStatus),n.linearIssueListAssignee=ac(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=yg(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=lc(n.linearIssueListPriority),n.fileEditorKeymap=oc(n.fileEditorKeymap),n.largeTextPasteBehavior=sc(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,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"})),Rg=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},Cg=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Og=e=>{const t=T.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Dg=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=Cg(t);return Rg(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},Mg=768,_g=800,Lg=()=>{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},Fg=()=>{if(typeof window>"u")return!1;const e=new URLSearchParams(window.location.search).get("surface");return e==="mobile"||e==="desktop"},ku=()=>{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<=Mg&&Lg()},Eu=()=>{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:vr()?"mobile":$e()||Oe()?"desktop":ku()?"mobile":"desktop"},$k=()=>{const e=Eu();return typeof window<"u"&&(window.__OPENCHAMBER_SURFACE__=e),e},jg=()=>Eu()==="mobile",zk=()=>{if(typeof window>"u")return()=>{};if(vr()||$e()||Oe())return()=>{};if(Fg())return()=>{};let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null;const n=window.__OPENCHAMBER_SURFACE__,r=ku()?"mobile":"desktop";n&&n!==r&&(window.__OPENCHAMBER_SURFACE__=void 0,window.location.reload())},_g)};return window.addEventListener("resize",t),()=>{e&&clearTimeout(e),window.removeEventListener("resize",t)}},Pu="surface",Ui=()=>{try{if(Oe())return"vscode";if($e())return"desktop";if(vr()||jg())return"mobile"}catch{}return"web"},Ug=()=>Ui()==="mobile"?"timeline":"projects",Ng=(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},qo=ut()(Sr(e=>({animatedActivityIndicators:!1,setAnimatedActivityIndicators:t=>e({animatedActivityIndicators:t}),projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sidebarViewMode:Ug(),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:Ng})),Au="directoryTreeShowHidden",Ko="directory-show-hidden-change",Vo=()=>{if(typeof window>"u")return!0;try{const e=Er().getItem(Au);return e===null?!0:e==="true"}catch{return!0}},Bg=()=>{typeof window>"u"||window.dispatchEvent(new Event(Ko))},Hg=()=>Vo(),$g=(e,t={})=>{if(!(typeof window>"u")){try{Er().setItem(Au,e?"true":"false"),Bg()}catch{}t.persist!==!1&&wt({directoryShowHidden:e})}},Wk=()=>{const e=yi.c(2),[t,n]=fs.useState(Vo);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(Vo())};return window.addEventListener("storage",o),window.addEventListener(Ko,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(Ko,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),fs.useEffect(r,s),t},Iu=[{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"}],zg=new Map(Iu.map(e=>[e.name,e])),Gk=e=>zg.get(e),qk=Iu.map(e=>({type:"command",name:e.name})),Kk="terminal-box",Vk="book-open",Jk=e=>`${e.type}:${e.name}`,Yk=(e,t)=>e.type===t.type&&e.name===t.name,Qk=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Wg=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},xu="filesViewShowGitignored",Jo="files-view-show-gitignored-change",Yo=()=>{if(typeof window>"u")return!1;try{return Er().getItem(xu)==="true"}catch{return!1}},Gg=()=>{typeof window>"u"||window.dispatchEvent(new Event(Jo))},qg=()=>Yo(),Kg=(e,t={})=>{if(!(typeof window>"u")){try{Er().setItem(xu,e?"true":"false"),Gg()}catch{}t.persist!==!1&&wt({filesViewShowGitignored:e})}},Xk=()=>{const e=yi.c(2),[t,n]=fs.useState(Yo);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(Yo())};return window.addEventListener("storage",o),window.addEventListener(Jo,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(Jo,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),fs.useEffect(r,s),t},Ru="session",Cu=40,Vg=1,Jg=100,Ou=e=>e==="global"||e==="session",Ni=e=>e!=null&&Number.isInteger(e)&&e>=Vg&&e<=Jg,Yg=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Bi=e=>e==="auto"||typeof e=="string"&&Yg.includes(e),Tn="openchamber-input-history.v1",Qg=8,Xg=50,Zg=[40,25,10,5,1],Eo=Object.freeze([]);let mt=null,dc=0;const or=(e=Ru,t=Cu)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Du=()=>(dc+=1,Date.now()*1e3+dc),Mu=e=>JSON.stringify([e]),Qo=(e,t,n)=>JSON.stringify([e,t,n]),Hi=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},ey=()=>{const e=Hi(),t=Ve?JSON.stringify(cs(Ve.base)):mt;if(!e)return t;try{return e.getItem(Tn)??(Ve?null:mt)}catch{return t}},fc=lt(f(),ye()),ty=S({key:f().min(1),source:ct([D("file-url"),D("vscode-file")]),filename:f().min(1),mimeType:f().min(1),size:x().finite().nonnegative(),reference:f().min(1)}),ny=S({text:f(),attachmentKeys:j(f()),restorableAttachments:j(ty),submittedAt:x().finite().nonnegative()}),ry=S({touchedAt:x().finite().nonnegative(),entries:j(ye())}),sy=(e,t)=>{try{const n=JSON.parse(e),s=(t===1?oa([f().trim().min(1)]):oa([f().trim().min(1),f().trim().min(1),f().trim().min(1)])).safeParse(n);if(!s.success)return null;if(t===3){const o=Xe(s.data[1]);if(!o||o!==s.data[1])return null}return s.data}catch{return null}},pc=(e,t)=>{const n=[];for(const[r,s]of Object.entries(e)){if(!sy(r,t))continue;const o=ry.safeParse(s);if(!o.success)continue;const i=o.data.entries.map(a=>ny.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:o.data.touchedAt,entries:i}])}return Object.fromEntries(n)},oy=()=>{const e=ey();if(e===null)return or();try{const t=JSON.parse(e),n=S({version:D(1),entryLimit:x().int().optional(),scope:ct([D("global"),D("session")]).optional(),global:fc.default({}),session:fc.default({})}).safeParse(t);return n.success?{entryLimit:Ni(n.data.entryLimit)?n.data.entryLimit:Cu,scope:n.data.scope??Ru,globalBuckets:pc(n.data.global,1),sessionBuckets:pc(n.data.session,3)}:or()}catch{const t=Hi();if(t)try{t.removeItem(Tn)}catch{}return mt=null,or()}};let Ve=null,as=or();const hc=(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},Yn=()=>{const e=oy();if(as=e,!Ve)return e;const{base:t,value:n}=Ve;return Xo({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:hc(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:hc(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},_u=(e,t)=>e.slice(Math.max(0,e.length-t)),mc=(e,t,n)=>{const r=Object.entries(e).map(([s,o])=>[s,{touchedAt:o.touchedAt,entries:_u(o.entries,n)}]).sort((s,o)=>o[1].touchedAt-s[1].touchedAt).slice(0,t);return Object.fromEntries(r)},Xo=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:mc(e.globalBuckets,Qg,t),sessionBuckets:mc(e.sessionBuckets,Xg,t)}),cs=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),gc=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Qn=e=>{const t=Xo(e),n=JSON.stringify(cs(t));Ve={base:as,value:t};const r=Hi();if(!r)return mt=n,t;try{return r.setItem(Tn,n),Ve=null,mt=n,t}catch(i){if(!(i instanceof Error)||!gc(i))return mt=n,t}try{r.removeItem(Tn)}catch{}for(const i of Zg){const a=Xo(t,i),c=JSON.stringify(cs(a));try{return r.setItem(Tn,c),Ve=null,mt=c,a}catch(l){if(!(l instanceof Error)||!gc(l))return Ve={base:as,value:a},mt=c,a}}const s=or(t.scope,t.entryLimit),o=JSON.stringify(cs(s));try{r.setItem(Tn,o),Ve=null}catch{Ve={base:as,value:s}}return mt=o,s},iy=(e,t,n)=>{const r=e.trim(),s=Xe(t),o=n.trim();return!r||!s||!o?null:{runtimeKey:r,directory:s,sessionId:o}},Lu=e=>e.source==="vscode"&&e.vscodeSource==="file"?Xe(e.vscodePath??null):e.dataUrl.trim()||null,ay=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Zo=e=>{const t=Lu(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("|")},cy=e=>{const t=Lu(e);return!t||!ay(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Zo(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Zo(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},ly=(e,t)=>({text:e,attachmentKeys:t.map(Zo),restorableAttachments:t.map(cy).filter(n=>n!==null)}),uy=(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}),dy=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&uy(e.restorableAttachments,t.restorableAttachments),yc=(e,t,n,r)=>{const s=e?[...e.entries]:[];for(const o of t){const i=s.at(-1);dy(i,o)||s.push({text:o.text,attachmentKeys:[...o.attachmentKeys],restorableAttachments:o.restorableAttachments.map(a=>({...a})),submittedAt:Du()})}return{touchedAt:n,entries:_u(s,r)}},fy=Qn(Yn()),Xn=ut(e=>({...fy,applyEntryLimit:t=>{Ni(t)&&e(n=>{const r=Yn();if(r.entryLimit===t)return{...n,...r};const s=Qn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},applyScope:t=>{Ou(t)&&e(n=>{const r=Yn();if(r.scope===t)return{...n,...r};const s=Qn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const s=Yn(),o=Du(),i=Mu(t.runtimeKey),a=Qo(t.runtimeKey,t.directory,t.sessionId),c=Qn({entryLimit:s.entryLimit,scope:s.scope,globalBuckets:{...s.globalBuckets,[i]:yc(s.globalBuckets[i],n,o,s.entryLimit)},sessionBuckets:{...s.sessionBuckets,[a]:yc(s.sessionBuckets[a],n,o,s.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=Yn(),s=Qo(t.runtimeKey,t.directory,t.sessionId);if(!(s in r.sessionBuckets))return{...n,...r};const o={...r.sessionBuckets};delete o[s];const i=Qn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:o});return{...n,...i}})}})),Zk=(e,t)=>t?e.scope==="session"?e.sessionBuckets[Qo(t.runtimeKey,t.directory,t.sessionId)]?.entries??Eo:e.globalBuckets[Mu(t.runtimeKey)]?.entries??Eo:Eo,py=S({text:f(),prefix:f(),suffix:f(),start:x()}),wc=32,hy=200,my="[data-chat-quote-root]";function eE(e,t){return e.querySelector(`[data-message-id="${CSS.escape(t)}"]`)?.querySelector(my)??null}function Sc(e,t,n){const r=e.ownerDocument.createRange();return r.setStart(e,0),r.setEnd(t,n),r.toString().length}function tE(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))return null;const n=e.textContent??"",r=Sc(e,t.startContainer,t.startOffset),s=Sc(e,t.endContainer,t.endOffset),o=n.slice(r,s);return o.trim()?{text:o,prefix:n.slice(Math.max(0,r-wc),r),suffix:n.slice(s,s+wc),start:r}:null}function gy(e,t){if(!t.text)return null;const n=[];for(let s=e.indexOf(t.text);s!==-1&&n.length<hy;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 Fu(e,t){for(let n=e.firstChild;n;n=n.nextSibling)n.nodeType===3?t.push(n):Fu(n,t);return t}function nE(e,t){const n=gy(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 Fu(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 rE(e){return{text:e.trim(),prefix:"",suffix:"",start:0}}const yy=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,wy=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
4
+ `).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}},Sy=(e,t)=>{const n=t.map(wy).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(`
5
+ `).map((a,c)=>` ${o.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
6
+ `);return e.trim()?`${e.trim()}
7
+
8
+ ${s}`:s},sE=e=>{const t=yy.exec(e);if(!t)return{visibleText:e,contexts:[]};const n=[];let r=null;for(const s of(t[1]??"").split(`
9
+ `)){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?`
10
+ `:""}${i[1]}`)}return r&&n.push(r),{visibleText:e.slice(0,t.index).trimEnd(),contexts:n}},$i="openchamberContext",zi="opencodeComment";function by(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}:
11
+ \`\`\`${e.language}
12
+ ${e.code}
13
+ \`\`\`
14
+
15
+ ${e.text}`}case"terminal":return Sy("",[{terminalId:e.terminalId,terminalLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,text:e.output}]);case"browser-annotation":return e.text?`${e.prompt}
16
+
17
+ ${e.text}`:e.prompt;case"pr-comment":return`Attached GitHub PR comment (${e.label}):
18
+
19
+ ${e.body}${e.text?`
20
+
21
+ ${e.text}`:""}`;case"file-quote":{const t=e.startLine!=null&&e.endLine!=null?` lines ${e.startLine}-${e.endLine}`:"",n=e.quote.split(`
22
+ `).map(r=>`> ${r}`).join(`
23
+ `);return`Comment on this fragment of \`${e.fileLabel}\`${t}:
24
+ ${n}${e.text?`
25
+
26
+ ${e.text}`:""}`}case"chat-quote":return`Comment on this fragment of an earlier message in this conversation:
27
+ ${e.quote.split(`
28
+ `).map(n=>`> ${n}`).join(`
29
+ `)}${e.text?`
30
+
31
+ ${e.text}`:""}`;case"pr-check":return`Attached failed GitHub PR check (${e.label}):
32
+ \`\`\`
33
+ ${e.output}
34
+ \`\`\`${e.text?`
35
+
36
+ ${e.text}`:""}`;case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return""}}function oE(e,t){const n=t??by(e),r={[$i]:e};return e.kind==="code-comment"&&(r[zi]={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 iE(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 ju=jt("kind",[S({kind:D("code-comment"),source:J(["diff","file","plan"]),fileLabel:f(),startLine:x(),endLine:x(),side:J(["original","modified"]).optional(),language:f(),code:f(),text:f()}),S({kind:D("terminal"),terminalId:f(),terminalLabel:f(),startLine:x(),endLine:x(),output:f()}),S({kind:D("browser-annotation"),pageUrl:f(),prompt:f(),text:f()}),S({kind:D("pr-comment"),label:f(),body:f(),text:f()}),S({kind:D("pr-check"),label:f(),output:f(),text:f()}),S({kind:D("file-quote"),fileLabel:f(),startLine:x().optional(),endLine:x().optional(),quote:f(),text:f()}),S({kind:D("chat-quote"),messageId:f().optional(),anchor:py.optional(),quote:f(),text:f()}),S({kind:D("github-issue"),number:x().int().positive(),title:f(),url:f()}),S({kind:D("github-pr"),number:x().int().positive(),title:f(),url:f()}),S({kind:D("linear-issue"),identifier:f().min(1),title:f(),url:f()}),S({kind:D("guest-issue"),providerId:f().min(1),id:f().min(1),title:f(),url:f(),data:ia().optional()}),S({kind:D("guest-pr"),providerId:f().min(1),id:f().min(1),title:f(),url:f(),data:ia().optional()})]),Uu=S({path:f(),selection:S({startLine:x().finite(),endLine:x().finite(),startChar:x().finite().optional(),endChar:x().finite().optional()}).optional(),comment:f(),preview:f().optional(),origin:J(["file","review"]).optional()}),vy=S({[$i]:ju,[zi]:Uu.optional()});function aE(e){if(e.type!==void 0&&e.type!=="text")return null;const t=ju.safeParse(e.metadata?.[$i]);if(t.success)return t.data;const n=Uu.safeParse(e.metadata?.[zi]);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 cE(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 Ty(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 ky(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"?Ty(r.metadata.openchamberContext):r.text).trim(),t))break}t||=e.attachments?.[0]?.filename??"";const n=t.split(`
37
+ `,1)[0];return n.slice(0,100)+(t.length>n.length||n.length>100?"...":"")}const Nu="queue",Ey=e=>e==="steer"||e==="queue",Py=(e,t)=>e==="immediate"?"steer":Ey(e)?e:t===!1?"steer":t===!0?"queue":Nu,xt=()=>!Oe(),bc=50,ei=(e,t,n=G())=>{const r=Xe(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},Be=e=>`${e.runtimeKey}
38
+ ${e.directory}
39
+ ${e.sessionId}`,Xt=e=>{const[t,n,...r]=e.split(`
40
+ `);return ei(r.join(`
41
+ `),n,t)},Ay=S({providerID:f().min(1),modelID:f().min(1),agent:f().optional(),variant:f().optional()}),Iy=S({id:f(),filename:f(),mimeType:f(),size:x(),source:J(["local","server","vscode"]),serverPath:f().optional(),dataUrl:f().optional()}),xy=jt("kind",[S({kind:D("context"),text:f(),metadata:vy,instructions:f().optional()}),S({kind:D("instruction"),text:f()}),S({kind:D("synthetic"),text:f()})]),Wi=S({id:f().min(1),createdAt:x(),content:f(),text:f(),agentMention:f().optional(),attachments:j(Iy),context:j(xy).optional(),contextPreview:f().optional(),sendConfig:Ay}),Gi=S({sessionId:f().min(1),directory:f(),items:j(Wi),sendingId:f().nullable()}),vc=S({revision:x(),sessions:j(Gi)}),ir=S({revision:x(),session:Gi}),Ry=ir.extend({item:Wi}),Cy=ir.extend({items:j(Wi)}),Oy=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}},Dy=e=>{const t=e.dataUrl??"",n=t?Oy(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},Yr=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(Dy)),e.context&&(t.context=e.context),e.contextPreview&&(t.contextPreview=e.contextPreview),t},My=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},Tc=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(s=>!!s.dataUrl).map(My),context:e.context??[],sendConfig:t};e.agentMention&&(n.agentMention=e.agentMention);const r=ky({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},Pt=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},At=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,Po=new Set,kc=new Map,rt=new Map,Qr=new Map;let Ao=0;const Ec=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),_y=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:Ec(n.queuedMessages??{}),quarantinedLegacyMessages:Ec({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:Py(n.followUpBehavior,n.queueModeEnabled??null)}},st=(e,t)=>{const{[t]:n,...r}=e;return r},Xr=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(s=>s.id!==n);return r.length===0?{queuedMessages:st(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},Ly=(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||(rt.get(i)??-1)>r||(rt.set(i,r),s=st(s,i),o=st(o,i))}return{queuedMessages:s,sendingIds:o}},ti=ut()(Mn(Sr((e,t)=>{let n=null,r=!1;const s=(a,c,l)=>{if(l!==G()||(Qr.get(l)??-1)>c)return;const u=ei(a.sessionId,a.directory,l);if(!u){if(a.items.length>0)return;e(h=>Ly(h,l,a.sessionId,c));return}const d=Be(u);(rt.get(d)??-1)>c||(rt.set(d,c),e(h=>{const m=a.items.map(Yr),y=m.length>0?{...h.queuedMessages,[d]:m}:st(h.queuedMessages,d),b=a.sendingId?{...h.sendingIds,[d]:[a.sendingId]}:st(h.sendingIds,d);return{queuedMessages:y,sendingIds:b}}))},o=async a=>{try{const c=await qt(vc,"/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(ir,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:Nu,sendingIds:{},addToQueue:async(a,c)=>{const l=Be(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]??[],w={...y.queuedMessages,[l]:[...b,d].slice(-20)},k=Object.keys(w);if(k.length>bc){k.sort((E,L)=>(w[E]?.[0]?.createdAt??0)-(w[L]?.[0]?.createdAt??0));for(const E of k.slice(0,k.length-bc))delete w[E]}return{queuedMessages:w}}),!xt())return;if(!c.sendConfig)throw e(y=>Xr(y,l,u)),new Error("A queued message needs a provider and model to be delivered later.");const h=iy(a.runtimeKey,a.directory,a.sessionId),m=ly(c.content,c.attachments??[]);try{const y=await qt(ir,`${At(a.sessionId)}/items`,Pt("POST",{directory:a.directory,item:Tc(c,c.sendConfig)}));e(b=>Xr(b,l,u)),s(y.session,y.revision,a.runtimeKey),h&&Xn.getState().appendSubmissions(h,[m])}catch(y){throw e(b=>Xr(b,l,u)),y}},removeFromQueue:(a,c)=>{const l=Be(a);e(u=>Xr(u,l,c)),xt()&&i(a,`${At(a.sessionId)}/items/${encodeURIComponent(c)}`,Pt("DELETE"))},reorderQueue:(a,c,l)=>{if(c===l)return;const u=Be(a),d=t().queuedMessages[u];if(!d)return;const h=d.findIndex(w=>w.id===c),m=d.findIndex(w=>w.id===l);if(h===-1||m===-1)return;const y=d.slice(),[b]=y.splice(h,1);if(y.splice(m,0,b),e(w=>({queuedMessages:{...w.queuedMessages,[u]:y}})),xt()){const w=y.map(k=>k.id);i(a,`${At(a.sessionId)}/order`,Pt("PUT",{itemIds:w}))}},popToInput:async(a,c)=>{const[l]=await t().takeForSend(a,c);return l??null},takeForSend:async(a,c)=>{const l=Be(a);if(xt())try{if(c){const b=await qt(Ry,`${At(a.sessionId)}/items/${encodeURIComponent(c)}/take`,Pt("POST"));return s(b.session,b.revision,a.runtimeKey),[Yr(b.item)]}const y=await qt(Cy,`${At(a.sessionId)}/take`,Pt("POST"));return s(y.session,y.revision,a.runtimeKey),y.items.map(Yr)}catch(y){throw await o(a),y}const u=t(),d=u.sendingIds[l]??[],h=(u.queuedMessages[l]??[]).filter(y=>(c?y.id===c:!0)&&!d.includes(y.id));if(h.length===0)return[];const m=new Set(h.map(y=>y.id));return e(y=>{const b=(y.queuedMessages[l]??[]).filter(w=>!m.has(w.id));return b.length===0?{queuedMessages:st(y.queuedMessages,l)}:{queuedMessages:{...y.queuedMessages,[l]:b}}}),h},clearQueue:a=>{const c=Be(a);e(l=>{const u=l.sendingIds[c]??[],d=(l.queuedMessages[c]??[]).filter(h=>u.includes(h.id));return d.length>0?{queuedMessages:{...l.queuedMessages,[c]:d}}:{queuedMessages:st(l.queuedMessages,c)}}),xt()&&i(a,At(a.sessionId),Pt("DELETE"))},forgetQueue:a=>{const c=Be(a);rt.delete(c),e(l=>({queuedMessages:st(l.queuedMessages,c),sendingIds:st(l.sendingIds,c)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(a,c)=>{const l=Be(a);e(u=>{const d=u.sendingIds[l]??[];return d.includes(c)?u:{sendingIds:{...u.sendingIds,[l]:[...d,c]}}})},clearSending:(a,c)=>{const l=Be(a);e(u=>{const d=u.sendingIds[l];if(!d||!d.includes(c))return u;const h=d.filter(m=>m!==c);return h.length===0?{sendingIds:st(u.sendingIds,l)}:{sendingIds:{...u.sendingIds,[l]:h}}})},getSendableQueue:a=>{const c=Be(a),l=t(),u=l.queuedMessages[c]??[],d=l.sendingIds[c];return!d||d.length===0?u:u.filter(h=>!d.includes(h.id))},setFollowUpBehavior:a=>{e({followUpBehavior:a}),wt({followUpBehavior:a})},getQueueForTarget:a=>t().queuedMessages[Be(a)]??[],hydrate:()=>{if(!xt())return Promise.resolve();const a=G();if(n?.runtimeKey===a)return n.promise;const c=++Ao,l=()=>c===Ao&&a===G(),u=(async()=>{let m=kc.get(a);for(m||(m={items:Object.entries(t().queuedMessages).flatMap(([b,w])=>{const k=Xt(b);return!k||k.runtimeKey!==a?[]:w.map(E=>({target:k,message:E}))}),pending:null},kc.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:w}=y,k=qt(ir,`${At(b.sessionId)}/items`,Pt("POST",{directory:b.directory,item:Tc(w,y.message.sendConfig)})).then(()=>{}).catch(L=>{console.warn("[queue] failed to migrate a locally queued message to the server:",L)});m.pending=k;const E=m;k.then(()=>{E.pending===k&&(E.pending=null)}),await k}if(l())do{r=!1;let y;try{y=await qt(vc,"/api/message-queue",{signal:AbortSignal.timeout(15e3)})}catch(b){if(!l())return;if(r)continue;throw b}if(!l())return;Po.add(a),!((Qr.get(a)??-1)>y.revision)&&(Qr.set(a,y.revision),e(b=>{const w=M=>(rt.get(M)??-1)>y.revision,k=M=>Xt(M)?.runtimeKey!==a||w(M),E={},L={};for(const[M,Y]of Object.entries(b.queuedMessages))k(M)&&(E[M]=Y);for(const[M,Y]of Object.entries(b.sendingIds))k(M)&&(L[M]=Y);for(const M of y.sessions){const Y=ei(M.sessionId,M.directory,a);if(!Y)continue;const C=Be(Y);w(C)||(rt.set(C,y.revision),M.items.length>0&&(E[C]=M.items.map(Yr)),M.sendingId&&(L[C]=[M.sendingId]))}return{queuedMessages:E,sendingIds:L}}))}while(r&&l())})(),d={runtimeKey:a,promise:u};n=d;const h=()=>{n===d&&(n=null)};return u.then(h,h),u},resync:()=>(n?.runtimeKey===G()&&(r=!0),t().hydrate()),applyServerSession:s,setServerHold:async(a,c)=>{if(!xt())return;const l=await g(`${At(a)}/hold`,Pt("PUT",{held:c}));if(!l.ok)throw new Error(`Message queue hold request failed (${l.status})`)},resetForRuntimeSwitch:a=>{if(Ao+=1,n=null,r=!1,a){Qr.delete(a);for(const c of rt.keys())Xt(c)?.runtimeKey===a&&rt.delete(c)}!a||!Po.has(a)||e(c=>{const l={},u={};for(const[d,h]of Object.entries(c.queuedMessages))Xt(d)?.runtimeKey===a?rt.delete(d):l[d]=h;for(const[d,h]of Object.entries(c.sendingIds))Xt(d)?.runtimeKey!==a&&(u[d]=h);return{queuedMessages:l,sendingIds:u}})}}},{name:"message-queue-store",version:3,storage:Di(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=Xt(t)?.runtimeKey;return!n||!Po.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:_y}),{name:"message-queue-store"})),Fy=S({type:D("openchamber:message-queue.updated"),properties:S({revision:x(),session:Gi})}),lE=(e,t)=>{if(!xt())return;const n=Fy.safeParse(e);if(!n.success)return;const{session:r,revision:s}=n.data.properties;ti.getState().applyServerSession(r,s,t)},jy=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,"_")}`},F=e=>t=>{const n=e.safeParse(t);return n.success?n.data:void 0},Ln=x().refine(Number.isFinite),je=f().transform(e=>e.trim()),pe=je.pipe(f().min(1)),Nt=lt(f(),ye()),P=F(he()),He=F(f().min(1)),Sn=F(je),mn=F(pe),Pc=e=>F(f().max(e)),qn=e=>F(je.transform(t=>t.slice(0,e))),X=e=>F(je.pipe(J(e))),Kt=F(Ln),Uy=(e,t)=>F(Ln.transform(n=>Math.max(e,Math.min(t,Math.round(n))))),Io=e=>F(Ln.transform(t=>Math.max(e,Math.round(t)))),Ny=F(Ln.positive().transform(Math.floor)),By=F(ct([lr(),Ln])),Hy=F(ct([lr(),je.transform(e=>e.length>0?e:null)])),$y=F(ct([lr(),je])),qi=j(ye()).transform(e=>e.filter(t=>f().min(1).safeParse(t).success)),Zr=F(qi.transform(e=>Array.from(new Set(e.map(String))))),xo=F(qi.transform(e=>e.map(String))),zy=Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=j(ye()).safeParse(r);s.success&&(t[n]=s.data.filter(o=>f().safeParse(o).success).map(String))}return t}),Ro=F(zy.pipe(lt(f(),j(f())).refine(e=>Object.keys(e).length>0))),Wy=S({providerID:pe,modelID:pe}),Co=e=>F(j(ye()).transform(t=>{const n=[],r=new Set;for(const s of t){const o=Wy.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})),Gy=F(Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){if(!n)continue;const s=qi.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)),qy=F(Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=pe.safeParse(r);!s||!o.success||(t[s]=o.data)}return t})),es={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."}},Ky=S({title:f().catch(""),message:f().catch("")}),Vy=F(Nt.transform(e=>{const t=i=>{const a=Ky.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??es.completion,error:r??es.error,question:s??es.question,subtask:o??es.subtask}}).pipe(Qc(e=>e!==void 0))),Ac=Nt.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{const r=f().safeParse(n);return r.success?[[t,r.data]]:[]}))),Jy=S({id:ye().transform(e=>String(e??"")),label:ye().transform(e=>String(e??"")),models:j(ye()).transform(e=>e.filter(t=>f().safeParse(t).success).map(String)).catch([]),order:x().catch(0)}),Yy=F(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=j(ye()).safeParse(s.data.customGroups);i.success&&(o.customGroups=i.data.flatMap(l=>{const u=Jy.safeParse(l);return u.success?[u.data]:[]}));const a=Ac.safeParse(s.data.modelAssignments);a.success&&(o.modelAssignments=a.data);const c=Ac.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)),Qy=S({id:pe,name:pe,hostname:pe.transform(e=>e.toLowerCase())}),Xy=F(j(ye()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=Qy.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})),Zy=F(Nt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=pe.safeParse(r);!s||!o.success||(t[s]=o.data)}return t}).refine(e=>Object.keys(e).length>0)),ew=S({id:pe,label:pe,source:pe,subpath:je.optional().catch(void 0),gitIdentityId:je.optional().catch(void 0)}),tw=F(j(ye()).transform(e=>{const t=[],n=new Set;for(const r of e){const s=ew.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})),nw=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Oo=Ln.nonnegative(),rw=S({path:pe,label:pe.optional().catch(void 0),icon:pe.optional().catch(void 0),iconImage:ct([lr(),S({mime:pe,updatedAt:Oo.transform(Math.round).pipe(x().positive()),source:J(["custom","auto"])})]).optional().catch(void 0),color:pe.optional().catch(void 0),iconBackground:ct([lr(),je.pipe(f().regex(nw)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:Oo.optional().catch(void 0),lastOpenedAt:Oo.optional().catch(void 0),sidebarCollapsed:he().optional().catch(void 0),defaultModel:pe.optional().catch(void 0),defaultAgent:pe.optional().catch(void 0),defaultVariant:pe.optional().catch(void 0)}),sw=F(j(ye()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=rw.safeParse(s);if(!o.success)continue;const i=Xe(o.data.path);if(!i)continue;const a=jy(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)),ow=J(["steer","queue"]),iw=(e,t)=>{const n=ow.safeParse(e);if(n.success)return n.data;if(e==="immediate")return"steer";const r=he().safeParse(t.queueModeEnabled);if(r.success)return r.data?"queue":"steer"},aw=F(je.pipe(J(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),cw=F(je.pipe(J(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),lw=F(je.transform(e=>e.replace(/\s+/g," ").slice(0,64))),uw=e=>F(j(ye()).transform(t=>{const n=[];for(const r of t){const s=je.transform(o=>o.toLowerCase()).safeParse(r);s.success&&e(s.data)&&!n.includes(s.data)&&n.push(s.data)}return n})),Ki=e=>F(Qc(e)),gr=(e,t)=>(n,r)=>{const s=e(n,r);return s===void 0?void 0:t(s)},p=e=>e,v=(e,t,n={})=>({read:()=>T.getState()[e],write:t,autoSave:n.autoSave??!0}),Vt=e=>t=>{T.setState({[e]:t})},Ic=()=>globalThis.window?.__zustand_config_store__??null,Jt=e=>({read:()=>Ic()?.getState()[e],write:t=>{Ic()?.setState({[e]:t})},autoSave:!1}),Kn=e=>({read:()=>qo.getState()[e],write:t=>{qo.setState({[e]:t})},autoSave:!1}),dw=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],fw=Ki(Bi),pw=Ki(jm),hw=Ki(Um),mw=F(f().refine(Ou)),gw=F(x().refine(Ni)),yw=gr(Sn,e=>Ws(e,void 0)),ww=gr(F(j(ye())),Wg),Sw=gr(F(j(ye())),e=>hu(e)),bw=X(["ask","attach","inline"]),vw=X(["default","vim"]),Tw=(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},Pr={themeId:p({scope:"profile",perSurface:!0,parse:He}),useSystemTheme:p({scope:"profile",perSurface:!0,parse:P}),themeVariant:p({scope:"profile",derived:!0,parse:X(["light","dark"])}),lightThemeId:p({scope:"profile",perSurface:!0,parse:He}),darkThemeId:p({scope:"profile",perSurface:!0,parse:He}),lastDirectory:p({scope:"instance",adopt:"bootstrap-only",parse:He}),homeDirectory:p({scope:"instance",parse:He}),opencodeBinary:p({scope:"instance",parse:Sn}),projects:p({scope:"instance",parse:sw}),activeProjectId:p({scope:"instance",adopt:"bootstrap-only",parse:He}),securityScopedBookmarks:p({scope:"instance",surfaces:["desktop"],parse:xo}),pinnedDirectories:p({scope:"instance",parse:Zr}),desktopLanAccessEnabled:p({scope:"instance",surfaces:["desktop"],parse:P}),desktopKeepAwakeEnabled:p({scope:"instance",surfaces:["desktop"],parse:P}),desktopMinimizeToTrayEnabled:p({scope:"instance",surfaces:["desktop"],parse:P}),desktopMacMenuBarEnabled:p({scope:"instance",surfaces:["desktop"],parse:P}),desktopUiPassword:p({scope:"instance",secret:!0,surfaces:["desktop"],parse:Sn}),hasDesktopUiPassword:p({scope:"instance",computed:!0,surfaces:["desktop"],parse:P}),desktopLanAccessActive:p({scope:"instance",computed:!0,surfaces:["desktop"],parse:P}),desktopLanAccessBlockedReason:p({scope:"instance",computed:!0,surfaces:["desktop"],parse:Sn}),githubClientId:p({scope:"instance",parse:mn}),githubScopes:p({scope:"instance",parse:mn}),skillCatalogs:p({scope:"instance",parse:tw}),defaultGitIdentityId:p({scope:"instance",parse:Sn}),permissionAutoAccept:p({scope:"instance",parse:F(S({sessions:lt(f().min(1),ct([he(),J(["ask","safety","auto"])])).catch({}),revision:x().int().nonnegative().catch(0)}))}),permissionDefaultMode:p({scope:"instance",surfaces:["web","desktop","mobile"],parse:F(J(["ask","safety","auto"])),ui:v("permissionDefaultMode",e=>T.getState().setPermissionDefaultMode(e))}),agentControlToolEnabled:p({scope:"instance",parse:P,ui:v("agentControlToolEnabled",e=>T.getState().setAgentControlToolEnabled(e))}),agentWebToolEnabled:p({scope:"instance",parse:P,ui:v("agentWebToolEnabled",e=>T.getState().setAgentWebToolEnabled(e))}),browserProvider:p({scope:"instance",parse:He,ui:v("browserProvider",e=>T.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:p({scope:"instance",parse:P,ui:v("agentNotifyToolEnabled",e=>T.getState().setAgentNotifyToolEnabled(e))}),agentToolsCodeMode:p({scope:"instance",parse:P,ui:v("agentToolsCodeMode",e=>T.getState().setAgentToolsCodeMode(e))}),agentMemoryToolEnabled:p({scope:"instance",parse:P,ui:v("agentMemoryToolEnabled",e=>T.getState().setAgentMemoryToolEnabled(e))}),isolatedSpacesEnabled:p({scope:"instance",parse:P,ui:v("isolatedSpacesEnabled",e=>T.getState().setIsolatedSpacesEnabled(e))}),isolatedSpacesIdleStop:p({scope:"instance",parse:F(S({enabled:he(),hours:x().int().min(1).max(168)}).strict())}),agentMemoryFeatureAvailable:p({scope:"instance",computed:!0,parse:P,ui:v("agentMemoryFeatureAvailable",e=>T.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),routingFeatureAvailable:p({scope:"instance",computed:!0,parse:P,ui:v("routingFeatureAvailable",e=>T.getState().setRoutingFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:p({scope:"instance",parse:qn(128)}),autoDeleteEnabled:p({scope:"instance",parse:P,ui:v("autoDeleteEnabled",e=>T.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:p({scope:"instance",parse:Uy(1,365),ui:v("autoDeleteAfterDays",e=>T.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:p({scope:"instance",parse:P,ui:v("sessionRetentionOnlyArchived",e=>T.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionAction:p({scope:"instance",parse:X(["archive","delete"]),ui:v("sessionRetentionAction",e=>T.getState().setSessionRetentionAction(e))}),terminalShell:p({scope:"instance",parse:fw,ui:v("terminalShell",e=>T.getState().setTerminalShell(e))}),terminalLoginShells:p({scope:"instance",parse:uw(Bi),ui:v("terminalLoginShells",e=>T.getState().setTerminalLoginShells(e))}),openInAppId:p({scope:"instance",parse:mn}),dictationEnabled:p({scope:"profile",parse:P,ui:Jt("dictationEnabled")}),sttProvider:p({scope:"instance",parse:aw,ui:Jt("sttProvider")}),sttServerUrl:p({scope:"instance",parse:qn(2048),ui:Jt("sttServerUrl")}),sttModel:p({scope:"instance",parse:qn(256),ui:Jt("sttModel")}),sttLocalModel:p({scope:"instance",parse:qn(256),ui:Jt("sttLocalModel")}),sttLanguage:p({scope:"profile",parse:qn(64),ui:Jt("sttLanguage")}),tunnelProvider:p({scope:"instance",parse:gr(mn,e=>e.toLowerCase())}),tunnelMode:p({scope:"instance",parse:F(f().transform(e=>e.trim().toLowerCase()).pipe(J(["quick","managed-remote","managed-local"])))}),tunnelBootstrapTtlMs:p({scope:"instance",parse:By}),tunnelSessionTtlMs:p({scope:"instance",parse:Kt}),managedLocalTunnelConfigPath:p({scope:"instance",parse:Hy}),managedRemoteTunnelHostname:p({scope:"instance",parse:Sn}),managedRemoteTunnelToken:p({scope:"instance",secret:!0,parse:$y}),hasManagedRemoteTunnelToken:p({scope:"instance",computed:!0,parse:P}),managedRemoteTunnelPresets:p({scope:"instance",parse:Xy}),managedRemoteTunnelSelectedPresetId:p({scope:"instance",parse:mn}),managedRemoteTunnelPresetTokens:p({scope:"instance",secret:!0,parse:Zy}),sidebarProjectDisplayMode:p({scope:"profile",parse:X(["all","single"]),ui:Kn("projectDisplayMode")}),sidebarViewMode:p({scope:"profile",perSurface:!0,parse:X(["projects","timeline"]),ui:Kn("sidebarViewMode")}),sidebarProjectSortOrder:p({scope:"profile",parse:X(["manual","a-z","z-a","date-added","recent"]),ui:Kn("projectSortOrder")}),sidebarWorktreeSortOrder:p({scope:"profile",parse:X(["recent","manual","a-z"]),ui:Kn("worktreeSortOrder")}),sidebarShowRecentSection:p({scope:"profile",perSurface:!0,parse:P,ui:Kn("showRecentSection")}),workStatusSectionOrder:p({scope:"profile",parse:gr(xo,xs),ui:v("workStatusSectionOrder",e=>T.getState().setWorkStatusSectionOrder(e))}),workStatusPanelEnabled:p({scope:"profile",parse:P,ui:v("workStatusPanelEnabled",e=>T.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:p({scope:"profile",parse:Sw,ui:{read:()=>T.getState().workStatusHiddenSections,write:(e,t)=>{const n=t.workStatusHiddenSectionsExplicit===!0;T.setState({workStatusHiddenSections:hu(e,n),workStatusHiddenSectionsExplicit:n})},autoSave:!0}}),workStatusHiddenSectionsExplicit:p({scope:"profile",parse:P,ui:v("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:p({scope:"profile",parse:P,ui:v("showReasoningTraces",e=>T.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:p({scope:"profile",perSurface:!0,parse:P,ui:v("streamingAutoFollowEnabled",e=>T.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:p({scope:"profile",parse:P,ui:v("collapsibleThinkingBlocks",e=>T.getState().setCollapsibleThinkingBlocks(e))}),showTextJustificationActivity:p({scope:"profile",parse:P}),chatRenderMode:p({scope:"profile",parse:X(["sorted","live"]),ui:v("chatRenderMode",e=>T.getState().setChatRenderMode(e))}),activityRenderMode:p({scope:"profile",parse:X(["collapsed","summary"]),ui:v("activityRenderMode",e=>T.getState().setActivityRenderMode(e))}),mermaidRenderingMode:p({scope:"profile",parse:X(["svg","ascii"]),ui:v("mermaidRenderingMode",e=>T.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:p({scope:"profile",parse:X(["markdown","plain"]),ui:v("userMessageRenderingMode",e=>T.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:p({scope:"profile",parse:P,ui:v("collapsibleUserMessages",e=>T.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:p({scope:"profile",perSurface:!0,parse:P,ui:v("stickyUserHeader",e=>T.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:p({scope:"profile",perSurface:!0,parse:P,ui:v("promptNavigatorEnabled",e=>T.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:p({scope:"profile",perSurface:!0,parse:P,ui:v("wideChatLayoutEnabled",e=>T.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:p({scope:"profile",parse:P,ui:v("showSplitAssistantMessageActions",e=>T.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:p({scope:"profile",parse:P,ui:v("showToolFileIcons",e=>T.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:p({scope:"profile",parse:P,ui:v("codeBlockLineWrap",e=>T.getState().setCodeBlockLineWrap(e))}),showTurnChangedFiles:p({scope:"profile",parse:P,ui:v("showTurnChangedFiles",e=>T.getState().setShowTurnChangedFiles(e))}),showExpandedBashTools:p({scope:"profile",parse:P,ui:v("showExpandedBashTools",e=>T.getState().setShowExpandedBashTools(e))}),showExpandedEditTools:p({scope:"profile",parse:P,ui:v("showExpandedEditTools",e=>T.getState().setShowExpandedEditTools(e))}),toolJsonViewMode:p({scope:"profile",parse:X(["summary","formatted","raw"]),ui:v("toolJsonViewMode",e=>T.getState().setToolJsonViewMode(e))}),timeFormatPreference:p({scope:"profile",parse:X(["auto","12h","24h"]),ui:v("timeFormatPreference",e=>T.getState().setTimeFormatPreference(e))}),weekStartPreference:p({scope:"profile",parse:X(["auto","sunday","monday"]),ui:v("weekStartPreference",e=>T.getState().setWeekStartPreference(e))}),messageStreamTransport:p({scope:"profile",parse:X(["auto","ws","sse"]),ui:Jt("settingsMessageStreamTransport")}),diffLayoutPreference:p({scope:"profile",parse:X(["dynamic","inline","side-by-side"]),ui:v("diffLayoutPreference",e=>T.getState().setDiffLayoutPreference(e))}),diffWrapLines:p({scope:"profile",parse:P,ui:v("diffWrapLines",e=>T.getState().setDiffWrapLines(e))}),gitChangesViewMode:p({scope:"profile",parse:X(["flat","tree"]),ui:v("gitChangesViewMode",e=>T.getState().setGitChangesViewMode(e))}),gitmojiEnabled:p({scope:"profile",parse:P}),defaultFileViewerPreview:p({scope:"profile",parse:P}),directoryShowHidden:p({scope:"profile",parse:P,ui:{read:Hg,write:e=>$g(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:p({scope:"profile",parse:P,ui:{read:qg,write:e=>Kg(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:p({scope:"profile",parse:vw,ui:v("fileEditorKeymap",e=>T.getState().setFileEditorKeymap(e))}),autoSaveEnabled:p({scope:"profile",parse:P,ui:v("autoSaveEnabled",e=>T.getState().setAutoSaveEnabled(e))}),autoCreateWorktree:p({scope:"profile",parse:P}),sessionTabsEnabled:p({scope:"profile",surfaces:["web","desktop","vscode"],parse:P,ui:v("sessionTabsEnabled",e=>T.getState().setSessionTabsEnabled(e))}),allowPromptingSubagentSessions:p({scope:"profile",parse:P,ui:v("allowPromptingSubagentSessions",e=>T.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:p({scope:"profile",parse:P,ui:v("inputSpellcheckEnabled",e=>T.getState().setInputSpellcheckEnabled(e))}),enterToSend:p({scope:"profile",parse:P,ui:v("enterToSend",e=>T.getState().setEnterToSend(e))}),enterToSendConfigured:p({scope:"profile",parse:P,ui:v("enterToSendConfigured",e=>T.getState().setEnterToSendConfigured(e))}),persistChatDraft:p({scope:"profile",parse:P,ui:v("persistChatDraft",e=>T.getState().setPersistChatDraft(e))}),largeTextPasteBehavior:p({scope:"profile",parse:bw,ui:v("largeTextPasteBehavior",e=>T.getState().setLargeTextPasteBehavior(e))}),followUpBehavior:p({scope:"profile",parse:iw,ui:{read:()=>ti.getState().followUpBehavior,write:e=>ti.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:p({scope:"profile",parse:P}),inputHistoryScope:p({scope:"profile",parse:mw,ui:{read:()=>Xn.getState().scope,write:e=>Xn.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:p({scope:"profile",parse:gw,ui:{read:()=>Xn.getState().entryLimit,write:e=>Xn.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:p({scope:"profile",parse:ww,ui:{read:()=>T.getState().globalDraftStarters??void 0,write:(e,t)=>T.getState().setGlobalDraftStarters(Tw(e,t)),autoSave:!1}}),draftStartersVisible:p({scope:"profile",parse:P,ui:v("draftStartersVisible",e=>T.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:p({scope:"profile",parse:P}),draftStartersScheduleTaskAdded:p({scope:"profile",parse:P}),fontSize:p({scope:"profile",perSurface:!0,parse:Kt,ui:v("fontSize",e=>T.getState().setFontSize(e))}),terminalFontSize:p({scope:"profile",perSurface:!0,parse:Kt,ui:v("terminalFontSize",e=>T.getState().setTerminalFontSize(e))}),editorFontSize:p({scope:"profile",perSurface:!0,parse:Kt,ui:v("editorFontSize",e=>T.getState().setEditorFontSize(e))}),uiFont:p({scope:"profile",parse:pw,ui:v("uiFont",e=>T.getState().setUiFont(e))}),monoFont:p({scope:"profile",parse:hw,ui:v("monoFont",e=>T.getState().setMonoFont(e))}),padding:p({scope:"profile",perSurface:!0,parse:Kt,ui:v("padding",e=>T.getState().setPadding(e))}),cornerRadius:p({scope:"profile",perSurface:!0,parse:Kt,ui:v("cornerRadius",e=>T.getState().setCornerRadius(e))}),shortcutOverrides:p({scope:"profile",parse:qy,ui:v("shortcutOverrides",Vt("shortcutOverrides"))}),defaultModel:p({scope:"profile",parse:He}),defaultVariant:p({scope:"profile",parse:He}),defaultAgent:p({scope:"profile",parse:He}),smallModelUseDefault:p({scope:"profile",parse:P}),smallModelOverride:p({scope:"profile",parse:He}),walkthroughModelOverride:p({scope:"profile",parse:He}),zenModel:p({scope:"profile",parse:mn}),favoriteModels:p({scope:"profile",parse:Co(64),ui:v("favoriteModels",Vt("favoriteModels"),{autoSave:!1})}),hiddenModels:p({scope:"profile",parse:Co(1024),ui:v("hiddenModels",Vt("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:p({scope:"profile",parse:Zr,ui:v("collapsedModelProviders",Vt("collapsedModelProviders"),{autoSave:!1})}),recentModels:p({scope:"profile",parse:Co(16),ui:v("recentModels",Vt("recentModels"),{autoSave:!1})}),recentAgents:p({scope:"profile",parse:Zr,ui:v("recentAgents",Vt("recentAgents"),{autoSave:!1})}),recentEfforts:p({scope:"profile",parse:Gy,ui:v("recentEfforts",Vt("recentEfforts"),{autoSave:!1})}),providerOrder:p({scope:"profile",parse:Zr,ui:v("providerOrder",e=>T.getState().setProviderOrder(e))}),sessionRecapEnabled:p({scope:"profile",parse:P,ui:v("sessionRecapEnabled",e=>T.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:p({scope:"profile",parse:P,ui:v("sessionSuggestionEnabled",e=>T.getState().setSessionSuggestionEnabled(e))}),sessionWorkEnabled:p({scope:"profile",parse:P,ui:v("sessionWorkEnabled",e=>T.getState().setSessionWorkEnabled(e))}),sessionWorkAutoOpen:p({scope:"profile",surfaces:["web","desktop","mobile"],parse:P,ui:v("sessionWorkAutoOpen",e=>T.getState().setSessionWorkAutoOpen(e))}),sessionGoalEnabled:p({scope:"profile",parse:P,ui:v("sessionGoalEnabled",e=>T.getState().setSessionGoalEnabled(e))}),sessionGoalChecker:p({scope:"profile",surfaces:["web","desktop","mobile"],parse:X(["classifier","small-model"]),ui:v("sessionGoalChecker",e=>T.getState().setSessionGoalChecker(e))}),sessionGoalDefaultBudgetEnabled:p({scope:"profile",parse:P,ui:v("sessionGoalDefaultBudgetEnabled",e=>T.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:p({scope:"profile",parse:Ny,ui:v("sessionGoalDefaultBudget",e=>T.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:p({scope:"profile",parse:P,ui:v("summarizeLastMessage",e=>T.getState().setSummarizeLastMessage(e))}),summaryThreshold:p({scope:"profile",parse:Io(0),ui:v("summaryThreshold",e=>T.getState().setSummaryThreshold(e))}),summaryLength:p({scope:"profile",parse:Io(10),ui:v("summaryLength",e=>T.getState().setSummaryLength(e))}),maxLastMessageLength:p({scope:"profile",parse:Io(10),ui:v("maxLastMessageLength",e=>T.getState().setMaxLastMessageLength(e))}),showDeletionDialog:p({scope:"profile",parse:P,ui:v("showDeletionDialog",e=>T.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:p({scope:"profile",parse:P,ui:v("nativeNotificationsEnabled",e=>T.getState().setNativeNotificationsEnabled(e))}),notificationMode:p({scope:"profile",parse:X(["always","hidden-only"]),ui:v("notificationMode",e=>T.getState().setNotificationMode(e))}),notifyOnSubtasks:p({scope:"profile",parse:P,ui:v("notifyOnSubtasks",e=>T.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:p({scope:"profile",parse:P,ui:v("notifyOnCompletion",e=>T.getState().setNotifyOnCompletion(e))}),notifyOnError:p({scope:"profile",parse:P,ui:v("notifyOnError",e=>T.getState().setNotifyOnError(e))}),notifyOnQuestion:p({scope:"profile",parse:P,ui:v("notifyOnQuestion",e=>T.getState().setNotifyOnQuestion(e))}),notificationTemplates:p({scope:"profile",parse:Vy,ui:v("notificationTemplates",e=>T.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:p({scope:"profile",parse:P,ui:v("showOpenCodeUpdateNotifications",e=>T.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:p({scope:"profile",parse:P,ui:v("reportUsage",e=>T.getState().setReportUsage(e))}),usageDisplayMode:p({scope:"profile",parse:X(["usage","remaining"])}),usageDropdownProviders:p({scope:"profile",parse:xo}),usageSelectedModels:p({scope:"profile",parse:Ro}),usageCollapsedFamilies:p({scope:"profile",parse:Ro}),usageExpandedFamilies:p({scope:"profile",parse:Ro}),usageModelGroups:p({scope:"profile",parse:Yy}),globalBehaviorPrompt:p({scope:"profile",parse:Pc(1024*1024)}),responseStyleEnabled:p({scope:"profile",parse:P}),responseStylePreset:p({scope:"profile",parse:X(dw)}),responseStyleCustomInstructions:p({scope:"profile",parse:Pc(5e4)}),pwaAppName:p({scope:"instance",surfaces:["web"],parse:lw}),pwaOrientation:p({scope:"instance",surfaces:["web"],parse:X(["system","portrait","landscape"])}),mobileKeyboardMode:p({scope:"device",surfaces:["mobile"],parse:yw,ui:v("mobileKeyboardMode",e=>T.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:p({scope:"device",surfaces:["desktop"],parse:cw,ui:v("desktopWindowControlsPosition",e=>T.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:p({scope:"device",surfaces:["desktop"],parse:X(["classic","traffic-lights"]),ui:v("desktopWindowControlsStyle",e=>T.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:p({scope:"device",surfaces:["mobile","web"],parse:Kt,ui:v("inputBarOffset",e=>T.getState().setInputBarOffset(e))})},kw=e=>Object.prototype.hasOwnProperty.call(Pr,e),Ar=Object.keys(Pr).filter(kw),Bu=e=>Pr[e].scope==="device",Ir=e=>Pr[e],Ew=e=>!Pr[e].computed&&!Bu(e),Pw=lt(f(),ye()),Aw=e=>{const t=Pw.safeParse(e);if(!t.success)return null;const n=t.data,r={};for(const s of Ar){const i=Ir(s).parse(n[s],n);i!==void 0&&Object.assign(r,{[s]:i})}return r},Iw=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),xw=e=>{for(const t of Ar){const n=Ir(t);if(!n.ui)continue;const r=e[t];r!==void 0&&(Iw(n.ui.read(),r)||n.ui.write(r,e))}},Rw=Ar.filter(e=>Ir(e).ui?.autoSave===!0),uE=()=>{const e={};for(const t of Rw){const r=Ir(t).ui?.read();r!==void 0&&Object.assign(e,{[t]:r})}return e},Cw=Ar.filter(e=>{const t=Ir(e);return t.scope!=="device"&&!t.secret&&!t.computed}),Ow=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},xc="openchamber.settingsMirror.v2.index",Dw="openchamber.deviceSeeded.v1:",Mw=e=>`${Dw}${encodeURIComponent(e)}`,_w=(e,t)=>{const n=Mw(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 Ar)e[o]===void 0||Bu(o)||Object.assign(s,{[o]:e[o]});return s},Lw="openchamber.settingsMirror.v2:",Fw=5,Rc=e=>`${Lw}${encodeURIComponent(e)}`,gn=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},jw=(e,t)=>{const n={};for(const o of Cw)e[o]!==void 0&&Object.assign(n,{[o]:e[o]});localStorage.setItem(Rc(t),JSON.stringify(n));let r=[];try{const o=JSON.parse(localStorage.getItem(xc)??"[]");Array.isArray(o)&&(r=o.filter(i=>typeof i=="string"))}catch{r=[]}const s=[t,...r.filter(o=>o!==t)].slice(0,Fw);for(const o of r)s.includes(o)||localStorage.removeItem(Rc(o));localStorage.setItem(xc,JSON.stringify(s))},Uw=e=>{if(!(typeof window>"u")){if(jw(e,G()),gn("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),Ow(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(fu(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)}},ni=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let ri="idle",ts=null;const si=new Set,dE=()=>ri,fE=e=>(si.add(e),()=>si.delete(e)),pE=e=>{qs(),Je(e)},Je=e=>{ts&&(clearTimeout(ts),ts=null);const t=e==="saved"?"idle":e;t!==ri&&(ri=t,si.forEach(n=>n())),t==="error"&&(ts=setTimeout(()=>Je("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},Hu=()=>{const e=T.persist;if(e&&typeof e=="object")return e},$u=()=>br()?.settings??null,zu=()=>`/api/config/settings?${Pu}=${Ui()}`,Nw=e=>{xw(e)},Os=e=>Aw(e);class Bw{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 Vi=0,Mt=null,On={},oi=!1;const hE=()=>oi,ii=e=>{oi=!0;try{Nw(e)}finally{oi=!1}};let Zt=null,Qe=null,it=null,Ce=null,ar=[],Cc=!1,Ds=0,ls=[];const Fe=new Bw,Hw=2e3,$w=200,Ji=()=>({runtimeKey:G(),generation:Vi}),Gs=e=>Object.keys(e),Wu=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),us=e=>{On={...On,...e}},zw=e=>{const t={...On};for(const n of e)delete t[n];On=t},Ww=e=>{const t={};for(const n of Gs(e))Wu(e[n],On[n])||Object.assign(t,{[n]:e[n]});return t},yr=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,Gu=e=>{let t=null;for(const n of ls)yr(n.context,e)&&(t={...t??{},...n.changes});return Qe&&it&&yr(it,e)&&(t={...t??{},...Qe}),t},Oc=(e,t)=>{const n=Gu(t);return e&&n?{...e,...n}:e},ae=e=>e.generation===Vi&&e.runtimeKey===G(),Vn=()=>{Qe&&(Ce&&(clearTimeout(Ce),Ce=null),Ms({keepalive:!0}))},qs=()=>{if(!(Cc||typeof window>"u")){Cc=!0,Ef(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Ce&&clearTimeout(Ce),Qe&&Ms())}),wl(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Vi+=1,Fe.reset(),Ds=0,Mt=null,Zt=null,On={},Je("saved"))});try{window.addEventListener("pagehide",Vn,{capture:!0}),window.addEventListener("beforeunload",Vn,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Vn()}),document.addEventListener("freeze",Vn)),vr()&&gi(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||Vn()})).catch(()=>{})}catch{}}},qu=async(e=Ji())=>{if(qs(),Mt&&yr(Mt.context,e)&&Date.now()-Mt.at<Hw)return Oc(Mt.value,e);if(Zt&&yr(Zt.context,e))return Zt.promise;const t=Fe.begin(),n=Gu(e),r=o=>{if(!ae(e)||!o)return null;const i=Oc(Fe.reconcile({...o,...n},t),e);Mt={value:i,at:Date.now(),context:e};const a={};for(const c of Gs(o))Wu(o[c],i?.[c])&&Object.assign(a,{[c]:o[c]});return us(a),i},s={context:e,promise:(async()=>{const o=$u();if(o)try{const i=await o.load();if(!ae(e))return null;const a=Os(i.settings);return r(a)}catch(i){if(!ae(e))return null;console.warn("Failed to load shared settings from runtime settings API:",i)}if(!ae(e))return null;try{const i=await g(zu(),{method:"GET",headers:{Accept:"application/json"}});if(!ae(e)||!i.ok)return null;const a=await i.json().catch(()=>null);if(!ae(e))return null;const c=Os(a);return r(c)}catch(i){return ae(e)&&console.warn("Failed to load shared settings from server:",i),null}})()};return Zt=s,s.promise.finally(()=>{Fe.finish(t),Zt===s&&(Zt=null)}),s.promise},mE=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;qs();const r=Ji(),s=Fe.begin(),o=[Hu(),qo.persist],i=u=>!u?.hasHydrated||u.hasHydrated()||!u.onFinishHydration?Promise.resolve():new Promise(d=>{let h=!1;const m=()=>{h||(h=!0,d())},y=u.onFinishHydration(()=>{y?.(),m()});u.hasHydrated?.()&&m()}),a=()=>Promise.all(o.map(i)).then(()=>{}),c=u=>!Qe||!it||!ae(it)?u:{...u,...Qe},l=async u=>{if(!ae(r))return;let d=c(Fe.reconcile(u,s));if(await a(),!!ae(r)){d=_w(c(Fe.reconcile(u,s)),r.runtimeKey);try{Uw(d)}catch(h){console.warn("persistToLocalStorage failed:",h)}try{ii(d)}catch(h){console.warn("applyDesktopUiPreferences failed:",h)}ni(d,t,n)}};try{const u=await qu(r);u&&ae(r)?await l(u):ae(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(u){ae(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",u)}finally{Fe.finish(s)}};async function Ms({keepalive:e=!1}={}){let t=!1;const n=Qe,r=it,s=Ds,o=ar;Qe=null,it=null,Ds=0,Ce=null,ar=[];try{if(!n||!r||Object.keys(n).length===0||!ae(r)){t=!0,Je("saved");return}const i=Fe.begin(s),a={context:r,changes:{...n}};ls.push(a),us(n);const c=()=>zw(Gs(n));try{const l=$u();if(l)try{const u=Os(await l.save(n));if(!ae(r))return;if(u){us(u);const d=Fe.reconcile(u,i);ii(d),ni(d,!1),Mt=null}u||c(),t=!!u,Je(u?"saved":"error");return}catch(u){if(!ae(r))return;console.warn("Failed to update settings via runtime settings API:",u)}if(!ae(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(!ae(r))return;if(!u.ok){console.warn("Failed to update shared settings via API:",u.status,u.statusText),c(),Je("error");return}const d=Os(await u.json().catch(()=>null));if(!ae(r))return;if(d){us(d);const h=Fe.reconcile(d,i);ii(h),ni(h,!1),t=!0,Je("saved"),Mt=null}else c(),Je("error")}catch(u){ae(r)&&(console.warn("Failed to update shared settings via API:",u),c(),Je("error"))}}finally{ls=ls.filter(l=>l!==a),Fe.finish(i)}}finally{o.forEach(i=>i({ok:t}))}}const gE=()=>qu(),wt=async e=>{if(typeof window>"u")return{ok:!1};qs();const t=Ji();it&&!yr(it,t)&&(Ce&&clearTimeout(Ce),Ms());const n={};for(const i of Gs(e))Ew(i)&&Object.assign(n,{[i]:e[i]});const r=Fe.record(n),s=Ww({...Qe??{},...n});if(Object.keys(s).length===0){Qe=null,it=null,Ce&&(clearTimeout(Ce),Ce=null);const i=ar;return ar=[],i.forEach(a=>a({ok:!0})),Je("saved"),{ok:!0}}Qe=s,it=t,Ds=r,Je("saving"),Ce&&clearTimeout(Ce);const o=new Promise(i=>{ar.push(i)});return Ce=setTimeout(()=>{Ms()},$w),o},yE=async()=>{if(typeof window>"u")return;const e=Hu();try{const t=await Dg();if(!t)return;const n=()=>Og(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)}},Gw=3e4,qw=40,Kw=60,Vw=(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])},Dc=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},Jw=ut()(Mn((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,s=Kw,o){if(!n||n.trim().length===0)return[];const i=n.trim(),a=G(),c=typeof r=="string"?r.trim():"",l=!!o?.includeHidden,u=o?.respectGitignore??!0,d=o?.type==="directory"?"directory":"file",h=Vw(a,i,c,s,l,u,d),m=Date.now(),y=t().cache[h];if(y&&m-y.timestamp<Gw)return y.files;const b=t().inFlight[h];if(b)return b;const w=ot.searchFiles(c,{directory:i,limit:s,type:d}).then(k=>(e(E=>{if(E.inFlight[h]!==w)return E;const L={...E.cache,[h]:{files:k,timestamp:Date.now()}},M=E.cacheKeys.filter(Y=>Y!==h);for(M.push(h);M.length>qw;){const Y=M.shift();Y&&delete L[Y]}return{cache:L,cacheKeys:M}}),k)).finally(()=>{e(k=>{if(k.inFlight[h]!==w)return k;const E={...k.inFlight};return delete E[h],{inFlight:E}})});return e(k=>({inFlight:{...k.inFlight,[h]:w}})),w},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=>Dc(l,r)?(delete o[l],!1):!0),a=Object.entries(s.inFlight).filter(([l])=>!Dc(l,r)),c=Object.fromEntries(a);return{cache:o,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),Yw=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},ai="openchamber_stream_perf",Qw=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(ai)==="1"}catch{return!1}};let Ku=Qw(),Vu=!1;const ln=()=>Ku||Vu,Ju=()=>{ln()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},Mc=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Yu=()=>{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},Qu=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),Yi=(e,t)=>{const n=Yu();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()},Xw=e=>{if(Ku=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(ai,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(ai),Ju()}catch{}},wE=e=>{if(Vu=e,!(typeof window>"u")){if(e){Yu();return}Ju()}},Zw=()=>{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()}))},eS=()=>{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:Qu(e.counters)}},SE=()=>{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:Qu(e.counters)}},bE=(e,t=1)=>{Yi(e,t)},vE=(e,t)=>{Yi(e,t)},TE=e=>{!ln()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},kE=(e,t)=>{if(!ln())return t();const n=Mc();try{return t()}finally{Yi(e,Mc()-n)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:Xw,reset:Zw,getSnapshot:eS});var tS={};let at=null,_c=0;const Ye=Er(),Lc=Ye.getItem("lastDirectory"),nS=typeof Lc=="string"&&Lc.length>0,ns=e=>{try{Jw.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Dn=e=>Xe(e)??"",rS=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},ds=(e,t)=>{const n=rS(e,t);return Dn(n)},sS=()=>{const e=Ye.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Dn(e);return t.length>0?t:null},oS=()=>{const e=Ye.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Dn(e);return t.length>0?t:null},iS=()=>{if(typeof process>"u")return null;const e=tS,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=Dn(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=Dn(n);return r.length>0?r:null}return null},Qi=()=>{if(typeof window<"u"){if(at)return at;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return at=t,Ye.setItem("homeDirectory",t),t;const n=sS();if(n&&!Oe())return at=n,n}const e=iS();return e||"/"},aS=e=>{const t=Xe(e);return t&&t!=="/"?t:null},cS=e=>(at=e,typeof window<"u"&&Ye.setItem("homeDirectory",e),wt({homeDirectory:e}),e),ci=async()=>{const e=r=>{const s=aS(r);return s?cS(s):null};try{const r=await ot.getFilesystemHome(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await ot.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 Tl(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=Qi(),n=e(t);return n||t},lS=()=>{if(!Oe())return null;const e=Sl()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Dn(e);return t.length>0?t:null},wr=lS()||Qi(),_s=(()=>{const e=oS();return e&&!Oe()?ds(e,wr):wr})();_s&&ot.setDirectory(_s);const uS=!!(wr&&wr!=="/"),li=ut()(Mn((e,t)=>({currentDirectory:_s,directoryHistory:[_s],historyIndex:0,homeDirectory:wr,hasPersistedDirectory:nS,isHomeReady:uS,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const s=at||t().homeDirectory||Ye.getItem("homeDirectory"),o=ds(n,s);Yw()&&console.log("[DirectoryStore] setDirectory called with path:",o),ot.setDirectory(o),ns(),e(i=>{const a=i.directoryHistory[i.historyIndex]===o,c=a?i.directoryHistory:[...i.directoryHistory.slice(0,i.historyIndex+1),o];return Ye.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];ot.setDirectory(s),ns(),Ye.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];ot.setDirectory(s),ns(),Ye.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=at||t().homeDirectory||Qi();if(n===s)return;const o=jh(n);o&&r(o)},goHome:async()=>{const n=at||t().homeDirectory||await ci();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),s=n;at=s;const o=r.homeDirectory!==s,i=Ye.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?ds(r.currentDirectory,s):r.currentDirectory,d=r.directoryHistory.map(b=>ds(b,s)),h=d.some((b,w)=>b!==r.directoryHistory[w]),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||h)&&(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;ot.setDirectory(b),ns(),Ye.setItem("lastDirectory",b),wt({lastDirectory:b})}wt({homeDirectory:s})}}),{name:"directory-store"}));typeof window<"u"&&(ci().then(e=>{li.getState().synchronizeHomeDirectory(e)}),wl(()=>{at=null;const e=++_c;ci().then(t=>{e===_c&&li.getState().synchronizeHomeDirectory(t)})}));const dS=(e,t)=>{const n=js();return n?n.openWebSocket(of(e),t):jf(new WebSocket(e))},Xu=1,Fc=512*1024,fS=0,yn=1,pS=15e3,Xi=new TextEncoder,Zu=new TextDecoder,Zi=J(["interactive","command"]),ed=J(["running","exited","error"]),hS=J(["node","bun"]),ea=jt("type",[S({type:D("terminal")}),S({type:D("project-action"),actionId:f(),executionId:f()})]),mS=S({sessionId:f(),cols:x(),rows:x(),status:ed,mode:Zi.optional(),purpose:ea.optional()}),gS=S({sessionId:f(),cwd:f(),status:J(["running","exited"]),createdAt:x().nullable().optional().transform(e=>e??null),mode:Zi.optional(),purpose:ea.optional()}),jc={mode:Zi.optional(),purpose:ea.optional()},yS=jt("t",[S({t:D("hello")}),S({t:D("pong")}),S({t:D("error"),s:f().optional(),message:f().optional(),code:f().optional(),fatal:he().optional()}),S({t:D("snapshot"),s:f(),q:x().int().nonnegative().default(0),history:f().default(""),status:ed,cols:x().int().positive().optional(),rows:x().int().positive().optional(),exitCode:x().nullish().transform(e=>e??void 0),signal:x().nullable().optional(),runtime:hS.optional(),ptyBackend:f().optional(),...jc}),S({t:D("output"),s:f(),q:x().int().nonnegative(),d:f(),r:f().optional()}),S({t:D("exit"),s:f(),q:x().int().nonnegative(),exitCode:x().nullish().transform(e=>e??void 0),signal:x().nullable().optional()}),S({t:D("restarted"),s:f(),q:x().int().nonnegative(),history:f().default(""),...jc})]),wS=e=>{const t=Xi.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=Xu,n.set(t,1),n},SS=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):Xi.encode(e);t[0]===Xu&&(t=t.subarray(1));try{return yS.safeParse(JSON.parse(Zu.decode(t))).data??null}catch{return null}};class bS extends Error{code;constructor(t,n){super(t),this.name="TerminalRequestError",this.code=n}}const EE=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,vS=S({error:f().optional(),code:f().optional()}),Ks=async(e,t)=>{const n=vS.safeParse(await e.json().catch(()=>null)).data;return new bS(n?.error??t,n?.code??null)},TS=e=>{const t=Xi.encode(e);if(t.byteLength<=Fc)return e;let n=t.byteLength-Fc;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return Zu.decode(t.subarray(n))},kS=S({sessions:j(ye())});class ES{constructor(t=td()){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(h),m?s(m):r())},h=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=SS(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:TS(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(wS(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())},pS))}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===fS||t.readyState===yn)&&t.close()}}const PS="",Ls=new Map;function td(e){return{refreshAuth:Bs,openSocket:()=>dS(Ae().websocket(Ai("/api/terminal/ws",e))),clearUrlAuthToken:Tr}}function xr(e){const t=Pi(e)??PS,n=Ls.get(t);if(n)return n;const r=new ES(td(e));return Ls.set(t,r),r}async function AS(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 Ks(t,"Failed to create terminal session");const n=await t.json().catch(()=>null),r=mS.safeParse(n).data;if(!r)throw new Error("Failed to create terminal session");return r}async function IS(e){const t=await g(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`,{directory:e});if(!t.ok)throw await Ks(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=kS.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=gS.safeParse(o).data;i&&s.push(i)}return s}async function xS(e,t){e.length!==0&&await Fn("/api/terminal/touch","POST",{sessionIds:e},t)}async function RS(){const e=await g("/api/terminal/shells");if(!e.ok)throw await Ks(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&Bi(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function CS(e,t,n,r){return xr(r).subscribe(e,{onEvent:t,onError:n})}async function OS(e,t,n){await xr(n).write(e,t)}async function Fn(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 Ks(o,"Terminal command failed");return o}async function DS(e,t,n,r){await Fn(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n},r),xr(r).noteResize(e,t,n)}async function MS(e,t,n){await Fn(`/api/terminal/${e}/appearance`,"POST",t,n)}async function _S(e,t){await Fn(`/api/terminal/${e}`,"DELETE",void 0,t),xr(t).forget(e)}async function LS(e,t){return(await Fn(`/api/terminal/${e}/restart`,"POST",t,t.cwd)).json()}async function FS(e){const n=await(await Fn("/api/terminal/force-kill","POST",e,e.cwd)).json().catch(()=>null),r=xr(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 PE(){for(const e of Ls.values())e.dispose();Ls.clear()}const jS=()=>({async listShells(){return RS()},async listSessions(e){return IS(e)},async touchSessions(e,t){await xS(e,t)},async createSession(e){return AS(e)},connect(e,t,n){const r=CS(e,t.onEvent,t.onError,n);return{close:()=>r()}},async sendInput(e,t,n){await OS(e,t,n)},async resize(e){await DS(e.sessionId,e.cols,e.rows,e.directory)},async updateAppearance(e,t,n){await MS(e,t,n)},async close(e,t){await _S(e,t)},async restartSession(e,t){return LS(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 FS(e)}}),ui=new Set,US=e=>(ui.add(e),()=>{ui.delete(e)}),NS=e=>{for(const t of ui)t(e)},di=new Set,BS=(e,t)=>JSON.stringify([t,Xe(e)]);function AE(e){return di.add(e),()=>{di.delete(e)}}function HS(e,t){const n=BS(e,t);for(const r of di)r(n)}class $S extends Error{reason;constructor(t,n){super(t),this.name="GitPathUnavailableError",this.reason=n}}const zS=S({error:f(),code:J(["path_not_found","nested_repository","untracked_directory"])}),nd=S({headCommit:f().nullable(),indexCommit:f().nullable(),worktreeCommit:f().nullable(),hasTrackedChanges:he(),hasUntrackedFiles:he(),hasConflict:he()}),A="/api/git",rd=S({diff:f()}),WS=S({files:j(S({path:f(),status:f()}))}),GS=S({error:f()}),qS=S({files:j(S({path:f(),previousPath:f().optional(),changeType:f(),insertions:x(),deletions:x(),isBinary:he()}))}),Uc=S({hash:f(),date:f(),message:f(),refs:f(),body:f(),author_name:f(),author_email:f(),filesChanged:x(),insertions:x(),deletions:x(),parents:j(f())}),KS=S({all:j(Uc),latest:Uc.nullable(),total:x()}),VS=S({diff:f(),submodule:nd.nullable().default(null)}),JS=S({original:f(),modified:f(),path:f(),isBinary:he().optional(),submodule:nd.nullable().default(null)});async function sd(e,t){const n=zS.safeParse(await e.json().catch(()=>null));return n.success&&(e.status===404||e.status===422)?new $S(n.data.error,n.data.code):new Error(`${t}: ${e.statusText}`)}async function Vs(e,t){const n=GS.safeParse(await e.json().catch(()=>null));return new Error(n.success?n.data.error:`${t}: ${e.statusText}`)}const YS=1200,QS=5e3,fi=new Map,Zn=new Map,od=new Map,Nc=new Map,rs=new Map,id=e=>e.trim(),ta=(e,t)=>JSON.stringify([e,id(t)]),ad=(e,t,n)=>JSON.stringify([e,id(t),n??"full"]),pi=(e,t)=>od.get(ta(e,t))??0,cd=(e,t)=>{const n=ta(e,t);od.set(n,pi(e,t)+1);for(const r of[void 0,"light"]){const s=ad(e,t,r);fi.delete(s),Zn.delete(s)}};US(e=>{cd(G(),e)});const Rr=e=>{NS(e)},re=async(e,t)=>{const n=await t.json();return Rr(e),n};function I(e,t,n){const r={...n};return t&&(r.directory=t),Ae().api(Ai(e,t),r)}async function XS(e){const t=ta(G(),e),n=Date.now(),r=Nc.get(t);if(r&&r.expiresAt>n)return r.value;const s=rs.get(t);if(s)return s;const o=(async()=>{const i=await g(I(`${A}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return Nc.set(t,{value:c,expiresAt:Date.now()+QS}),c})();rs.set(t,o);try{return await o}finally{rs.get(t)===o&&rs.delete(t)}}class ZS extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function IE(e){const t=await g("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new ZS;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=>Xe(r?.path??null)).filter(r=>r!==null)}async function eb(e,t){const n=t?.mode,r=G();t?.fresh&&cd(r,e);const s=ad(r,e,n),o=Date.now(),i=fi.get(s);if(i&&i.expiresAt>o)return i.value;const a=Zn.get(s);if(a)return a;const c=(async()=>{const l=pi(r,e),u=await g(I(`${A}/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 pi(r,e)===l&&fi.set(s,{value:d,expiresAt:Date.now()+YS}),d})();Zn.set(s,c);try{return await c}finally{Zn.get(s)===c&&Zn.delete(s)}}async function xE(e){const t=await g(I(`${A}/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 RE(e){const t=await g(I(`${A}/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 CE(e,t){const n=await g(I(`${A}/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 tb(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(I(`${A}/diff`,e,{path:n,staged:r?"true":void 0,context:s}));if(!o.ok)throw await sd(o,"Failed to get git diff");return VS.parse(await o.json())}async function nb(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(I(`${A}/range-diff`,e,{base:n,head:r,path:s||void 0,context:o,includeWorkingTree:i}));if(!a.ok)throw await Vs(a,"Failed to get git range diff");return rd.parse(await a.json())}async function rb(e,t){const n=await g(I(`${A}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!n.ok)throw await Vs(n,"Failed to get commit diff");return rd.parse(await n.json())}async function sb(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(I(`${A}/range-files`,e,{base:n,head:r,includeWorkingTree:s}));if(!o.ok)throw await Vs(o,"Failed to get git range files");return WS.parse(await o.json()).files}async function ob(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await g(I(`${A}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function ib(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(I(`${A}/file-diff`,e,{path:n,staged:r?"true":void 0}));if(!s.ok)throw await sd(s,"Failed to get git file diff");return JS.parse(await s.json())}async function ab(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await g(I(`${A}/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")}Rr(e)}async function cb(e,t){await ld(e,[t])}async function ld(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(I(`${A}/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")}Rr(e)}async function lb(e,t){await ud(e,[t])}async function ud(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(I(`${A}/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")}Rr(e)}async function ub(e,t,n){await na(e,t,n,"stage")}async function db(e,t,n){await na(e,t,n,"unstage")}async function fb(e,t,n){await na(e,t,n,"discard")}async function na(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(I(`${A}/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")}Rr(e)}async function pb(e){if(!e)return!1;const t=await g(I(`${A}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function hb(e){const t=await g(I(`${A}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function mb(e,t){const n=await g(I(`${A}/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 gb(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await g(I(`${A}/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 re(e,n)}async function yb(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await g(I(`${A}/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 re(e,n)}async function wb(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await g(I(`${A}/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 re(e,r)}async function Sb(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(I(`${A}/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 bb(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(I(`${A}/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:"",h=typeof u?.body=="string"?u.body:"";if(!d&&!h)throw new Error("Malformed PR description response");return{title:d,body:h}}async function Bc(e){const t=await g(I(`${A}/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 Hc(e,t){const n=await g(I(`${A}/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 vb(e){const t=await g(I(`${A}/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 Tb(e,t){const n=await g(I(`${A}/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 $c(e,t){const n=await g(I(`${A}/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 zc(e,t){const n=await g(I(`${A}/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 kb=S({ref:f(),commit:f().min(1),head:f().min(1)});async function Eb(e,t){const n=await g(I(`${A}/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 kb.parse(await n.json())}async function Pb(e,t,n={}){const r=await g(I(`${A}/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 re(e,r)}async function Ab(e,t={}){const n=G(),r=await g(I(`${A}/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 re(e,r);return s.success&&HS(e,n),s}async function Ib(e,t={}){const n=await g(I(`${A}/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 re(e,n)}async function xb(e,t={}){const n=await g(I(`${A}/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 re(e,n)}async function Rb(e){const t=await g(I(`${A}/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 Cb(e,t){const n=await g(I(`${A}/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 dd(e,t={}){const n=await g(I(`${A}/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 re(e,n)}const ra=async(e,t,n)=>{const r=await g(I(`${A}/${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 re(e,r)},Ob=(e,t)=>ra(e,"stash/apply",t),fd=(e,t)=>ra(e,"stash/pop",t),Db=(e,t)=>ra(e,"stash/drop",t);async function Mb(e,t){const n=await g(I(`${A}/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 re(e,n)}async function _b(e,t,n){const r=await g(I(`${A}/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 re(e,r)}async function Lb(e,t,n){const r=await g(I(`${A}/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 re(e,r)}async function Fb(e,t={}){const n=await g(I(`${A}/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 KS.parse(await n.json())}async function jb(e,t){const n=await g(I(`${A}/commit-files`,e,{hash:t}));if(!n.ok)throw await Vs(n,"Failed to get commit files");return qS.parse(await n.json())}async function OE(e,t,n,r){const s=await g(I(`${A}/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 Ub(){const e=await g(I(`${A}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Nb(e){const t=await g(I(`${A}/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 Bb(e,t){const n=await g(I(`${A}/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 Hb(e){const t=await g(I(`${A}/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 $b(e){if(!e)return null;const t=await g(I(`${A}/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 zb(e){if(!e)return!1;const t=await g(I(`${A}/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 DE(){const e=await g(I(`${A}/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 Wb(e,t){const n=await g(I(`${A}/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 ME(){const e=await g(I(`${A}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function _E(e,t){if(!e)return null;const n=await g(I(`${A}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function Gb(e){const t=await g(I(`${A}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function qb(e,t){const n=await g(I(`${A}/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 re(e,n)}async function Kb(e){const t=await g(I(`${A}/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 re(e,t)}async function Vb(e,t){const n=await g(I(`${A}/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 re(e,n)}async function Jb(e,t){const n=await g(I(`${A}/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 re(e,n)}async function Yb(e,t){const n=await g(I(`${A}/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 re(e,n)}async function Qb(e,t){const n=await g(I(`${A}/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 re(e,n)}async function Xb(e,t,n,r){const s=await g(I(`${A}/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 re(e,s)}async function Zb(e){const t=await g(I(`${A}/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 re(e,t)}async function ev(e){const t=await g(I(`${A}/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 re(e,t)}async function tv(e){const t=await g(I(`${A}/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 re(e,t)}async function nv(e,t){return await dd(e,{message:t?.message}),{success:!0}}async function rv(e){return await fd(e,{ref:"stash@{0}"}),{success:!0}}async function sv(e){const t=await g(I(`${A}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function ov(e,t){const n=await g(`${A}/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 iv(e){const t=await g(`${A}/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 av=()=>({checkIsGitRepository:XS,getGitStatus:eb,getGitDiff:tb,getGitFileDiff:ib,getGitRangeDiff:nb,getGitRangeFiles:sb,getBranchBase:ob,revertGitFile:ab,stageGitFile:cb,stageGitFiles:ld,unstageGitFile:lb,unstageGitFiles:ud,stageGitHunk:ub,unstageGitHunk:db,revertGitHunk:fb,isLinkedWorktree:pb,getGitBranches:hb,getGitUnpushedBranchCounts:mb,deleteGitBranch:gb,deleteRemoteBranch:yb,removeRemote:wb,generateCommitMessage:Sb,generatePullRequestDescription:bb,listGitWorktrees:Bc,validateGitWorktree:Hc,createGitWorktree:$c,deleteGitWorktree:zc,validateWorktreeDirectory:ov,canonicalizeWorktreeState:iv,createGitCommit(e,t,n){return Pb(e,t,n)},gitPush:Ab,gitPull:Ib,gitFetch:xb,listGitStashes:Rb,countGitStashFiles:Cb,stashGitChanges:dd,applyGitStash:Ob,popGitStash:fd,dropGitStash:Db,checkoutBranch:Mb,createBranch:_b,renameBranch:Lb,getGitLog(e,t){return Fb(e,t)},getCommitFiles:jb,getGitCommitDiff:rb,getCurrentGitIdentity:$b,hasLocalIdentity:zb,setGitIdentity:Wb,getGitIdentities:Ub,createGitIdentity:Nb,updateGitIdentity:Bb,deleteGitIdentity:Hb,getRemotes:Gb,rebase:qb,abortRebase:Kb,continueRebase:ev,merge:Vb,abortMerge:Zb,continueMerge:tv,checkoutCommit:Jb,cherryPick:Yb,revertCommit:Qb,resetToCommit:Xb,stash:nv,stashPop:rv,getConflictDetails:sv,worktree:{list:Bc,validate:Hc,bootstrapStatus:vb,preview:Tb,create:$c,remove:zc,snapshot:Eb}});let Wc=null;const cv=()=>window.Capacitor,lv=e=>e.getPlatform?.()!=="android"||!e.registerPlugin?null:(Wc??=e.registerPlugin("FileShare"),Wc),uv=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)},dv=async e=>{const t=cv(),n=t?lv(t):null;if(n){await n.share({fileName:e.name,mimeType:e.type||"application/octet-stream",data:await uv(e)});return}if(!navigator.canShare?.({files:[e]}))throw new Error("File sharing is unavailable in this mobile runtime");await navigator.share({files:[e]})},fe=e=>e.replace(/\\/g,"/"),fv=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new tn("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:fe(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:fe(r.path),isDirectory:!!r.isDirectory}))}},Ge=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},pv=({getDirectory:e})=>({async listDirectory(t,n){const r=fe(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:Ge(e)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new tn(a.error||"Failed to list directory",{reason:Es(a.reason),status:o.status})}const i=await o.json();return fv(r,i)},async search(t){const n=new URLSearchParams,r=fe(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:Ge(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:fe(`${r}/${a}`),preview:[fe(a)]}))},async createDirectory(t){const n=fe(t),r=await g("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...Ge(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"?fe(s.path):n}},async statFile(t,n){const r=fe(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:Ge(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"?fe(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=fe(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:Ge(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=fe(t),s=await g("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...Ge(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"?fe(o.path):r}},async uploadFile(t,n,r){const s=fe(t),o=await g("/api/fs/upload",{method:"POST",query:{path:s,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...Ge(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:Es(a.reason),status:o.status})}const i=await o.json().catch(()=>({}));return{success:!!i.success,path:i.path?fe(i.path):s}},async delete(t){const n=fe(t),r=await g("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...Ge(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",...Ge(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"?fe(s.path):n}},async revealPath(t){const n=await g("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...Ge(e)},body:JSON.stringify({path:fe(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=fe(t),r=await g("/api/fs/raw",{query:{path:n,download:!0},headers:Ge(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 dv(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)}}),hv="/api/config/settings",Gc=()=>`${hv}?${Pu}=${Ui()}`,mv="/api/config/reload",qc=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},gv=()=>({async load(){const e=await g(Gc(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:qc(await e.json()),source:"web"}},async save(e){const t=await g(Gc(),{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 qc(await t.json())},async restartOpenCode(){const e=await g(mv,{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}}}),yv=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),wv=1500,hi=5e3,Sv="openchamber-notification-claim:",cr=new Map,bv=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),vv=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("|")},Tv=e=>{for(const[t,n]of cr)e-n>hi&&cr.delete(t)},kv=e=>{const t=vv(e);if(!t)return!0;const n=Date.now();Tv(n);const r=cr.get(t)??0;if(n-r<hi)return!1;try{if(typeof window<"u"&&window.localStorage){const s=`${Sv}${t}`,o=Number(window.localStorage.getItem(s)??"0");if(Number.isFinite(o)&&n-o<hi)return cr.set(t,o),!1;Number.isFinite(o)&&o>0&&window.localStorage.removeItem(s),window.localStorage.setItem(s,String(n))}}catch{}return cr.set(t,n),!0},pd=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),wv)})])??e}catch{return e}},Ev=async e=>{const t=await pd();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}},Pv=async()=>{const e=await pd();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},Av=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(!bv()&&await Pv()||!kv(e))return!0;try{return await Ev(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},Iv=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}},xv=()=>({async notifyAgentCompletion(e){return await Iv(e)||await Av(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}},Rv=()=>({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)})}}),ue=async e=>await e.json().catch(()=>null),Cv=({urls:e})=>({async authStatus(){const t=await g("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await ue(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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(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 ue(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issue comments");return i}});async function Me(e){try{return await e.json()}catch{return null}}function _e(e,t){return e?.error?.trim()||t}function hd(e){return Number.isFinite(e)?e??null:null}function md(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function gd(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 Ov(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function Dv(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:gd(e?.user),authorizedAt:hd(n)}}function Kc(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(Dv).filter(n=>n!=null):[];return{connected:e.connected,user:gd(e.user),organization:Ov(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function Mv(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 _v(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 Lv(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:hd(r)??0}}function Fv(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 jv(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 Uv(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function Nv(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 Bv(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:Nv(e.color)}}function Hv(e){return Array.isArray(e)?e.map(Bv).filter(t=>t!=null):[]}function yd(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:_v(e.state),assignee:Fv(e.assignee),team:jv(e.team),priority:Uv(e.priority),labels:Hv(e.labels)}}function $v(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:md(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 wd(e){const t=yd(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map($v).filter(s=>s!=null):[],r=e?.description;return{...t,description:md(r),comments:n}}function zv(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(yd).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function Wv(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:wd(e.issue)}}function Gv(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(Lv).filter(n=>n!=null):[]}}function qv(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:wd(e.issue)}}function Kv(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 Vc(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(Kv).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const Vv=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function Jv(e){return Vv.find(t=>t===e)??null}function Jc(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function Yv(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=Jv(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const Qv=()=>({async authStatus(){const e=await g("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await Me(e),n=Kc(t);if(!e.ok||!n)throw new Error(_e(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 Me(t),r=Mv(n);if(!t.ok||!r)throw new Error(_e(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 Me(e);if(!e.ok)throw new Error(_e(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 Me(t),r=Kc(n);if(!t.ok||!r)throw new Error(_e(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 Me(u),h=zv(d);if(!u.ok||!h)throw new Error(_e(d,u.statusText||"Failed to load Linear issues"));return h},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 Me(n),s=Wv(r);if(!n.ok||!s)throw new Error(_e(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 Me(n),s=Gv(r);if(!n.ok||!s)throw new Error(_e(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 Me(t),r=qv(n);if(!t.ok||!r)throw new Error(_e(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 Me(e),n=Vc(t);if(!e.ok||!n)throw new Error(_e(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 Me(t),r=Vc(n);if(!t.ok||!r)throw new Error(_e(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 Me(t),r=Yv(n);if(!t.ok||!r)throw new Error(_e(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 Me(e),n=Jc(t);if(!e.ok||!n)throw new Error(_e(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 Me(t),r=Jc(n);if(!t.ok||!r)throw new Error(_e(n,t.statusText||"Failed to save Linear preferences"));return r}}),It=async e=>await e.json().catch(()=>null),Xv=()=>({async listClients(){const e=await g("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await It(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 It(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 It(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 It(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 It(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 It(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 It(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 It(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),Zv=()=>({api:(...e)=>Ae().api(...e),authenticatedAsset:(...e)=>Ae().authenticatedAsset(...e),assetWithUrlToken:(...e)=>Ae().assetWithUrlToken(...e),auth:(...e)=>Ae().auth(...e),health:(...e)=>Ae().health(...e),rawFile:(...e)=>Ae().rawFile(...e),sse:(...e)=>Ae().sse(...e),websocket:(...e)=>Ae().websocket(...e)}),eT=(e={})=>{const t=e.urls??Si();bf(t);const n=Zv();return{themeFiles:xf(),runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:jS(),git:av(),files:pv({getDirectory:()=>li.getState().currentDirectory}),settings:gv(),permissions:yv(),notifications:xv(),github:Cv({urls:n}),linear:Qv(),push:Rv(),clientAuth:Xv()}},tT=3e3,Yc=(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 mi=Promise.resolve();const LE=()=>mi,FE=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:s,relayHostId:o,relay:i}=e??nT(),a=e?null:dl(),c=o||(a?.target==="remote"?a.hostId:""),l=pl({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return kf({apiBaseUrl:t,runtimeKey:Yc(t,r)?"local":c?`host:${c}`:null}),Cl(n||null),Ol(s||null),i&&ys({apiBaseUrl:t,clientToken:n||null,requestHeaders:s||null,runtimeKey:o?`host:${o}`:null,relay:i}),ot.reconnectToRuntimeBaseUrl(),Bs(t||void 0).catch(()=>{}),r&&!Yc(t,r)&&Object.keys(Ns()).length>0&&Ul(r).catch(()=>{}),ql(),mi=i?Promise.resolve():Promise.race([nh(o||void 0).catch(()=>{}),new Promise(u=>{window.setTimeout(u,1e4)})]).then(()=>{ot.reconnectToRuntimeBaseUrl()}),mi.then(()=>{window.setTimeout(()=>{Qp().catch(()=>{})},tT)}),eT({urls:l})};export{Wk as $,wl as A,Ss as B,dT as C,ot as D,yE as E,mE as F,$S as G,$e as H,Pe as I,UT as J,Df as K,is as L,vf as M,EE as N,bE as O,_n as P,Oe as Q,Ri as R,Jl as S,nk as T,Wp as U,Lt as V,Vl as W,se as X,Dl as Y,ET as Z,AT as _,G as a,$m as a$,Xk as a0,Jw as a1,Di as a2,js as a3,Bs as a4,Ae as a5,dS as a6,Ns as a7,kg as a8,lg as a9,MT as aA,OT as aB,DT as aC,on as aD,pE as aE,gE as aF,Sk as aG,bk as aH,wk as aI,mk as aJ,hk as aK,pk as aL,fk as aM,uk as aN,lk as aO,dk as aP,yk as aQ,Pi as aR,RT as aS,CT as aT,ik as aU,ht as aV,jh as aW,aE as aX,Ef as aY,pm as aZ,xT as a_,_k as aa,hg as ab,$T as ac,PT as ad,Mk as ae,Uh as af,TE as ag,vl as ah,IT as ai,eS as aj,SE as ak,Zw as al,Hr as am,sr as an,Rm as ao,Ke as ap,Tk as aq,pf as ar,dl as as,cT as at,wE as au,Dk as av,lT as aw,uT as ax,_T as ay,mT as az,kl as b,yb as b$,_m as b0,Fm as b1,PE as b2,ti as b3,fT as b4,pT as b5,hT as b6,Lk as b7,bl as b8,Sl as b9,Wg as bA,Ua as bB,Qh as bC,Yh as bD,nm as bE,Tr as bF,ih as bG,Fy as bH,lE as bI,Zb as bJ,Kb as bK,Ob as bL,iv as bM,XS as bN,Mb as bO,Jb as bP,Yb as bQ,tv as bR,ev as bS,Cb as bT,_b as bU,Pb as bV,Nb as bW,$c as bX,gb as bY,Hb as bZ,zc as b_,mn as ba,jy as bb,Yw as bc,Ek as bd,kk as be,Nh as bf,Bh as bg,Hh as bh,uu as bi,py as bj,Pk as bk,NS as bl,Rk as bm,Ik as bn,jg as bo,ei as bp,xt as bq,iy as br,Xn as bs,ua as bt,cE as bu,co as bv,Pn as bw,K as bx,lo as by,vb as bz,FE as c,sk as c$,ME as c0,Db as c1,ob as c2,OE as c3,jb as c4,sv as c5,$b as c6,hb as c7,rb as c8,CE as c9,Xb as cA,xE as cB,RE as cC,Qb as cD,ab as cE,fb as cF,Wb as cG,cb as cH,ld as cI,ub as cJ,nv as cK,dd as cL,rv as cM,lb as cN,ud as cO,db as cP,Bb as cQ,ov as cR,Ie as cS,Ck as cT,Cm as cU,hl as cV,uE as cW,hE as cX,Rw as cY,HT as cZ,rk as c_,tb as ca,ib as cb,Ub as cc,Fb as cd,nb as ce,sb as cf,eb as cg,mb as ch,DE as ci,_E as cj,Gb as ck,Eb as cl,Hc as cm,Bc as cn,xb as co,Ib as cp,Ab as cq,zb as cr,pb as cs,Rb as ct,Vb as cu,fd as cv,Tb as cw,qb as cx,wb as cy,Lb as cz,Er as d,fE as d$,Ee as d0,Fp as d1,qp as d2,Yp as d3,Gp as d4,Ci as d5,zp as d6,ok as d7,ZT as d8,tk as d9,Jk as dA,Iu as dB,Yk as dC,tn as dD,oE as dE,iE as dF,ck as dG,io as dH,gk as dI,ak as dJ,ly as dK,Zk as dL,$i as dM,kE as dN,eE as dO,nE as dP,Ak as dQ,jk as dR,Uk as dS,Bk as dT,fg as dU,Fk as dV,Nk as dW,Hk as dX,Xt as dY,Mm as dZ,Lm as d_,ek as da,jp as db,th as dc,VT as dd,IE as de,ZS as df,US as dg,rE as dh,sE as di,Wr as dj,mo as dk,vE as dl,tE as dm,dv as dn,jT as dp,FT as dq,su as dr,xk as ds,ky as dt,Be as du,Gk as dv,Kk as dw,Qk as dx,Vk as dy,qk as dz,xn as e,dE as e0,Up as e1,Op as e2,JT as e3,YT as e4,LT as e5,Kg as e6,TT as e7,kT as e8,Ni as e9,Ok as ea,Om as eb,Dm as ec,Bi as ed,Jg as ee,Vg as ef,$g as eg,Ws as eh,gT as ei,wT as ej,bT as ek,yT as el,ST as em,vT as en,ug as eo,GT as ep,BS as eq,AE as er,BT as es,Ai as et,qT as eu,KT as ev,NT as ew,XT as ex,yt as ey,zT as f,LE as g,g as h,vr as i,WT as j,vi as k,Rt as l,QT as m,li as n,Xe as o,xp as p,qo as q,$k as r,ys as s,vk as t,T as u,Ps as v,zk as w,wt as x,og as y,br as z};