@vantran-se/openchamber-web 2.0.4 → 2.0.6

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