@vantran-se/openchamber-web 2.0.9 → 2.0.10

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 (117) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-DngoXxGT.js → CodeMirrorCommentWidgets-e9rY9Jxg.js} +1 -1
  2. package/dist/assets/{DiffView-UeB7OS2J.js → DiffView-rYnmKnFF.js} +1 -1
  3. package/dist/assets/{FilesView-Cs3Y7IF5.js → FilesView-DtzJk1Ke.js} +3 -3
  4. package/dist/assets/{GitView-DsJqHet1.js → GitView-DYd5gOSc.js} +1 -1
  5. package/dist/assets/{GuestAttachDialog-CN0FTkqY.js → GuestAttachDialog-Bsi0q3M9.js} +1 -1
  6. package/dist/assets/{GuestSurfacePane-BFbUwJOB.js → GuestSurfacePane-CYMRe3EI.js} +1 -1
  7. package/dist/assets/{JsonTreeView-B2artBdi.js → JsonTreeView-DIy-frOy.js} +1 -1
  8. package/dist/assets/{LinearIssuesView-DCcXvS3Q.js → LinearIssuesView-DDHJKaVb.js} +1 -1
  9. package/dist/assets/{MarkdownImageGallery-Du-Ph58N.js → MarkdownImageGallery-BMQ4KHaO.js} +1 -1
  10. package/dist/assets/{MarkdownRendererImpl-CnXfZsIi.js → MarkdownRendererImpl-CQi_ZSPc.js} +1 -1
  11. package/dist/assets/{OnboardingScreen-DdB_pV9d.js → OnboardingScreen-DiMFS3A7.js} +1 -1
  12. package/dist/assets/{PatchDiff-JvRN2s5u.js → PatchDiff-4jmPWx6l.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-BOIbtTSo.js → PierreDiffViewer-DKHxCmze.js} +1 -1
  14. package/dist/assets/{PlanView-DYZs8zCF.js → PlanView-CN21khuJ.js} +1 -1
  15. package/dist/assets/{PluginPane-CaHXDA-2.js → PluginPane-Dx0_Dldo.js} +1 -1
  16. package/dist/assets/{SettingsView-CfFMLncG.js → SettingsView-CBGx68I6.js} +1 -1
  17. package/dist/assets/{SettingsWindow-0vSQTxkV.js → SettingsWindow-B8RpyNyO.js} +1 -1
  18. package/dist/assets/{SubmoduleDiffSummary-DhLlAYSb.js → SubmoduleDiffSummary-hkelCkS-.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-CdV4zEAG.js → ToolOutputDialog-UbbhHm0d.js} +1 -1
  20. package/dist/assets/{ToolPartDiffPreview-XL2mZzAG.js → ToolPartDiffPreview-7FbKWkeu.js} +1 -1
  21. package/dist/assets/{VirtualizedFileDiff-ACObo6xZ.js → VirtualizedFileDiff-DapU3oMs.js} +1 -1
  22. package/dist/assets/{WalkthroughView-B-3eK3lX.js → WalkthroughView-DhvkEmfP.js} +1 -1
  23. package/dist/assets/{appThemeRegistry-CgfpF2VR.js → appThemeRegistry-CWAKiwky.js} +1 -1
  24. package/dist/assets/{ar-SA-G6X2FPQ2-ChXWTl2B.js → ar-SA-G6X2FPQ2-DswVk5Qr.js} +1 -1
  25. package/dist/assets/{az-AZ-76LH7QW2-qjuQaC-s.js → az-AZ-76LH7QW2-DjkREsRV.js} +1 -1
  26. package/dist/assets/{bg-BG-XCXSNQG7-dsvyn4OJ.js → bg-BG-XCXSNQG7-DQo0fDKV.js} +1 -1
  27. package/dist/assets/{bn-BD-2XOGV67Q-BjdT9u1P.js → bn-BD-2XOGV67Q-CzA0IjiR.js} +1 -1
  28. package/dist/assets/{ca-ES-6MX7JW3Y-BTTmpcqZ.js → ca-ES-6MX7JW3Y-L92o9vc1.js} +1 -1
  29. package/dist/assets/{commitAndPush-dBUe7z8F.js → commitAndPush-D51hG7WM.js} +1 -1
  30. package/dist/assets/{computeVirtualFileMetrics-DfI7BTln.js → computeVirtualFileMetrics-BWISD0Ee.js} +1 -1
  31. package/dist/assets/{cs-CZ-2BRQDIVT-C5rG2tZX.js → cs-CZ-2BRQDIVT-BXRAPYTK.js} +1 -1
  32. package/dist/assets/{da-DK-5WZEPLOC-BOaJLF6Z.js → da-DK-5WZEPLOC-Be9eTSFu.js} +1 -1
  33. package/dist/assets/{de-DE-XR44H4JA-Dt-4U2No.js → de-DE-XR44H4JA-D7jcygnK.js} +1 -1
  34. package/dist/assets/{de-DoDk6ixL.js → de-Dzva6tmf.js} +1 -1
  35. package/dist/assets/{el-GR-BZB4AONW-CR60bCOY.js → el-GR-BZB4AONW-DWPB-4gi.js} +1 -1
  36. package/dist/assets/{es-uuDOJL65.js → es-Be7FJA1p.js} +1 -1
  37. package/dist/assets/{es-ES-U4NZUMDT-BxBSKTXR.js → es-ES-U4NZUMDT-BteMlYd0.js} +1 -1
  38. package/dist/assets/{eu-ES-A7QVB2H4-DCoZ1mko.js → eu-ES-A7QVB2H4-D3K4uMB7.js} +1 -1
  39. package/dist/assets/{fa-IR-HGAKTJCU-CGlSV3Cv.js → fa-IR-HGAKTJCU-D7LwSGvX.js} +1 -1
  40. package/dist/assets/{fi-FI-Z5N7JZ37-DjiU77q2.js → fi-FI-Z5N7JZ37-61Yx90sI.js} +1 -1
  41. package/dist/assets/{fr-C0viImM8.js → fr-CvtTZ_7n.js} +1 -1
  42. package/dist/assets/{fr-FR-RHASNOE6-tQI46EwI.js → fr-FR-RHASNOE6-BokbdDAr.js} +1 -1
  43. package/dist/assets/{gl-ES-HMX3MZ6V-UebXQim9.js → gl-ES-HMX3MZ6V-CfKWvFjV.js} +1 -1
  44. package/dist/assets/{he-IL-6SHJWFNN-CrEAMSem.js → he-IL-6SHJWFNN-BiuDhPeJ.js} +1 -1
  45. package/dist/assets/{hi-IN-IWLTKZ5I-CDElf1It.js → hi-IN-IWLTKZ5I-CBpbpt_D.js} +1 -1
  46. package/dist/assets/{hu-HU-A5ZG7DT2-BxrPciUB.js → hu-HU-A5ZG7DT2-YdbIKZJs.js} +1 -1
  47. package/dist/assets/{id-ID-SAP4L64H-BEUMSOdC.js → id-ID-SAP4L64H-B6lOIjuX.js} +1 -1
  48. package/dist/assets/{index-BW492zXv.js → index-BvpIhpBI.js} +1 -1
  49. package/dist/assets/{index-hsqFIGlo.js → index-CxBGclAj.js} +1 -1
  50. package/dist/assets/{isDiffPlainText-BrLxBox_.js → isDiffPlainText-DU3lrpLL.js} +1 -1
  51. package/dist/assets/{isFilePlainText-Cgi_4AsZ.js → isFilePlainText-udb3VTt2.js} +1 -1
  52. package/dist/assets/{it-IT-JPQ66NNP-DU7yvppw.js → it-IT-JPQ66NNP-Bmx3ltTW.js} +1 -1
  53. package/dist/assets/{ja-B9orD75V.js → ja-BPgcBIXr.js} +1 -1
  54. package/dist/assets/{ja-JP-DBVTYXUO-3JN7QvVc.js → ja-JP-DBVTYXUO-Ble1Hn10.js} +1 -1
  55. package/dist/assets/{kaa-6HZHGXH3-ZZvAjpex.js → kaa-6HZHGXH3-DZbQ2VK_.js} +1 -1
  56. package/dist/assets/{kab-KAB-ZGHBKWFO-C4wThQdT.js → kab-KAB-ZGHBKWFO-iJv1iHzt.js} +1 -1
  57. package/dist/assets/{kk-KZ-P5N5QNE5-DtGbDE5-.js → kk-KZ-P5N5QNE5-CVPa7-_X.js} +1 -1
  58. package/dist/assets/{km-KH-HSX4SM5Z-BBzQ-auj.js → km-KH-HSX4SM5Z-CG3n2D2z.js} +1 -1
  59. package/dist/assets/{ko-DMWq9y4E.js → ko-DavkJfF9.js} +1 -1
  60. package/dist/assets/{ko-KR-MTYHY66A-DKypF9JQ.js → ko-KR-MTYHY66A-4ypCzC-G.js} +1 -1
  61. package/dist/assets/{ku-TR-6OUDTVRD-D9ejnihQ.js → ku-TR-6OUDTVRD-rnEkr74f.js} +1 -1
  62. package/dist/assets/{lt-LT-XHIRWOB4-Dqmjn0mI.js → lt-LT-XHIRWOB4-CyRnYc4K.js} +1 -1
  63. package/dist/assets/{lv-LV-5QDEKY6T-UrP5oB7q.js → lv-LV-5QDEKY6T-ZRIiC6FR.js} +1 -1
  64. package/dist/assets/{main-xwL5wKzs.js → main-CrXZnahe.js} +2 -2
  65. package/dist/assets/{main-BjJBl7Nu.js → main-xs-JggnC.js} +4 -4
  66. package/dist/assets/{markdownCore-DSFyd8zF.js → markdownCore-CUxMtJCS.js} +1 -1
  67. package/dist/assets/{miniChat-DYbqo1MM.js → miniChat-BISrLEQj.js} +2 -2
  68. package/dist/assets/{mobile-BfD16Eag.js → mobile-C5yhjorl.js} +2 -2
  69. package/dist/assets/{mr-IN-CRQNXWMA-IPWmH5Ni.js → mr-IN-CRQNXWMA-UgSO2DIH.js} +1 -1
  70. package/dist/assets/{my-MM-5M5IBNSE-BLfvJLfS.js → my-MM-5M5IBNSE-D_F1DCJR.js} +1 -1
  71. package/dist/assets/{nb-NO-T6EIAALU-DpTcOSVU.js → nb-NO-T6EIAALU-oIGhTIX7.js} +1 -1
  72. package/dist/assets/{nl-NL-IS3SIHDZ-BnEpZrEO.js → nl-NL-IS3SIHDZ-cScIrIxG.js} +1 -1
  73. package/dist/assets/{nn-NO-6E72VCQL-cguGGiOn.js → nn-NO-6E72VCQL-CjEAl_Lv.js} +1 -1
  74. package/dist/assets/{oc-FR-POXYY2M6-DZRflDPj.js → oc-FR-POXYY2M6-1rehXYxp.js} +1 -1
  75. package/dist/assets/{pa-IN-N4M65BXN-B4LAi-bY.js → pa-IN-N4M65BXN-7iWEsMEJ.js} +1 -1
  76. package/dist/assets/{patchFileDiff-DkL8Aa2N.js → patchFileDiff-DzgiH2zi.js} +1 -1
  77. package/dist/assets/{percentages-BXMCSKIN-ChsKj3Ud.js → percentages-BXMCSKIN-nJkK2U43.js} +4 -4
  78. package/dist/assets/{pl-DOQ2hiXE.js → pl-DU7WIv6_.js} +1 -1
  79. package/dist/assets/{pl-PL-T2D74RX3-DIa8_Rxw.js → pl-PL-T2D74RX3-8-4_uRcY.js} +1 -1
  80. package/dist/assets/{pt-BR-5N22H2LF-CjvHq8Nl.js → pt-BR-5N22H2LF-5f518RJn.js} +1 -1
  81. package/dist/assets/{pt-BR-GRNT4bJk.js → pt-BR-nKukDIco.js} +1 -1
  82. package/dist/assets/{pt-PT-UZXXM6DQ-De7WYkMm.js → pt-PT-UZXXM6DQ-CX60-bds.js} +1 -1
  83. package/dist/assets/{renderElectronMiniChatApp-COuZPzkA.js → renderElectronMiniChatApp-BsUuzGo8.js} +2 -2
  84. package/dist/assets/{renderMobileApp-BO162-O8.js → renderMobileApp-4lMkhU0J.js} +3 -3
  85. package/dist/assets/{ro-RO-JPDTUUEW-8cucu0w7.js → ro-RO-JPDTUUEW-WRbjlbWZ.js} +1 -1
  86. package/dist/assets/{ru-RU-B4JR7IUQ-C-EfBvoP.js → ru-RU-B4JR7IUQ-BOe15dMj.js} +1 -1
  87. package/dist/assets/{runtimeEndpointReset-B_5A-WIc.js → runtimeEndpointReset-D56xMbiw.js} +19 -19
  88. package/dist/assets/{scheduledTasksApi-MxDvG-t3.js → scheduledTasksApi-BZMS2h6Z.js} +1 -1
  89. package/dist/assets/{shikiHighlight-B39UxQvQ.js → shikiHighlight-BPUnGgQg.js} +1 -1
  90. package/dist/assets/{si-LK-N5RQ5JYF-Dtp4SfIy.js → si-LK-N5RQ5JYF-DdWuRf76.js} +1 -1
  91. package/dist/assets/{sk-SK-C5VTKIMK-C2URq6ko.js → sk-SK-C5VTKIMK-C6bkxrp7.js} +1 -1
  92. package/dist/assets/{sl-SI-NN7IZMDC-DFa24yvi.js → sl-SI-NN7IZMDC-9Kz16LlM.js} +1 -1
  93. package/dist/assets/{subset-shared.chunk-DT8U7cSF.js → subset-shared.chunk-TyCa-VC5.js} +1 -1
  94. package/dist/assets/{subset-worker.chunk-DsFk1l-v.js → subset-worker.chunk-BEUpJy0_.js} +1 -1
  95. package/dist/assets/{sv-SE-XGPEYMSR-BW357iMU.js → sv-SE-XGPEYMSR-CEKYbCUy.js} +1 -1
  96. package/dist/assets/{ta-IN-2NMHFXQM-ByJpqKo_.js → ta-IN-2NMHFXQM-lt4RexfZ.js} +1 -1
  97. package/dist/assets/{textMateThemeFromAppTheme-Dmu3ECWz.js → textMateThemeFromAppTheme-AUvSJIJn.js} +1 -1
  98. package/dist/assets/{th-TH-HPSO5L25-oBYiL2Sw.js → th-TH-HPSO5L25-BTLJeK_p.js} +1 -1
  99. package/dist/assets/{tr-CcLlZCMC.js → tr-C7G7YZuM.js} +1 -1
  100. package/dist/assets/{tr-TR-DEFEU3FU-DuccnkGw.js → tr-TR-DEFEU3FU-D1x5-N8S.js} +1 -1
  101. package/dist/assets/{uk-DeV8vTnQ.js → uk-D-OHqF3o.js} +1 -1
  102. package/dist/assets/{uk-UA-QMV73CPH-EKbyzxQM.js → uk-UA-QMV73CPH-BoCWhdiB.js} +1 -1
  103. package/dist/assets/{useAppFontEffects-Cz-1Efdn.js → useAppFontEffects-FdVEdwq7.js} +101 -101
  104. package/dist/assets/{useInlineCommentController-BFwu6eZI.js → useInlineCommentController-Bf5t_8QQ.js} +1 -1
  105. package/dist/assets/{useRootScrollLock-sHvuqb26.js → useRootScrollLock-BhAup8Zd.js} +2 -2
  106. package/dist/assets/{vendor-codemirror-language-data-CbrKiV7x.js → vendor-codemirror-language-data-CaoLP1ZV.js} +2 -2
  107. package/dist/assets/{vi-VN-M7AON7JQ-FnoyhtCt.js → vi-VN-M7AON7JQ-BNXFIbWh.js} +1 -1
  108. package/dist/assets/{web-components-CyKxJIMp.js → web-components-BKRdx0aw.js} +1 -1
  109. package/dist/assets/{zh-CN-CytFue-5.js → zh-CN-CN_mO1LM.js} +1 -1
  110. package/dist/assets/{zh-CN-LNUGB5OW-CxzUpimL.js → zh-CN-LNUGB5OW-BzAzBoiv.js} +1 -1
  111. package/dist/assets/{zh-HK-E62DVLB3-Bm2BpZIC.js → zh-HK-E62DVLB3-gszEMx80.js} +1 -1
  112. package/dist/assets/{zh-TW-B-BGC0pY.js → zh-TW-DRymoioH.js} +1 -1
  113. package/dist/assets/{zh-TW-RAJ6MFWO-NVEuq9tQ.js → zh-TW-RAJ6MFWO-jlMY0UDt.js} +1 -1
  114. package/dist/index.html +2 -2
  115. package/dist/mini-chat.html +2 -2
  116. package/dist/mobile.html +2 -2
  117. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-BHETom3P.js","assets/vendor-react-C3AD0CRp.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
- import{s as f,o as S,n as R,b as Ae,d as Zt,l as _,a as F,_ as X,u as it,r as at,t as vd,e as ge,f as ra,j as sa,c as cr,g as Yc}from"./vendor-zod-C3BVLiwa.js";import{_ as hi}from"./vendor-vite-runtime-DD1OZmLC.js";import{a as ct,d as Dn,p as wr,b as Td}from"./vendor-zustand-XNmn2Hnw.js";import{e as kd,C as Ed}from"./vendor-opencode-client-DSZl7jSi.js";import{e as mi,R as ds}from"./vendor-react-C3AD0CRp.js";const Zn=1,Pd="openchamber-relay-v1",Qc=1,Xc=12,er=1+Xc,lr=64*1024,ur=5,fs=128,Zc=0,el=1,Pn=4,Ad=1+Pn,Ro=lr-ur-Ad,$={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},Id=new Set(Object.values($)),xd=e=>Id.has(e),Qt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},yt=globalThis.crypto.subtle,tl={name:"ECDH",namedCurve:"P-256"},nl=16,Ys=32,Rd=16,Co=4,rl=8;class Dt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Cd=()=>yt.generateKey(tl,!0,["deriveBits"]),Od=async e=>{const t=await yt.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Dd=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Dt("invalid ECDH public key JWK");try{return await yt.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},tl,!0,[])}catch{throw new Dt("invalid ECDH public key JWK")}},Md=()=>{const e=new Uint8Array(nl);return globalThis.crypto.getRandomValues(e),e},_d=async(e,t,n)=>{if(n.length!==nl)throw new Dt("invalid handshake nonce length");const r=await yt.deriveBits({name:"ECDH",public:t},e,256),s=await yt.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await yt.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(Pd)},s,Ys*2*8)),i=(a,c)=>yt.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(o.slice(0,Ys),["encrypt","decrypt"]),hostToClient:await i(o.slice(Ys),["encrypt","decrypt"])}},Ld=(e,t,n)=>{for(let r=rl-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Fd=(e,t)=>{let n=0n;for(let r=0;r<rl;r+=1)n=n<<8n|BigInt(e[t+r]);return n},jd=e=>{const t=new Uint8Array(Co);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>lr)throw new Dt("plaintext frame exceeds maximum size");n+=1n;const s=new Uint8Array(Xc);s.set(t,0),Ld(s,Co,n);const o=new Uint8Array(await yt.encrypt({name:"AES-GCM",iv:s},e,r)),i=new Uint8Array(er+o.length);return i[0]=Qc,i.set(s,1),i.set(o,er),i}}},Ud=e=>{let t=0n;return{async decrypt(n){if(n.length<er+Rd)throw new Dt("encrypted frame too short");if(n[0]!==Qc)throw new Dt("unsupported encrypted frame version");const r=n.slice(1,er),s=Fd(r,Co);if(s<=t)throw new Dt("frame counter regression");let o;try{o=await yt.decrypt({name:"AES-GCM",iv:r},e,n.slice(er))}catch{throw new Dt("frame decryption failed")}return t=s,new Uint8Array(o)}}},Dr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Nd=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+=Dr[r>>2],t+=Dr[(r&3)<<4|(s??0)>>4],s!==void 0&&(t+=Dr[(s&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Dr[o&63])}return t},oa=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!==Zn)return null;const r=n.batch===!0,s=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:Zn,batch:r,flowControl:s}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:Zn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:s}:null},Bd=e=>({type:"fail",closeCode:Qt.ChannelFailure,reason:e}),Hd=async(e,t={})=>{const n=t.batch!==!1,r=await Dd(e),s=await Cd(),o=Md(),i={t:"hello",v:Zn,clientPubJwk:await Od(s.publicKey),nonce:Nd(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 oa(c)?.t==="ready"?{type:"ignore"}:Bd("plaintext frame on established channel");const l=oa(c);if(l?.t!=="ready")return{type:"ignore"};const u=await _d(s.privateKey,r,o);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:jd(u.clientToHost),decryptor:Ud(u.hostToClient)}}}}},sl=4294967295,$d=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>sl)throw new be("invalid stream id");if(n.length>Ro)throw new be("tunnel payload exceeds maximum size");const s=new Uint8Array(ur+n.length);return s[0]=r?e|fs:e,s[1]=t>>>24&255,s[2]=t>>>16&255,s[3]=t>>>8&255,s[4]=t&255,s.set(n,ur),s},zd=e=>{if(e.length<ur)throw new be("tunnel frame too short");const t=e[0],n=(t&fs)!==0,r=t&~fs;if(!xd(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(ur),hasMoreFragments:n}},Wd=new TextEncoder,Gd=new TextDecoder,Mr=e=>Wd.encode(JSON.stringify(e)),_r=(e,t)=>{let n;try{n=JSON.parse(Gd.decode(e))}catch{throw new be("malformed JSON tunnel payload")}if(!t(n))throw new be("unexpected JSON tunnel payload shape");return n},ol=(e,t=Ro)=>{if(t<=0||t>Ro)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},ia=(e,t,n)=>{const r=ol(n);return r.map((s,o)=>We(e,t,s,o<r.length-1))},qd=(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)}}},Kd=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>lr)throw new be("frame batch exceeds maximum plaintext size");return o}let t=1;for(const s of e)t+=Pn+s.length;if(t>lr)throw new be("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=el;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+=Pn,n.set(s,r),r+=s.length;return n},Vd=e=>{if(e.length<1)throw new be("empty batch plaintext");const t=e[0];if(t===Zc)return[e.slice(1)];if(t!==el)throw new be(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+Pn>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+=Pn,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},Jd=new Set([$.HttpBody,$.WsText,$.WsBinary]),il=150,Yd=24*1024,Qd=32,Xd=e=>{const t=e.windowMs??il,n=e.maxBatchBytes??Yd,r=e.maxBatchFrames??Qd,s=e.now??(()=>Date.now()),o=e.setTimer??((b,w)=>setTimeout(b,w)),i=e.clearTimer??(b=>clearTimeout(b));let a=[],c=0,l=null,u=0,d=!1;const h=()=>{l!==null&&(i(l),l=null)},m=()=>{if(h(),a.length===0)return;const b=a;a=[],c=0,u=s(),e.sendBatch(Kd(b))};return{enqueue:b=>{if(d)return;const w=b[0]&~fs;if(!Jd.has(w)){a.push(b),m();return}const k=s();if(a.length===0&&k-u>=t){a.push(b),m();return}const E=Pn+b.length;if(a.length>0&&1+c+E>lr&&m(),a.push(b),c+=E,c>=n||a.length>=r){m();return}l===null&&(l=o(m,t))},flush:m,dispose(){d=!0,h(),a=[],c=0}}},Zd=()=>{let e=1;return{next(){if(e>sl)throw new be("stream id space exhausted");const t=e;return e+=2,t}}},_s=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ef=e=>_s(e)&&Object.values(e).every(t=>typeof t=="string"),tf=e=>_s(e)&&typeof e.status=="number"&&ef(e.headers),aa=e=>_s(e)&&typeof e.reason=="string",nf=e=>_s(e)&&typeof e.code=="number"&&typeof e.reason=="string",al=/^[a-z][a-z\d+.-]*:\/\//i,gi="http://tunnel.invalid",rf=e=>{try{const t=al.test(e)?new URL(e):new URL(e,gi);return`${t.pathname}${t.search}`}catch{return e}},Lr=e=>({async*[Symbol.asyncIterator](){yield e}}),sf=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()}}}),of=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},af=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:sf(e)};if(typeof e=="string")return{body:Lr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Lr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Lr(of(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Lr(r),contentType:n}},cf=async(e,t)=>{let n;const r=new Headers;let s="GET",o=null,i;e instanceof Request?(n=e.url,s=e.method,e.headers.forEach((d,h)=>r.set(h,d)),i=e.signal,o=e.body):n=e.toString(),t&&(t.method&&(s=t.method),t.headers&&new Headers(t.headers).forEach((d,h)=>r.set(h,d)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const a=al.test(n)?new URL(n):new URL(n,gi),{body:c,contentType:l}=await af(o);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,h)=>{u[h]=d}),{method:s.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},cl="__openchamberAmbiguousTransport",Oo=e=>(Object.defineProperty(e,cl,{value:!0,enumerable:!1,configurable:!0}),e),ca=e=>!e||typeof e!="object"?!1:e[cl]===!0,lf=["local","remote",null],uf=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function ll(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"||!lf.includes(r)))return{valid:!1};if(typeof s!="string"||!uf.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 rT(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 sT(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function oT(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function ul(){if(df()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=ll(t);return n.valid?n.outcome:null}function df(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":ll(e).valid?"valid":"malformed"}const ps=/^[a-z][a-z\d+.-]*:\/\//i,ff=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},hs=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),pf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return hs(e)},hf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return hs(e)},mf=()=>Object.keys(js()).length>0,gf=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Do=(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))},yf=(e,t)=>{if(!t)return e;const n=new URLSearchParams;Do({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},la=(e,t,n)=>{if(ps.test(t)){const o=new URL(t);return Do(o,n),o.toString()}const r=ff(t);if(!e)return yf(r,n);const s=new URL(r,`${e}/`);return Do(s,n),s.toString()},Fr=(e,t=qf())=>{if(!t)return e;const n=ps.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),ps.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},dl=(e,t)=>{const n=ps.test(e)?new URL(e):new URL(e,gf(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},ua=(e,t,n)=>{if(!mf())return null;const r=hf();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=Kf(r);return o&&s.searchParams.set("oc_url_token",o),e==="ws"?(s.protocol=s.protocol==="https:"?"wss:":"ws:",dl(s.toString(),n)):s.toString()}catch{return null}},yi=(e={})=>{const t=hs(e.apiBaseUrl),n=hs(e.realtimeBaseUrl),r=()=>t||pf(),s=()=>n||r(),o=(a,c)=>la(r(),a,c),i=(a,c)=>la(s(),a,c);return{api:o,authenticatedAsset:(a,c)=>Fr(o(a,c)),assetWithUrlToken:(a,c,l)=>Fr(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=Fr(i(a,c));return ua("sse",l,e)||l},websocket:(a,c)=>{const l=dl(Fr(i(a,c)),e);return ua("ws",l,e)||l}}};let ms=yi();const Pe=()=>ms,wf=e=>{ms=e},fl=e=>(ms=yi(e),ms),Mo="openchamber:runtime-endpoint-changed",_o="openchamber:runtime-endpoint-will-change";let An="",dr="";const Qs=(e,t,n)=>{try{e[t]=n}catch{}},wi=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"}`}},Sf="mobile-disconnected",bf="url:default",pl=e=>e===""||e===bf||e===Sf,hl=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},ml=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},gl=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},In=()=>An||hl();let Xs="",da=null,fa,pa;const ha=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},G=()=>{if(dr)return dr;const e=ha("__OPENCHAMBER_API_BASE_URL__"),t=ha("__OPENCHAMBER_LOCAL_ORIGIN__");if(da===An&&fa===e&&pa===t)return Xs;const n=In();return Xs=gl(n,ml())?"local":wi(n),da=An,fa=e,pa=t,Xs},vf=(e={})=>{if(An||dr)return;const t=e.apiBaseUrl?.trim()||hl(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const s=ml(),o=s&&(!t||gl(t,s));An=t,dr=e.runtimeKey?.trim()||(o?"local":wi(t||r))},gs=e=>{const t=e.apiBaseUrl.trim(),n=In(),r=G(),s=e.runtimeKey?.trim()||wi(t),o={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:s,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(_o,{detail:o})),An=t,dr=s,typeof window<"u"){const i=window;Qs(i,"__OPENCHAMBER_API_BASE_URL__",t),Qs(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Qs(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}fl({apiBaseUrl:t,realtimeBaseUrl:t}),Cl(e.requestHeaders||null),Rl(e.clientToken||null),e.relay?Nf(e.relay):Bf(),Us(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Mo,{detail:o}))},Tf=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(_o,t),()=>window.removeEventListener(_o,t)},yl=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Mo,t),()=>window.removeEventListener(Mo,t)};let Lo=null;const iT=e=>{Lo=e},Sr=()=>Lo||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),wl=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Sl=(e=wl())=>!!e,kf=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Lt=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,rn=()=>kf()?.runtime==="electron",Ef=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},Pf="right",aT=()=>{if(!rn())return!1;const e=Ef();return e==="win32"||e==="linux"},cT=e=>e==="left"?"left":Pf,lT=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Ie=()=>typeof Lt()?.invoke=="function",Mn=()=>rn()&&Ie(),Af=()=>{if(Lt()?.pickThemeFile)return{async pick(){const e=Lt()?.pickThemeFile;return e?{status:"picked",file:S({name:f(),size:R().nonnegative(),text:f()}).nullable().parse(await e())}:{status:"unsupported"}}}},se=async(e,t)=>{const n=Lt();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},uT=async()=>{if(!Be()||!Ee())return!1;const e=In();try{const t=Ae().safeParse(await se("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===In()}catch{return!1}},dT=async()=>{if(!Mn()||!Ee())return null;try{const e=await se("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},fT=async e=>{if(!Mn()||!Ee())return null;try{const t=await se("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},pT=async()=>{if(!Mn()||!Ee())return null;try{const e=await se("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},hT=async e=>{if(!Mn()||!Ee())return null;try{const t=await se("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},mT=async()=>{if(!Mn()||!Ee())return null;try{const e=await se("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},gT=async e=>{if(!Mn()||!Ee())return null;try{const t=await se("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},ma=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}}},Zs=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}}},If=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Hn=e=>{const t=If(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=Zs(e),n=Zs(In());if(!n&&t&&ul()?.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&&Hn(t.hostname)&&Hn(n.hostname)}const r=Zs(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&&Hn(t.hostname)&&Hn(r.hostname)}const s=ma(e),o=ma(window.location.origin)||window.location.origin;return s&&o&&s===o?!0:!!(r&&Hn(r.hostname))},Be=()=>typeof window>"u"?!1:rn(),yT=async()=>{if(!Be())return!1;try{return!!await se("desktop_focus_window")}catch{return!1}},bl=()=>Be()&&Ie()&&Ee(),xf=f().min(1),wT=e=>{if(!bl())return null;try{const t=xf.safeParse(Lt()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},ST=async()=>{if(!Be())return!1;try{return await se("desktop_start_window_drag"),!0}catch{return!1}},Oe=()=>Sl()?!0:Sr()?.runtime?.isVSCode===!0,bT=()=>{const t=Sr()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Oe()},vT=(e,t=Be())=>e==="web"&&!t,vl=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},TT=async e=>{if(bl())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"}},Rf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),kT=async e=>{if(Ie()&&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(!Rf(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"}},ET=async e=>({success:!0}),PT=async e=>({success:!0}),AT=async()=>Ie()?await se("desktop_check_for_updates"):null,IT=async e=>{if(!Ie())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 se("desktop_download_and_install_update"),!0}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{if(n)try{const o=n();o instanceof Promise&&await o}catch{}}},xT=async()=>Ie()?(await se("desktop_restart"),!0):!1,RT=async()=>{if(!Ie())return!1;try{return await se("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},CT=async()=>{if(!Ie()||!Ee())return null;try{const e=await se("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},Cf=async(e,t)=>{if(!Ie()||!Ee())return!1;const n=e?.trim();if(!n)return!1;try{return await se("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},OT=async e=>{if(!Ie()||!Ee())return!1;const t=e?.trim();if(!t)return!1;try{return await se("desktop_reveal_path",{path:t}),!0}catch{return Cf(t)}},DT=async(e,t)=>{if(!Ie()||!Ee())return null;const n=e?.trim();if(!n)return null;try{const r=await se("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},MT=async(e,t,n)=>{if(!Ie()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await se("desktop_open_in_app",{projectPath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},_T=async(e,t,n)=>{if(!Ie()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await se("desktop_open_file_in_app",{filePath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},LT=async(e,t)=>{if(!Ie()||!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 se("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=r;return s.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(s.apps)?{apps:s.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:s.hasCache===!0,isCacheStale:s.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},br=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",FT=()=>{if(typeof window>"u"||!br()||Tl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Tl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Oe()?"vscode":Be()?"desktop":"web"},Of="2.0.9",jr=new Uint8Array(0),Df=new TextEncoder,Mf=new TextDecoder,$e=e=>e instanceof Error?e:new Error(String(e)),Ur=()=>new DOMException("The operation was aborted.","AbortError"),_f=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},Lf=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},ga=0,eo=1,ya=2,wa=3,Ff=new Set([Qt.AuthFailed,Qt.DuplicateClient,Qt.LimitExceeded]),jf={[Qt.AuthFailed]:"relay authentication failed",[Qt.DuplicateClient]:"relay connection replaced by another client",[Qt.LimitExceeded]:"relay connection limit reached"},Sa=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Si=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,s=e.pingTimeoutMs??15e3,o=e.batchWindowMs??il,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(x=>_f(new WebSocket(x)));let d=!1,h=null,m={state:"idle"};const y=new Set;let b=null,w=null,k=null,E=0,L=0,D=null,J=[],C=!1;const ve=x=>{if(!(m.state===x.state&&m.lastError===x.lastError)){m=x;for(const W of y)try{W(m)}catch{}}},ce=x=>{const W=J;J=[];for(const M of W)M.reject(x)},Ks=x=>{const W=J;J=[];for(const M of W)M.resolve(x)},xe=(x,W)=>{x.dead=!0;const M=Array.from(x.streams.values());x.streams.clear();for(const U of M)try{U.fail(W)}catch{}},Fn=()=>{D!==null&&(clearTimeout(D),D=null)},jn=()=>{d||D===null||Sa()||(Fn(),Qe(),Un())},jt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&jn()},N=()=>{C||typeof window>"u"||(C=!0,window.addEventListener("online",jn),typeof document<"u"&&document.addEventListener("visibilitychange",jt))},Qe=()=>{!C||typeof window>"u"||(C=!1,window.removeEventListener("online",jn),typeof document<"u"&&document.removeEventListener("visibilitychange",jt))},ln=()=>{if(d||D!==null)return;const x=Math.max(0,L-1),W=a*2**Math.min(x,10),M=Sa()?l:c,U=Math.min(M,W);N(),D=setTimeout(()=>{D=null,Qe(),Un()},U)},Rr=()=>{const x=new URL(e.relayUrl);return x.searchParams.set("v",String(Zn)),x.searchParams.set("role","client"),x.searchParams.set("serverId",e.serverId),x.searchParams.set("appId","openchamber"),x.searchParams.set("appVersion",Of),x.searchParams.set("platform",Tl()),e.grant&&x.searchParams.set("grant",e.grant),x.toString()},Un=async()=>{if(d)return;Fn(),E+=1;const x=E;ve({state:L>0?"reconnecting":"connecting",lastError:m.lastError});let W;try{W=await Hd(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(Y){if(x!==E||d)return;na(x,$e(Y),!0);return}if(x!==E||d)return;let M;try{M=u(Rr())}catch(Y){na(x,$e(Y));return}w=M;let U=!1,B=null,q=null,De=null,ye=null,H=Promise.resolve(),z=null,oe=null,lt=!1,he=!1,me=0,we=0,Se=null,ut=null,te=Date.now();const bt=()=>{Se!==null&&(clearTimeout(Se),Se=null),B!==null&&(clearInterval(B),B=null),q!==null&&(clearTimeout(q),q=null),De!==null&&(clearInterval(De),De=null),ye!==null&&(clearTimeout(ye),ye=null),ut!==null&&(ut.dispose(),ut=null)};k=bt;function V(Y,ie=!1,Z=!1){if(!(U||x!==E)){U=!0,Z&&(h=Y),bt(),z&&(b=null,xe(z,new Error(`relay tunnel reset: ${Y.message}`))),ce(Y);try{M.close()}catch{}if(w===M&&(w=null),!d){if(L+=1,Z){ve({state:"error",lastError:Y.message});return}ve({state:ie?"error":"reconnecting",lastError:Y.message}),ln()}}}const Nn=()=>{try{M.send(W.helloText)}catch{}},Or=(Y,ie,Z)=>{oe=Y,lt=ie,he=Z,B!==null&&(clearInterval(B),B=null),q!==null&&(clearTimeout(q),q=null);const le=new Map,Ut=Zd(),He=qd();let Nt=Promise.resolve();const vt=Bn=>{Nt=Nt.then(async()=>{if(Bt.dead)return;const bd=await Y.encryptor.encrypt(Bn);Bt.dead||M.send(bd)}).catch(()=>{V(new Error("relay encrypt/send failed"))})},Js=ie?Xd({windowMs:o,sendBatch:vt}):null;ut=Js;const Bt={streams:le,assembler:He,nextStreamId:()=>Ut.next(),dead:!1,send(Bn){Bt.dead||(Js?Js.enqueue(Bn):vt(Bn))}};z=Bt,b=Bt,L=0,te=Date.now(),ve({state:"connected"}),Ks(Bt),De=setInterval(()=>{Date.now()-te<r||(Bt.send(We($.Ping,0,jr)),ye===null&&(ye=setTimeout(()=>{ye=null,V(new Error("relay keepalive timeout"))},s)))},r)},un=()=>{Se!==null&&clearTimeout(Se),Se=null,!(!z||z.dead||me===we)&&(we=me,z.send(We($.DeliveryAck,0,$d(me))))},Sd=(Y,ie)=>{let Z;try{Z=zd(ie)}catch(He){V($e(He));return}if(Z.frameType===$.DeliveryAck){V(new Error("unexpected downstream delivery acknowledgement"));return}if(he&&Z.streamId!==0&&(me+=ie.length,Se===null&&(Se=setTimeout(un,10))),te=Date.now(),ye!==null&&(clearTimeout(ye),ye=null),Z.frameType===$.Ping){Y.send(We($.Pong,Z.streamId,jr));return}if(Z.frameType===$.Pong)return;let le=Z.payload;if(Z.frameType===$.WsText||Z.frameType===$.WsBinary){let He;try{He=Y.assembler.push(Z)}catch(Nt){V($e(Nt));return}if(He===null)return;le=He}else if(Z.hasMoreFragments){V(new Error("unexpected fragmented tunnel frame"));return}const Ut=Y.streams.get(Z.streamId);Ut&&Ut.handleFrame(Z.frameType,le)};M.onopen=()=>{U||x!==E||(Nn(),B=setInterval(Nn,t))},M.onmessage=Y=>{if(U||x!==E)return;const ie=Y.data;if(typeof ie=="string"){H=H.then(async()=>{if(U||x!==E)return;const le=await W.handleText(ie);if(le.type==="established"){if(oe)return;Or(le.channel,le.batch,le.flowControl)}else le.type==="fail"&&V(new Error(`relay handshake failed: ${le.reason}`))}).catch(le=>{V($e(le))});return}const Z=ie instanceof ArrayBuffer?new Uint8Array(ie):ie instanceof Uint8Array?ie:null;Z&&(H=H.then(async()=>{if(U||x!==E)return;const le=z,Ut=oe;if(!le||!Ut){V(new Error("encrypted frame before handshake completed"));return}let He;try{He=await Ut.decryptor.decrypt(Z)}catch(vt){V($e(vt));return}let Nt;try{Nt=lt?Vd(He):[He]}catch(vt){V($e(vt));return}for(const vt of Nt){if(U||x!==E||le.dead)return;Sd(le,vt)}he&&me-we>=16*1024&&un()}).catch(le=>{V($e(le))}))},M.onclose=Y=>{const ie=Ff.has(Y.code);V(new Error(jf[Y.code]??`relay socket closed (code ${Y.code})`),ie,ie)},M.onerror=()=>{},q=setTimeout(()=>{q=null,V(new Error("relay handshake timeout"),!0)},n);function na(Y,ie,Z=!1){Y!==E||d||(ce(ie),L+=1,ve({state:Z?"error":"reconnecting",lastError:ie.message}),ln())}},Cr=x=>d?Promise.reject(new Error("relay tunnel closed")):x?.aborted?Promise.reject(Ur()):h?Promise.reject(h):b&&!b.dead?Promise.resolve(b):new Promise((W,M)=>{let U=null;const B={resolve(q){U&&x&&x.removeEventListener("abort",U),W(q)},reject(q){U&&x&&x.removeEventListener("abort",U),M(q)}};x&&(U=()=>{J=J.filter(q=>q!==B),M(Ur())},x.addEventListener("abort",U,{once:!0})),J.push(B)}),St=async(x,W)=>{const M=await cf(x,W),U=M.signal;if(U?.aborted)throw Ur();const B=await Cr(U),q=B.nextStreamId();return await new Promise((De,ye)=>{let H=!1,z=!1,oe=null,lt=null;const he=()=>{B.streams.delete(q),B.assembler.dropStream(q),lt&&U&&U.removeEventListener("abort",lt)},me=te=>{if(!z){if(z=!0,he(),!H){ye(te);return}try{oe?.error(te)}catch{}}},we=te=>{B.dead||B.send(We($.StreamAbort,q,Mr({reason:te})))},Se=te=>Oo(new Error(te));lt=()=>{we("aborted"),me(Ur())},B.streams.set(q,{handleFrame(te,bt){if(te===$.HttpResponse){if(H||z)return;let V;try{V=_r(bt,tf)}catch(un){we("malformed response head"),me(Se($e(un).message));return}const Nn=V.status===204||V.status===205||V.status===304;let Or=null;Nn||(Or=new ReadableStream({start(un){oe=un},cancel(){z||(z=!0,he(),we("response body cancelled"))}})),H=!0,De(new Response(Or,{status:V.status,headers:V.headers})),Nn&&(z=!0,he());return}if(te===$.HttpBody){if(!H||z)return;try{oe?.enqueue(bt)}catch{}return}if(te===$.StreamEnd){if(z)return;if(!H){me(Se("tunnel stream ended before response head"));return}z=!0,he();try{oe?.close()}catch{}return}if(te===$.StreamAbort){let V="stream aborted by host";try{V=_r(bt,aa).reason}catch{}me(Se(V))}},fail(te){me(Se(te.message))}}),U&&U.addEventListener("abort",lt,{once:!0});const ut={method:M.method,path:M.path,query:M.query,headers:M.headers,hasBody:M.body!==null};B.send(We($.HttpRequest,q,Mr(ut))),(async()=>{try{let te=!1;if(M.body)for await(const bt of M.body){if(z||B.dead)return;for(const V of ol(bt))B.send(We($.HttpBody,q,V)),te=!0}!z&&!B.dead&&(M.body&&!te&&B.send(We($.HttpBody,q,jr)),B.send(We($.StreamEnd,q,jr)))}catch(te){we("request body failed"),me(Se($e(te).message))}})()})},Vs=x=>{const W=x.indexOf("?");return W===-1?{path:x,query:""}:{path:x.slice(0,W),query:x.slice(W+1)}},yd=(x,W)=>{let M=ga,U=null,B=0,q=!1;const De={get readyState(){return M},onopen:null,onmessage:null,onerror:null,onclose:null,send(H){if(M!==eo||!U||U.dead)throw new Error("relay tunnel socket is not open");if(typeof H=="string"){for(const oe of ia($.WsText,B,Df.encode(H)))U.send(oe);return}const z=H instanceof ArrayBuffer?new Uint8Array(H.slice(0)):(()=>{const oe=new Uint8Array(H.byteLength);return oe.set(new Uint8Array(H.buffer,H.byteOffset,H.byteLength)),oe})();for(const oe of ia($.WsBinary,B,z))U.send(oe)},close(H=1e3,z=""){M===wa||M===ya||(M===eo&&U&&!U.dead&&(M=ya,U.send(We($.WsClose,B,Mr({code:H,reason:z})))),ye(H,z))}},ye=(H,z,oe=!1)=>{if(!q){if(q=!0,U&&(U.streams.delete(B),U.assembler.dropStream(B)),M=wa,oe)try{De.onerror?.()}catch{}try{De.onclose?.({code:H,reason:z})}catch{}}};return(async()=>{let H;try{H=await Cr()}catch(he){ye(1006,$e(he).message,!0);return}if(q)return;U=H,B=H.nextStreamId(),H.streams.set(B,{handleFrame(he,me){if(he===$.WsOpened){if(M===ga){M=eo;try{De.onopen?.()}catch{}}return}if(he===$.WsText){try{De.onmessage?.({data:Mf.decode(me)})}catch{}return}if(he===$.WsBinary){const we=new ArrayBuffer(me.byteLength);new Uint8Array(we).set(me);try{De.onmessage?.({data:we})}catch{}return}if(he===$.WsClose){let we=1e3,Se="";try{const ut=_r(me,nf);we=ut.code,Se=ut.reason}catch{}ye(we,Se);return}if(he===$.StreamAbort){let we="stream aborted";try{we=_r(me,aa).reason}catch{}ye(1006,we,!0)}},fail(he){ye(1012,he.message,!0)}});const{path:z,query:oe}=Vs(x),lt=W&&W.length>0?{path:z,query:oe,protocols:W}:{path:z,query:oe};H.send(We($.WsOpen,B,Mr(lt)))})(),De},wd=()=>{if(d)return;d=!0,E+=1,Fn(),Qe(),k?.(),k=null;const x=b;b=null;const W=new Error("relay tunnel closed");x&&xe(x,W),ce(W);try{w?.close()}catch{}w=null,ve({state:"idle"})};return Un(),{fetch:St,openWebSocket:yd,getStatus:()=>m,subscribeStatus(x){return y.add(x),()=>{y.delete(x)}},close:wd}};let Le=null,wt=null;const Uf=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Ls=()=>Le,jT=()=>!Le||!wt?null:{relayUrl:wt.relayUrl,serverId:wt.serverId,hostEncPubJwk:{...wt.hostEncPubJwk}},UT=()=>Le!==null,Nf=e=>(Le&&wt&&Uf(wt,e)||(Le?.close(),wt=e,Le=Si(e)),Le),NT=(e,t)=>{Le!==t&&(Le?.close(),wt=e,Le=t)},Bf=()=>{Le?.close(),Le=null,wt=null};let kl=()=>null,El="",ys={},en="",fr=0,Kt=null,Tn="",pr=0,tn="",Vt=null,Rt="",rs=0,ss=0;const bi=1e4,Hf=e=>e.toLowerCase()==="authorization",Pl=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const s=n.trim(),o=r.trim();s&&o&&!Hf(s)&&(t[s]=o)}return t},$f=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,s])=>t[r]===s)},Fs=e=>typeof e!="string"?"":e.trim(),zf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Fs(e)},Wf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Al=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():Wf();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},vi=e=>{try{return new URL(e).origin}catch{return""}},Il=()=>{Tn="",pr=0,tn="",Vt=null,Rt="",rs+=1},vr=()=>{en="",fr=0,Il()},xl=()=>{ss+=1,Kt=null,vr(),Ti()},Rl=e=>{const t=Fs(e);El=t,xl(),kl=()=>t?{type:"bearer",token:t}:null},Cl=e=>{const t=Pl(e);$f(ys,t)||(ys=t,xl())},js=()=>{if(Object.keys(ys).length>0)return ys;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Pl(e):{}},Ol=()=>El||zf(),Gf=(e,t)=>{const n=Fs(e);if(!n||typeof t!="number"||!Number.isFinite(t)){vr();return}const r=en;en=n,fr=t,r&&r!==n&&Qf()},Dl=()=>!en||fr<=Date.now()+bi?(vr(),""):en,Ml=e=>{const t=vi(e);return!t||tn!==t?"":!Tn||pr<=Date.now()+bi?(Tn="",pr=0,tn="",""):Tn},qf=()=>{const e=Dl();return!e&&(Ol()||typeof window<"u")&&Us().catch(()=>{}),e},Kf=e=>{const t=e?Ml(e):"";return!t&&e&&typeof window<"u"&&jl(e).catch(()=>{}),t},_l=async()=>{const e=await kl(),t=e?.type==="bearer"?Fs(e.token):Ol();return t?{type:"bearer",token:t}:null},Vf=S({token:f(),expiresAt:R()}),Ll=async(e,t)=>{const n=await _l(),r=new Headers;for(const[c,l]of Object.entries(js()))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=Ls(),i=o?await o.fetch(s,{method:"POST",headers:r}):await fetch(Al(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=Vf.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},BT=async e=>{const t=await Ll(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Fl=e=>{if(Kt)return Kt;const t=ss,r=(async()=>{let s;try{s=await Ll(e)}catch(o){throw t===ss&&vr(),o}if(t!==ss)throw new Error("Runtime URL auth token response is stale");if(Gf(s.token,s.expiresAt),!en)throw new Error("Runtime URL auth token response was invalid");return en})().finally(()=>{Kt===r&&(Kt=null)});return Kt=r,Kt},Jf=e=>{const t=vi(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Vt&&Rt===t)return Vt;const n=rs,s=(async()=>{const o=await fetch(Al(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw n===rs&&t===Rt&&(Tn="",pr=0,tn=""),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!==rs||t!==Rt)throw new Error("Local runtime URL auth token response is stale");return Tn=a,pr=c,tn=t,a})().finally(()=>{Vt===s&&(Vt=null,Rt="")});return Vt=s,Rt=t,Vt},Us=async e=>{const t=Dl();return t||Fl(e)},jl=async e=>{const t=vi(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=Ml(t);return n||((tn&&tn!==t||Rt&&Rt!==t)&&Il(),Jf(t))};let Sn=0,tr=null,Ul=null;const Fo=new Set,Yf=5e3,Qf=()=>{for(const e of Fo)try{e()}catch{}},Nl=()=>{tr!==null&&(clearTimeout(tr),tr=null)},Ti=()=>{if(Nl(),Sn<=0||typeof window>"u")return;const e=fr-bi-Yf,t=fr>0?Math.max(0,e-Date.now()):0;tr=setTimeout(()=>{tr=null,!(Sn<=0)&&Fl(Ul).catch(()=>{}).finally(()=>{Ti()})},t)},HT=e=>{typeof e=="string"&&e.trim()&&(Ul=e.trim()),Sn+=1,Ti();let t=!1;return()=>{t||(t=!0,Sn=Math.max(0,Sn-1),Sn===0&&Nl())}},$T=e=>(Fo.add(e),()=>{Fo.delete(e)}),Xf=async e=>{const t=new Headers(e);for(const[r,s]of Object.entries(js()))t.has(r)||t.set(r,s);if(t.has("Authorization"))return t;const n=await _l();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},ws=ct(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Zf=15e3,ep=5*6e4;let jo=0,to=!1;const tp=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),np=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!tp(t)},Bl=async()=>{if(!to){to=!0;try{const{runtimeFetch:e}=await hi(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>Sp);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){ws.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=ws.getState();n==="expired"&&r()}}catch{}finally{to=!1}}},rp=(e,t)=>{if(t!==401||ws.getState().state==="expired"||!np(e))return;const n=Date.now();n-jo<Zf||(jo=n,Bl())};let ba=!1;const zT=()=>{if(ba)return;ba=!0;let e=Date.now();const t=()=>{if(ws.getState().state!=="ok")return;const n=Date.now();n-e<ep||(e=n,jo=n,Bl())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},sp=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,va="/api/",Hl="/api/spaces/",ki=e=>{if(!e)return null;const t=sp.exec(e);return t?t[1]:null},Ta=e=>ki(e)!==null,op=e=>e.startsWith(Hl),ip=()=>Sl()||Sr()?.runtime?.isVSCode===!0,Ei=(e,t)=>{if(ip())return e;const n=ki(t);return n===null||!e.startsWith(va)||op(e)?e:`${Hl}${n}/${e.slice(va.length)}`},nn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",ap=()=>typeof window>"u"?"":window.location.origin||"",Ns=e=>{if(typeof window>"u")return!1;const t=ap();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}},Bs=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),cp=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),It=(e,t)=>{try{cp(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},Pi=(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))},$l=e=>{if(!e)return null;try{return decodeURIComponent(e)}catch{return e}},ka=e=>{const t=new URLSearchParams(e);return $l(t.get("directory")??t.get("location[directory]"))},Ea=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 $l(r);return null},lp=e=>{if(!Bs(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!Ns(t)&&!nr(t)?null:{path:t.pathname,rest:`${t.search}${t.hash}`,origin:t.origin}}catch{return null}},up=(e,t)=>{const n=e instanceof Request?e.url:e.toString(),r=lp(n);if(!r||!r.path.startsWith("/api/"))return e;const s=t.directory??ka(r.rest)??(t.query?ka(new URLSearchParams(t.query instanceof URLSearchParams?t.query:Object.entries(t.query).flatMap(([a,c])=>c==null?[]:[[a,String(c)]])).toString()):null)??Ea(t.headers)??(e instanceof Request?Ea(e.headers):null),o=Ei(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},nr=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:nn(e.pathname)}catch{return!1}},no=e=>{if(nn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return Ns(t)&&nn(t.pathname)}catch{return!1}},dp=(e,t)=>{try{const n=new URL(e);if(!Ns(n))return e;const r=_t(`${n.pathname}${n.search}`,t);return!Bs(r)&&(n.protocol==="http:"||n.protocol==="https:")?(Pi(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},_t=(e,t)=>e==="/health"?Pe().health(t):e.startsWith("/auth/")||e==="/auth"?Pe().auth(e,t):nn(e)?Pe().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?dp(e,t):e,fp=e=>{const t=e instanceof Request?e.url:e.toString();if(!Bs(t))return nn(t);try{return nr(new URL(t))}catch{return!1}},zl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},pp=(e,t)=>!zl(t),Uo=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)pp(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},dt=async(e,t,n=!0)=>{const r=new Headers(Uo(e)??e);return t&&new Headers(Uo(t)??t).forEach((s,o)=>r.set(o,s)),n?Xf(r):r},hp=(e,t)=>{if(!t)return e;const n=new URL(e,gi);return Pi(n,t),`${n.pathname}${n.search}`},Wl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!Bs(n))return nn(n)?hp(n,t):null;try{const r=new URL(n);return!Ns(r)||!nn(r.pathname)?null:(Pi(r,t),`${r.pathname}${r.search}`)}catch{return null}},mp=async(e,t,n)=>{const r=Ls();if(!r)return null;const s=Wl(e,n);if(s===null)return null;const o=e instanceof Request?e.headers:void 0,i=await dt(o,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(s,{...t,headers:i})},gp=(e,t)=>{if(typeof e=="string")return _t(e,t);if(e instanceof URL)return _t(e.toString(),t);const n=_t(e.url,t);return n===e.url?e:new Request(n,e)},yp=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Nr=new Map,wp=(e,t,n,r)=>n||e!=="GET"||t.includes("/event")||!yp.test(t)?null:`GET ${t}\0${r.get("x-opencode-directory")??""}`,g=async(e,t={})=>{const n=up(e,t),{query:r,directory:s,...o}=t,i=Ls(),a=i?Wl(n,r):null;let c,l,u,d;if(i&&a!==null){const k=n instanceof Request?n.headers:void 0,E=await dt(k,o.headers,!0);c=n instanceof Request?()=>i.fetch(n,{...o,headers:E}):()=>i.fetch(a,{...o,headers:E}),d=E,l=a,u=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase()}else{const k=gp(n,r),E=k instanceof Request?k.headers:void 0,L=await dt(E,o.headers,fp(k)),D=k instanceof Request?k.url:k instanceof URL?k.toString():String(k);It(D,L),c=k instanceof Request?()=>fetch(new Request(k,{...o,headers:L})):()=>fetch(k,{...o,headers:L}),d=L,l=D,u=String(o.method??(k instanceof Request?k.method:"GET")).toUpperCase()}const h=c;c=()=>h().then(k=>(rp(l,k.status),k));const m=o.signal!=null||n instanceof Request,y=wp(u,l,m,d);if(!y)return c();const b=Nr.get(y);if(b)return b.then(k=>k.clone());const w=c();return Nr.set(y,w),w.then(()=>Nr.delete(y),()=>Nr.delete(y)),w.then(k=>k.clone())};let Pa=!1;const Gl=()=>{if(Pa||typeof window>"u")return;Pa=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await mp(t,n??{});if(r)return r;if(typeof t=="string"){if(!no(t)){try{const i=new URL(t);if(nr(i)){const a=await dt(void 0,n?.headers);return It(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const s=await dt(void 0,n?.headers),o=_t(t);return It(o,s),e(o,{...n,headers:s})}if(t instanceof URL){const s=t.toString();if(!no(s)){if(nr(t)){const a=await dt(void 0,n?.headers);return It(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const o=await dt(void 0,n?.headers),i=_t(s);return It(i,o),e(i,{...n,headers:o})}if(t instanceof Request){if(!no(t.url)){try{const a=new URL(t.url);if(nr(a)){const c=await dt(t.headers,n?.headers);return It(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const s=await dt(t.headers,n?.headers),o=_t(t.url);It(o,s);const i=o===t.url?t:new Request(o,t);return e(new Request(i,{...n,headers:s}))}return e(t,n)}},Sp=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:It,buildRuntimeFetchUrl:_t,installRuntimeFetchBridge:Gl,isLatin1Safe:zl,runtimeFetch:g,sanitizeHeadersForBrowser:Uo},Symbol.toStringTag,{value:"Module"})),kn=16384,Ss=globalThis,bp=e=>{if(Ss.Buffer)return Ss.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,"")},ql=e=>{try{if(Ss.Buffer)return Ss.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}},vp=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}},Tp=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}},Aa=e=>typeof e=="string"&&e.length>0,kp=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Aa(t.x)||!Aa(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Ep=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pp=e=>{if(!e||typeof e!="object")return null;const t=e,n=Ep(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=vp(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=Tp(t.relayUrl);if(!r)return null;const s=typeof t.serverId=="string"?t.serverId.trim():"";if(!s)return null;const o=kp(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},Ai=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}},WT=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}),GT=e=>{const t=Ai(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",bp(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},Ap=e=>{const t=e.trim();if(!t||t.length>kn)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>kn)return null;const s=ql(r);return!s||s.length>kn?null:Ai(JSON.parse(s))}catch{return null}},qT=e=>{const t=e.trim();if(!t||t.length>kn)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>kn)return null;const o=ql(s);if(!o||o.length>kn)return null;try{return Ai(JSON.parse(o))}catch{return null}},xn=e=>typeof e=="object"&&e!==null,Ip=e=>e.trim().toLowerCase()==="authorization",xp=e=>{if(!xn(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)||Ip(s)||(t[s]=o)}return Object.keys(t).length>0?t:void 0},Rp=e=>`relay://${e}`,Cp=e=>{if(!xn(e))return null;const t=Te(e,"relayUrl")||Te(e,"relay_url"),n=Te(e,"serverId")||Te(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!xn(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Op=()=>{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"},KT=async(e,t)=>{const n=Ap(e);if(!n)throw new Error("invalid-connect-link");const r=await Fp().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:Op(),...r?{dedupeKey:`desktop:${r}`}:{}})},o=async w=>{if(!w.ok)return null;const k=await w.json().catch(()=>null);return(typeof k?.clientToken=="string"?k.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((w,k)=>(w.type==="relay"?1:0)-(k.type==="relay"?1:0));for(const w of a){if(w.type==="relay"){const E=Si({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const L=await o(await E.fetch("/api/client-auth/pairing/redeem",s));if(L){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:L};break}}catch{}finally{E.close()}continue}const k=ke(w.url);if(k)try{const E=await o(await fetch(`${k}/api/client-auth/pairing/redeem`,s));if(E){i={directUrl:k,token:E};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(w=>w.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),u=n.candidates.filter(w=>w.type!=="relay").map(w=>ke(w.url)).find(w=>!!w),d=i.directUrl||u,h=d||(l?Rp(l.serverId):null);if(!h)throw new Error("pairing-missing-transport");const m=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&ke(w.apiUrl||w.url)===h),y=m?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),b={...m||{},id:y,label:n.label||m?.label||Kl(h),url:h,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:y,hosts:m?t.map(w=>w.id===y?b:w):[b,...t]}},Dp=/^(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}},VT=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"}},Kl=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)Dp.test(s)&&n.searchParams.set(s,"[REDACTED]");return n.toString()}catch{return t}},Br=(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}},Te=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},Ia=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},Mp=e=>{if(!xn(e))return null;const t=Te(e,"id"),n=Te(e,"label"),r=Te(e,"url"),s=Te(e,"apiUrl")||Te(e,"api_url"),o=Te(e,"clientToken")||Te(e,"client_token"),i=xp(e.requestHeaders),a=Cp(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}:{}}},rr=e=>ke(e.apiUrl||e.url)||e.apiUrl||e.url,sn=()=>Ie()?(e,t)=>se(e,t):null,Ii=async()=>{const e=sn();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!xn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(Mp).filter(a=>!!a):[],s=Te(t,"defaultHostId")||Te(t,"default_host_id")||Te(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=Te(t,"localOrigin")||Te(t,"local_origin");return{hosts:r,defaultHostId:s,initialHostChoiceCompleted:o,localOrigin:i}},_p=async e=>{const t=sn();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})},Lp=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Fp=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},jp=8e3,Up=15e3,Np=400,Bp=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)}},xa=async(e,t,n,r)=>{for(;;){const s=n-Date.now();if(s<=0)throw new Error("relay probe deadline exceeded");try{return await Bp(e,t,Math.min(jp,s),r)}catch(o){if(e.getStatus().state==="error"||Date.now()>=n)throw o;await new Promise(i=>window.setTimeout(i,Np))}}},Hp=async(e,t)=>{const n=Si({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),s=r+Up;let o=!1;try{if(!(await xa(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 xa(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()}},xi=async(e,t)=>{const n=sn();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(!xn(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=Ia(r,"latencyMs")??Ia(r,"latency_ms")??0;return{status:o,latencyMs:i}},JT=async(e,t)=>{const n=sn();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},YT=async e=>{const t=sn();t&&await t("desktop_new_window_for_host",{hostId:e})},Mt="local",$p=e=>({id:Mt,label:"Local",url:e||Vl()}),Vl=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,zp=e=>e.id===Mt?"local":`host:${e.id}`,QT=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Mt)?.url||Vl(),r=In(),s=ke(n)||n,o=ke(t)||t,i=G(),a=e.find(u=>u.relay&&zp(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Br(r,n))return{id:Mt,label:"Local",url:s};const c=e.find(u=>r?Br(r,rr(u)):!1);if(c)return{id:c.id,label:c.label,url:ke(rr(c))||rr(c)};if(t&&Br(t,n))return{id:Mt,label:"Local",url:s};const l=e.find(u=>t?Br(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:Kl(o||"Instance"),url:o}},bs=new Map;let Jl=0;const vs=new Map;let No=0,Yl={byHostId:{},isProbing:!1};const Bo=new Set,Ts=()=>{Yl={byHostId:Object.fromEntries(bs),isProbing:No>0};for(const e of Bo)try{e()}catch{}},XT=e=>(Bo.add(e),()=>{Bo.delete(e)}),ZT=()=>Yl,Ql=(e,t)=>{bs.set(e,t),Ts()},ek=(e,t)=>{vs.set(e,++Jl),Ql(e,t)},Wp=e=>{const t=new Set([Mt,...e]);let n=!1;for(const r of Array.from(bs.keys()))t.has(r)||(bs.delete(r),vs.delete(r),n=!0);n&&Ts()},Gp=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",qp=async()=>rn()?Lp().catch(()=>""):"",Kp=async(e,t)=>{const n=e.id===Mt?t:e.clientToken||"",r=async()=>{const i=await Hp(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(rn()?rr(e):e.url);if(!s)return{status:"unreachable",latencyMs:0};const o=await xi(s,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Gp(o.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:o.status,latencyMs:o.latencyMs}},Vp=async e=>{if(!Be())return;const t=++Jl;for(const n of e)vs.set(n.id,t);No+=1,Ts();try{const n=await qp();await Promise.all(e.map(async r=>{const s=await Kp(r,n);vs.get(r.id)===t&&Ql(r.id,s)}))}finally{No-=1,Ts()}};let Ra=!1;const Jp=async()=>{if(Ra||!Be())return;Ra=!0;const e=await Ii().catch(()=>null);e&&(Wp(e.hosts.map(t=>t.id)),await Vp([$p(e.localOrigin),...e.hosts]))},Yp=5e3,Qp=1500;let ro=!1;const Xp=async e=>{if(!rn()||ro)return;const t=`host:${e}`;if(G()===t){ro=!0;try{const n=await Ii().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 h=d;if(h.type!=="lan"||typeof h.url!="string")continue;const m=ke(h.url);m&&!c.includes(m)&&c.push(m)}if(c.length===0)return;const l=s&&c.includes(s)?s:c[0];l!==s&&await _p({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await xi(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;gs({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{ro=!1}}},Zp=e=>{typeof window>"u"||window.setTimeout(()=>{Xp(e).catch(()=>{})},Yp)},eh=async e=>{if(!rn())return;const t=await Ii().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=>{gs({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:s})},i=()=>{gs({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:s,relay:r.relay??void 0}),Zp(r.id)},a=r.apiUrl?ke(rr(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=xi(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),Qp))]);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 tk=e=>e instanceof Xt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),ks=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},on="/api/openchamber/spaces",Tr=f().regex(/^[0-9a-f]{12}$/),Hs=S({code:f(),message:f()});class so extends Error{code;status;constructor(t,n,r){super(n),this.name="SpacesRequestError",this.code=t,this.status=r}}const th=S({id:Tr,name:f(),state:f()});Zt("enabled",[S({enabled:_(!1)}),S({enabled:_(!0),spaces:F(th).nullable(),failure:Hs.optional()})]);const nh=S({id:Tr,name:f(),code:f(),message:f()});S({enabled:Ae(),stopped:F(S({id:Tr,name:f()})),stillRunning:F(nh),unknown:Hs.optional()});const Xl=S({mode:X(["allowlist","open"]),domains:F(f())}),Zl=Zt("kind",[S({kind:_("model"),id:f(),provider:f(),upstream:f(),source:Zt("kind",[S({kind:_("typed")}),S({kind:_("env"),name:f()})]),url:f()}),S({kind:_("domain"),id:f(),upstream:f(),url:f()})]),rh=["checking_place","creating","setting_network","bringing_code","ready"],sh=X(rh),eu=S({id:Tr,name:f(),projectDirectory:f().nullable(),directory:f().nullable(),state:X(["preparing","running","exited","missing","failed"]),step:sh.nullable(),failure:Hs.nullable(),network:Xl.nullable(),grants:F(Zl),access:X(["granted","needs_access","unknown"]).nullable(),needsAccess:F(f())}),oh=it([S({id:f(),available:_(!0),hostIsolation:Ae()}),S({id:f(),available:_(!1),code:f(),message:f()})]),ih=S({code:f(),message:f()}),an=async(e,t,n={})=>{const r=await g(e,{...n,headers:n.body===void 0?n.headers:{"Content-Type":"application/json",...n.headers}}),s=await r.json().catch(()=>null);if(!r.ok){const i=ih.safeParse(s);throw i.success?new so(i.data.code,i.data.message,r.status):new so("space_request_failed",`The server answered ${r.status}.`,r.status)}const o=t.safeParse(s);if(!o.success)throw new so("space_answer_malformed","The server answered in a shape this version does not know.",r.status);return o.data},nk=async e=>(await an(`${on}/places`,S({places:F(oh)}),{signal:e})).places,ah=async e=>(await an(on,S({spaces:F(eu)}),{signal:e})).spaces,rk=e=>an(on,eu,{method:"POST",body:JSON.stringify(e)}),sk=async(e,t)=>(await an(`${on}/${e}/grants`,S({grant:Zl}),{method:"POST",body:JSON.stringify(t)})).grant,ok=async(e,t)=>(await an(`${on}/${e}/network/domains`,S({network:Xl}),{method:"POST",body:JSON.stringify({domain:t})})).network,ch=S({at:f(),listener:f(),host:f(),port:R(),decision:f()}),lh=S({records:F(ch),dropped:R(),since:f()}),ik=(e,t)=>an(`${on}/${e}/journal`,lh,{signal:t}),uh=S({id:Tr,removed:Ae(),failures:F(Hs)}),ak=e=>an(`${on}/${e}`,uh,{method:"DELETE"}),dh=S({id:f().regex(/^[0-9a-f]{12}$/),name:f().default(""),state:X(["complete","partial","stale","unknown"]),projectDirectory:f().nullable().default(null),directory:f().nullable().default(null)}),Ca=new Map,$n=new Map,fh=(e,t)=>t.step==="failed"?{...e,state:"failed",failure:t.failure}:{...e,state:t.step==="ready"?"running":"preparing",step:t.step==="ready"?null:t.step,failure:null},Oa=(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},Es=ct((e,t)=>({spaces:Ca,journey:null,progressRevision:0,applyJourney:(n,r)=>e(s=>{const o=new Map(n.map(i=>[i.id,i]));for(const[i,a]of $n){const c=s.journey?.get(i);a>r&&c&&o.set(i,c)}return{journey:o}}),addJourneyEntry:n=>e(r=>{const s=r.progressRevision+1;$n.set(n.id,s);const o=new Map(r.journey??[]);return o.set(n.id,n),{journey:o,progressRevision:s}}),creationAccess:new Map,noteCreationAccess:(n,r)=>e(s=>{const o=new Map(s.creationAccess);return r?o.set(n,r):o.delete(n),{creationAccess:o}}),noteProviderGranted:(n,r)=>e(s=>{const o=s.creationAccess.get(n);if(o?.kind!=="failed")return s;const i=o.failures.filter(c=>c.provider!==r),a=new Map(s.creationAccess);return i.length>0?a.set(n,{kind:"failed",failures:i}):a.delete(n),{creationAccess:a}}),noteGrantGiven:(n,r)=>e(s=>{const o=s.journey?.get(n);if(!o)return s;const i=s.progressRevision+1;$n.set(n,i);const a=new Map(s.journey);return a.set(n,{...o,grants:[...o.grants.filter(c=>c.id!==r.id),r],needsAccess:o.needsAccess.filter(c=>c!==r.id)}),{journey:a,progressRevision:i}}),accessDialog:null,openAccessDialog:(n,r=null)=>e({accessDialog:{spaceId:n,providerId:r}}),closeAccessDialog:()=>e({accessDialog:null}),noteProgress:n=>{const r=t().progressRevision+1;$n.set(n.spaceId,r);const s=t().journey?.get(n.spaceId);if(!s)return e({progressRevision:r}),!1;const o=new Map(t().journey);return o.set(n.spaceId,fh(s,n)),e({journey:o,progressRevision:r}),!0},applyMarks:n=>e(r=>{const s=new Map(n.map(o=>[o.id,o]));return s.size===0&&r.spaces.size===0?r:{spaces:s}}),noteStream:(n,r)=>e(s=>r==="connected"?s:{spaces:Oa(s.spaces,n,"stale")}),noteReachable:n=>e(r=>({spaces:Oa(r.spaces,n,"complete")})),resetForRuntimeSwitch:()=>{$n.clear(),Ho+=1,e({spaces:Ca,journey:null,progressRevision:0,creationAccess:new Map,accessDialog:null})},forgetForSwitchOff:()=>t().resetForRuntimeSwitch()}));let Ho=0;const ck=async()=>{const e=Ho,t=Es.getState().progressRevision,n=await ah();e===Ho&&Es.getState().applyJourney(n,t)},ph=(e,t)=>{const n=Array.from(e.values());for(const r of t?.values()??[])e.has(r.id)||r.projectDirectory===null||r.directory===null||n.push({id:r.id,name:r.name,state:"complete",projectDirectory:r.projectDirectory,directory:r.directory});return n},lk=()=>{const e=mi.c(3),t=Es(hh),n=Es(mh);let r;return e[0]!==n||e[1]!==t?(r=ph(t,n),e[0]=n,e[1]=t,e[2]=r):r=e[2],r};function hh(e){return e.spaces}function mh(e){return e.journey}const Da=500,tu=()=>{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}},uk=()=>tu(),Ge=(e,t)=>{if(!tu())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>Da&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Da)},gh=()=>{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__=gh);const dk=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}},yh=3,wh=3e4,Sh=32e3,bh=3600*1e3,vh=600*1e3,Th=200,kh=new Set([429,502,503,504]),ht=new Map,Ri=e=>JSON.stringify([G(),e]);function Eh(){const e=Date.now();for(const[t,n]of ht){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>bh&&ht.delete(t)}}typeof setInterval<"u"&&setInterval(Eh,vh).unref?.();function Ph(e){const t=Ri(e);let n=ht.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:wh},ht.set(t,n);ht.size>Th;){const r=ht.keys().next().value;if(!r)break;ht.delete(r)}return n}function Ah(e){e&&ht.delete(Ri(e))}function Ih(e,t){if(!e)return;const n=Ph(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),xh(t)&&n.consecutiveErrors>=yh&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function xh(e){return e!==void 0&&kh.has(e)}function Rh(e){const t=ht.get(Ri(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Sh*4),!1):!0:!1}function Ch(e){if(!(!e||!Rh(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const nu=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,Ma=/^(?:\/\/\?\/)?[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==="/"?"/":nu.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},Dh=e=>{if(e==="/"||nu.test(e)||Ma.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 Ma.test(n)?`${n}/`:n},Mh=e=>Ye(e)??"",_h="openchamber",Lh="auto",Fh=(e,t)=>e===_h&&t===Lh,jh=at(f().min(1),S({type:_("running")})),Uh=S({id:f().min(1),sessionID:f().min(1),action:f(),resources:F(f())}),Nh=S({id:f().min(1),sessionID:f().min(1),title:f()}),Bh=S({sessions:at(f().min(1),S({status:f(),lastUpdateAt:R()})),pending:at(f().min(1),S({permissions:F(Uh),forms:F(Nh)})).optional(),serverTime:R()});function fk(e,t){if(!(!e||!t))return e.find(n=>n.id===t)??e.find(n=>n.modelID===t)}function K(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const En={text:(e,t)=>`${e}:text:${t}`,reasoning:(e,t)=>`${e}:reasoning:${t}`,tool:e=>e,userText:e=>`${e}:text:0`,userFile:(e,t)=>`${e}:file:${t}`,userAgent:(e,t)=>`${e}:agent:${t}`},pk=e=>e==="completed"||e==="error",ru=e=>e.role==="user"||e.role==="assistant",hk=e=>e==="user"||e==="assistant",mk=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&ru(n))return n}},gk=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.info&&ru(n.info))return n}},yk=e=>e?.role==="assistant"&&e.time.completed===void 0,_a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Hh=14;let La=0,oo=0;const $h=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+=_a[t[r]%_a.length];return n},Fa=e=>{const t=Date.now();t!==La&&(La=t,oo=0),oo+=1;const n=BigInt(t)*BigInt(4096)+BigInt(oo),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}${$h(Hh)}`};function Hr(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 zh(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 ja(e){return!e||e.length===0?"":e.filter(t=>t.type==="text").map(t=>t.text).join(`
2
+ import{s as f,o as S,n as R,b as Ae,d as Zt,l as _,a as F,_ as X,u as it,r as at,t as vd,e as ge,f as ra,j as sa,c as cr,g as Yc}from"./vendor-zod-C3BVLiwa.js";import{_ as hi}from"./vendor-vite-runtime-DD1OZmLC.js";import{a as ct,d as Dn,p as wr,b as Td}from"./vendor-zustand-XNmn2Hnw.js";import{e as kd,C as Ed}from"./vendor-opencode-client-DSZl7jSi.js";import{e as mi,R as ds}from"./vendor-react-C3AD0CRp.js";const Zn=1,Pd="openchamber-relay-v1",Qc=1,Xc=12,er=1+Xc,lr=64*1024,ur=5,fs=128,Zc=0,el=1,Pn=4,Ad=1+Pn,Ro=lr-ur-Ad,$={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},Id=new Set(Object.values($)),xd=e=>Id.has(e),Qt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},yt=globalThis.crypto.subtle,tl={name:"ECDH",namedCurve:"P-256"},nl=16,Ys=32,Rd=16,Co=4,rl=8;class Dt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Cd=()=>yt.generateKey(tl,!0,["deriveBits"]),Od=async e=>{const t=await yt.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Dd=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Dt("invalid ECDH public key JWK");try{return await yt.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},tl,!0,[])}catch{throw new Dt("invalid ECDH public key JWK")}},Md=()=>{const e=new Uint8Array(nl);return globalThis.crypto.getRandomValues(e),e},_d=async(e,t,n)=>{if(n.length!==nl)throw new Dt("invalid handshake nonce length");const r=await yt.deriveBits({name:"ECDH",public:t},e,256),s=await yt.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await yt.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(Pd)},s,Ys*2*8)),i=(a,c)=>yt.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(o.slice(0,Ys),["encrypt","decrypt"]),hostToClient:await i(o.slice(Ys),["encrypt","decrypt"])}},Ld=(e,t,n)=>{for(let r=rl-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Fd=(e,t)=>{let n=0n;for(let r=0;r<rl;r+=1)n=n<<8n|BigInt(e[t+r]);return n},jd=e=>{const t=new Uint8Array(Co);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>lr)throw new Dt("plaintext frame exceeds maximum size");n+=1n;const s=new Uint8Array(Xc);s.set(t,0),Ld(s,Co,n);const o=new Uint8Array(await yt.encrypt({name:"AES-GCM",iv:s},e,r)),i=new Uint8Array(er+o.length);return i[0]=Qc,i.set(s,1),i.set(o,er),i}}},Ud=e=>{let t=0n;return{async decrypt(n){if(n.length<er+Rd)throw new Dt("encrypted frame too short");if(n[0]!==Qc)throw new Dt("unsupported encrypted frame version");const r=n.slice(1,er),s=Fd(r,Co);if(s<=t)throw new Dt("frame counter regression");let o;try{o=await yt.decrypt({name:"AES-GCM",iv:r},e,n.slice(er))}catch{throw new Dt("frame decryption failed")}return t=s,new Uint8Array(o)}}},Dr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Nd=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+=Dr[r>>2],t+=Dr[(r&3)<<4|(s??0)>>4],s!==void 0&&(t+=Dr[(s&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Dr[o&63])}return t},oa=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!==Zn)return null;const r=n.batch===!0,s=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:Zn,batch:r,flowControl:s}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:Zn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:s}:null},Bd=e=>({type:"fail",closeCode:Qt.ChannelFailure,reason:e}),Hd=async(e,t={})=>{const n=t.batch!==!1,r=await Dd(e),s=await Cd(),o=Md(),i={t:"hello",v:Zn,clientPubJwk:await Od(s.publicKey),nonce:Nd(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 oa(c)?.t==="ready"?{type:"ignore"}:Bd("plaintext frame on established channel");const l=oa(c);if(l?.t!=="ready")return{type:"ignore"};const u=await _d(s.privateKey,r,o);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:jd(u.clientToHost),decryptor:Ud(u.hostToClient)}}}}},sl=4294967295,$d=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>sl)throw new be("invalid stream id");if(n.length>Ro)throw new be("tunnel payload exceeds maximum size");const s=new Uint8Array(ur+n.length);return s[0]=r?e|fs:e,s[1]=t>>>24&255,s[2]=t>>>16&255,s[3]=t>>>8&255,s[4]=t&255,s.set(n,ur),s},zd=e=>{if(e.length<ur)throw new be("tunnel frame too short");const t=e[0],n=(t&fs)!==0,r=t&~fs;if(!xd(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(ur),hasMoreFragments:n}},Wd=new TextEncoder,Gd=new TextDecoder,Mr=e=>Wd.encode(JSON.stringify(e)),_r=(e,t)=>{let n;try{n=JSON.parse(Gd.decode(e))}catch{throw new be("malformed JSON tunnel payload")}if(!t(n))throw new be("unexpected JSON tunnel payload shape");return n},ol=(e,t=Ro)=>{if(t<=0||t>Ro)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},ia=(e,t,n)=>{const r=ol(n);return r.map((s,o)=>We(e,t,s,o<r.length-1))},qd=(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)}}},Kd=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>lr)throw new be("frame batch exceeds maximum plaintext size");return o}let t=1;for(const s of e)t+=Pn+s.length;if(t>lr)throw new be("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=el;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+=Pn,n.set(s,r),r+=s.length;return n},Vd=e=>{if(e.length<1)throw new be("empty batch plaintext");const t=e[0];if(t===Zc)return[e.slice(1)];if(t!==el)throw new be(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+Pn>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+=Pn,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},Jd=new Set([$.HttpBody,$.WsText,$.WsBinary]),il=150,Yd=24*1024,Qd=32,Xd=e=>{const t=e.windowMs??il,n=e.maxBatchBytes??Yd,r=e.maxBatchFrames??Qd,s=e.now??(()=>Date.now()),o=e.setTimer??((b,w)=>setTimeout(b,w)),i=e.clearTimer??(b=>clearTimeout(b));let a=[],c=0,l=null,u=0,d=!1;const h=()=>{l!==null&&(i(l),l=null)},m=()=>{if(h(),a.length===0)return;const b=a;a=[],c=0,u=s(),e.sendBatch(Kd(b))};return{enqueue:b=>{if(d)return;const w=b[0]&~fs;if(!Jd.has(w)){a.push(b),m();return}const k=s();if(a.length===0&&k-u>=t){a.push(b),m();return}const E=Pn+b.length;if(a.length>0&&1+c+E>lr&&m(),a.push(b),c+=E,c>=n||a.length>=r){m();return}l===null&&(l=o(m,t))},flush:m,dispose(){d=!0,h(),a=[],c=0}}},Zd=()=>{let e=1;return{next(){if(e>sl)throw new be("stream id space exhausted");const t=e;return e+=2,t}}},_s=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ef=e=>_s(e)&&Object.values(e).every(t=>typeof t=="string"),tf=e=>_s(e)&&typeof e.status=="number"&&ef(e.headers),aa=e=>_s(e)&&typeof e.reason=="string",nf=e=>_s(e)&&typeof e.code=="number"&&typeof e.reason=="string",al=/^[a-z][a-z\d+.-]*:\/\//i,gi="http://tunnel.invalid",rf=e=>{try{const t=al.test(e)?new URL(e):new URL(e,gi);return`${t.pathname}${t.search}`}catch{return e}},Lr=e=>({async*[Symbol.asyncIterator](){yield e}}),sf=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()}}}),of=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},af=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:sf(e)};if(typeof e=="string")return{body:Lr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Lr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Lr(of(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Lr(r),contentType:n}},cf=async(e,t)=>{let n;const r=new Headers;let s="GET",o=null,i;e instanceof Request?(n=e.url,s=e.method,e.headers.forEach((d,h)=>r.set(h,d)),i=e.signal,o=e.body):n=e.toString(),t&&(t.method&&(s=t.method),t.headers&&new Headers(t.headers).forEach((d,h)=>r.set(h,d)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const a=al.test(n)?new URL(n):new URL(n,gi),{body:c,contentType:l}=await af(o);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,h)=>{u[h]=d}),{method:s.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},cl="__openchamberAmbiguousTransport",Oo=e=>(Object.defineProperty(e,cl,{value:!0,enumerable:!1,configurable:!0}),e),ca=e=>!e||typeof e!="object"?!1:e[cl]===!0,lf=["local","remote",null],uf=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function ll(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"||!lf.includes(r)))return{valid:!1};if(typeof s!="string"||!uf.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 rT(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 sT(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function oT(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function ul(){if(df()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=ll(t);return n.valid?n.outcome:null}function df(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":ll(e).valid?"valid":"malformed"}const ps=/^[a-z][a-z\d+.-]*:\/\//i,ff=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},hs=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),pf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return hs(e)},hf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return hs(e)},mf=()=>Object.keys(js()).length>0,gf=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Do=(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))},yf=(e,t)=>{if(!t)return e;const n=new URLSearchParams;Do({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},la=(e,t,n)=>{if(ps.test(t)){const o=new URL(t);return Do(o,n),o.toString()}const r=ff(t);if(!e)return yf(r,n);const s=new URL(r,`${e}/`);return Do(s,n),s.toString()},Fr=(e,t=qf())=>{if(!t)return e;const n=ps.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),ps.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},dl=(e,t)=>{const n=ps.test(e)?new URL(e):new URL(e,gf(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},ua=(e,t,n)=>{if(!mf())return null;const r=hf();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=Kf(r);return o&&s.searchParams.set("oc_url_token",o),e==="ws"?(s.protocol=s.protocol==="https:"?"wss:":"ws:",dl(s.toString(),n)):s.toString()}catch{return null}},yi=(e={})=>{const t=hs(e.apiBaseUrl),n=hs(e.realtimeBaseUrl),r=()=>t||pf(),s=()=>n||r(),o=(a,c)=>la(r(),a,c),i=(a,c)=>la(s(),a,c);return{api:o,authenticatedAsset:(a,c)=>Fr(o(a,c)),assetWithUrlToken:(a,c,l)=>Fr(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=Fr(i(a,c));return ua("sse",l,e)||l},websocket:(a,c)=>{const l=dl(Fr(i(a,c)),e);return ua("ws",l,e)||l}}};let ms=yi();const Pe=()=>ms,wf=e=>{ms=e},fl=e=>(ms=yi(e),ms),Mo="openchamber:runtime-endpoint-changed",_o="openchamber:runtime-endpoint-will-change";let An="",dr="";const Qs=(e,t,n)=>{try{e[t]=n}catch{}},wi=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"}`}},Sf="mobile-disconnected",bf="url:default",pl=e=>e===""||e===bf||e===Sf,hl=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},ml=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},gl=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},In=()=>An||hl();let Xs="",da=null,fa,pa;const ha=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},G=()=>{if(dr)return dr;const e=ha("__OPENCHAMBER_API_BASE_URL__"),t=ha("__OPENCHAMBER_LOCAL_ORIGIN__");if(da===An&&fa===e&&pa===t)return Xs;const n=In();return Xs=gl(n,ml())?"local":wi(n),da=An,fa=e,pa=t,Xs},vf=(e={})=>{if(An||dr)return;const t=e.apiBaseUrl?.trim()||hl(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const s=ml(),o=s&&(!t||gl(t,s));An=t,dr=e.runtimeKey?.trim()||(o?"local":wi(t||r))},gs=e=>{const t=e.apiBaseUrl.trim(),n=In(),r=G(),s=e.runtimeKey?.trim()||wi(t),o={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:s,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(_o,{detail:o})),An=t,dr=s,typeof window<"u"){const i=window;Qs(i,"__OPENCHAMBER_API_BASE_URL__",t),Qs(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Qs(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}fl({apiBaseUrl:t,realtimeBaseUrl:t}),Cl(e.requestHeaders||null),Rl(e.clientToken||null),e.relay?Nf(e.relay):Bf(),Us(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Mo,{detail:o}))},Tf=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(_o,t),()=>window.removeEventListener(_o,t)},yl=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Mo,t),()=>window.removeEventListener(Mo,t)};let Lo=null;const iT=e=>{Lo=e},Sr=()=>Lo||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),wl=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Sl=(e=wl())=>!!e,kf=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Lt=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,rn=()=>kf()?.runtime==="electron",Ef=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},Pf="right",aT=()=>{if(!rn())return!1;const e=Ef();return e==="win32"||e==="linux"},cT=e=>e==="left"?"left":Pf,lT=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Ie=()=>typeof Lt()?.invoke=="function",Mn=()=>rn()&&Ie(),Af=()=>{if(Lt()?.pickThemeFile)return{async pick(){const e=Lt()?.pickThemeFile;return e?{status:"picked",file:S({name:f(),size:R().nonnegative(),text:f()}).nullable().parse(await e())}:{status:"unsupported"}}}},se=async(e,t)=>{const n=Lt();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},uT=async()=>{if(!Be()||!Ee())return!1;const e=In();try{const t=Ae().safeParse(await se("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===In()}catch{return!1}},dT=async()=>{if(!Mn()||!Ee())return null;try{const e=await se("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},fT=async e=>{if(!Mn()||!Ee())return null;try{const t=await se("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},pT=async()=>{if(!Mn()||!Ee())return null;try{const e=await se("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},hT=async e=>{if(!Mn()||!Ee())return null;try{const t=await se("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},mT=async()=>{if(!Mn()||!Ee())return null;try{const e=await se("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},gT=async e=>{if(!Mn()||!Ee())return null;try{const t=await se("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},ma=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}}},Zs=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}}},If=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Hn=e=>{const t=If(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=Zs(e),n=Zs(In());if(!n&&t&&ul()?.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&&Hn(t.hostname)&&Hn(n.hostname)}const r=Zs(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&&Hn(t.hostname)&&Hn(r.hostname)}const s=ma(e),o=ma(window.location.origin)||window.location.origin;return s&&o&&s===o?!0:!!(r&&Hn(r.hostname))},Be=()=>typeof window>"u"?!1:rn(),yT=async()=>{if(!Be())return!1;try{return!!await se("desktop_focus_window")}catch{return!1}},bl=()=>Be()&&Ie()&&Ee(),xf=f().min(1),wT=e=>{if(!bl())return null;try{const t=xf.safeParse(Lt()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},ST=async()=>{if(!Be())return!1;try{return await se("desktop_start_window_drag"),!0}catch{return!1}},Oe=()=>Sl()?!0:Sr()?.runtime?.isVSCode===!0,bT=()=>{const t=Sr()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Oe()},vT=(e,t=Be())=>e==="web"&&!t,vl=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},TT=async e=>{if(bl())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"}},Rf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),kT=async e=>{if(Ie()&&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(!Rf(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"}},ET=async e=>({success:!0}),PT=async e=>({success:!0}),AT=async()=>Ie()?await se("desktop_check_for_updates"):null,IT=async e=>{if(!Ie())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 se("desktop_download_and_install_update"),!0}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{if(n)try{const o=n();o instanceof Promise&&await o}catch{}}},xT=async()=>Ie()?(await se("desktop_restart"),!0):!1,RT=async()=>{if(!Ie())return!1;try{return await se("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},CT=async()=>{if(!Ie()||!Ee())return null;try{const e=await se("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},Cf=async(e,t)=>{if(!Ie()||!Ee())return!1;const n=e?.trim();if(!n)return!1;try{return await se("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},OT=async e=>{if(!Ie()||!Ee())return!1;const t=e?.trim();if(!t)return!1;try{return await se("desktop_reveal_path",{path:t}),!0}catch{return Cf(t)}},DT=async(e,t)=>{if(!Ie()||!Ee())return null;const n=e?.trim();if(!n)return null;try{const r=await se("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},MT=async(e,t,n)=>{if(!Ie()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await se("desktop_open_in_app",{projectPath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},_T=async(e,t,n)=>{if(!Ie()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await se("desktop_open_file_in_app",{filePath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},LT=async(e,t)=>{if(!Ie()||!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 se("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=r;return s.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(s.apps)?{apps:s.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:s.hasCache===!0,isCacheStale:s.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},br=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",FT=()=>{if(typeof window>"u"||!br()||Tl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Tl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Oe()?"vscode":Be()?"desktop":"web"},Of="2.0.10",jr=new Uint8Array(0),Df=new TextEncoder,Mf=new TextDecoder,$e=e=>e instanceof Error?e:new Error(String(e)),Ur=()=>new DOMException("The operation was aborted.","AbortError"),_f=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},Lf=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},ga=0,eo=1,ya=2,wa=3,Ff=new Set([Qt.AuthFailed,Qt.DuplicateClient,Qt.LimitExceeded]),jf={[Qt.AuthFailed]:"relay authentication failed",[Qt.DuplicateClient]:"relay connection replaced by another client",[Qt.LimitExceeded]:"relay connection limit reached"},Sa=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Si=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,s=e.pingTimeoutMs??15e3,o=e.batchWindowMs??il,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(x=>_f(new WebSocket(x)));let d=!1,h=null,m={state:"idle"};const y=new Set;let b=null,w=null,k=null,E=0,L=0,D=null,J=[],C=!1;const ve=x=>{if(!(m.state===x.state&&m.lastError===x.lastError)){m=x;for(const W of y)try{W(m)}catch{}}},ce=x=>{const W=J;J=[];for(const M of W)M.reject(x)},Ks=x=>{const W=J;J=[];for(const M of W)M.resolve(x)},xe=(x,W)=>{x.dead=!0;const M=Array.from(x.streams.values());x.streams.clear();for(const U of M)try{U.fail(W)}catch{}},Fn=()=>{D!==null&&(clearTimeout(D),D=null)},jn=()=>{d||D===null||Sa()||(Fn(),Qe(),Un())},jt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&jn()},N=()=>{C||typeof window>"u"||(C=!0,window.addEventListener("online",jn),typeof document<"u"&&document.addEventListener("visibilitychange",jt))},Qe=()=>{!C||typeof window>"u"||(C=!1,window.removeEventListener("online",jn),typeof document<"u"&&document.removeEventListener("visibilitychange",jt))},ln=()=>{if(d||D!==null)return;const x=Math.max(0,L-1),W=a*2**Math.min(x,10),M=Sa()?l:c,U=Math.min(M,W);N(),D=setTimeout(()=>{D=null,Qe(),Un()},U)},Rr=()=>{const x=new URL(e.relayUrl);return x.searchParams.set("v",String(Zn)),x.searchParams.set("role","client"),x.searchParams.set("serverId",e.serverId),x.searchParams.set("appId","openchamber"),x.searchParams.set("appVersion",Of),x.searchParams.set("platform",Tl()),e.grant&&x.searchParams.set("grant",e.grant),x.toString()},Un=async()=>{if(d)return;Fn(),E+=1;const x=E;ve({state:L>0?"reconnecting":"connecting",lastError:m.lastError});let W;try{W=await Hd(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(Y){if(x!==E||d)return;na(x,$e(Y),!0);return}if(x!==E||d)return;let M;try{M=u(Rr())}catch(Y){na(x,$e(Y));return}w=M;let U=!1,B=null,q=null,De=null,ye=null,H=Promise.resolve(),z=null,oe=null,lt=!1,he=!1,me=0,we=0,Se=null,ut=null,te=Date.now();const bt=()=>{Se!==null&&(clearTimeout(Se),Se=null),B!==null&&(clearInterval(B),B=null),q!==null&&(clearTimeout(q),q=null),De!==null&&(clearInterval(De),De=null),ye!==null&&(clearTimeout(ye),ye=null),ut!==null&&(ut.dispose(),ut=null)};k=bt;function V(Y,ie=!1,Z=!1){if(!(U||x!==E)){U=!0,Z&&(h=Y),bt(),z&&(b=null,xe(z,new Error(`relay tunnel reset: ${Y.message}`))),ce(Y);try{M.close()}catch{}if(w===M&&(w=null),!d){if(L+=1,Z){ve({state:"error",lastError:Y.message});return}ve({state:ie?"error":"reconnecting",lastError:Y.message}),ln()}}}const Nn=()=>{try{M.send(W.helloText)}catch{}},Or=(Y,ie,Z)=>{oe=Y,lt=ie,he=Z,B!==null&&(clearInterval(B),B=null),q!==null&&(clearTimeout(q),q=null);const le=new Map,Ut=Zd(),He=qd();let Nt=Promise.resolve();const vt=Bn=>{Nt=Nt.then(async()=>{if(Bt.dead)return;const bd=await Y.encryptor.encrypt(Bn);Bt.dead||M.send(bd)}).catch(()=>{V(new Error("relay encrypt/send failed"))})},Js=ie?Xd({windowMs:o,sendBatch:vt}):null;ut=Js;const Bt={streams:le,assembler:He,nextStreamId:()=>Ut.next(),dead:!1,send(Bn){Bt.dead||(Js?Js.enqueue(Bn):vt(Bn))}};z=Bt,b=Bt,L=0,te=Date.now(),ve({state:"connected"}),Ks(Bt),De=setInterval(()=>{Date.now()-te<r||(Bt.send(We($.Ping,0,jr)),ye===null&&(ye=setTimeout(()=>{ye=null,V(new Error("relay keepalive timeout"))},s)))},r)},un=()=>{Se!==null&&clearTimeout(Se),Se=null,!(!z||z.dead||me===we)&&(we=me,z.send(We($.DeliveryAck,0,$d(me))))},Sd=(Y,ie)=>{let Z;try{Z=zd(ie)}catch(He){V($e(He));return}if(Z.frameType===$.DeliveryAck){V(new Error("unexpected downstream delivery acknowledgement"));return}if(he&&Z.streamId!==0&&(me+=ie.length,Se===null&&(Se=setTimeout(un,10))),te=Date.now(),ye!==null&&(clearTimeout(ye),ye=null),Z.frameType===$.Ping){Y.send(We($.Pong,Z.streamId,jr));return}if(Z.frameType===$.Pong)return;let le=Z.payload;if(Z.frameType===$.WsText||Z.frameType===$.WsBinary){let He;try{He=Y.assembler.push(Z)}catch(Nt){V($e(Nt));return}if(He===null)return;le=He}else if(Z.hasMoreFragments){V(new Error("unexpected fragmented tunnel frame"));return}const Ut=Y.streams.get(Z.streamId);Ut&&Ut.handleFrame(Z.frameType,le)};M.onopen=()=>{U||x!==E||(Nn(),B=setInterval(Nn,t))},M.onmessage=Y=>{if(U||x!==E)return;const ie=Y.data;if(typeof ie=="string"){H=H.then(async()=>{if(U||x!==E)return;const le=await W.handleText(ie);if(le.type==="established"){if(oe)return;Or(le.channel,le.batch,le.flowControl)}else le.type==="fail"&&V(new Error(`relay handshake failed: ${le.reason}`))}).catch(le=>{V($e(le))});return}const Z=ie instanceof ArrayBuffer?new Uint8Array(ie):ie instanceof Uint8Array?ie:null;Z&&(H=H.then(async()=>{if(U||x!==E)return;const le=z,Ut=oe;if(!le||!Ut){V(new Error("encrypted frame before handshake completed"));return}let He;try{He=await Ut.decryptor.decrypt(Z)}catch(vt){V($e(vt));return}let Nt;try{Nt=lt?Vd(He):[He]}catch(vt){V($e(vt));return}for(const vt of Nt){if(U||x!==E||le.dead)return;Sd(le,vt)}he&&me-we>=16*1024&&un()}).catch(le=>{V($e(le))}))},M.onclose=Y=>{const ie=Ff.has(Y.code);V(new Error(jf[Y.code]??`relay socket closed (code ${Y.code})`),ie,ie)},M.onerror=()=>{},q=setTimeout(()=>{q=null,V(new Error("relay handshake timeout"),!0)},n);function na(Y,ie,Z=!1){Y!==E||d||(ce(ie),L+=1,ve({state:Z?"error":"reconnecting",lastError:ie.message}),ln())}},Cr=x=>d?Promise.reject(new Error("relay tunnel closed")):x?.aborted?Promise.reject(Ur()):h?Promise.reject(h):b&&!b.dead?Promise.resolve(b):new Promise((W,M)=>{let U=null;const B={resolve(q){U&&x&&x.removeEventListener("abort",U),W(q)},reject(q){U&&x&&x.removeEventListener("abort",U),M(q)}};x&&(U=()=>{J=J.filter(q=>q!==B),M(Ur())},x.addEventListener("abort",U,{once:!0})),J.push(B)}),St=async(x,W)=>{const M=await cf(x,W),U=M.signal;if(U?.aborted)throw Ur();const B=await Cr(U),q=B.nextStreamId();return await new Promise((De,ye)=>{let H=!1,z=!1,oe=null,lt=null;const he=()=>{B.streams.delete(q),B.assembler.dropStream(q),lt&&U&&U.removeEventListener("abort",lt)},me=te=>{if(!z){if(z=!0,he(),!H){ye(te);return}try{oe?.error(te)}catch{}}},we=te=>{B.dead||B.send(We($.StreamAbort,q,Mr({reason:te})))},Se=te=>Oo(new Error(te));lt=()=>{we("aborted"),me(Ur())},B.streams.set(q,{handleFrame(te,bt){if(te===$.HttpResponse){if(H||z)return;let V;try{V=_r(bt,tf)}catch(un){we("malformed response head"),me(Se($e(un).message));return}const Nn=V.status===204||V.status===205||V.status===304;let Or=null;Nn||(Or=new ReadableStream({start(un){oe=un},cancel(){z||(z=!0,he(),we("response body cancelled"))}})),H=!0,De(new Response(Or,{status:V.status,headers:V.headers})),Nn&&(z=!0,he());return}if(te===$.HttpBody){if(!H||z)return;try{oe?.enqueue(bt)}catch{}return}if(te===$.StreamEnd){if(z)return;if(!H){me(Se("tunnel stream ended before response head"));return}z=!0,he();try{oe?.close()}catch{}return}if(te===$.StreamAbort){let V="stream aborted by host";try{V=_r(bt,aa).reason}catch{}me(Se(V))}},fail(te){me(Se(te.message))}}),U&&U.addEventListener("abort",lt,{once:!0});const ut={method:M.method,path:M.path,query:M.query,headers:M.headers,hasBody:M.body!==null};B.send(We($.HttpRequest,q,Mr(ut))),(async()=>{try{let te=!1;if(M.body)for await(const bt of M.body){if(z||B.dead)return;for(const V of ol(bt))B.send(We($.HttpBody,q,V)),te=!0}!z&&!B.dead&&(M.body&&!te&&B.send(We($.HttpBody,q,jr)),B.send(We($.StreamEnd,q,jr)))}catch(te){we("request body failed"),me(Se($e(te).message))}})()})},Vs=x=>{const W=x.indexOf("?");return W===-1?{path:x,query:""}:{path:x.slice(0,W),query:x.slice(W+1)}},yd=(x,W)=>{let M=ga,U=null,B=0,q=!1;const De={get readyState(){return M},onopen:null,onmessage:null,onerror:null,onclose:null,send(H){if(M!==eo||!U||U.dead)throw new Error("relay tunnel socket is not open");if(typeof H=="string"){for(const oe of ia($.WsText,B,Df.encode(H)))U.send(oe);return}const z=H instanceof ArrayBuffer?new Uint8Array(H.slice(0)):(()=>{const oe=new Uint8Array(H.byteLength);return oe.set(new Uint8Array(H.buffer,H.byteOffset,H.byteLength)),oe})();for(const oe of ia($.WsBinary,B,z))U.send(oe)},close(H=1e3,z=""){M===wa||M===ya||(M===eo&&U&&!U.dead&&(M=ya,U.send(We($.WsClose,B,Mr({code:H,reason:z})))),ye(H,z))}},ye=(H,z,oe=!1)=>{if(!q){if(q=!0,U&&(U.streams.delete(B),U.assembler.dropStream(B)),M=wa,oe)try{De.onerror?.()}catch{}try{De.onclose?.({code:H,reason:z})}catch{}}};return(async()=>{let H;try{H=await Cr()}catch(he){ye(1006,$e(he).message,!0);return}if(q)return;U=H,B=H.nextStreamId(),H.streams.set(B,{handleFrame(he,me){if(he===$.WsOpened){if(M===ga){M=eo;try{De.onopen?.()}catch{}}return}if(he===$.WsText){try{De.onmessage?.({data:Mf.decode(me)})}catch{}return}if(he===$.WsBinary){const we=new ArrayBuffer(me.byteLength);new Uint8Array(we).set(me);try{De.onmessage?.({data:we})}catch{}return}if(he===$.WsClose){let we=1e3,Se="";try{const ut=_r(me,nf);we=ut.code,Se=ut.reason}catch{}ye(we,Se);return}if(he===$.StreamAbort){let we="stream aborted";try{we=_r(me,aa).reason}catch{}ye(1006,we,!0)}},fail(he){ye(1012,he.message,!0)}});const{path:z,query:oe}=Vs(x),lt=W&&W.length>0?{path:z,query:oe,protocols:W}:{path:z,query:oe};H.send(We($.WsOpen,B,Mr(lt)))})(),De},wd=()=>{if(d)return;d=!0,E+=1,Fn(),Qe(),k?.(),k=null;const x=b;b=null;const W=new Error("relay tunnel closed");x&&xe(x,W),ce(W);try{w?.close()}catch{}w=null,ve({state:"idle"})};return Un(),{fetch:St,openWebSocket:yd,getStatus:()=>m,subscribeStatus(x){return y.add(x),()=>{y.delete(x)}},close:wd}};let Le=null,wt=null;const Uf=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Ls=()=>Le,jT=()=>!Le||!wt?null:{relayUrl:wt.relayUrl,serverId:wt.serverId,hostEncPubJwk:{...wt.hostEncPubJwk}},UT=()=>Le!==null,Nf=e=>(Le&&wt&&Uf(wt,e)||(Le?.close(),wt=e,Le=Si(e)),Le),NT=(e,t)=>{Le!==t&&(Le?.close(),wt=e,Le=t)},Bf=()=>{Le?.close(),Le=null,wt=null};let kl=()=>null,El="",ys={},en="",fr=0,Kt=null,Tn="",pr=0,tn="",Vt=null,Rt="",rs=0,ss=0;const bi=1e4,Hf=e=>e.toLowerCase()==="authorization",Pl=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const s=n.trim(),o=r.trim();s&&o&&!Hf(s)&&(t[s]=o)}return t},$f=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,s])=>t[r]===s)},Fs=e=>typeof e!="string"?"":e.trim(),zf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Fs(e)},Wf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Al=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():Wf();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},vi=e=>{try{return new URL(e).origin}catch{return""}},Il=()=>{Tn="",pr=0,tn="",Vt=null,Rt="",rs+=1},vr=()=>{en="",fr=0,Il()},xl=()=>{ss+=1,Kt=null,vr(),Ti()},Rl=e=>{const t=Fs(e);El=t,xl(),kl=()=>t?{type:"bearer",token:t}:null},Cl=e=>{const t=Pl(e);$f(ys,t)||(ys=t,xl())},js=()=>{if(Object.keys(ys).length>0)return ys;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Pl(e):{}},Ol=()=>El||zf(),Gf=(e,t)=>{const n=Fs(e);if(!n||typeof t!="number"||!Number.isFinite(t)){vr();return}const r=en;en=n,fr=t,r&&r!==n&&Qf()},Dl=()=>!en||fr<=Date.now()+bi?(vr(),""):en,Ml=e=>{const t=vi(e);return!t||tn!==t?"":!Tn||pr<=Date.now()+bi?(Tn="",pr=0,tn="",""):Tn},qf=()=>{const e=Dl();return!e&&(Ol()||typeof window<"u")&&Us().catch(()=>{}),e},Kf=e=>{const t=e?Ml(e):"";return!t&&e&&typeof window<"u"&&jl(e).catch(()=>{}),t},_l=async()=>{const e=await kl(),t=e?.type==="bearer"?Fs(e.token):Ol();return t?{type:"bearer",token:t}:null},Vf=S({token:f(),expiresAt:R()}),Ll=async(e,t)=>{const n=await _l(),r=new Headers;for(const[c,l]of Object.entries(js()))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=Ls(),i=o?await o.fetch(s,{method:"POST",headers:r}):await fetch(Al(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=Vf.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},BT=async e=>{const t=await Ll(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Fl=e=>{if(Kt)return Kt;const t=ss,r=(async()=>{let s;try{s=await Ll(e)}catch(o){throw t===ss&&vr(),o}if(t!==ss)throw new Error("Runtime URL auth token response is stale");if(Gf(s.token,s.expiresAt),!en)throw new Error("Runtime URL auth token response was invalid");return en})().finally(()=>{Kt===r&&(Kt=null)});return Kt=r,Kt},Jf=e=>{const t=vi(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Vt&&Rt===t)return Vt;const n=rs,s=(async()=>{const o=await fetch(Al(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw n===rs&&t===Rt&&(Tn="",pr=0,tn=""),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!==rs||t!==Rt)throw new Error("Local runtime URL auth token response is stale");return Tn=a,pr=c,tn=t,a})().finally(()=>{Vt===s&&(Vt=null,Rt="")});return Vt=s,Rt=t,Vt},Us=async e=>{const t=Dl();return t||Fl(e)},jl=async e=>{const t=vi(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=Ml(t);return n||((tn&&tn!==t||Rt&&Rt!==t)&&Il(),Jf(t))};let Sn=0,tr=null,Ul=null;const Fo=new Set,Yf=5e3,Qf=()=>{for(const e of Fo)try{e()}catch{}},Nl=()=>{tr!==null&&(clearTimeout(tr),tr=null)},Ti=()=>{if(Nl(),Sn<=0||typeof window>"u")return;const e=fr-bi-Yf,t=fr>0?Math.max(0,e-Date.now()):0;tr=setTimeout(()=>{tr=null,!(Sn<=0)&&Fl(Ul).catch(()=>{}).finally(()=>{Ti()})},t)},HT=e=>{typeof e=="string"&&e.trim()&&(Ul=e.trim()),Sn+=1,Ti();let t=!1;return()=>{t||(t=!0,Sn=Math.max(0,Sn-1),Sn===0&&Nl())}},$T=e=>(Fo.add(e),()=>{Fo.delete(e)}),Xf=async e=>{const t=new Headers(e);for(const[r,s]of Object.entries(js()))t.has(r)||t.set(r,s);if(t.has("Authorization"))return t;const n=await _l();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},ws=ct(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Zf=15e3,ep=5*6e4;let jo=0,to=!1;const tp=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),np=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!tp(t)},Bl=async()=>{if(!to){to=!0;try{const{runtimeFetch:e}=await hi(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>Sp);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){ws.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=ws.getState();n==="expired"&&r()}}catch{}finally{to=!1}}},rp=(e,t)=>{if(t!==401||ws.getState().state==="expired"||!np(e))return;const n=Date.now();n-jo<Zf||(jo=n,Bl())};let ba=!1;const zT=()=>{if(ba)return;ba=!0;let e=Date.now();const t=()=>{if(ws.getState().state!=="ok")return;const n=Date.now();n-e<ep||(e=n,jo=n,Bl())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},sp=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,va="/api/",Hl="/api/spaces/",ki=e=>{if(!e)return null;const t=sp.exec(e);return t?t[1]:null},Ta=e=>ki(e)!==null,op=e=>e.startsWith(Hl),ip=()=>Sl()||Sr()?.runtime?.isVSCode===!0,Ei=(e,t)=>{if(ip())return e;const n=ki(t);return n===null||!e.startsWith(va)||op(e)?e:`${Hl}${n}/${e.slice(va.length)}`},nn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",ap=()=>typeof window>"u"?"":window.location.origin||"",Ns=e=>{if(typeof window>"u")return!1;const t=ap();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}},Bs=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),cp=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),It=(e,t)=>{try{cp(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},Pi=(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))},$l=e=>{if(!e)return null;try{return decodeURIComponent(e)}catch{return e}},ka=e=>{const t=new URLSearchParams(e);return $l(t.get("directory")??t.get("location[directory]"))},Ea=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 $l(r);return null},lp=e=>{if(!Bs(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!Ns(t)&&!nr(t)?null:{path:t.pathname,rest:`${t.search}${t.hash}`,origin:t.origin}}catch{return null}},up=(e,t)=>{const n=e instanceof Request?e.url:e.toString(),r=lp(n);if(!r||!r.path.startsWith("/api/"))return e;const s=t.directory??ka(r.rest)??(t.query?ka(new URLSearchParams(t.query instanceof URLSearchParams?t.query:Object.entries(t.query).flatMap(([a,c])=>c==null?[]:[[a,String(c)]])).toString()):null)??Ea(t.headers)??(e instanceof Request?Ea(e.headers):null),o=Ei(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},nr=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:nn(e.pathname)}catch{return!1}},no=e=>{if(nn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return Ns(t)&&nn(t.pathname)}catch{return!1}},dp=(e,t)=>{try{const n=new URL(e);if(!Ns(n))return e;const r=_t(`${n.pathname}${n.search}`,t);return!Bs(r)&&(n.protocol==="http:"||n.protocol==="https:")?(Pi(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},_t=(e,t)=>e==="/health"?Pe().health(t):e.startsWith("/auth/")||e==="/auth"?Pe().auth(e,t):nn(e)?Pe().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?dp(e,t):e,fp=e=>{const t=e instanceof Request?e.url:e.toString();if(!Bs(t))return nn(t);try{return nr(new URL(t))}catch{return!1}},zl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},pp=(e,t)=>!zl(t),Uo=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)pp(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},dt=async(e,t,n=!0)=>{const r=new Headers(Uo(e)??e);return t&&new Headers(Uo(t)??t).forEach((s,o)=>r.set(o,s)),n?Xf(r):r},hp=(e,t)=>{if(!t)return e;const n=new URL(e,gi);return Pi(n,t),`${n.pathname}${n.search}`},Wl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!Bs(n))return nn(n)?hp(n,t):null;try{const r=new URL(n);return!Ns(r)||!nn(r.pathname)?null:(Pi(r,t),`${r.pathname}${r.search}`)}catch{return null}},mp=async(e,t,n)=>{const r=Ls();if(!r)return null;const s=Wl(e,n);if(s===null)return null;const o=e instanceof Request?e.headers:void 0,i=await dt(o,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(s,{...t,headers:i})},gp=(e,t)=>{if(typeof e=="string")return _t(e,t);if(e instanceof URL)return _t(e.toString(),t);const n=_t(e.url,t);return n===e.url?e:new Request(n,e)},yp=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Nr=new Map,wp=(e,t,n,r)=>n||e!=="GET"||t.includes("/event")||!yp.test(t)?null:`GET ${t}\0${r.get("x-opencode-directory")??""}`,g=async(e,t={})=>{const n=up(e,t),{query:r,directory:s,...o}=t,i=Ls(),a=i?Wl(n,r):null;let c,l,u,d;if(i&&a!==null){const k=n instanceof Request?n.headers:void 0,E=await dt(k,o.headers,!0);c=n instanceof Request?()=>i.fetch(n,{...o,headers:E}):()=>i.fetch(a,{...o,headers:E}),d=E,l=a,u=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase()}else{const k=gp(n,r),E=k instanceof Request?k.headers:void 0,L=await dt(E,o.headers,fp(k)),D=k instanceof Request?k.url:k instanceof URL?k.toString():String(k);It(D,L),c=k instanceof Request?()=>fetch(new Request(k,{...o,headers:L})):()=>fetch(k,{...o,headers:L}),d=L,l=D,u=String(o.method??(k instanceof Request?k.method:"GET")).toUpperCase()}const h=c;c=()=>h().then(k=>(rp(l,k.status),k));const m=o.signal!=null||n instanceof Request,y=wp(u,l,m,d);if(!y)return c();const b=Nr.get(y);if(b)return b.then(k=>k.clone());const w=c();return Nr.set(y,w),w.then(()=>Nr.delete(y),()=>Nr.delete(y)),w.then(k=>k.clone())};let Pa=!1;const Gl=()=>{if(Pa||typeof window>"u")return;Pa=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await mp(t,n??{});if(r)return r;if(typeof t=="string"){if(!no(t)){try{const i=new URL(t);if(nr(i)){const a=await dt(void 0,n?.headers);return It(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const s=await dt(void 0,n?.headers),o=_t(t);return It(o,s),e(o,{...n,headers:s})}if(t instanceof URL){const s=t.toString();if(!no(s)){if(nr(t)){const a=await dt(void 0,n?.headers);return It(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const o=await dt(void 0,n?.headers),i=_t(s);return It(i,o),e(i,{...n,headers:o})}if(t instanceof Request){if(!no(t.url)){try{const a=new URL(t.url);if(nr(a)){const c=await dt(t.headers,n?.headers);return It(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const s=await dt(t.headers,n?.headers),o=_t(t.url);It(o,s);const i=o===t.url?t:new Request(o,t);return e(new Request(i,{...n,headers:s}))}return e(t,n)}},Sp=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:It,buildRuntimeFetchUrl:_t,installRuntimeFetchBridge:Gl,isLatin1Safe:zl,runtimeFetch:g,sanitizeHeadersForBrowser:Uo},Symbol.toStringTag,{value:"Module"})),kn=16384,Ss=globalThis,bp=e=>{if(Ss.Buffer)return Ss.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,"")},ql=e=>{try{if(Ss.Buffer)return Ss.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}},vp=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}},Tp=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}},Aa=e=>typeof e=="string"&&e.length>0,kp=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Aa(t.x)||!Aa(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Ep=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pp=e=>{if(!e||typeof e!="object")return null;const t=e,n=Ep(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=vp(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=Tp(t.relayUrl);if(!r)return null;const s=typeof t.serverId=="string"?t.serverId.trim():"";if(!s)return null;const o=kp(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},Ai=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}},WT=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}),GT=e=>{const t=Ai(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",bp(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},Ap=e=>{const t=e.trim();if(!t||t.length>kn)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>kn)return null;const s=ql(r);return!s||s.length>kn?null:Ai(JSON.parse(s))}catch{return null}},qT=e=>{const t=e.trim();if(!t||t.length>kn)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>kn)return null;const o=ql(s);if(!o||o.length>kn)return null;try{return Ai(JSON.parse(o))}catch{return null}},xn=e=>typeof e=="object"&&e!==null,Ip=e=>e.trim().toLowerCase()==="authorization",xp=e=>{if(!xn(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)||Ip(s)||(t[s]=o)}return Object.keys(t).length>0?t:void 0},Rp=e=>`relay://${e}`,Cp=e=>{if(!xn(e))return null;const t=Te(e,"relayUrl")||Te(e,"relay_url"),n=Te(e,"serverId")||Te(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!xn(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Op=()=>{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"},KT=async(e,t)=>{const n=Ap(e);if(!n)throw new Error("invalid-connect-link");const r=await Fp().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:Op(),...r?{dedupeKey:`desktop:${r}`}:{}})},o=async w=>{if(!w.ok)return null;const k=await w.json().catch(()=>null);return(typeof k?.clientToken=="string"?k.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((w,k)=>(w.type==="relay"?1:0)-(k.type==="relay"?1:0));for(const w of a){if(w.type==="relay"){const E=Si({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const L=await o(await E.fetch("/api/client-auth/pairing/redeem",s));if(L){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:L};break}}catch{}finally{E.close()}continue}const k=ke(w.url);if(k)try{const E=await o(await fetch(`${k}/api/client-auth/pairing/redeem`,s));if(E){i={directUrl:k,token:E};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(w=>w.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),u=n.candidates.filter(w=>w.type!=="relay").map(w=>ke(w.url)).find(w=>!!w),d=i.directUrl||u,h=d||(l?Rp(l.serverId):null);if(!h)throw new Error("pairing-missing-transport");const m=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&ke(w.apiUrl||w.url)===h),y=m?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),b={...m||{},id:y,label:n.label||m?.label||Kl(h),url:h,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:y,hosts:m?t.map(w=>w.id===y?b:w):[b,...t]}},Dp=/^(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}},VT=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"}},Kl=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)Dp.test(s)&&n.searchParams.set(s,"[REDACTED]");return n.toString()}catch{return t}},Br=(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}},Te=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},Ia=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},Mp=e=>{if(!xn(e))return null;const t=Te(e,"id"),n=Te(e,"label"),r=Te(e,"url"),s=Te(e,"apiUrl")||Te(e,"api_url"),o=Te(e,"clientToken")||Te(e,"client_token"),i=xp(e.requestHeaders),a=Cp(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}:{}}},rr=e=>ke(e.apiUrl||e.url)||e.apiUrl||e.url,sn=()=>Ie()?(e,t)=>se(e,t):null,Ii=async()=>{const e=sn();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!xn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(Mp).filter(a=>!!a):[],s=Te(t,"defaultHostId")||Te(t,"default_host_id")||Te(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=Te(t,"localOrigin")||Te(t,"local_origin");return{hosts:r,defaultHostId:s,initialHostChoiceCompleted:o,localOrigin:i}},_p=async e=>{const t=sn();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})},Lp=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Fp=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},jp=8e3,Up=15e3,Np=400,Bp=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)}},xa=async(e,t,n,r)=>{for(;;){const s=n-Date.now();if(s<=0)throw new Error("relay probe deadline exceeded");try{return await Bp(e,t,Math.min(jp,s),r)}catch(o){if(e.getStatus().state==="error"||Date.now()>=n)throw o;await new Promise(i=>window.setTimeout(i,Np))}}},Hp=async(e,t)=>{const n=Si({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),s=r+Up;let o=!1;try{if(!(await xa(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 xa(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()}},xi=async(e,t)=>{const n=sn();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(!xn(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=Ia(r,"latencyMs")??Ia(r,"latency_ms")??0;return{status:o,latencyMs:i}},JT=async(e,t)=>{const n=sn();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},YT=async e=>{const t=sn();t&&await t("desktop_new_window_for_host",{hostId:e})},Mt="local",$p=e=>({id:Mt,label:"Local",url:e||Vl()}),Vl=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,zp=e=>e.id===Mt?"local":`host:${e.id}`,QT=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Mt)?.url||Vl(),r=In(),s=ke(n)||n,o=ke(t)||t,i=G(),a=e.find(u=>u.relay&&zp(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Br(r,n))return{id:Mt,label:"Local",url:s};const c=e.find(u=>r?Br(r,rr(u)):!1);if(c)return{id:c.id,label:c.label,url:ke(rr(c))||rr(c)};if(t&&Br(t,n))return{id:Mt,label:"Local",url:s};const l=e.find(u=>t?Br(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:Kl(o||"Instance"),url:o}},bs=new Map;let Jl=0;const vs=new Map;let No=0,Yl={byHostId:{},isProbing:!1};const Bo=new Set,Ts=()=>{Yl={byHostId:Object.fromEntries(bs),isProbing:No>0};for(const e of Bo)try{e()}catch{}},XT=e=>(Bo.add(e),()=>{Bo.delete(e)}),ZT=()=>Yl,Ql=(e,t)=>{bs.set(e,t),Ts()},ek=(e,t)=>{vs.set(e,++Jl),Ql(e,t)},Wp=e=>{const t=new Set([Mt,...e]);let n=!1;for(const r of Array.from(bs.keys()))t.has(r)||(bs.delete(r),vs.delete(r),n=!0);n&&Ts()},Gp=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",qp=async()=>rn()?Lp().catch(()=>""):"",Kp=async(e,t)=>{const n=e.id===Mt?t:e.clientToken||"",r=async()=>{const i=await Hp(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(rn()?rr(e):e.url);if(!s)return{status:"unreachable",latencyMs:0};const o=await xi(s,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Gp(o.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:o.status,latencyMs:o.latencyMs}},Vp=async e=>{if(!Be())return;const t=++Jl;for(const n of e)vs.set(n.id,t);No+=1,Ts();try{const n=await qp();await Promise.all(e.map(async r=>{const s=await Kp(r,n);vs.get(r.id)===t&&Ql(r.id,s)}))}finally{No-=1,Ts()}};let Ra=!1;const Jp=async()=>{if(Ra||!Be())return;Ra=!0;const e=await Ii().catch(()=>null);e&&(Wp(e.hosts.map(t=>t.id)),await Vp([$p(e.localOrigin),...e.hosts]))},Yp=5e3,Qp=1500;let ro=!1;const Xp=async e=>{if(!rn()||ro)return;const t=`host:${e}`;if(G()===t){ro=!0;try{const n=await Ii().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 h=d;if(h.type!=="lan"||typeof h.url!="string")continue;const m=ke(h.url);m&&!c.includes(m)&&c.push(m)}if(c.length===0)return;const l=s&&c.includes(s)?s:c[0];l!==s&&await _p({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await xi(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;gs({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{ro=!1}}},Zp=e=>{typeof window>"u"||window.setTimeout(()=>{Xp(e).catch(()=>{})},Yp)},eh=async e=>{if(!rn())return;const t=await Ii().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=>{gs({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:s})},i=()=>{gs({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:s,relay:r.relay??void 0}),Zp(r.id)},a=r.apiUrl?ke(rr(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=xi(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),Qp))]);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 tk=e=>e instanceof Xt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),ks=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},on="/api/openchamber/spaces",Tr=f().regex(/^[0-9a-f]{12}$/),Hs=S({code:f(),message:f()});class so extends Error{code;status;constructor(t,n,r){super(n),this.name="SpacesRequestError",this.code=t,this.status=r}}const th=S({id:Tr,name:f(),state:f()});Zt("enabled",[S({enabled:_(!1)}),S({enabled:_(!0),spaces:F(th).nullable(),failure:Hs.optional()})]);const nh=S({id:Tr,name:f(),code:f(),message:f()});S({enabled:Ae(),stopped:F(S({id:Tr,name:f()})),stillRunning:F(nh),unknown:Hs.optional()});const Xl=S({mode:X(["allowlist","open"]),domains:F(f())}),Zl=Zt("kind",[S({kind:_("model"),id:f(),provider:f(),upstream:f(),source:Zt("kind",[S({kind:_("typed")}),S({kind:_("env"),name:f()})]),url:f()}),S({kind:_("domain"),id:f(),upstream:f(),url:f()})]),rh=["checking_place","creating","setting_network","bringing_code","ready"],sh=X(rh),eu=S({id:Tr,name:f(),projectDirectory:f().nullable(),directory:f().nullable(),state:X(["preparing","running","exited","missing","failed"]),step:sh.nullable(),failure:Hs.nullable(),network:Xl.nullable(),grants:F(Zl),access:X(["granted","needs_access","unknown"]).nullable(),needsAccess:F(f())}),oh=it([S({id:f(),available:_(!0),hostIsolation:Ae()}),S({id:f(),available:_(!1),code:f(),message:f()})]),ih=S({code:f(),message:f()}),an=async(e,t,n={})=>{const r=await g(e,{...n,headers:n.body===void 0?n.headers:{"Content-Type":"application/json",...n.headers}}),s=await r.json().catch(()=>null);if(!r.ok){const i=ih.safeParse(s);throw i.success?new so(i.data.code,i.data.message,r.status):new so("space_request_failed",`The server answered ${r.status}.`,r.status)}const o=t.safeParse(s);if(!o.success)throw new so("space_answer_malformed","The server answered in a shape this version does not know.",r.status);return o.data},nk=async e=>(await an(`${on}/places`,S({places:F(oh)}),{signal:e})).places,ah=async e=>(await an(on,S({spaces:F(eu)}),{signal:e})).spaces,rk=e=>an(on,eu,{method:"POST",body:JSON.stringify(e)}),sk=async(e,t)=>(await an(`${on}/${e}/grants`,S({grant:Zl}),{method:"POST",body:JSON.stringify(t)})).grant,ok=async(e,t)=>(await an(`${on}/${e}/network/domains`,S({network:Xl}),{method:"POST",body:JSON.stringify({domain:t})})).network,ch=S({at:f(),listener:f(),host:f(),port:R(),decision:f()}),lh=S({records:F(ch),dropped:R(),since:f()}),ik=(e,t)=>an(`${on}/${e}/journal`,lh,{signal:t}),uh=S({id:Tr,removed:Ae(),failures:F(Hs)}),ak=e=>an(`${on}/${e}`,uh,{method:"DELETE"}),dh=S({id:f().regex(/^[0-9a-f]{12}$/),name:f().default(""),state:X(["complete","partial","stale","unknown"]),projectDirectory:f().nullable().default(null),directory:f().nullable().default(null)}),Ca=new Map,$n=new Map,fh=(e,t)=>t.step==="failed"?{...e,state:"failed",failure:t.failure}:{...e,state:t.step==="ready"?"running":"preparing",step:t.step==="ready"?null:t.step,failure:null},Oa=(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},Es=ct((e,t)=>({spaces:Ca,journey:null,progressRevision:0,applyJourney:(n,r)=>e(s=>{const o=new Map(n.map(i=>[i.id,i]));for(const[i,a]of $n){const c=s.journey?.get(i);a>r&&c&&o.set(i,c)}return{journey:o}}),addJourneyEntry:n=>e(r=>{const s=r.progressRevision+1;$n.set(n.id,s);const o=new Map(r.journey??[]);return o.set(n.id,n),{journey:o,progressRevision:s}}),creationAccess:new Map,noteCreationAccess:(n,r)=>e(s=>{const o=new Map(s.creationAccess);return r?o.set(n,r):o.delete(n),{creationAccess:o}}),noteProviderGranted:(n,r)=>e(s=>{const o=s.creationAccess.get(n);if(o?.kind!=="failed")return s;const i=o.failures.filter(c=>c.provider!==r),a=new Map(s.creationAccess);return i.length>0?a.set(n,{kind:"failed",failures:i}):a.delete(n),{creationAccess:a}}),noteGrantGiven:(n,r)=>e(s=>{const o=s.journey?.get(n);if(!o)return s;const i=s.progressRevision+1;$n.set(n,i);const a=new Map(s.journey);return a.set(n,{...o,grants:[...o.grants.filter(c=>c.id!==r.id),r],needsAccess:o.needsAccess.filter(c=>c!==r.id)}),{journey:a,progressRevision:i}}),accessDialog:null,openAccessDialog:(n,r=null)=>e({accessDialog:{spaceId:n,providerId:r}}),closeAccessDialog:()=>e({accessDialog:null}),noteProgress:n=>{const r=t().progressRevision+1;$n.set(n.spaceId,r);const s=t().journey?.get(n.spaceId);if(!s)return e({progressRevision:r}),!1;const o=new Map(t().journey);return o.set(n.spaceId,fh(s,n)),e({journey:o,progressRevision:r}),!0},applyMarks:n=>e(r=>{const s=new Map(n.map(o=>[o.id,o]));return s.size===0&&r.spaces.size===0?r:{spaces:s}}),noteStream:(n,r)=>e(s=>r==="connected"?s:{spaces:Oa(s.spaces,n,"stale")}),noteReachable:n=>e(r=>({spaces:Oa(r.spaces,n,"complete")})),resetForRuntimeSwitch:()=>{$n.clear(),Ho+=1,e({spaces:Ca,journey:null,progressRevision:0,creationAccess:new Map,accessDialog:null})},forgetForSwitchOff:()=>t().resetForRuntimeSwitch()}));let Ho=0;const ck=async()=>{const e=Ho,t=Es.getState().progressRevision,n=await ah();e===Ho&&Es.getState().applyJourney(n,t)},ph=(e,t)=>{const n=Array.from(e.values());for(const r of t?.values()??[])e.has(r.id)||r.projectDirectory===null||r.directory===null||n.push({id:r.id,name:r.name,state:"complete",projectDirectory:r.projectDirectory,directory:r.directory});return n},lk=()=>{const e=mi.c(3),t=Es(hh),n=Es(mh);let r;return e[0]!==n||e[1]!==t?(r=ph(t,n),e[0]=n,e[1]=t,e[2]=r):r=e[2],r};function hh(e){return e.spaces}function mh(e){return e.journey}const Da=500,tu=()=>{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}},uk=()=>tu(),Ge=(e,t)=>{if(!tu())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>Da&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Da)},gh=()=>{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__=gh);const dk=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}},yh=3,wh=3e4,Sh=32e3,bh=3600*1e3,vh=600*1e3,Th=200,kh=new Set([429,502,503,504]),ht=new Map,Ri=e=>JSON.stringify([G(),e]);function Eh(){const e=Date.now();for(const[t,n]of ht){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>bh&&ht.delete(t)}}typeof setInterval<"u"&&setInterval(Eh,vh).unref?.();function Ph(e){const t=Ri(e);let n=ht.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:wh},ht.set(t,n);ht.size>Th;){const r=ht.keys().next().value;if(!r)break;ht.delete(r)}return n}function Ah(e){e&&ht.delete(Ri(e))}function Ih(e,t){if(!e)return;const n=Ph(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),xh(t)&&n.consecutiveErrors>=yh&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function xh(e){return e!==void 0&&kh.has(e)}function Rh(e){const t=ht.get(Ri(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Sh*4),!1):!0:!1}function Ch(e){if(!(!e||!Rh(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const nu=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,Ma=/^(?:\/\/\?\/)?[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==="/"?"/":nu.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},Dh=e=>{if(e==="/"||nu.test(e)||Ma.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 Ma.test(n)?`${n}/`:n},Mh=e=>Ye(e)??"",_h="openchamber",Lh="auto",Fh=(e,t)=>e===_h&&t===Lh,jh=at(f().min(1),S({type:_("running")})),Uh=S({id:f().min(1),sessionID:f().min(1),action:f(),resources:F(f())}),Nh=S({id:f().min(1),sessionID:f().min(1),title:f()}),Bh=S({sessions:at(f().min(1),S({status:f(),lastUpdateAt:R()})),pending:at(f().min(1),S({permissions:F(Uh),forms:F(Nh)})).optional(),serverTime:R()});function fk(e,t){if(!(!e||!t))return e.find(n=>n.id===t)??e.find(n=>n.modelID===t)}function K(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const En={text:(e,t)=>`${e}:text:${t}`,reasoning:(e,t)=>`${e}:reasoning:${t}`,tool:e=>e,userText:e=>`${e}:text:0`,userFile:(e,t)=>`${e}:file:${t}`,userAgent:(e,t)=>`${e}:agent:${t}`},pk=e=>e==="completed"||e==="error",ru=e=>e.role==="user"||e.role==="assistant",hk=e=>e==="user"||e==="assistant",mk=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&ru(n))return n}},gk=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.info&&ru(n.info))return n}},yk=e=>e?.role==="assistant"&&e.time.completed===void 0,_a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Hh=14;let La=0,oo=0;const $h=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+=_a[t[r]%_a.length];return n},Fa=e=>{const t=Date.now();t!==La&&(La=t,oo=0),oo+=1;const n=BigInt(t)*BigInt(4096)+BigInt(oo),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}${$h(Hh)}`};function Hr(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 zh(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 ja(e){return!e||e.length===0?"":e.filter(t=>t.type==="text").map(t=>t.text).join(`
3
3
  `)}function Gh(e,t){if(!e)return;const n=e.filter(r=>r.type==="file");if(n.length!==0)return n.map((r,s)=>K({id:`${t.callID}:file:${s}`,sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name??void 0,url:r.uri}))}function qh(e){return e.message||e.type}function Kh(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:ja(e.state.content),metadata:e.state.metadata,time:{start:n,end:r},attachments:Gh(e.state.content,s)});break;case"error":o=K({status:"error",input:e.state.input,error:qh(e.state.error),output:ja(e.state.content)||void 0,metadata:e.state.metadata,time:{start:n,end:r}});break}return K({id:En.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:En.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:En.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(Kh(o,t));break}return n}function Jh(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 Yh(e){return e.source.type==="uri"?e.source.uri:`data:${e.mime};base64,${e.data}`}function Qh(e,t){const n=[];return e.text.length>0&&n.push({id:En.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:En.userFile(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name,url:Yh(r)}))}),e.agents?.forEach((r,s)=>{n.push({id:En.userAgent(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"agent",name:r.name})}),n}function Xh(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:Qh(e,{sessionID:t,messageID:e.id,created:e.time.created})};case"assistant":return{message:Jh(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:Zh(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 Zh(e){return e==="Infinity"||e==="-Infinity"||e==="NaN"?void 0:e}function Ua(e,t){return e.map(n=>Xh(n,t))}const em=e=>e.type==="document";function tm(e){const t={};for(const n of e)if(em(n))for(const[r,s]of Object.entries(n.info)){if(s===void 0)continue;const o=t[r];t[r]=Na(o)&&Na(s)?{...o,...s}:s}return t}function Na(e){return Object.prototype.toString.call(e)==="[object Object]"}const nm=e=>({...e,name:e.id,displayName:e.name}),Ba="/api",rm=1e4,sm=4e3,om=100,im=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 ft 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 am=S({_tag:f(),message:f().optional(),ref:f().optional()});function cm(e,t){if(t instanceof ft)return t;if(t instanceof Ed){if(t.reason==="UnexpectedStatus"){const s=t.cause?.status;return new ft(e,"unexpected status",{status:typeof s=="number"?s:void 0,cause:t})}const r=new ft(e,t.reason==="Transport"?"transport failure":t.reason,{cause:t.cause??t});return t.reason==="Transport"&&ca(t.cause)&&Oo(r),r}const n=am.safeParse(t);if(n.success)return new ft(e,n.data.message??n.data._tag,{status:im.get(n.data._tag),tag:n.data._tag,ref:n.data.ref,cause:t});if(t instanceof Error){const r=new ft(e,t.message,{cause:t});return ca(t)&&Oo(r),r}return new ft(e,String(t),{cause:t})}const lm=e=>e.tag==="InvalidRequestError"&&e.detail.startsWith("Skill not found"),um=e=>e instanceof ft&&e.status===404;async function O(e,t){try{return await t()}catch(n){throw cm(e,n)}}const dm=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ha=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(dm.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}},$a=()=>{try{return Pe().api("/api")}catch{return null}},su=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)}},fm=3e4,pm=e=>e.pathname.endsWith("/event")||e.pathname.endsWith("/log"),hm="x-opencode-directory",mm=e=>e.replace(/\/api\/*$/,"")||"/",io=e=>{const t=e.requestTimeoutMs??fm;return kd.make({baseUrl:mm(e.baseUrl),headers:e.directory?{[hm]: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(pm(s)||o==="POST")return g(n,r);const i=su(t),a=r?.signal!==void 0?r.signal:n instanceof Request?n.signal:void 0,c=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let l,u=null;if(a&&c)l=AbortSignal.any([a,i.signal]);else if(a){const m=new AbortController,y=()=>m.abort(a.reason),b=()=>m.abort(i.signal.reason);a.aborted?y():i.signal.aborted?b():(a.addEventListener("abort",y,{once:!0}),i.signal.addEventListener("abort",b,{once:!0}),u=()=>{a.removeEventListener("abort",y),i.signal.removeEventListener("abort",b)}),l=m.signal}else l=i.signal;const d=()=>{u?.(),i.cleanup()};let h=!1;try{const m=await g(n,{...r,signal:l});return h=m.body!==null,m}catch(m){throw i.signal.aborted&&!a?.aborted?new Error(`OpenCode request timed out after ${t}ms`):m}finally{!h||l.aborted?d():l.addEventListener("abort",d,{once:!0})}}})},gm=S({spaces:F(dh).optional()}),ym=S({reason:f().optional(),isDirectory:Ae().optional()}),dn=e=>e.replace(/\\/g,"/"),za=400,Wa=()=>{const e=Sr();return e&&e.runtime?.isDesktop&&e.files?e.files:null},$r=f().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),wm=S({home:$r,chatsRoot:$r.optional(),canonicalChatsRoot:$r.optional(),canonicalLegacyChatsRoot:$r.optional()}),ao=e=>JSON.parse(JSON.stringify(e)),Ga=e=>K({previous:e.previous??void 0,next:e.next??void 0}),qa=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 Sm{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=Ba){const r=$a()||t;this.baseUrl=Ha(r),this.client=io({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=$a(),n=Ha(t||Ba);this.baseUrl=n,this.client=io({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=io({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(zh)}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=ym.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&s?.isDirectory===!0)return"available";const o=ks(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??om,order:t.order,search:t.search,cursor:t.cursor,parentID:t.parentID})),o=t.global?gm.safeParse(s).data?.spaces:void 0;return{sessions:s.data.map(Hr),cursor:Ga(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&&Fh(t.model.providerID,t.model.id)?void 0:t?.model,location:r?{directory:r}:void 0,metadata:t?.metadata}));return Hr(s)}async getSession(t,n){const r=await O("session.get",()=>this.clientFor(n).session.get({sessionID:t}));return Hr(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=Ua(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:Ga({...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]=Ua([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 hi(async()=>{const{default:d}=await import("./vendor-heic2any-BHETom3P.js").then(h=>h.h);return{default:d}},__vite__mapDeps([0,1,2]))).default,r=t.url.indexOf(",");if(r===-1)return t;const s=t.url.substring(r+1),o=atob(s),i=new Uint8Array(o.length);for(let d=0;d<o.length;d++)i[d]=o.charCodeAt(d);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((d,h)=>{const m=new FileReader;m.onload=()=>d(m.result),m.onerror=h,m.readAsDataURL(c)});let u=t.filename;return u&&(u=u.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:u,url:l}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let n=t.url;if(t.url.startsWith("data:")){const r=t.url.indexOf(",");if(r!==-1){const s=t.url.substring(5,r),o=t.url.substring(r);n=`data:${s.replace(/^[^;,]+/,"text/plain")}${o}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toPromptFile(t){const n=await this.normalizeFilePart(t);return{uri:n.url,name:n.filename}}async applySendSelection(t,n,r,s){n.model&&(this.assertRuntimeUnchanged(s),await this.switchSessionModel(t,n.model,r)),n.agent&&(this.assertRuntimeUnchanged(s),await this.switchSessionAgent(t,n.agent,r))}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??Fa("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)");Ch(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?ao(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 ft)||!lm(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 Ih(t.providerID,a instanceof ft?a.status:void 0),a}return Ah(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?ao(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??Fa("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 Hr(r)}async getActiveSessionStatuses(t){try{const n=Ta(t)&&t?this.getScopedSdkClient(t):this.client,r=jh.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=Bh.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?ao(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 um(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 qa(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 qa(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=tm(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()+rm}),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=Ta(n)?this.client:i,[c,l,u]=await Promise.all([O("provider.list",()=>a.provider.list().then(d=>d.data)),O("model.list",()=>i.model.list().then(d=>d.data)),O("model.default",()=>i.model.default().then(d=>d.data)).catch(()=>{})]);return K({providers:c,models:l,default:u?{id:u.modelID,providerID:u.providerID}:void 0})})();this.providerCatalogInFlight.set(r,o);try{return await o}finally{this.providerCatalogInFlight.get(r)===o&&this.providerCatalogInFlight.delete(r)}}async listAgents(t){const n=this.resolveDirectory(t),r=n??"",s=this.listAgentsInFlight.get(r);if(s)return s;const o=O("agent.list",()=>this.clientFor(n).agent.list().then(i=>i.data.map(nm)));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=su(sm);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=Wa();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"?dn(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=Wa();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 k=w.entries.map(E=>({name:E.name,path:dn(E.path),isDirectory:!!E.isDirectory,isFile:!E.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(s,{entries:k,expiresAt:Date.now()+za}),k}const d=new URLSearchParams;t&&t.trim().length>0&&d.set("path",t),n?.respectGitignore&&d.set("respectGitignore","true");const h=d.toString(),m=await g(`${this.baseUrl}/fs/list${h?`?${h}`:""}`);if(!m.ok){const w=await m.json().catch(()=>({})),k=typeof w.error=="string"?w.error:"Failed to list directory";throw new Xt(k,{reason:ks(w.reason),status:m.status})}const y=await m.json();if(!y||!Array.isArray(y.entries))throw new Xt("Directory listing returned an invalid response",{reason:"invalid-response"});const b=y.entries;return this.listDirectoryCache.set(s,{entries:b,expiresAt:Date.now()+za}),b}catch(d){throw console.error("Failed to list directory contents:",d),d}})().finally(()=>{this.listDirectoryInFlight.get(s)===l&&this.listDirectoryInFlight.delete(s)});return this.listDirectoryInFlight.set(s,l),l}async searchFiles(t,n){const r=this.resolveDirectory(n?.directory),s=r?dn(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=dn(i.path),c=a.split("/").filter(Boolean).pop()||a,l=dn(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 vl();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 wm.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 Sm;let co=null,lo=null,uo=null;const Ka=new Set;let Va=!1;const ou=e=>{if(Ka.add(e),Va||typeof window>"u")return;Va=!0;const t=()=>{for(const n of Ka)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{}},bm=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,s=new Set;let o;const i=()=>{if(o=void 0,r.size===0&&s.size===0)return;const c=Array.from(r.entries()),l=Array.from(s);r.clear(),s.clear();for(const[u,d]of c)try{n.setItem(u,JSON.stringify(d,t?.replacer))}catch(h){console.error("Failed to persist deferred storage value",h),!r.has(u)&&!s.has(u)&&r.set(u,d)}for(const u of l)try{n.removeItem(u)}catch(d){console.error("Failed to remove deferred storage value",d),r.has(u)||s.add(u)}},a=()=>{o===void 0&&(o=setTimeout(i,0))};return ou(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()}}},Ci=e=>bm(()=>cu(),e),vm=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 ou(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}}},iu=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},Oi=()=>{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}}},au=e=>{const t=Oi(),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}}},Tm=()=>{const e=iu("localStorage");return e?au(e):Oi()},cu=()=>(co||(co=Tm()),co),kr=()=>(uo||(uo=vm(cu())),uo),km=()=>{const e=iu("sessionStorage");return e?au(e):Oi()},Em=()=>(lo||(lo=km()),lo),Pm={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.84375rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},wk={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function Ja(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const zr={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)"}}},fo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...zr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...zr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...zr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...zr.tool.inline})},Am=[{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'}],Im=[{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'}],lu=e=>Object.fromEntries(e.map(t=>[t.id,t])),xm=lu(Am),Rm=lu(Im),Cm="system",Om="system-mono",Dm=e=>typeof e=="string"&&e in xm,Mm=e=>typeof e=="string"&&e in Rm,$o="openchamber.mobileKeyboardMode",_m='meta[name="viewport"]',Ya="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Sk=()=>!0;function $s(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const Lm=e=>$s(e)==="resize-content"?`${Ya}, interactive-widget=resizes-content`:Ya,Fm=()=>{if(typeof window>"u")return"resize-content";try{return $s(localStorage.getItem($o))}catch{return"resize-content"}},uu=e=>{const t=$s(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem($o):localStorage.setItem($o,t)}catch{}return t},bk=e=>{const t=uu(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(_m);if(n instanceof HTMLMetaElement){const r=Lm(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},po=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),jm=new Set(["starting","running","stopping"]),Um=e=>!!e?.tabs.some(t=>bn(t.purpose)&&t.lifecycle!=="exited"),zo=512*1024,Nm=new TextEncoder,Bm=new TextDecoder,ho=e=>{const t=Nm.encode(e);if(t.byteLength<=zo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-zo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Bm.decode(r),byteLength:r.byteLength}},Xe=(e,t)=>`${e}\0${t}`,fn=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Hm="terminal-store";let Qa=!1,Xa=0;const $m=S({type:_("project-action"),actionId:f()}),Vn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Xa+=1,`tab-${Date.now().toString(36)}-${Xa.toString(36)}`),mo=e=>typeof e=="object"&&e!==null,bn=e=>e.type==="project-action",Wr=(e,t)=>bn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,zm=()=>Vn().replace(/^tab-/,"exec-"),Za=e=>e==="running"?"running":"exited",Wm=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),Gm=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()]},go={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},qm=e=>e.trim()||"Action",Km=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},ne=Mh,Ps=(e,t)=>`${e}\0${t}`,zn=(e,t,n,r)=>{e.set(Ps(t,n),r)},ec=(e,t,n,r)=>{if(!r)return!1;const s=Ps(t,n),o=e.actionMutationRevisions.get(s)??0,i=r.get(s)??0;return o>i},Vm=/^Terminal(?: (\d+))?$/,tc=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}`},vk=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&jm.has(e.lifecycle),Jm=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),Gr=(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}),yo=e=>({tabs:[e],activeTabId:e.id}),Re=(e,t)=>e.tabs.findIndex(n=>n.id===t);let wo=null,So=null;const Ym=e=>{if(So&&wo?.sessions===e.sessions&&wo.nextTabId===e.nextTabId)return So;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 wo={sessions:e.sessions,nextTabId:e.nextTabId},So=t,t},Qm=()=>{const e=Td(()=>Em());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))}},os=ct()(Dn(wr((e,t)=>({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=ne(n);r&&e(s=>{if(s.sessions.has(r))return s;const o=new Map(s.sessions),i=Vn(),a=Gr(i,"Terminal");return o.set(r,yo(a)),{sessions:o,nextTabId:s.nextTabId+1}})},getDirectoryState:n=>{const r=ne(n);return t().sessions.get(r)},getActiveTab:n=>{const r=ne(n),s=t().sessions.get(r);if(!s)return;const o=s.activeTabId;return o?s.tabs.find(i=>i.id===o)??s.tabs[0]:s.tabs[0]},getBuffer:(n,r)=>t().buffers.get(Xe(ne(n),r))??po,matchesActionExecution:(n,r,s)=>{const o=t().sessions.get(ne(n))?.tabs.find(i=>i.id===r);return!!(o&&bn(o.purpose)&&o.purpose.executionId===s)},captureStartedActionMutationRevisions:n=>{const r=ne(n),s=Ps(r,""),o=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(s)&&o.set(i,a);return o},createTab:n=>{const r=ne(n);if(!r)return"tab-invalid";const s=Vn();return e(o=>{const i=new Map(o.sessions),a=i.get(r),c=o.nextTabId+1,l=tc(a?.tabs??[]),u=Gr(s,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,yo(u)),{sessions:i,nextTabId:c}}),s},reconcileServerSessions:(n,r,s)=>{const o=ne(n);o&&e(i=>{const a=i.sessions.get(o);if(!a&&r.length===0)return i;const c=[...a?.tabs??[]];let l=i.buffers,u=!1,d=null;const h=new Set,m=new Set,y=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(Xe(o,c[0].id))?c[0]:null;y&&r.length>0&&(c.length=0);for(const C of Gm(r)){let ve=c.findIndex(N=>N.terminalSessionId===C.sessionId||N.id===C.sessionId);const ce=C.purpose,Ks=ce?.type==="project-action"&&ec(i,o,ce.actionId,s?.startedActionMutationRevisions);if(ce?.type==="project-action"){h.add(ce.actionId);const N=c.findIndex(Qe=>bn(Qe.purpose)&&Qe.purpose.actionId===ce.actionId);if(Ks){N>=0&&m.add(c[N].id);continue}ve<0&&(ve=N)}const xe=ce?.type==="project-action"?Wm(ce,C.status):{type:"terminal"};if(ve>=0){const N=c[ve];let Qe=N.purpose.type==="project-action"||ce?.type==="project-action"?Za(C.status):C.status;N.lifecycle==="stopping"&&C.status==="running"&&N.purpose.type==="project-action"&&xe.type==="project-action"&&N.purpose.executionId===xe.executionId&&(Qe="stopping");const ln=C.createdAt??N.createdAt,Rr=ce?.type==="project-action"&&(N.terminalSessionId!==C.sessionId||xe.type==="project-action"&&xe.executionId!==null&&(N.purpose.type!=="project-action"||N.purpose.executionId!==xe.executionId));if(Rr){const St=Xe(o,N.id);l=fn(l,Vs=>Vs===St)??l}const Un=ce?.type==="project-action"&&C.status==="running"&&(N.terminalSessionId!==C.sessionId||N.lifecycle!=="running"),Cr=N.purpose.type!==xe.type||N.purpose.type==="project-action"&&xe.type==="project-action"&&(N.purpose.actionId!==xe.actionId||N.purpose.executionId!==xe.executionId);if((N.terminalSessionId!==C.sessionId||N.lifecycle!==Qe||N.isConnecting!==!1||N.createdAt!==ln||Cr)&&(c[ve]={...N,terminalSessionId:C.sessionId,lifecycle:Qe,purpose:xe,isConnecting:!1,createdAt:ln},Rr&&Object.assign(c[ve],go),u=!0),Un){const St={tabId:N.id,createdAt:ln,index:ve};(!d||St.createdAt>d.createdAt||St.createdAt===d.createdAt&&St.index>d.index)&&(d=St)}m.add(N.id);continue}const Fn=ce?.type==="project-action"?qm(ce.actionId):y&&c.length===0?y.label:tc(c),jn=ce?.type==="project-action"?"play":null,jt={...Gr(C.sessionId,Fn),terminalSessionId:C.sessionId,lifecycle:ce?.type==="project-action"?Za(C.status):C.status,purpose:xe,iconKey:jn,createdAt:C.createdAt??Date.now()};if(c.push(jt),u=!0,ce?.type==="project-action"&&C.status==="running"){const N={tabId:jt.id,createdAt:jt.createdAt,index:c.length-1};(!d||N.createdAt>d.createdAt||N.createdAt===d.createdAt&&N.index>d.index)&&(d=N)}m.add(jt.id)}let b=u||!!(y&&r.length>0);const w=c.map(C=>!bn(C.purpose)||h.has(C.purpose.actionId)||m.has(C.id)||C.lifecycle==="starting"||ec(i,o,C.purpose.actionId,s?.startedActionMutationRevisions)||C.lifecycle==="exited"&&!C.isConnecting?C:(b=!0,{...C,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:C.purpose.actionId,executionId:null}})),k=a?.activeTabId??null,E=k&&w.some(C=>C.id===k)?k:w[0]?.id??null,L=E?w.find(C=>C.id===E):w[0],D=d&&!Jm(L)?d.tabId:E;if(!b&&a&&D===a.activeTabId&&w.length===a.tabs.length&&w.every((C,ve)=>C===a.tabs[ve]))return i;const J=new Map(i.sessions);return J.set(o,{tabs:w,activeTabId:D}),{sessions:J,buffers:l}})},setActiveTab:(n,r)=>{const s=ne(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);return!a||a.activeTabId===r||Re(a,r)<0?o:(i.set(s,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,s)=>{const o=ne(n),i=s.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const u=Re(l,r);if(u<0||l.tabs[u]?.label===i)return a;const d=[...l.tabs];return d[u]={...d[u],label:i},c.set(o,{...l,tabs:d}),{sessions:c}})},setTabIconKey:(n,r,s)=>{const o=ne(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const l=Re(c,r);if(l<0)return i;const u=s?.trim()||null;if(c.tabs[l]?.iconKey===u)return i;const d=[...c.tabs];return d[l]={...d[l],iconKey:u},a.set(o,{...c,tabs:d}),{sessions:a}})},closeTab:(n,r)=>{const s=ne(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=Re(a,r);if(c<0)return o;const l=a.tabs[c].purpose;let u=o.actionMutationRevisions,d=o.nextActionMutationRevision;l.type==="project-action"&&(u=new Map(u),zn(u,s,l.actionId,d),d+=1);const h={actionMutationRevisions:u,nextActionMutationRevision:d},m=a.tabs.filter(E=>E.id!==r),y=Xe(s,r),b=o.buffers.has(y)?fn(o.buffers,E=>E===y):null;if(m.length===0){const E=Vn(),L=Gr(E,"Terminal");i.set(s,yo(L));const D={sessions:i,nextTabId:o.nextTabId+1};return b&&(D.buffers=b),{...D,...h}}let w=a.activeTabId;a.activeTabId===r&&(w=m[Math.min(c,m.length-1)]?.id??m[0]?.id??null),i.set(s,{...a,tabs:m,activeTabId:w});const k={sessions:i};return b&&(k.buffers=b),{...k,...h}})},setTabPurpose:(n,r,s)=>{const o=ne(n);e(i=>{const a=i.sessions.get(o);if(!a)return i;const c=Re(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(s))return i;const u=[...a.tabs],d=s.type==="project-action"&&s.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==s.executionId);u[c]={...l,purpose:s},d&&Object.assign(u[c],go);const h=Xe(o,r),m=d?fn(i.buffers,w=>w===h)??i.buffers:i.buffers,y=new Map(i.sessions);if(y.set(o,{...a,tabs:u}),s.type!=="project-action")return{sessions:y};const b=new Map(i.actionMutationRevisions);return zn(b,o,s.actionId,i.nextActionMutationRevision),{sessions:y,buffers:m,actionMutationRevisions:b,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,s)=>{const o=ne(n),i=t().sessions.get(o);if(!i||Re(i,r)<0)return null;const a=zm();return e(c=>{const l=c.sessions.get(o);if(!l)return c;const u=Re(l,r);if(u<0)return c;const d=[...l.tabs];d[u]={...d[u],purpose:{type:"project-action",actionId:s,executionId:a},lifecycle:"starting",terminalSessionId:null,...go,isConnecting:!1};const h=new Map(c.sessions);h.set(o,{...l,tabs:d});const m=new Map(c.actionMutationRevisions);zn(m,o,s,c.nextActionMutationRevision);const y=Xe(o,r),b=fn(c.buffers,w=>w===y)??c.buffers;return{sessions:h,buffers:b,actionMutationRevisions:m,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,s,o)=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Re(l,r);if(u<0)return a;const d=l.tabs[u];if(!Wr(d,o?.expectedExecutionId))return a;const h=s!==null&&d.terminalSessionId!==s,m=s?"running":d.terminalSessionId?"exited":d.lifecycle,y={...d,terminalSessionId:s,lifecycle:m,isConnecting:!1},b=Xe(i,r),w=h&&a.buffers.has(b)?fn(a.buffers,L=>L===b):null,k=[...l.tabs];k[u]=y,c.set(i,{...l,tabs:k});const E={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(bn(d.purpose)){const L=new Map(a.actionMutationRevisions);zn(L,i,d.purpose.actionId,a.nextActionMutationRevision),E.actionMutationRevisions=L,E.nextActionMutationRevision=a.nextActionMutationRevision+1}return w&&(E.buffers=w),E})},setTabLifecycle:(n,r,s,o)=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Re(l,r);if(u<0||!Wr(l.tabs[u],o?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===s&&!d.isConnecting)return a;const h=[...l.tabs];if(h[u]={...d,lifecycle:s,isConnecting:!1},c.set(i,{...l,tabs:h}),d.purpose.type!=="project-action"||d.lifecycle===s)return{sessions:c};const m=new Map(a.actionMutationRevisions);return zn(m,i,d.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:m,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,s,o)=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Re(l,r);if(u<0||!Wr(l.tabs[u],o?.expectedExecutionId))return a;const d=[...l.tabs];return d[u]={...d[u],isConnecting:s},c.set(i,{...l,tabs:d}),{sessions:c}})},replaceBuffer:(n,r,s,o,i)=>{const a=ne(n);e(c=>{const l=c.sessions.get(a);if(!l||Re(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??po;if(d.lastSequence>o)return c;const h=ho(s),m=d.chunks[0]?.size;if(d.lastSequence===o&&d.byteLength===h.byteLength&&d.chunks.map(w=>w.data).join("")===h.text&&m?.cols===i?.cols&&m?.rows===i?.rows)return c;const y=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:h.text?[{id:y,data:h.text,byteLength:h.byteLength,...i?{size:i}:{}}]:[],byteLength:h.byteLength,lastSequence:o}),{buffers:b,nextChunkId:h.text?y+1:y}})},appendToBuffer:(n,r,s,o,i)=>{if(!s)return;const a=ne(n);e(c=>{const l=c.sessions.get(a);if(!l||Re(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??po;if(o!==void 0&&o<=d.lastSequence)return c;const h=c.nextChunkId,m=ho(s),y=i!==void 0&&i!==s?ho(i).text:void 0,b={id:h,data:m.text,...y!==void 0?{replayData:y}:{},byteLength:m.byteLength},w=[...d.chunks,b];let k=d.byteLength+b.byteLength;for(;k>zo&&w.length>1;){const L=w.shift();if(!L)break;k-=L.byteLength}const E=new Map(c.buffers);return E.set(u,{chunks:w,byteLength:k,lastSequence:o??d.lastSequence}),{buffers:E,nextChunkId:h+1}})},setTabPreviewUrl:(n,r,s,o={})=>{const i=ne(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Re(l,r);if(u<0)return a;const d=l.tabs[u];if(!Wr(d,o.expectedExecutionId))return a;const h=o.autoOpened??d.previewAutoOpened,m=o.locked??d.previewUrlLocked;if(d.previewUrl===s&&d.previewAutoOpened===h&&d.previewUrlLocked===m)return a;const y=[...l.tabs];return y[u]={...d,previewUrl:s,previewAutoOpened:h,previewUrlLocked:m},c.set(i,{...l,tabs:y}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const s=ne(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=Re(a,r);if(c<0)return o;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return o;const u=[...a.tabs];return u[c]={...l,previewAutoOpened:!0},i.set(s,{...a,tabs:u}),{sessions:i}})},removeDirectory:n=>{const r=ne(n);e(s=>{const o=new Map(s.sessions);o.delete(r);const i=Xe(r,""),a=fn(s.buffers,d=>d.startsWith(i)),c=Ps(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:Hm,storage:Qm(),partialize:Ym,merge:(e,t)=>{if(!mo(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"||!mo(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],h=new Map;for(const w of u){if(!mo(w))continue;const k=typeof w.id=="string"?w.id:null;if(!k)continue;const E=Km(k);E!==null&&(s=Math.max(s,E));const L=E===null?k:Vn();h.set(k,L);const D=$m.safeParse(w.purpose).data,J=D?{type:"project-action",actionId:D.actionId,executionId:null}:{type:"terminal"};d.push({id:L,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:J,createdAt:typeof w.createdAt=="number"?w.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(d.length===0)continue;const m=typeof l.activeTabId=="string"?l.activeTabId:null,y=m?h.get(m)??m:null,b=y?d.some(w=>w.id===y):!1;r.set(c,{tabs:d,activeTabId:b?y:d[0].id})}const o=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,i=Math.max(t.nextTabId,o,s+1);return{...t,sessions:r,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:i,hasHydrated:!0}}})));if(typeof window<"u"&&!Qa){Qa=!0;const e=os.persist,t=()=>{os.getState().hasHydrated||os.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Ze=20,Xm=8,nc=4096,Zm=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},xt=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Ct=(e,t)=>{const n=Q(t),r=Q(e);if(!n||!r)return!1;const s=xt(n),o=xt(r);return o===s||o.startsWith(`${s}/`)},Wn=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(m=>typeof m=="string").map(m=>Q(m)).filter(m=>m.length<=nc&&Ct(m,o)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(m=>typeof m=="string").map(m=>Q(m)).filter(m=>m.length<=nc&&Ct(m,o)))).slice(-500):[],l=typeof i.selectedPath=="string"?Q(i.selectedPath):null,u=l&&Ct(l,o)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>Zm)continue;const h=n[o];if(h){const m=Array.from(new Set([...h.openPaths,...a])),y=Array.from(new Set([...h.expandedPaths,...c])),b=h.selectedPath??u??m[0]??null;n[o]={openPaths:m,selectedPath:b,expandedPaths:y,touchedAt:Math.max(h.touchedAt,d)};continue}n[o]={openPaths:a,selectedPath:u,expandedPaths:c,touchedAt:d}}return 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},pn=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},eg=ct()(Dn(wr((e,t)=>({byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const s={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Wn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:s,byRoot:Wn(s[n]?.byRoot)}})},addOpenPath:(n,r,s)=>{const o=Q((n||"").trim()),i=Q((r||"").trim());!o||!i||!s?.allowOutsideRoot&&!Ct(i,o)||e(a=>{const c=a.byRoot[o],l=pn(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],h=l.selectedPath??i;if(c&&u&&c.selectedPath===h)return a;const m={...a.byRoot,[o]:{...l,openPaths:d,selectedPath:h}};return{byRoot:et(m,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=xt(o),l=y=>xt(y)===c,u=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!u)return i;const d=a.openPaths.filter(y=>!l(y)),h=u?d[0]??null:a.selectedPath,m={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:h,touchedAt:Date.now()}};return{byRoot:et(m,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=xt(o),l=c.endsWith("/")?c:`${c}/`,u=y=>{const b=xt(y);return b===c||b.startsWith(l)},d=a.openPaths.filter(y=>!u(y));if(d.length===a.openPaths.length)return i;const h=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,m={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:h,touchedAt:Date.now()}};return{byRoot:et(m,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=xt(o),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(h=>{const m=xt(h);return m!==c&&!m.startsWith(l)});if(u.length===a.expandedPaths.length)return i;const d={...i.byRoot,[s]:{...a,expandedPaths:u,touchedAt:Date.now()}};return{byRoot:et(d,Ze)}})},setSelectedPath:(n,r,s)=>{const o=Q((n||"").trim()),i=r?Q(r.trim()):null;!o||i&&!s?.allowOutsideRoot&&!Ct(i,o)||e(a=>{const c=a.byRoot[o],l=pn(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||!Ct(o,s)||e(i=>{const a=i.byRoot[s],c=pn(a),u=c.expandedPaths.includes(o)?c.expandedPaths.filter(h=>h!==o):[...c.expandedPaths,o];if(a&&a.expandedPaths===u&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:u}};return{byRoot: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]:{...pn(o),expandedPaths:[]}};return{byRoot:et(i,Ze)}})},expandPath:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||!Ct(o,s)||e(i=>{const a=i.byRoot[s],c=pn(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&&Ct(i,s));o.length!==0&&e(i=>{const a=i.byRoot[s],c=pn(a),l=new Set(c.expandedPaths),u=o.filter(h=>!l.has(h));if(u.length===0)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:et(d,Ze)}})}}),{name:"files-view-tabs-store",version:3,storage:Ci(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Wn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,Xm).map(([r,s])=>[r,{byRoot:Wn(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:Wn(r[s]?.byRoot)}}}),{name:"files-view-tabs-store"})),tg=["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"],ng=/^plugin:[a-z][a-z0-9-]*$/,rg=new Set(tg),sg=e=>ng.test(e),og=e=>rg.has(e)||sg(e),Tk=e=>e.slice(7),kk=e=>`plugin:${e}`,Di=["session","repository","usage","telemetry","subagents","mcp","pinned","contextSources"],Ek={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"},ig=/^ext:[a-z][a-z0-9-]*$/,Pk=e=>`ext:${e}`,ag=e=>ig.test(e),cg=it([X(Di),vd(["ext:",f().regex(/^[a-z][a-z0-9-]*$/)])]),du=e=>{const t=cg.safeParse(e);return t.success?t.data:null},As=e=>{const t=new Set;if(Array.isArray(e))for(const n of e){const r=du(n);r&&t.add(r)}for(const n of Di)t.add(n);return[...t]},Ak=(e,t)=>{const n=new Set(t),r=As(e).filter(o=>!ag(o)||n.has(o)),s=new Set(r);for(const o of t)s.has(o)||r.push(o);return r},Ik=(e,t)=>!e?.includes(t),xk=(e,t=[])=>e!=null&&Di.every(n=>e.includes(n))&&t.every(n=>e.includes(n)),Rk=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),fu=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e){const s=du(r);s&&n.add(s)}return t||n.delete("telemetry"),[...n]},lg=e=>Math.min(480,Math.max(200,Math.round(e))),ug=X(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),dg=S({widthByMode:at(f(),R().finite().optional().catch(void 0)).catch({}),widthFractionByMode:at(f(),R().positive().max(1).optional().catch(void 0)).catch({})}),pu="ask",rc=e=>e==="attach"||e==="inline"||e==="ask"?e:pu;function sc(e){return e==="vim"?"vim":"default"}const mt="all";function oc(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function ic(e){return e==="me"||e==="any"?e:"any"}function hu(e){return typeof e!="string"?mt:e.trim()||mt}function ac(e,t){const n=G();if(pl(n))return e;const r={...e};return t===mt?delete r[n]:r[n]=t,r}function fg(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=hu(r);s!==mt&&(t[n]=s)}return t}function cc(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const qr={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:""}},Kr=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,pg=e=>{if(!e||typeof e!="object")return!1;const t=e;return Kr(t.completion,qr.completion)&&Kr(t.error,qr.error)&&Kr(t.question,qr.question)&&Kr(t.subtask,qr.subtask)},hg=380,mg=320,gg=1e4,mu=12,lc=120,yg=280;let Vr=0;const wg=e=>de(e),de=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?t.startsWith("/")?"/":"":r},gu=e=>Number.isFinite(e)?Math.min(gg,Math.max(mg,Math.round(e))):hg,hr=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Is=e=>{const t=hr(e);return t&&wg(t)||null},xs=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>lc?t.slice(0,lc):t:null},Mi=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,yu=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},Sg=(e,t)=>(e==="file"||e==="browser")&&t||e,wu=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return Sg(e,t)},_i=(e,t)=>t===e?e:`${e}:${t}`,Li=e=>{const t=hr(e.targetPath),n=e.mode==="terminal"?Is(e.targetDirectory):null,r=wu(e.mode,t,e.dedupeKey);return{id:_i(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:yu(e.projectPlanRef),dedupeKey:r,label:xs(e.label),sessionTitleFallback:xs(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:Mi(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Su=(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))},bu=e=>{if(!Array.isArray(e))return[];const t=Oe(),n=[],r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s;if(typeof o.mode!="string"||!og(o.mode)||t&&o.mode==="browser")continue;const i=hr(typeof o.targetPath=="string"?o.targetPath:null),a=o.mode==="terminal"?Is(o.targetDirectory):null,c=typeof o.projectPlanId=="string"&&o.projectPlanId.trim()?o.projectPlanId.trim():null,l=yu(o.projectPlanRef);if(o.mode==="plan"&&c!==null!=(l!==null))continue;const u=wu(o.mode,i,typeof o.dedupeKey=="string"?o.dedupeKey:null),d=_i(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:xs(typeof o.label=="string"?o.label:null),sessionTitleFallback:xs(typeof o.sessionTitleFallback=="string"?o.sessionTitleFallback:null),readOnly:o.readOnly===!0,stagedDiff:o.stagedDiff===!0,diffScope:Mi(o.diffScope)??(o.stagedDiff===!0?"staged":"working"),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return n},Rn=(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=bu(e.tabs),n=Rn(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()}},bg=(e,t,n)=>{const r=n?.reveal!==!1,s=Li(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=Su(a,mu,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:Rn(l,c),touchedAt:Date.now()}},vg=(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:Rn(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=Li({mode:"file"});return{...e,tabs:[...s,l],activeTabId:l.id,isOpen:e.isOpen,touchedAt:Date.now()}}return{...e,tabs:s,activeTabId:c?.id??Rn(s,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},Tg=(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},kg=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),bo=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=de(r);if(!o||!s||typeof s!="object")continue;const i=s;let a=bu(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=[Li({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=Rn(a,c),u=Su(a,mu,l),d={},h={},m=dg.parse(s);for(const y of ug.options){const b=m.widthByMode[y],w=m.widthFractionByMode[y];b!==void 0&&(d[y]=gu(b)),w!==void 0&&(h[y]=w)}n[o]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:Rn(u,l),widthByMode:d,widthFractionByMode:h,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},T=ct()(Dn(wr((e,t)=>({theme:"system",runOverviewKey:null,parallelComposerRequest:null,isSidebarOpen:!0,sidebarWidth:yg,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:As([]),workStatusHiddenSectionsExplicit:!1,isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,openGuestPageId:null,worktreesPageProjectId:null,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsProjectPath:null,settingsProvidersConnectRequested:!1,settingsProvidersClassificationRequested:!1,settingsProvidersOpenRequested:null,settingsJumpRequest:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,streamingAutoFollowEnabled:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionWorkEnabled:!0,sessionWorkAutoOpen:!0,sessionGoalEnabled:!0,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:Cm,monoFont:Om,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Fm(),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:mt,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,permissionDefaultMode:"ask",agentMemoryFeatureAvailable:!1,routingFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:pu,enterToSend:!1,enterToSendConfigured:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,showSplitAssistantMessageActions:!1,allowPromptingSubagentSessions:!1,draftStartersVisible:!0,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:n=>{e({theme:n}),t().applyTheme()},toggleSidebar:()=>{e(n=>({isSidebarOpen:!n.isSidebarOpen}))},setSidebarOpen:n=>{e(r=>r.isSidebarOpen===n?r:{isSidebarOpen:n})},setSidebarWidth:n=>{e({sidebarWidth:n})},setContextRailOrder:n=>{const r=Array.isArray(n)?n.filter((s,o)=>typeof s=="string"&&s.trim()!==""&&n.indexOf(s)===o):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(n=>n.contextEditorTreeVisible&&!n.contextEditorVisible?{contextEditorTreeVisible:!1,contextEditorVisible:!0}:{contextEditorTreeVisible:!n.contextEditorTreeVisible})},toggleContextEditor:()=>{e(n=>n.contextEditorVisible&&!n.contextEditorTreeVisible?{contextEditorVisible:!1,contextEditorTreeVisible:!0}:{contextEditorVisible:!n.contextEditorVisible})},setContextEditorTreeWidth:n=>{Number.isFinite(n)&&e({contextEditorTreeWidth:lg(n)})},openContextSurface:(n,r)=>{const s=de((n||"").trim());if(!s)return;const o=t(),i=o.contextPanelByDirectory[s],a=i?.tabs??[],c=a.find(d=>d.id===i?.activeTabId)??null,l=()=>{if(r==="terminal"){const h=(a.find(m=>m.mode==="terminal")??null)?.targetDirectory??null;if(h){const m=os.getState().getDirectoryState(h);if(Um(m))return}o.openContextPanelTab(s,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),o.closeContextPanel(s);return}r==="file"&&!o.contextEditorTreeVisible&&e({contextEditorTreeVisible:!0});const u=a.filter(d=>d.mode===r);if(u.length>0){l();const d=u.reduce((h,m)=>m.touchedAt>=h.touchedAt?m:h);o.setActiveContextPanelTab(s,d.id);return}r!=="chat"&&o.openContextPanelTab(s,{mode:r})},openContextPanelTab:(n,r,s)=>{const o=de((n||"").trim());if(!o)return;const i=r.mode==="terminal"?{...r,targetDirectory:Is(r.targetDirectory)===o?null:Is(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]:bg(u,i,s)};return{contextPanelByDirectory:$t(d,20),contextEditorVisible:a||c.contextEditorVisible}})},openContextDiff:(n,r,s=!1,o=null)=>{const i=de((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=Mi(o)??(s?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const s=de((n||"").trim()),o=hr(r);!s||!o||(t().openContextPanelTab(s,{mode:"file",targetPath:o}),t().setPendingFileFocusPath(o),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,s,o)=>{const i=de((n||"").trim()),a=hr(r),c=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1,l=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:n=>{const r=de((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const s=de((n||"").trim()),o=(r||"").trim();!s||!o||Oe()||t().openContextPanelTab(s,{mode:"browser",targetPath:o,dedupeKey:o,label:null})},openAgentBrowserTab:(n,r)=>{const s=de((n||"").trim());if(!s||Oe())return null;Vr+=1;const o=`browser:agent:${Date.now()}-${Vr}`;return t().openContextPanelTab(s,{mode:"browser",targetPath:r.trim(),dedupeKey:o,label:null},{reveal:!1}),_i("browser",o)},openNewContextBrowserTab:n=>{const r=de((n||"").trim());!r||Oe()||(Vr+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${Vr}`,label:null}))},openContextBrowser:(n,r="",s)=>{const o=de((n||"").trim());if(!o||Oe())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(o,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},s)},setContextPanelTabTargetPath:(n,r,s)=>{const o=de((n||"").trim()),i=(r||"").trim();!o||!i||e(a=>{const c=a.contextPanelByDirectory[o];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[o]:kg(c,i,s)}}:a})},setActiveContextPanelTab:(n,r)=>{const s=de((n||"").trim()),o=(r||"").trim();!s||!o||e(i=>{const a=i.contextPanelByDirectory[s],c=Ht(a),l=c.tabs.find(h=>h.id===o);if(!l)return i;const u=l.mode==="file"&&!!l.targetPath;if(c.activeTabId===o&&c.isOpen)return u?{contextEditorVisible:!0}:i;const d={...i.contextPanelByDirectory,[s]:{...c,isOpen:!0,activeTabId:o,touchedAt:Date.now(),tabs:c.tabs.map(h=>h.id===o?{...h,touchedAt:Date.now()}:h)}};return{contextPanelByDirectory:$t(d,20),contextEditorVisible:u||i.contextEditorVisible}})},reorderContextPanelTabs:(n,r,s)=>{const o=de((n||"").trim()),i=(r||"").trim(),a=(s||"").trim();!o||!i||!a||e(c=>{const l=c.contextPanelByDirectory[o],u=Ht(l);if(!u.tabs.some(m=>m.id===i)||!u.tabs.some(m=>m.id===a))return c;const d=Tg(u,i,a);if(d.tabs===u.tabs)return c;const h={...c.contextPanelByDirectory,[o]:d};return{contextPanelByDirectory:$t(h,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const s=de((n||"").trim()),o=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!s||o.length===0)return;const i=o.map(a=>t().contextPanelByDirectory[s]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[s],l=Ht(c);if(!l.tabs.some(y=>o.includes(y.id)))return a;const u=vg(l,o),d=u.tabs.find(y=>y.id===u.activeTabId),h=u.isOpen&&d?.mode==="file"&&!d.targetPath,m={...a.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:$t(m,20),contextEditorTreeVisible:h||a.contextEditorTreeVisible}});for(const a of i)a.mode==="file"&&a.targetPath&&eg.getState().removeOpenPath(s,a.targetPath)},closeContextPanel:n=>{const r=de((n||"").trim());r&&e(s=>{const o=s.contextPanelByDirectory[r];if(!o||!o.isOpen)return s;const i={...s.contextPanelByDirectory,[r]:{...Ht(o),isOpen:!1}};return{contextPanelByDirectory:$t(i,20)}})},toggleContextPanelExpanded:n=>{const r=de((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=de((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=Ht(c),u=gu(s),d={...l.widthFractionByMode};o!==void 0&&Number.isFinite(o)&&o>0?d[r]=Math.min(1,u/o):delete d[r];const h={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:$t(h,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(s=>s.workStatusExpandedSections[n]===r?s:{workStatusExpandedSections:{...s.workStatusExpandedSections,[n]:r}})},setMessageQueueExpanded:n=>{e(r=>r.messageQueueExpanded===n?r:{messageQueueExpanded:n})},setWorkStatusScrollTop:n=>{e({workStatusScrollTop:Math.max(0,n)})},setWorkStatusPanelEnabled:n=>{e({workStatusPanelEnabled:n})},setWorkStatusPanelVisible:n=>{e(r=>r.workStatusPanelVisible===n?r:{workStatusPanelVisible:n})},setWorkStatusPanelFits:n=>{e(r=>r.workStatusPanelFits===n?r:n?{workStatusPanelFits:!0,workStatusOverlayOpen:!1}:{workStatusPanelFits:!1})},setWorkStatusOverlayOpen:n=>{e(r=>r.workStatusOverlayOpen===n?r:{workStatusOverlayOpen:n})},setWorkStatusSectionVisible:(n,r)=>{e(s=>{const o=s.workStatusHiddenSections,i=o.includes(n);return r===!i?s:{workStatusHiddenSectionsExplicit:!0,workStatusHiddenSections:r?o.filter(a=>a!==n):[...o,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)],workStatusHiddenSectionsExplicit:!0})},setWorkStatusSectionOrder:n=>{e({workStatusSectionOrder:As(n)})},setContextRailSurfaceVisible:(n,r)=>{e(s=>{const o=s.contextRailHiddenSurfaces,i=o.includes(n);return r===!i?s:{contextRailHiddenSurfaces:r?o.filter(a=>a!==n):[...o,n]}})},setContextRailHiddenSurfaces:n=>{e({contextRailHiddenSurfaces:[...new Set(n)]})},setSessionSwitcherOpen:n=>{t().isSessionSwitcherOpen!==n&&e({isSessionSwitcherOpen:n})},setSessionDropdownOpen:n=>{t().isSessionDropdownOpen!==n&&e({isSessionDropdownOpen:n})},setPendingDiffFile:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?s:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:s})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=t();return n&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),n},setIsMobile:n=>{e({isMobile:n})},toggleCommandPalette:()=>{e(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{e({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{e(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{e({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{e({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{e({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{e({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{e({isSessionCreateDialogOpen:n})},setScheduledTasksDialogOpen:n=>{e(n?{isScheduledTasksDialogOpen:!0,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isUsageStatsPageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isArchivePageOpen:!1})},setUsageStatsPageOpen:n=>{e(n?{isUsageStatsPageOpen:!0,isArchivePageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,runOverviewKey:null,openGuestPageId:null}:{isUsageStatsPageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,runOverviewKey:null,openGuestPageId:null}:{worktreesPageProjectId:null})},setOpenGuestPage:n=>{e(n?{openGuestPageId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,runOverviewKey:null}:{openGuestPageId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.isUsageStatsPageOpen&&!n.worktreesPageProjectId&&!n.runOverviewKey&&!n.openGuestPageId||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,runOverviewKey:null,openGuestPageId:null})},setSettingsDialogOpen:n=>{e(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:n=>{e({isNewWorktreeDialogOpen:n})},setModelSelectorOpen:n=>{e({isModelSelectorOpen:n})},setSidebarSection:n=>{e({sidebarSection:n})},setSettingsPage:n=>{e({settingsPage:n})},setSettingsProvidersClassificationRequested:n=>{e({settingsProvidersClassificationRequested:n})},setSettingsProvidersOpenRequested:n=>{e({settingsProvidersOpenRequested:n})},requestSettingsJump:(n,r=null)=>{e({settingsJumpRequest:{page:n,itemId:r}})},clearSettingsJumpRequest:()=>{e({settingsJumpRequest:null})},setSettingsProvidersConnectRequested:n=>{e({settingsProvidersConnectRequested:n})},setSettingsProjectPath:n=>{const r=n?.trim();e({settingsProjectPath:r||null})},setSettingsProjectsSelectedId:n=>{e({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{e({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{e({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{e({showReasoningTraces:n})},setStreamingAutoFollowEnabled:n=>{e({streamingAutoFollowEnabled:n})},setSessionRecapEnabled:n=>{e({sessionRecapEnabled:n})},setSessionSuggestionEnabled:n=>{e({sessionSuggestionEnabled:n})},setSessionWorkEnabled:n=>{e({sessionWorkEnabled:n})},setSessionWorkAutoOpen:n=>{e({sessionWorkAutoOpen:n})},setSessionGoalEnabled:n=>{e({sessionGoalEnabled:n})},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(Pm);if(s===1){r.style.removeProperty("font-size");for(const[i]of o)r.style.removeProperty(Ja(i));return}r.style.fontSize=`${s*100}%`;for(const[i]of o)r.style.removeProperty(Ja(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:oc(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:ic(n)})},setLinearIssueListTeamId:n=>{const r=hu(n);e(s=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:ac(s.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=G();e(r=>({linearIssueListTeamId:pl(n)?mt:r.linearIssueListTeamIdByRuntime[n]??mt}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:cc(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:mt,linearIssueListTeamIdByRuntime:ac(n.linearIssueListTeamIdByRuntime,mt),linearIssueListPriority:"all"}))},setLinearIssueFocus:n=>{const r=n?.trim()??"";e({linearIssueFocus:r||null})},setInputBarOffset:n=>{e({inputBarOffset:n})},setMobileKeyboardMode:n=>{e(r=>r.mobileKeyboardMode===n?r:{mobileKeyboardMode:n})},toggleFavoriteModel:(n,r)=>{e(s=>s.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:s.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...s.favoriteModels]})},reorderFavoriteModel:(n,r,s,o)=>{e(i=>{const a=i.favoriteModels.findIndex(d=>d.providerID===n&&d.modelID===r),c=i.favoriteModels.findIndex(d=>d.providerID===s&&d.modelID===o);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[u]=l.splice(a,1);return u?(l.splice(c,0,u),{favoriteModels:l}):i})},setProviderOrder:n=>{e(r=>{const s=n.filter(i=>typeof i=="string"&&i.length>0),o=r.providerOrder;return o.length===s.length&&o.every((i,a)=>i===s[a])?r:{providerOrder:s}})},toggleHiddenModel:(n,r)=>{e(s=>s.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:s.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...s.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},hideAllModels:(n,r)=>{e(s=>{const o=s.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...o]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(s=>s.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>s.collapsedModelProviders.includes(r)?{collapsedModelProviders:s.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...s.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const s=Array.from(new Set(n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)));s.length!==0&&e(o=>{const i=new Set(s),a=o.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...s]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},addRecentModel:(n,r)=>{e(s=>{const o=s.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...o].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>{if(s.recentAgents.includes(r))return s;const o=s.recentAgents;return{recentAgents:[r,...o].slice(0,5)}})},addRecentEffort:(n,r,s)=>{const o=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!o||!i)return;const a=`${o}/${i}`,c=typeof s=="string"&&s.trim().length>0?s.trim():"default";e(l=>{const u=l.recentEfforts[a]??[];if(u.includes(c))return l;const d=u;return{recentEfforts:{...l.recentEfforts,[a]:[c,...d].slice(0,5)}}})},applyTheme:()=>{const{theme:n}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(s)}else r.classList.add(n)},setRunOverviewKey:n=>{e(n?{runOverviewKey:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,openGuestPageId:null}:{runOverviewKey:null})},requestParallelComposer:(n="")=>{e(r=>({parallelComposerRequest:{id:(r.parallelComposerRequest?.id??0)+1,prompt:n},isSessionSwitcherOpen:!1}))},consumeParallelComposerRequest:n=>{t().parallelComposerRequest?.id===n&&e({parallelComposerRequest:null})},setTimelineDialogOpen:n=>{e({isTimelineDialogOpen:n})},setPromptNavigatorPanelOpen:n=>{e({isPromptNavigatorPanelOpen:n})},togglePromptNavigatorPanel:()=>{e(n=>({isPromptNavigatorPanelOpen:!n.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:n=>{e({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{e({nativeNotificationsEnabled:n})},setNotificationMode:n=>{e({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{e({showTerminalQuickKeysOnDesktop:n})},setSessionTabsEnabled:n=>{e({sessionTabsEnabled:n})},setNotifyOnSubtasks:n=>{e({notifyOnSubtasks:n})},setDockBadgeEnabled:n=>{e({dockBadgeEnabled:n})},setAlwaysShowScrollbars:n=>{e({alwaysShowScrollbars:n})},setNotifyOnCompletion:n=>{e({notifyOnCompletion:n})},setNotifyOnError:n=>{e({notifyOnError:n})},setNotifyOnQuestion:n=>{e({notifyOnQuestion:n})},setNotificationTemplates:n=>{e(r=>({notificationTemplates:typeof n=="function"?n(r.notificationTemplates):n}))},setSummarizeLastMessage:n=>{e({summarizeLastMessage:n})},setSummaryThreshold:n=>{e({summaryThreshold:n})},setSummaryLength:n=>{e({summaryLength:n})},setMaxLastMessageLength:n=>{e({maxLastMessageLength:n})},setPersistChatDraft:n=>{e({persistChatDraft:n})},setShowOpenCodeUpdateNotifications:n=>{e({showOpenCodeUpdateNotifications:n})},setAgentControlToolEnabled:n=>{e({agentControlToolEnabled:n})},setAgentWebToolEnabled:n=>{e({agentWebToolEnabled:n})},setBrowserProvider:n=>{e({browserProvider:n})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setIsolatedSpacesEnabled:n=>{e({isolatedSpacesEnabled:n})},setPermissionDefaultMode:n=>{e({permissionDefaultMode:n})},setAgentNotifyToolEnabled:n=>{e({agentNotifyToolEnabled:n})},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:rc(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:sc(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:Ci(),version:21,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<21&&n.workStatusHiddenSectionsExplicit!==!0&&(n.workStatusHiddenSections=Array.isArray(n.workStatusHiddenSections)?n.workStatusHiddenSections.filter(r=>r!=="telemetry"):[],n.workStatusHiddenSectionsExplicit=!1),t<16&&(delete n.activeMainTab,delete n.activeSurface),t<17&&delete n.expandedEditorToolbar,t<18&&delete n.shortcutOverrides,t<14){const r=n.contextPanelByDirectory;if(r&&typeof r=="object")for(const s of Object.values(r)){if(!s||typeof s!="object")continue;const o=s,i=o.widthByMode;if(i&&typeof i=="object"){const l=i;l.preview!==void 0&&(l.browser===void 0&&(l.browser=l.preview),delete l.preview)}if(!Array.isArray(o.tabs))continue;const a=new Set,c=[];for(const l of o.tabs){if(!l||typeof l!="object")continue;const u=l;if(u.mode!=="preview"){typeof u.id=="string"&&a.add(u.id),c.push(u);continue}const d=typeof u.targetPath=="string"?u.targetPath:"",h=typeof u.dedupeKey=="string"&&u.dedupeKey.trim()?u.dedupeKey.trim():d||"browser",m=h==="browser"?"browser":`browser:${h}`;a.has(m)||(a.add(m),c.push({...u,mode:"browser",id:m,dedupeKey:h}))}if(o.tabs=c,typeof o.activeTabId=="string"&&o.activeTabId.startsWith("preview")){const l=c.find(u=>typeof u.id=="string");o.activeTabId=l&&typeof l.id=="string"?l.id:null}}}if(t<13&&typeof n.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const s=localStorage.getItem("openchamber:files:auto-save-enabled");s!==null&&(r=s!=="false",localStorage.removeItem("openchamber:files:auto-save-enabled"))}}catch{r=!0}n.autoSaveEnabled=r}if(t<12&&(n.desktopWindowControlsPosition==="auto"||n.desktopWindowControlsPosition==null)&&(n.desktopWindowControlsPosition="right"),t<11&&n.terminalFontSize===13&&(n.terminalFontSize=14),t<10&&delete n.diffViewMode,t<9&&((!n.workStatusExpandedSections||typeof n.workStatusExpandedSections!="object")&&(n.workStatusExpandedSections={}),(typeof n.workStatusScrollTop!="number"||!Number.isFinite(n.workStatusScrollTop))&&(n.workStatusScrollTop=0),typeof n.workStatusPanelEnabled!="boolean"&&(n.workStatusPanelEnabled=!0),Array.isArray(n.workStatusHiddenSections)||(n.workStatusHiddenSections=[]),(typeof n.notesPanelHeight!="number"||!Number.isFinite(n.notesPanelHeight))&&(n.notesPanelHeight=112)),t<1&&pg(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=bo(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=bo(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=bo(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=oc(n.linearIssueListStatus),n.linearIssueListAssignee=ic(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=fg(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=cc(n.linearIssueListPriority),n.fileEditorKeymap=sc(n.fileEditorKeymap),n.largeTextPasteBehavior=rc(n.largeTextPasteBehavior),n.toolJsonViewMode!=="summary"&&n.toolJsonViewMode!=="formatted"&&n.toolJsonViewMode!=="raw"&&(n.toolJsonViewMode="summary"),typeof n.autoSaveEnabled!="boolean"&&(n.autoSaveEnabled=!0),n.contextRailHiddenSurfaces=Array.isArray(n.contextRailHiddenSurfaces)?n.contextRailHiddenSurfaces.filter(r=>typeof r=="string"&&r.trim()!==""):[],n.contextRailOrder=Array.isArray(n.contextRailOrder)?n.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""):[],n},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextRailHiddenSurfaces:e.contextRailHiddenSurfaces,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorVisible:e.contextEditorVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,notesPanelHeight:e.notesPanelHeight,workStatusExpandedSections:e.workStatusExpandedSections,messageQueueExpanded:e.messageQueueExpanded,workStatusScrollTop:e.workStatusScrollTop,workStatusPanelEnabled:e.workStatusPanelEnabled,workStatusHiddenSections:e.workStatusHiddenSections,workStatusSectionOrder:e.workStatusSectionOrder,workStatusHiddenSectionsExplicit:e.workStatusHiddenSectionsExplicit,isSessionSwitcherOpen:e.isSessionSwitcherOpen,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,streamingAutoFollowEnabled:e.streamingAutoFollowEnabled,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,sessionWorkEnabled:e.sessionWorkEnabled,sessionWorkAutoOpen:e.sessionWorkAutoOpen,sessionGoalEnabled:e.sessionGoalEnabled,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,permissionDefaultMode:e.permissionDefaultMode,agentMemoryViewedAt:e.agentMemoryViewedAt,projectContextSidebarWidth:e.projectContextSidebarWidth,inputSpellcheckEnabled:e.inputSpellcheckEnabled,largeTextPasteBehavior:e.largeTextPasteBehavior,enterToSend:e.enterToSend,enterToSendConfigured:e.enterToSendConfigured,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,inputBarOffset:e.inputBarOffset,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,allowPromptingSubagentSessions:e.allowPromptingSubagentSessions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Eg=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},Pg=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Ag=e=>{const t=T.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Ig=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=Pg(t);return Eg(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},xg=768,Rg=800,Cg=()=>{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"},vu=()=>{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<=xg&&Cg()},Tu=()=>{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:br()?"mobile":Be()||Oe()?"desktop":vu()?"mobile":"desktop"},Ck=()=>{const e=Tu();return typeof window<"u"&&(window.__OPENCHAMBER_SURFACE__=e),e},Dg=()=>Tu()==="mobile",Ok=()=>{if(typeof window>"u")return()=>{};if(br()||Be()||Oe())return()=>{};if(Og())return()=>{};let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null;const n=window.__OPENCHAMBER_SURFACE__,r=vu()?"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)}},ku="surface",Fi=()=>{try{if(Oe())return"vscode";if(Be())return"desktop";if(br()||Dg())return"mobile"}catch{}return"web"},Mg=()=>Fi()==="mobile"?"timeline":"projects",_g=(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},Wo=ct()(wr(e=>({animatedActivityIndicators:!1,setAnimatedActivityIndicators:t=>e({animatedActivityIndicators:t}),projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sidebarViewMode:Mg(),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:_g})),Eu="directoryTreeShowHidden",Go="directory-show-hidden-change",qo=()=>{if(typeof window>"u")return!0;try{const e=kr().getItem(Eu);return e===null?!0:e==="true"}catch{return!0}},Lg=()=>{typeof window>"u"||window.dispatchEvent(new Event(Go))},Fg=()=>qo(),jg=(e,t={})=>{if(!(typeof window>"u")){try{kr().setItem(Eu,e?"true":"false"),Lg()}catch{}t.persist!==!1&&gt({directoryShowHidden:e})}},Dk=()=>{const e=mi.c(2),[t,n]=ds.useState(qo);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(qo())};return window.addEventListener("storage",o),window.addEventListener(Go,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(Go,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),ds.useEffect(r,s),t},Pu=[{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"}],Ug=new Map(Pu.map(e=>[e.name,e])),Mk=e=>Ug.get(e),_k=Pu.map(e=>({type:"command",name:e.name})),Lk="terminal-box",Fk="book-open",jk=e=>`${e.type}:${e.name}`,Uk=(e,t)=>e.type===t.type&&e.name===t.name,Nk=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Ng=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},Au="filesViewShowGitignored",Ko="files-view-show-gitignored-change",Vo=()=>{if(typeof window>"u")return!1;try{return kr().getItem(Au)==="true"}catch{return!1}},Bg=()=>{typeof window>"u"||window.dispatchEvent(new Event(Ko))},Hg=()=>Vo(),$g=(e,t={})=>{if(!(typeof window>"u")){try{kr().setItem(Au,e?"true":"false"),Bg()}catch{}t.persist!==!1&&gt({filesViewShowGitignored:e})}},Bk=()=>{const e=mi.c(2),[t,n]=ds.useState(Vo);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(Vo())};return window.addEventListener("storage",o),window.addEventListener(Ko,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(Ko,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),ds.useEffect(r,s),t},Iu="session",xu=40,zg=1,Wg=100,Ru=e=>e==="global"||e==="session",ji=e=>e!=null&&Number.isInteger(e)&&e>=zg&&e<=Wg,Gg=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Ui=e=>e==="auto"||typeof e=="string"&&Gg.includes(e),vn="openchamber-input-history.v1",qg=8,Kg=50,Vg=[40,25,10,5,1],vo=Object.freeze([]);let pt=null,uc=0;const sr=(e=Iu,t=xu)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Cu=()=>(uc+=1,Date.now()*1e3+uc),Ou=e=>JSON.stringify([e]),Jo=(e,t,n)=>JSON.stringify([e,t,n]),Ni=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},Jg=()=>{const e=Ni(),t=qe?JSON.stringify(as(qe.base)):pt;if(!e)return t;try{return e.getItem(vn)??(qe?null:pt)}catch{return t}},dc=at(f(),ge()),Yg=S({key:f().min(1),source:it([_("file-url"),_("vscode-file")]),filename:f().min(1),mimeType:f().min(1),size:R().finite().nonnegative(),reference:f().min(1)}),Qg=S({text:f(),attachmentKeys:F(f()),restorableAttachments:F(Yg),submittedAt:R().finite().nonnegative()}),Xg=S({touchedAt:R().finite().nonnegative(),entries:F(ge())}),Zg=(e,t)=>{try{const n=JSON.parse(e),s=(t===1?ra([f().trim().min(1)]):ra([f().trim().min(1),f().trim().min(1),f().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}},fc=(e,t)=>{const n=[];for(const[r,s]of Object.entries(e)){if(!Zg(r,t))continue;const o=Xg.safeParse(s);if(!o.success)continue;const i=o.data.entries.map(a=>Qg.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:o.data.touchedAt,entries:i}])}return Object.fromEntries(n)},ey=()=>{const e=Jg();if(e===null)return sr();try{const t=JSON.parse(e),n=S({version:_(1),entryLimit:R().int().optional(),scope:it([_("global"),_("session")]).optional(),global:dc.default({}),session:dc.default({})}).safeParse(t);return n.success?{entryLimit:ji(n.data.entryLimit)?n.data.entryLimit:xu,scope:n.data.scope??Iu,globalBuckets:fc(n.data.global,1),sessionBuckets:fc(n.data.session,3)}:sr()}catch{const t=Ni();if(t)try{t.removeItem(vn)}catch{}return pt=null,sr()}};let qe=null,is=sr();const pc=(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},Jn=()=>{const e=ey();if(is=e,!qe)return e;const{base:t,value:n}=qe;return Yo({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:pc(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:pc(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},Du=(e,t)=>e.slice(Math.max(0,e.length-t)),hc=(e,t,n)=>{const r=Object.entries(e).map(([s,o])=>[s,{touchedAt:o.touchedAt,entries:Du(o.entries,n)}]).sort((s,o)=>o[1].touchedAt-s[1].touchedAt).slice(0,t);return Object.fromEntries(r)},Yo=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:hc(e.globalBuckets,qg,t),sessionBuckets:hc(e.sessionBuckets,Kg,t)}),as=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),mc=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Yn=e=>{const t=Yo(e),n=JSON.stringify(as(t));qe={base:is,value:t};const r=Ni();if(!r)return pt=n,t;try{return r.setItem(vn,n),qe=null,pt=n,t}catch(i){if(!(i instanceof Error)||!mc(i))return pt=n,t}try{r.removeItem(vn)}catch{}for(const i of Vg){const a=Yo(t,i),c=JSON.stringify(as(a));try{return r.setItem(vn,c),qe=null,pt=c,a}catch(l){if(!(l instanceof Error)||!mc(l))return qe={base:is,value:a},pt=c,a}}const s=sr(t.scope,t.entryLimit),o=JSON.stringify(as(s));try{r.setItem(vn,o),qe=null}catch{qe={base:is,value:s}}return pt=o,s},ty=(e,t,n)=>{const r=e.trim(),s=Ye(t),o=n.trim();return!r||!s||!o?null:{runtimeKey:r,directory:s,sessionId:o}},Mu=e=>e.source==="vscode"&&e.vscodeSource==="file"?Ye(e.vscodePath??null):e.dataUrl.trim()||null,ny=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Qo=e=>{const t=Mu(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("|")},ry=e=>{const t=Mu(e);return!t||!ny(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Qo(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Qo(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},sy=(e,t)=>({text:e,attachmentKeys:t.map(Qo),restorableAttachments:t.map(ry).filter(n=>n!==null)}),oy=(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}),iy=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&oy(e.restorableAttachments,t.restorableAttachments),gc=(e,t,n,r)=>{const s=e?[...e.entries]:[];for(const o of t){const i=s.at(-1);iy(i,o)||s.push({text:o.text,attachmentKeys:[...o.attachmentKeys],restorableAttachments:o.restorableAttachments.map(a=>({...a})),submittedAt:Cu()})}return{touchedAt:n,entries:Du(s,r)}},ay=Yn(Jn()),Qn=ct(e=>({...ay,applyEntryLimit:t=>{ji(t)&&e(n=>{const r=Jn();if(r.entryLimit===t)return{...n,...r};const s=Yn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},applyScope:t=>{Ru(t)&&e(n=>{const r=Jn();if(r.scope===t)return{...n,...r};const s=Yn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const s=Jn(),o=Cu(),i=Ou(t.runtimeKey),a=Jo(t.runtimeKey,t.directory,t.sessionId),c=Yn({entryLimit:s.entryLimit,scope:s.scope,globalBuckets:{...s.globalBuckets,[i]:gc(s.globalBuckets[i],n,o,s.entryLimit)},sessionBuckets:{...s.sessionBuckets,[a]:gc(s.sessionBuckets[a],n,o,s.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=Jn(),s=Jo(t.runtimeKey,t.directory,t.sessionId);if(!(s in r.sessionBuckets))return{...n,...r};const o={...r.sessionBuckets};delete o[s];const i=Yn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:o});return{...n,...i}})}})),Hk=(e,t)=>t?e.scope==="session"?e.sessionBuckets[Jo(t.runtimeKey,t.directory,t.sessionId)]?.entries??vo:e.globalBuckets[Ou(t.runtimeKey)]?.entries??vo:vo,cy=S({text:f(),prefix:f(),suffix:f(),start:R()}),yc=32,ly=200,uy="[data-chat-quote-root]";function $k(e,t){return e.querySelector(`[data-message-id="${CSS.escape(t)}"]`)?.querySelector(uy)??null}function wc(e,t,n){const r=e.ownerDocument.createRange();return r.setStart(e,0),r.setEnd(t,n),r.toString().length}function zk(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))return null;const n=e.textContent??"",r=wc(e,t.startContainer,t.startOffset),s=wc(e,t.endContainer,t.endOffset),o=n.slice(r,s);return o.trim()?{text:o,prefix:n.slice(Math.max(0,r-yc),r),suffix:n.slice(s,s+yc),start:r}:null}function dy(e,t){if(!t.text)return null;const n=[];for(let s=e.indexOf(t.text);s!==-1&&n.length<ly;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 _u(e,t){for(let n=e.firstChild;n;n=n.nextSibling)n.nodeType===3?t.push(n):_u(n,t);return t}function Wk(e,t){const n=dy(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 _u(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 Gk(e){return{text:e.trim(),prefix:"",suffix:"",start:0}}const fy=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,py=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
4
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}},hy=(e,t)=>{const n=t.map(py).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
5
  `).map((a,c)=>` ${o.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`