@openchamber/web 2.0.0 → 2.0.1

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 (162) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-hJbl3JX4.js → CodeMirrorCommentWidgets-zm3C1FvM.js} +1 -1
  2. package/dist/assets/DiffView-DNExNi1z.js +4 -0
  3. package/dist/assets/FilesView-DUCLmHBi.js +17 -0
  4. package/dist/assets/{GitView-DY4pelsO.js → GitView-Bz9z6gZA.js} +4 -4
  5. package/dist/assets/{GuestAttachDialog-D6mHDTB2.js → GuestAttachDialog-UGp4KDlK.js} +1 -1
  6. package/dist/assets/GuestSurfacePane-B3pdB_2u.js +1 -0
  7. package/dist/assets/{JsonTreeView-DEXI2NvJ.js → JsonTreeView-7lVecnZl.js} +1 -1
  8. package/dist/assets/{LinearIssuesView-BTNc-4dN.js → LinearIssuesView-CTGRS9Vq.js} +1 -1
  9. package/dist/assets/{MarkdownImageGallery-wcUUcf8l.js → MarkdownImageGallery-DQk5adUs.js} +1 -1
  10. package/dist/assets/MarkdownRendererImpl-DPF8fZpX.js +12 -0
  11. package/dist/assets/{OnboardingScreen-FJUreEgI.js → OnboardingScreen-CBx6cXPP.js} +1 -1
  12. package/dist/assets/{PatchDiff-C0oOkKnO.js → PatchDiff-D7VVpR_l.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-asuSQAsf.js → PierreDiffViewer-Gbfks1pk.js} +3 -3
  14. package/dist/assets/{PlanView-DGbasNHP.js → PlanView-CPSK0x97.js} +4 -4
  15. package/dist/assets/PluginPane-BIGsUx69.js +3 -0
  16. package/dist/assets/SettingsView-Dql7z6Ww.js +30 -0
  17. package/dist/assets/{SettingsWindow-By4cqnqy.js → SettingsWindow-D6oi-UmV.js} +1 -1
  18. package/dist/assets/{SubmoduleDiffSummary-C0P2tXLU.js → SubmoduleDiffSummary-BXA0FAWj.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-Cayc-yIM.js → ToolOutputDialog-BQJsSbDm.js} +6 -6
  20. package/dist/assets/{ToolPartDiffPreview-B0jmpPQz.js → ToolPartDiffPreview-FY9w0TVT.js} +2 -2
  21. package/dist/assets/{VirtualizedFileDiff-DsOpvWZD.js → VirtualizedFileDiff-B9YhAya5.js} +1 -1
  22. package/dist/assets/{WalkthroughView-CCakjyn9.js → WalkthroughView-CmFgOUFN.js} +2 -2
  23. package/dist/assets/{appThemeRegistry-Bw5oTm41.js → appThemeRegistry-BebxalUt.js} +1 -1
  24. package/dist/assets/changesTree-CePHbFcj.js +1 -0
  25. package/dist/assets/commitAndPush-Wfxng_IK.js +1 -0
  26. package/dist/assets/{computeVirtualFileMetrics-B-4aLf4A.js → computeVirtualFileMetrics-BCOqgixN.js} +2 -2
  27. package/dist/assets/de-CMA45TC-.js +10 -0
  28. package/dist/assets/es-DPL4fBtl.js +16 -0
  29. package/dist/assets/fr-OHBKBseP.js +14 -0
  30. package/dist/assets/{index-B6r0Kv-B.js → index-3TiDNtfN.js} +1 -1
  31. package/dist/assets/index-BLUZa5u0.js +41 -0
  32. package/dist/assets/index-Cm2rrq69.css +1 -0
  33. package/dist/assets/{isDiffPlainText-Ok-kgtJA.js → isDiffPlainText-DnDYQmWK.js} +1 -1
  34. package/dist/assets/{isFilePlainText-0dLnkYm8.js → isFilePlainText-BA_AHX7d.js} +1 -1
  35. package/dist/assets/ja-DvX4WSRf.js +16 -0
  36. package/dist/assets/ko-BUcLd8YZ.js +16 -0
  37. package/dist/assets/main-B_jri4i-.js +896 -0
  38. package/dist/assets/{main-CjXBM_Xe.js → main-DtUmJp9B.js} +2 -2
  39. package/dist/assets/{markdown-shiki.worker-CahLvHIq.js → markdown-shiki.worker-Bg8SoAJJ.js} +8 -5
  40. package/dist/assets/markdownCore-BSnlUXBf.js +7 -0
  41. package/dist/assets/{miniChat-DZ3OAeLN.js → miniChat-BYfLUnDK.js} +2 -2
  42. package/dist/assets/{mobile-CH0LOIF-.js → mobile-DH3hI6gd.js} +2 -2
  43. package/dist/assets/patchFileDiff--L7lt_GZ.js +13 -0
  44. package/dist/assets/pl-BkI_xHqz.js +16 -0
  45. package/dist/assets/pt-BR-7wFtQlV9.js +16 -0
  46. package/dist/assets/{renderElectronMiniChatApp-CB1uLYvh.js → renderElectronMiniChatApp-C7kpNW_-.js} +2 -2
  47. package/dist/assets/renderMobileApp-i0nq7Dwy.js +25 -0
  48. package/dist/assets/runtimeEndpointReset-CfEYbcCc.js +27 -0
  49. package/dist/assets/scheduledTasksApi-Cy7uZCaI.js +1 -0
  50. package/dist/assets/{shikiHighlight-CocY80VR.js → shikiHighlight-D4vxipfr.js} +1 -1
  51. package/dist/assets/{textMateThemeFromAppTheme-CF77r8FA.js → textMateThemeFromAppTheme-BYAHtJwQ.js} +1 -1
  52. package/dist/assets/tr-TsD-AqEH.js +7 -0
  53. package/dist/assets/uk-B-qspCmD.js +16 -0
  54. package/dist/assets/{useAppFontEffects-Dc5nTHi8.js → useAppFontEffects-DHZ9-L30.js} +158 -157
  55. package/dist/assets/{useInlineCommentController-Dbza5c8l.js → useInlineCommentController-CvpOMK-R.js} +2 -2
  56. package/dist/assets/{useRootScrollLock-CSCLv396.js → useRootScrollLock-DzNFi-fn.js} +2 -2
  57. package/dist/assets/{vendor-codemirror-language-data-CkmYWcRI.js → vendor-codemirror-language-data-j3fhlwUM.js} +2 -2
  58. package/dist/assets/{vendor-opencode-client-_BAHQo4R.js → vendor-opencode-client-DYdsLbCM.js} +2 -2
  59. package/dist/assets/vendor-zod-BSoePkpP.js +39 -0
  60. package/dist/assets/{web-components-nsStrYq9.js → web-components-BvHNFSEG.js} +1 -1
  61. package/dist/assets/zh-CN-DYuPJV5i.js +16 -0
  62. package/dist/assets/zh-TW-BX_2D_lV.js +16 -0
  63. package/dist/index.html +5 -5
  64. package/dist/mini-chat.html +5 -5
  65. package/dist/mobile.html +5 -5
  66. package/package.json +4 -4
  67. package/server/index.js +18 -0
  68. package/server/lib/agent-tool/DOCUMENTATION.md +5 -0
  69. package/server/lib/agent-tool/runtime.js +34 -6
  70. package/server/lib/agent-tool/runtime.test.js +15 -0
  71. package/server/lib/browser-control/DOCUMENTATION.md +14 -2
  72. package/server/lib/git/DOCUMENTATION.md +1 -1
  73. package/server/lib/git/service.js +22 -0
  74. package/server/lib/git/service.test.js +8 -0
  75. package/server/lib/guests/DOCUMENTATION.md +4 -3
  76. package/server/lib/guests/catalog.js +19 -1
  77. package/server/lib/guests/catalog.test.js +22 -0
  78. package/server/lib/guests/html-styles.js +5 -3
  79. package/server/lib/guests/html-styles.test.js +3 -1
  80. package/server/lib/guests/routes.js +11 -3
  81. package/server/lib/guests/service.js +5 -0
  82. package/server/lib/guests/surface.js +55 -9
  83. package/server/lib/guests/surface.test.js +56 -6
  84. package/server/lib/notifications/DOCUMENTATION.md +10 -0
  85. package/server/lib/notifications/emit-route.js +118 -0
  86. package/server/lib/notifications/emit-route.test.js +112 -0
  87. package/server/lib/openchamber-control/actions.js +16 -2
  88. package/server/lib/openchamber-control/service.js +23 -0
  89. package/server/lib/openchamber-control/service.test.js +31 -0
  90. package/server/lib/openchamber-sessions/fork-inheritance.js +103 -0
  91. package/server/lib/openchamber-sessions/fork-inheritance.test.js +69 -0
  92. package/server/lib/openchamber-sessions/routes.js +11 -0
  93. package/server/lib/openchamber-sessions/routes.test.js +18 -0
  94. package/server/lib/opencode/DOCUMENTATION.md +31 -22
  95. package/server/lib/opencode/bootstrap-runtime.js +12 -0
  96. package/server/lib/opencode/compatibility.js +6 -3
  97. package/server/lib/opencode/compatibility.test.js +8 -0
  98. package/server/lib/opencode/config-v2.d.ts +2 -0
  99. package/server/lib/opencode/config-v2.js +42 -0
  100. package/server/lib/opencode/config-v2.test.js +17 -0
  101. package/server/lib/opencode/core-routes.js +3 -0
  102. package/server/lib/opencode/core-routes.test.js +15 -0
  103. package/server/lib/opencode/env-runtime.js +1 -8
  104. package/server/lib/opencode/feature-routes-runtime.js +2 -1
  105. package/server/lib/opencode/lifecycle.js +30 -2
  106. package/server/lib/opencode/lifecycle.test.js +27 -0
  107. package/server/lib/opencode/managed-config-file.js +18 -6
  108. package/server/lib/opencode/managed-config-file.test.js +23 -7
  109. package/server/lib/opencode/openchamber-routes.js +29 -11
  110. package/server/lib/opencode/openchamber-routes.test.js +18 -0
  111. package/server/lib/opencode/provider-source-route.test.js +59 -0
  112. package/server/lib/opencode/providers.js +3 -0
  113. package/server/lib/opencode/providers.test.js +62 -0
  114. package/server/lib/opencode/routes-upgrade.test.js +1 -1
  115. package/server/lib/opencode/routes.js +18 -1
  116. package/server/lib/opencode/settings-helpers.js +7 -0
  117. package/server/lib/opencode/settings-helpers.test.js +2 -2
  118. package/server/lib/opencode/settings-registry.json +14 -0
  119. package/server/lib/opencode/settings-runtime.js +1 -0
  120. package/server/lib/opencode/shared.js +32 -2
  121. package/server/lib/opencode/shared.test.js +79 -1
  122. package/server/lib/opencode/skill-routes.js +28 -12
  123. package/server/lib/opencode/skill-routes.test.js +121 -1
  124. package/server/lib/opencode/upgrade-capability.js +0 -14
  125. package/server/lib/opencode/v1-migration-topup.js +21 -15
  126. package/server/lib/opencode/v1-migration-topup.test.js +14 -6
  127. package/server/lib/opencode/v2-install.d.ts +1 -0
  128. package/server/lib/opencode/v2-install.js +8 -7
  129. package/server/lib/opencode/v2-install.test.js +13 -4
  130. package/server/lib/opencode/websearch-config.js +13 -1
  131. package/server/lib/quota/providers/kimi.js +1 -1
  132. package/server/lib/session-assist/DOCUMENTATION.md +17 -5
  133. package/server/lib/session-assist/runtime.js +19 -2
  134. package/server/lib/session-assist/runtime.test.js +8 -0
  135. package/server/lib/session-goal/DOCUMENTATION.md +11 -0
  136. package/dist/assets/DiffView-BucGEJYa.js +0 -4
  137. package/dist/assets/FilesView-CQcaaAVP.js +0 -17
  138. package/dist/assets/GuestSurfacePane--DJ7rsmY.js +0 -1
  139. package/dist/assets/MarkdownRendererImpl-BPe2TVV2.js +0 -12
  140. package/dist/assets/PluginPane-DImv8hV2.js +0 -3
  141. package/dist/assets/SettingsView-DOjuOljf.js +0 -29
  142. package/dist/assets/commitAndPush-sGEelpjh.js +0 -1
  143. package/dist/assets/de-CD9utsNj.js +0 -10
  144. package/dist/assets/es-NNum2rX8.js +0 -16
  145. package/dist/assets/fr-CJLGmduQ.js +0 -14
  146. package/dist/assets/index-DjGPR5vW.js +0 -41
  147. package/dist/assets/index-fCXJ-8Qt.css +0 -1
  148. package/dist/assets/ja-BuddHNi6.js +0 -16
  149. package/dist/assets/ko-BrwMbHmf.js +0 -16
  150. package/dist/assets/main-CxVyUDU_.js +0 -896
  151. package/dist/assets/markdownCore-B6PpX409.js +0 -5
  152. package/dist/assets/patchFileDiff-BFRGKaGH.js +0 -13
  153. package/dist/assets/pl-BwN4TNlP.js +0 -16
  154. package/dist/assets/pt-BR-BhMtownO.js +0 -16
  155. package/dist/assets/renderMobileApp-nQ4sjQtb.js +0 -25
  156. package/dist/assets/runtimeEndpointReset-9ZGlXU4J.js +0 -27
  157. package/dist/assets/scheduledTasksApi-6DsL_SwM.js +0 -1
  158. package/dist/assets/tr-DRzvqMdi.js +0 -7
  159. package/dist/assets/uk-b2aYOSNh.js +0 -16
  160. package/dist/assets/vendor-zod-Gea9uBlY.js +0 -39
  161. package/dist/assets/zh-CN-DZeUThm_.js +0 -16
  162. package/dist/assets/zh-TW-2fRE7uc6.js +0 -16
@@ -0,0 +1,41 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CEam9pDc.js","assets/vendor-react-BUCujlKS.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
+ import{s as m,o as v,n as R,b as Ne,r as it,l as N,a as G,u as _t,_ as Se,t as Qu,c as me,d as Gi,e as As,j as qi,f as sr,g as Oc}from"./vendor-zod-BSoePkpP.js";import{_ as ri}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as yt,d as Cn,p as hr,a as Xu}from"./vendor-zustand-BAGL70zf.js";import{e as Zu,C as ed}from"./vendor-opencode-client-DYdsLbCM.js";import{f as Mc,R as os}from"./vendor-react-BUCujlKS.js";const Yn=1,td="openchamber-relay-v1",Dc=1,_c=12,Qn=1+_c,or=64*1024,ir=5,is=128,Lc=0,Fc=1,kn=4,nd=1+kn,bo=or-ir-nd,H={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},rd=new Set(Object.values(H)),sd=e=>rd.has(e),Xt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},mt=globalThis.crypto.subtle,Uc={name:"ECDH",namedCurve:"P-256"},jc=16,Hs=32,od=16,So=4,Nc=8;class Ot extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const id=()=>mt.generateKey(Uc,!0,["deriveBits"]),ad=async e=>{const t=await mt.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},cd=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Ot("invalid ECDH public key JWK");try{return await mt.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Uc,!0,[])}catch{throw new Ot("invalid ECDH public key JWK")}},ld=()=>{const e=new Uint8Array(jc);return globalThis.crypto.getRandomValues(e),e},ud=async(e,t,n)=>{if(n.length!==jc)throw new Ot("invalid handshake nonce length");const r=await mt.deriveBits({name:"ECDH",public:t},e,256),s=await mt.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await mt.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(td)},s,Hs*2*8)),i=(a,c)=>mt.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(o.slice(0,Hs),["encrypt","decrypt"]),hostToClient:await i(o.slice(Hs),["encrypt","decrypt"])}},dd=(e,t,n)=>{for(let r=Nc-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},fd=(e,t)=>{let n=0n;for(let r=0;r<Nc;r+=1)n=n<<8n|BigInt(e[t+r]);return n},pd=e=>{const t=new Uint8Array(So);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>or)throw new Ot("plaintext frame exceeds maximum size");n+=1n;const s=new Uint8Array(_c);s.set(t,0),dd(s,So,n);const o=new Uint8Array(await mt.encrypt({name:"AES-GCM",iv:s},e,r)),i=new Uint8Array(Qn+o.length);return i[0]=Dc,i.set(s,1),i.set(o,Qn),i}}},hd=e=>{let t=0n;return{async decrypt(n){if(n.length<Qn+od)throw new Ot("encrypted frame too short");if(n[0]!==Dc)throw new Ot("unsupported encrypted frame version");const r=n.slice(1,Qn),s=fd(r,So);if(s<=t)throw new Ot("frame counter regression");let o;try{o=await mt.decrypt({name:"AES-GCM",iv:r},e,n.slice(Qn))}catch{throw new Ot("frame decryption failed")}return t=s,new Uint8Array(o)}}},Pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",md=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+=Pr[r>>2],t+=Pr[(r&3)<<4|(s??0)>>4],s!==void 0&&(t+=Pr[(s&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Pr[o&63])}return t},Ki=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!==Yn)return null;const r=n.batch===!0,s=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:Yn,batch:r,flowControl:s}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:Yn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:s}:null},gd=e=>({type:"fail",closeCode:Xt.ChannelFailure,reason:e}),yd=async(e,t={})=>{const n=t.batch!==!1,r=await cd(e),s=await id(),o=ld(),i={t:"hello",v:Yn,clientPubJwk:await ad(s.publicKey),nonce:md(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 Ki(c)?.t==="ready"?{type:"ignore"}:gd("plaintext frame on established channel");const l=Ki(c);if(l?.t!=="ready")return{type:"ignore"};const u=await ud(s.privateKey,r,o);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:pd(u.clientToHost),decryptor:hd(u.hostToClient)}}}}},Bc=4294967295,wd=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class be extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const We=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>Bc)throw new be("invalid stream id");if(n.length>bo)throw new be("tunnel payload exceeds maximum size");const s=new Uint8Array(ir+n.length);return s[0]=r?e|is:e,s[1]=t>>>24&255,s[2]=t>>>16&255,s[3]=t>>>8&255,s[4]=t&255,s.set(n,ir),s},bd=e=>{if(e.length<ir)throw new be("tunnel frame too short");const t=e[0],n=(t&is)!==0,r=t&~is;if(!sd(r))throw new be(`unknown tunnel frame type ${r}`);const s=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:s,payload:e.slice(ir),hasMoreFragments:n}},Sd=new TextEncoder,Td=new TextDecoder,Ar=e=>Sd.encode(JSON.stringify(e)),Ir=(e,t)=>{let n;try{n=JSON.parse(Td.decode(e))}catch{throw new be("malformed JSON tunnel payload")}if(!t(n))throw new be("unexpected JSON tunnel payload shape");return n},Hc=(e,t=bo)=>{if(t<=0||t>bo)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},Vi=(e,t,n)=>{const r=Hc(n);return r.map((s,o)=>We(e,t,s,o<r.length-1))},vd=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,s=t.get(r);if(!n.hasMoreFragments&&!s)return n.payload;const o=s?.chunks??[],i=(s?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new 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]=Lc,o.set(s,1),o.length>or)throw new be("frame batch exceeds maximum plaintext size");return o}let t=1;for(const s of e)t+=kn+s.length;if(t>or)throw new be("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=Fc;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+=kn,n.set(s,r),r+=s.length;return n},Ed=e=>{if(e.length<1)throw new be("empty batch plaintext");const t=e[0];if(t===Lc)return[e.slice(1)];if(t!==Fc)throw new be(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+kn>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+=kn,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},Pd=new Set([H.HttpBody,H.WsText,H.WsBinary]),zc=150,Ad=24*1024,Id=32,xd=e=>{const t=e.windowMs??zc,n=e.maxBatchBytes??Ad,r=e.maxBatchFrames??Id,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 f=()=>{l!==null&&(i(l),l=null)},p=()=>{if(f(),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]&~is;if(!Pd.has(w)){a.push(b),p();return}const E=s();if(a.length===0&&E-u>=t){a.push(b),p();return}const k=kn+b.length;if(a.length>0&&1+c+k>or&&p(),a.push(b),c+=k,c>=n||a.length>=r){p();return}l===null&&(l=o(p,t))},flush:p,dispose(){d=!0,f(),a=[],c=0}}},Rd=()=>{let e=1;return{next(){if(e>Bc)throw new be("stream id space exhausted");const t=e;return e+=2,t}}},Is=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cd=e=>Is(e)&&Object.values(e).every(t=>typeof t=="string"),Od=e=>Is(e)&&typeof e.status=="number"&&Cd(e.headers),Ji=e=>Is(e)&&typeof e.reason=="string",Md=e=>Is(e)&&typeof e.code=="number"&&typeof e.reason=="string",$c=/^[a-z][a-z\d+.-]*:\/\//i,si="http://tunnel.invalid",Dd=e=>{try{const t=$c.test(e)?new URL(e):new URL(e,si);return`${t.pathname}${t.search}`}catch{return e}},xr=e=>({async*[Symbol.asyncIterator](){yield e}}),_d=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()}}}),Ld=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Fd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:_d(e)};if(typeof e=="string")return{body:xr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:xr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:xr(Ld(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:xr(r),contentType:n}},Ud=async(e,t)=>{let n;const r=new Headers;let s="GET",o=null,i;e instanceof Request?(n=e.url,s=e.method,e.headers.forEach((d,f)=>r.set(f,d)),i=e.signal,o=e.body):n=e.toString(),t&&(t.method&&(s=t.method),t.headers&&new Headers(t.headers).forEach((d,f)=>r.set(f,d)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const a=$c.test(n)?new URL(n):new URL(n,si),{body:c,contentType:l}=await Fd(o);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,f)=>{u[f]=d}),{method:s.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},Wc="__openchamberAmbiguousTransport",To=e=>(Object.defineProperty(e,Wc,{value:!0,enumerable:!1,configurable:!0}),e),Yi=e=>!e||typeof e!="object"?!1:e[Wc]===!0,jd=["local","remote",null],Nd=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Gc(e){if(!e||typeof e!="object")return{valid:!1};const t=e,n=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,s=t.status;if(r!==null&&(typeof r!="string"||!jd.includes(r)))return{valid:!1};if(typeof s!="string"||!Nd.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 oT(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 iT(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function aT(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function qc(){if(Bd()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=Gc(t);return n.valid?n.outcome:null}function Bd(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Gc(e).valid?"valid":"malformed"}const as=/^[a-z][a-z\d+.-]*:\/\//i,Hd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},cs=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),zd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return cs(e)},$d=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return cs(e)},Wd=()=>Object.keys(Os()).length>0,Gd=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},vo=(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))},qd=(e,t)=>{if(!t)return e;const n=new URLSearchParams;vo({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},Qi=(e,t,n)=>{if(as.test(t)){const o=new URL(t);return vo(o,n),o.toString()}const r=Hd(t);if(!e)return qd(r,n);const s=new URL(r,`${e}/`);return vo(s,n),s.toString()},Rr=(e,t=kf())=>{if(!t)return e;const n=as.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),as.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},Kc=(e,t)=>{const n=as.test(e)?new URL(e):new URL(e,Gd(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},Xi=(e,t,n)=>{if(!Wd())return null;const r=$d();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=Ef(r);return o&&s.searchParams.set("oc_url_token",o),e==="ws"?(s.protocol=s.protocol==="https:"?"wss:":"ws:",Kc(s.toString(),n)):s.toString()}catch{return null}},oi=(e={})=>{const t=cs(e.apiBaseUrl),n=cs(e.realtimeBaseUrl),r=()=>t||zd(),s=()=>n||r(),o=(a,c)=>Qi(r(),a,c),i=(a,c)=>Qi(s(),a,c);return{api:o,authenticatedAsset:(a,c)=>Rr(o(a,c)),assetWithUrlToken:(a,c,l)=>Rr(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=Rr(i(a,c));return Xi("sse",l,e)||l},websocket:(a,c)=>{const l=Kc(Rr(i(a,c)),e);return Xi("ws",l,e)||l}}};let ls=oi();const Pe=()=>ls,Kd=e=>{ls=e},Vc=e=>(ls=oi(e),ls),ko="openchamber:runtime-endpoint-changed",Eo="openchamber:runtime-endpoint-will-change";let En="",ar="";const zs=(e,t,n)=>{try{e[t]=n}catch{}},ii=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"}`}},Vd="mobile-disconnected",Jd="url:default",Jc=e=>e===""||e===Jd||e===Vd,Yc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Qc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Xc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Pn=()=>En||Yc();let $s="",Zi=null,ea,ta;const na=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},W=()=>{if(ar)return ar;const e=na("__OPENCHAMBER_API_BASE_URL__"),t=na("__OPENCHAMBER_LOCAL_ORIGIN__");if(Zi===En&&ea===e&&ta===t)return $s;const n=Pn();return $s=Xc(n,Qc())?"local":ii(n),Zi=En,ea=e,ta=t,$s},Yd=(e={})=>{if(En||ar)return;const t=e.apiBaseUrl?.trim()||Yc(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const s=Qc(),o=s&&(!t||Xc(t,s));En=t,ar=e.runtimeKey?.trim()||(o?"local":ii(t||r))},us=e=>{const t=e.apiBaseUrl.trim(),n=Pn(),r=W(),s=e.runtimeKey?.trim()||ii(t),o={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:s,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Eo,{detail:o})),En=t,ar=s,typeof window<"u"){const i=window;zs(i,"__OPENCHAMBER_API_BASE_URL__",t),zs(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),zs(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Vc({apiBaseUrl:t,realtimeBaseUrl:t}),dl(e.requestHeaders||null),ul(e.clientToken||null),e.relay?gf(e.relay):yf(),Ms(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ko,{detail:o}))},Qd=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Eo,t),()=>window.removeEventListener(Eo,t)},Zc=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(ko,t),()=>window.removeEventListener(ko,t)};let Po=null;const cT=e=>{Po=e},xs=()=>Po||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),el=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Xd=(e=el())=>!!e,Zd=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Lt=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,rn=()=>Zd()?.runtime==="electron",ef=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},tf="right",lT=()=>{if(!rn())return!1;const e=ef();return e==="win32"||e==="linux"},uT=e=>e==="left"?"left":tf,dT=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Ae=()=>typeof Lt()?.invoke=="function",On=()=>rn()&&Ae(),nf=()=>{if(Lt()?.pickThemeFile)return{async pick(){const e=Lt()?.pickThemeFile;return e?{status:"picked",file:v({name:m(),size:R().nonnegative(),text:m()}).nullable().parse(await e())}:{status:"unsupported"}}}},re=async(e,t)=>{const n=Lt();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},fT=async()=>{if(!Be()||!Ee())return!1;const e=Pn();try{const t=Ne().safeParse(await re("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===Pn()}catch{return!1}},pT=async()=>{if(!On()||!Ee())return null;try{const e=await re("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},hT=async e=>{if(!On()||!Ee())return null;try{const t=await re("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},mT=async()=>{if(!On()||!Ee())return null;try{const e=await re("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},gT=async e=>{if(!On()||!Ee())return null;try{const t=await re("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},yT=async()=>{if(!On()||!Ee())return null;try{const e=await re("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},wT=async e=>{if(!On()||!Ee())return null;try{const t=await re("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},ra=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}}},Ws=e=>{const t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith("/")?t:`${t}/`)}catch{return null}}},rf=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Nn=e=>{const t=rf(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ee=()=>{if(typeof window>"u"||!Be())return!1;if(W()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Ws(e),n=Ws(Pn());if(!n&&t&&qc()?.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&&Nn(t.hostname)&&Nn(n.hostname)}const r=Ws(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&&Nn(t.hostname)&&Nn(r.hostname)}const s=ra(e),o=ra(window.location.origin)||window.location.origin;return s&&o&&s===o?!0:!!(r&&Nn(r.hostname))},Be=()=>typeof window>"u"?!1:rn(),bT=async()=>{if(!Be())return!1;try{return!!await re("desktop_focus_window")}catch{return!1}},tl=()=>Be()&&Ae()&&Ee(),sf=m().min(1),ST=e=>{if(!tl())return null;try{const t=sf.safeParse(Lt()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},TT=async()=>{if(!Be())return!1;try{return await re("desktop_start_window_drag"),!0}catch{return!1}},Ce=()=>Xd()?!0:xs()?.runtime?.isVSCode===!0,vT=()=>{const t=xs()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Ce()},kT=(e,t=Be())=>e==="web"&&!t,nl=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},ET=async e=>{if(tl())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"}},of=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),PT=async e=>{if(Ae()&&Ee())try{const t=await Lt()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!of(t))return{success:!1,error:"File selection cancelled"};const n=typeof t.path=="string"?t.path:"";return n?{success:!0,path:n,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},AT=async e=>({success:!0}),IT=async e=>({success:!0}),xT=async()=>Ae()?await re("desktop_check_for_updates"):null,RT=async e=>{if(!Ae())return!1;const t=Lt();let n=null,r=0,s;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("openchamber:update-progress",o=>{const i=o?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){r=0,s=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:s});return}if(c==="Progress"){const u=l?.downloaded,d=l?.total;typeof u=="number"&&(r=u),typeof d=="number"&&(s=d),e({downloaded:r,total:s});return}c==="Finished"&&e({downloaded:r,total:s})})),await re("desktop_download_and_install_update"),!0}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{if(n)try{const o=n();o instanceof Promise&&await o}catch{}}},CT=async()=>Ae()?(await re("desktop_restart"),!0):!1,OT=async()=>{if(!Ae())return!1;try{return await re("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},MT=async()=>{if(!Ae()||!Ee())return null;try{const e=await re("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},af=async(e,t)=>{if(!Ae()||!Ee())return!1;const n=e?.trim();if(!n)return!1;try{return await re("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},DT=async e=>{if(!Ae()||!Ee())return!1;const t=e?.trim();if(!t)return!1;try{return await re("desktop_reveal_path",{path:t}),!0}catch{return af(t)}},_T=async(e,t)=>{if(!Ae()||!Ee())return null;const n=e?.trim();if(!n)return null;try{const r=await re("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},LT=async(e,t,n)=>{if(!Ae()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await re("desktop_open_in_app",{projectPath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},FT=async(e,t,n)=>{if(!Ae()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await re("desktop_open_file_in_app",{filePath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},UT=async(e,t)=>{if(!Ae()||!Ee())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const r=await re("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=r;return s.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(s.apps)?{apps:s.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:s.hasCache===!0,isCacheStale:s.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},mr=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",jT=()=>{if(typeof window>"u"||!mr()||rl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},rl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ce()?"vscode":Be()?"desktop":"web"},cf="2.0.1",Cr=new Uint8Array(0),lf=new TextEncoder,uf=new TextDecoder,ze=e=>e instanceof Error?e:new Error(String(e)),Or=()=>new DOMException("The operation was aborted.","AbortError"),df=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},ff=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},sa=0,Gs=1,oa=2,ia=3,pf=new Set([Xt.AuthFailed,Xt.DuplicateClient,Xt.LimitExceeded]),hf={[Xt.AuthFailed]:"relay authentication failed",[Xt.DuplicateClient]:"relay connection replaced by another client",[Xt.LimitExceeded]:"relay connection limit reached"},aa=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ai=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,s=e.pingTimeoutMs??15e3,o=e.batchWindowMs??zc,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(x=>df(new WebSocket(x)));let d=!1,f=null,p={state:"idle"};const y=new Set;let b=null,w=null,E=null,k=0,U=0,D=null,J=[],C=!1;const Te=x=>{if(!(p.state===x.state&&p.lastError===x.lastError)){p=x;for(const $ of y)try{$(p)}catch{}}},ae=x=>{const $=J;J=[];for(const M of $)M.reject(x)},js=x=>{const $=J;J=[];for(const M of $)M.resolve(x)},Ie=(x,$)=>{x.dead=!0;const M=Array.from(x.streams.values());x.streams.clear();for(const _ of M)try{_.fail($)}catch{}},_n=()=>{D!==null&&(clearTimeout(D),D=null)},Ln=()=>{d||D===null||aa()||(_n(),Qe(),Fn())},jt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Ln()},F=()=>{C||typeof window>"u"||(C=!0,window.addEventListener("online",Ln),typeof document<"u"&&document.addEventListener("visibilitychange",jt))},Qe=()=>{!C||typeof window>"u"||(C=!1,window.removeEventListener("online",Ln),typeof document<"u"&&document.removeEventListener("visibilitychange",jt))},an=()=>{if(d||D!==null)return;const x=Math.max(0,U-1),$=a*2**Math.min(x,10),M=aa()?l:c,_=Math.min(M,$);F(),D=setTimeout(()=>{D=null,Qe(),Fn()},_)},vr=()=>{const x=new URL(e.relayUrl);return x.searchParams.set("v",String(Yn)),x.searchParams.set("role","client"),x.searchParams.set("serverId",e.serverId),x.searchParams.set("appId","openchamber"),x.searchParams.set("appVersion",cf),x.searchParams.set("platform",rl()),e.grant&&x.searchParams.set("grant",e.grant),x.toString()},Fn=async()=>{if(d)return;_n(),k+=1;const x=k;Te({state:U>0?"reconnecting":"connecting",lastError:p.lastError});let $;try{$=await yd(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(Y){if(x!==k||d)return;Wi(x,ze(Y),!0);return}if(x!==k||d)return;let M;try{M=u(vr())}catch(Y){Wi(x,ze(Y));return}w=M;let _=!1,j=null,q=null,Oe=null,ge=null,B=Promise.resolve(),z=null,se=null,at=!1,pe=!1,he=0,ye=0,we=null,ct=null,ee=Date.now();const bt=()=>{we!==null&&(clearTimeout(we),we=null),j!==null&&(clearInterval(j),j=null),q!==null&&(clearTimeout(q),q=null),Oe!==null&&(clearInterval(Oe),Oe=null),ge!==null&&(clearTimeout(ge),ge=null),ct!==null&&(ct.dispose(),ct=null)};E=bt;function V(Y,oe=!1,X=!1){if(!(_||x!==k)){_=!0,X&&(f=Y),bt(),z&&(b=null,Ie(z,new Error(`relay tunnel reset: ${Y.message}`))),ae(Y);try{M.close()}catch{}if(w===M&&(w=null),!d){if(U+=1,X){Te({state:"error",lastError:Y.message});return}Te({state:oe?"error":"reconnecting",lastError:Y.message}),an()}}}const Un=()=>{try{M.send($.helloText)}catch{}},Er=(Y,oe,X)=>{se=Y,at=oe,pe=X,j!==null&&(clearInterval(j),j=null),q!==null&&(clearTimeout(q),q=null);const ce=new Map,Nt=Rd(),He=vd();let Bt=Promise.resolve();const St=jn=>{Bt=Bt.then(async()=>{if(Ht.dead)return;const Yu=await Y.encryptor.encrypt(jn);Ht.dead||M.send(Yu)}).catch(()=>{V(new Error("relay encrypt/send failed"))})},Bs=oe?xd({windowMs:o,sendBatch:St}):null;ct=Bs;const Ht={streams:ce,assembler:He,nextStreamId:()=>Nt.next(),dead:!1,send(jn){Ht.dead||(Bs?Bs.enqueue(jn):St(jn))}};z=Ht,b=Ht,U=0,ee=Date.now(),Te({state:"connected"}),js(Ht),Oe=setInterval(()=>{Date.now()-ee<r||(Ht.send(We(H.Ping,0,Cr)),ge===null&&(ge=setTimeout(()=>{ge=null,V(new Error("relay keepalive timeout"))},s)))},r)},cn=()=>{we!==null&&clearTimeout(we),we=null,!(!z||z.dead||he===ye)&&(ye=he,z.send(We(H.DeliveryAck,0,wd(he))))},Ju=(Y,oe)=>{let X;try{X=bd(oe)}catch(He){V(ze(He));return}if(X.frameType===H.DeliveryAck){V(new Error("unexpected downstream delivery acknowledgement"));return}if(pe&&X.streamId!==0&&(he+=oe.length,we===null&&(we=setTimeout(cn,10))),ee=Date.now(),ge!==null&&(clearTimeout(ge),ge=null),X.frameType===H.Ping){Y.send(We(H.Pong,X.streamId,Cr));return}if(X.frameType===H.Pong)return;let ce=X.payload;if(X.frameType===H.WsText||X.frameType===H.WsBinary){let He;try{He=Y.assembler.push(X)}catch(Bt){V(ze(Bt));return}if(He===null)return;ce=He}else if(X.hasMoreFragments){V(new Error("unexpected fragmented tunnel frame"));return}const Nt=Y.streams.get(X.streamId);Nt&&Nt.handleFrame(X.frameType,ce)};M.onopen=()=>{_||x!==k||(Un(),j=setInterval(Un,t))},M.onmessage=Y=>{if(_||x!==k)return;const oe=Y.data;if(typeof oe=="string"){B=B.then(async()=>{if(_||x!==k)return;const ce=await $.handleText(oe);if(ce.type==="established"){if(se)return;Er(ce.channel,ce.batch,ce.flowControl)}else ce.type==="fail"&&V(new Error(`relay handshake failed: ${ce.reason}`))}).catch(ce=>{V(ze(ce))});return}const X=oe instanceof ArrayBuffer?new Uint8Array(oe):oe instanceof Uint8Array?oe:null;X&&(B=B.then(async()=>{if(_||x!==k)return;const ce=z,Nt=se;if(!ce||!Nt){V(new Error("encrypted frame before handshake completed"));return}let He;try{He=await Nt.decryptor.decrypt(X)}catch(St){V(ze(St));return}let Bt;try{Bt=at?Ed(He):[He]}catch(St){V(ze(St));return}for(const St of Bt){if(_||x!==k||ce.dead)return;Ju(ce,St)}pe&&he-ye>=16*1024&&cn()}).catch(ce=>{V(ze(ce))}))},M.onclose=Y=>{const oe=pf.has(Y.code);V(new Error(hf[Y.code]??`relay socket closed (code ${Y.code})`),oe,oe)},M.onerror=()=>{},q=setTimeout(()=>{q=null,V(new Error("relay handshake timeout"),!0)},n);function Wi(Y,oe,X=!1){Y!==k||d||(ae(oe),U+=1,Te({state:X?"error":"reconnecting",lastError:oe.message}),an())}},kr=x=>d?Promise.reject(new Error("relay tunnel closed")):x?.aborted?Promise.reject(Or()):f?Promise.reject(f):b&&!b.dead?Promise.resolve(b):new Promise(($,M)=>{let _=null;const j={resolve(q){_&&x&&x.removeEventListener("abort",_),$(q)},reject(q){_&&x&&x.removeEventListener("abort",_),M(q)}};x&&(_=()=>{J=J.filter(q=>q!==j),M(Or())},x.addEventListener("abort",_,{once:!0})),J.push(j)}),wt=async(x,$)=>{const M=await Ud(x,$),_=M.signal;if(_?.aborted)throw Or();const j=await kr(_),q=j.nextStreamId();return await new Promise((Oe,ge)=>{let B=!1,z=!1,se=null,at=null;const pe=()=>{j.streams.delete(q),j.assembler.dropStream(q),at&&_&&_.removeEventListener("abort",at)},he=ee=>{if(!z){if(z=!0,pe(),!B){ge(ee);return}try{se?.error(ee)}catch{}}},ye=ee=>{j.dead||j.send(We(H.StreamAbort,q,Ar({reason:ee})))},we=ee=>To(new Error(ee));at=()=>{ye("aborted"),he(Or())},j.streams.set(q,{handleFrame(ee,bt){if(ee===H.HttpResponse){if(B||z)return;let V;try{V=Ir(bt,Od)}catch(cn){ye("malformed response head"),he(we(ze(cn).message));return}const Un=V.status===204||V.status===205||V.status===304;let Er=null;Un||(Er=new ReadableStream({start(cn){se=cn},cancel(){z||(z=!0,pe(),ye("response body cancelled"))}})),B=!0,Oe(new Response(Er,{status:V.status,headers:V.headers})),Un&&(z=!0,pe());return}if(ee===H.HttpBody){if(!B||z)return;try{se?.enqueue(bt)}catch{}return}if(ee===H.StreamEnd){if(z)return;if(!B){he(we("tunnel stream ended before response head"));return}z=!0,pe();try{se?.close()}catch{}return}if(ee===H.StreamAbort){let V="stream aborted by host";try{V=Ir(bt,Ji).reason}catch{}he(we(V))}},fail(ee){he(we(ee.message))}}),_&&_.addEventListener("abort",at,{once:!0});const ct={method:M.method,path:M.path,query:M.query,headers:M.headers,hasBody:M.body!==null};j.send(We(H.HttpRequest,q,Ar(ct))),(async()=>{try{let ee=!1;if(M.body)for await(const bt of M.body){if(z||j.dead)return;for(const V of Hc(bt))j.send(We(H.HttpBody,q,V)),ee=!0}!z&&!j.dead&&(M.body&&!ee&&j.send(We(H.HttpBody,q,Cr)),j.send(We(H.StreamEnd,q,Cr)))}catch(ee){ye("request body failed"),he(we(ze(ee).message))}})()})},Ns=x=>{const $=x.indexOf("?");return $===-1?{path:x,query:""}:{path:x.slice(0,$),query:x.slice($+1)}},Ku=(x,$)=>{let M=sa,_=null,j=0,q=!1;const Oe={get readyState(){return M},onopen:null,onmessage:null,onerror:null,onclose:null,send(B){if(M!==Gs||!_||_.dead)throw new Error("relay tunnel socket is not open");if(typeof B=="string"){for(const se of Vi(H.WsText,j,lf.encode(B)))_.send(se);return}const z=B instanceof ArrayBuffer?new Uint8Array(B.slice(0)):(()=>{const se=new Uint8Array(B.byteLength);return se.set(new Uint8Array(B.buffer,B.byteOffset,B.byteLength)),se})();for(const se of Vi(H.WsBinary,j,z))_.send(se)},close(B=1e3,z=""){M===ia||M===oa||(M===Gs&&_&&!_.dead&&(M=oa,_.send(We(H.WsClose,j,Ar({code:B,reason:z})))),ge(B,z))}},ge=(B,z,se=!1)=>{if(!q){if(q=!0,_&&(_.streams.delete(j),_.assembler.dropStream(j)),M=ia,se)try{Oe.onerror?.()}catch{}try{Oe.onclose?.({code:B,reason:z})}catch{}}};return(async()=>{let B;try{B=await kr()}catch(pe){ge(1006,ze(pe).message,!0);return}if(q)return;_=B,j=B.nextStreamId(),B.streams.set(j,{handleFrame(pe,he){if(pe===H.WsOpened){if(M===sa){M=Gs;try{Oe.onopen?.()}catch{}}return}if(pe===H.WsText){try{Oe.onmessage?.({data:uf.decode(he)})}catch{}return}if(pe===H.WsBinary){const ye=new ArrayBuffer(he.byteLength);new Uint8Array(ye).set(he);try{Oe.onmessage?.({data:ye})}catch{}return}if(pe===H.WsClose){let ye=1e3,we="";try{const ct=Ir(he,Md);ye=ct.code,we=ct.reason}catch{}ge(ye,we);return}if(pe===H.StreamAbort){let ye="stream aborted";try{ye=Ir(he,Ji).reason}catch{}ge(1006,ye,!0)}},fail(pe){ge(1012,pe.message,!0)}});const{path:z,query:se}=Ns(x),at=$&&$.length>0?{path:z,query:se,protocols:$}:{path:z,query:se};B.send(We(H.WsOpen,j,Ar(at)))})(),Oe},Vu=()=>{if(d)return;d=!0,k+=1,_n(),Qe(),E?.(),E=null;const x=b;b=null;const $=new Error("relay tunnel closed");x&&Ie(x,$),ae($);try{w?.close()}catch{}w=null,Te({state:"idle"})};return Fn(),{fetch:wt,openWebSocket:Ku,getStatus:()=>p,subscribeStatus(x){return y.add(x),()=>{y.delete(x)}},close:Vu}};let _e=null,gt=null;const mf=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Rs=()=>_e,NT=()=>!_e||!gt?null:{relayUrl:gt.relayUrl,serverId:gt.serverId,hostEncPubJwk:{...gt.hostEncPubJwk}},BT=()=>_e!==null,gf=e=>(_e&&gt&&mf(gt,e)||(_e?.close(),gt=e,_e=ai(e)),_e),HT=(e,t)=>{_e!==t&&(_e?.close(),gt=e,_e=t)},yf=()=>{_e?.close(),_e=null,gt=null};let sl=()=>null,ol="",ds={},en="",cr=0,Vt=null,Sn="",lr=0,tn="",Jt=null,xt="",Yr=0,Qr=0;const ci=1e4,wf=e=>e.toLowerCase()==="authorization",il=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const s=n.trim(),o=r.trim();s&&o&&!wf(s)&&(t[s]=o)}return t},bf=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,s])=>t[r]===s)},Cs=e=>typeof e!="string"?"":e.trim(),Sf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Cs(e)},Tf=()=>{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():Tf();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},li=e=>{try{return new URL(e).origin}catch{return""}},cl=()=>{Sn="",lr=0,tn="",Jt=null,xt="",Yr+=1},gr=()=>{en="",cr=0,cl()},ll=()=>{Qr+=1,Vt=null,gr(),ui()},ul=e=>{const t=Cs(e);ol=t,ll(),sl=()=>t?{type:"bearer",token:t}:null},dl=e=>{const t=il(e);bf(ds,t)||(ds=t,ll())},Os=()=>{if(Object.keys(ds).length>0)return ds;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?il(e):{}},fl=()=>ol||Sf(),vf=(e,t)=>{const n=Cs(e);if(!n||typeof t!="number"||!Number.isFinite(t)){gr();return}const r=en;en=n,cr=t,r&&r!==n&&xf()},pl=()=>!en||cr<=Date.now()+ci?(gr(),""):en,hl=e=>{const t=li(e);return!t||tn!==t?"":!Sn||lr<=Date.now()+ci?(Sn="",lr=0,tn="",""):Sn},kf=()=>{const e=pl();return!e&&(fl()||typeof window<"u")&&Ms().catch(()=>{}),e},Ef=e=>{const t=e?hl(e):"";return!t&&e&&typeof window<"u"&&wl(e).catch(()=>{}),t},ml=async()=>{const e=await sl(),t=e?.type==="bearer"?Cs(e.token):fl();return t?{type:"bearer",token:t}:null},Pf=v({token:m(),expiresAt:R()}),gl=async(e,t)=>{const n=await ml(),r=new Headers;for(const[c,l]of Object.entries(Os()))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=Rs(),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=Pf.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},zT=async e=>{const t=await gl(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},yl=e=>{if(Vt)return Vt;const t=Qr,r=(async()=>{let s;try{s=await gl(e)}catch(o){throw t===Qr&&gr(),o}if(t!==Qr)throw new Error("Runtime URL auth token response is stale");if(vf(s.token,s.expiresAt),!en)throw new Error("Runtime URL auth token response was invalid");return en})().finally(()=>{Vt===r&&(Vt=null)});return Vt=r,Vt},Af=e=>{const t=li(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Jt&&xt===t)return Jt;const n=Yr,s=(async()=>{const o=await fetch(al(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw n===Yr&&t===xt&&(Sn="",lr=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!==Yr||t!==xt)throw new Error("Local runtime URL auth token response is stale");return Sn=a,lr=c,tn=t,a})().finally(()=>{Jt===s&&(Jt=null,xt="")});return Jt=s,xt=t,Jt},Ms=async e=>{const t=pl();return t||yl(e)},wl=async e=>{const t=li(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=hl(t);return n||((tn&&tn!==t||xt&&xt!==t)&&cl(),Af(t))};let yn=0,Xn=null,bl=null;const Ao=new Set,If=5e3,xf=()=>{for(const e of Ao)try{e()}catch{}},Sl=()=>{Xn!==null&&(clearTimeout(Xn),Xn=null)},ui=()=>{if(Sl(),yn<=0||typeof window>"u")return;const e=cr-ci-If,t=cr>0?Math.max(0,e-Date.now()):0;Xn=setTimeout(()=>{Xn=null,!(yn<=0)&&yl(bl).catch(()=>{}).finally(()=>{ui()})},t)},$T=e=>{typeof e=="string"&&e.trim()&&(bl=e.trim()),yn+=1,ui();let t=!1;return()=>{t||(t=!0,yn=Math.max(0,yn-1),yn===0&&Sl())}},WT=e=>(Ao.add(e),()=>{Ao.delete(e)}),Rf=async e=>{const t=new Headers(e);for(const[r,s]of Object.entries(Os()))t.has(r)||t.set(r,s);if(t.has("Authorization"))return t;const n=await ml();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},fs=yt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Cf=15e3,Of=5*6e4;let Io=0,qs=!1;const Mf=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),Df=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!Mf(t)},Tl=async()=>{if(!qs){qs=!0;try{const{runtimeFetch:e}=await ri(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>Gf);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){fs.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=fs.getState();n==="expired"&&r()}}catch{}finally{qs=!1}}},_f=(e,t)=>{if(t!==401||fs.getState().state==="expired"||!Df(e))return;const n=Date.now();n-Io<Cf||(Io=n,Tl())};let ca=!1;const GT=()=>{if(ca)return;ca=!0;let e=Date.now();const t=()=>{if(fs.getState().state!=="ok")return;const n=Date.now();n-e<Of||(e=n,Io=n,Tl())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},nn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Lf=()=>typeof window>"u"?"":window.location.origin||"",di=e=>{if(typeof window>"u")return!1;const t=Lf();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}},fi=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Ff=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),At=(e,t)=>{try{Ff(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))},Xr=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}},Ks=e=>{if(nn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return di(t)&&nn(t.pathname)}catch{return!1}},Uf=(e,t)=>{try{const n=new URL(e);if(!di(n))return e;const r=Dt(`${n.pathname}${n.search}`,t);return!fi(r)&&(n.protocol==="http:"||n.protocol==="https:")?(pi(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},Dt=(e,t)=>e==="/health"?Pe().health(t):e.startsWith("/auth/")||e==="/auth"?Pe().auth(e,t):nn(e)?Pe().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Uf(e,t):e,jf=e=>{const t=e instanceof Request?e.url:e.toString();if(!fi(t))return nn(t);try{return Xr(new URL(t))}catch{return!1}},vl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Nf=(e,t)=>!vl(t),xo=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)Nf(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},lt=async(e,t,n=!0)=>{const r=new Headers(xo(e)??e);return t&&new Headers(xo(t)??t).forEach((s,o)=>r.set(o,s)),n?Rf(r):r},Bf=(e,t)=>{if(!t)return e;const n=new URL(e,si);return pi(n,t),`${n.pathname}${n.search}`},kl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!fi(n))return nn(n)?Bf(n,t):null;try{const r=new URL(n);return!di(r)||!nn(r.pathname)?null:(pi(r,t),`${r.pathname}${r.search}`)}catch{return null}},Hf=async(e,t,n)=>{const r=Rs();if(!r)return null;const s=kl(e,n);if(s===null)return null;const o=e instanceof Request?e.headers:void 0,i=await lt(o,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(s,{...t,headers:i})},zf=(e,t)=>{if(typeof e=="string")return Dt(e,t);if(e instanceof URL)return Dt(e.toString(),t);const n=Dt(e.url,t);return n===e.url?e:new Request(n,e)},$f=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Mr=new Map,Wf=(e,t,n,r)=>n||e!=="GET"||t.includes("/event")||!$f.test(t)?null:`GET ${t}\0${r.get("x-opencode-directory")??""}`,g=async(e,t={})=>{const{query:n,...r}=t,s=Rs(),o=s?kl(e,n):null;let i,a,c,l;if(s&&o!==null){const b=e instanceof Request?e.headers:void 0,w=await lt(b,r.headers,!0);i=e instanceof Request?()=>s.fetch(e,{...r,headers:w}):()=>s.fetch(o,{...r,headers:w}),l=w,a=o,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const b=zf(e,n),w=b instanceof Request?b.headers:void 0,E=await lt(w,r.headers,jf(b)),k=b instanceof Request?b.url:b instanceof URL?b.toString():String(b);At(k,E),i=b instanceof Request?()=>fetch(new Request(b,{...r,headers:E})):()=>fetch(b,{...r,headers:E}),l=E,a=k,c=String(r.method??(b instanceof Request?b.method:"GET")).toUpperCase()}const u=i;i=()=>u().then(b=>(_f(a,b.status),b));const d=r.signal!=null||e instanceof Request,f=Wf(c,a,d,l);if(!f)return i();const p=Mr.get(f);if(p)return p.then(b=>b.clone());const y=i();return Mr.set(f,y),y.then(()=>Mr.delete(f),()=>Mr.delete(f)),y.then(b=>b.clone())};let la=!1;const El=()=>{if(la||typeof window>"u")return;la=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await Hf(t,n??{});if(r)return r;if(typeof t=="string"){if(!Ks(t)){try{const i=new URL(t);if(Xr(i)){const a=await lt(void 0,n?.headers);return At(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const s=await lt(void 0,n?.headers),o=Dt(t);return At(o,s),e(o,{...n,headers:s})}if(t instanceof URL){const s=t.toString();if(!Ks(s)){if(Xr(t)){const a=await lt(void 0,n?.headers);return At(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const o=await lt(void 0,n?.headers),i=Dt(s);return At(i,o),e(i,{...n,headers:o})}if(t instanceof Request){if(!Ks(t.url)){try{const a=new URL(t.url);if(Xr(a)){const c=await lt(t.headers,n?.headers);return At(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const s=await lt(t.headers,n?.headers),o=Dt(t.url);At(o,s);const i=o===t.url?t:new Request(o,t);return e(new Request(i,{...n,headers:s}))}return e(t,n)}},Gf=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:At,buildRuntimeFetchUrl:Dt,installRuntimeFetchBridge:El,isLatin1Safe:vl,runtimeFetch:g,sanitizeHeadersForBrowser:xo},Symbol.toStringTag,{value:"Module"})),Tn=16384,ps=globalThis,qf=e=>{if(ps.Buffer)return ps.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,"")},Pl=e=>{try{if(ps.Buffer)return ps.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}},Kf=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}},Vf=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}},ua=e=>typeof e=="string"&&e.length>0,Jf=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ua(t.x)||!ua(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Yf=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Qf=e=>{if(!e||typeof e!="object")return null;const t=e,n=Yf(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=Kf(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=Vf(t.relayUrl);if(!r)return null;const s=typeof t.serverId=="string"?t.serverId.trim():"";if(!s)return null;const o=Jf(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},hi=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(Qf).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}},qT=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}),KT=e=>{const t=hi(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",qf(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},Xf=e=>{const t=e.trim();if(!t||t.length>Tn)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>Tn)return null;const s=Pl(r);return!s||s.length>Tn?null:hi(JSON.parse(s))}catch{return null}},VT=e=>{const t=e.trim();if(!t||t.length>Tn)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>Tn)return null;const o=Pl(s);if(!o||o.length>Tn)return null;try{return hi(JSON.parse(o))}catch{return null}},An=e=>typeof e=="object"&&e!==null,Zf=e=>e.trim().toLowerCase()==="authorization",ep=e=>{if(!An(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)||Zf(s)||(t[s]=o)}return Object.keys(t).length>0?t:void 0},tp=e=>`relay://${e}`,np=e=>{if(!An(e))return null;const t=ve(e,"relayUrl")||ve(e,"relay_url"),n=ve(e,"serverId")||ve(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!An(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},rp=()=>{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"},JT=async(e,t)=>{const n=Xf(e);if(!n)throw new Error("invalid-connect-link");const r=await cp().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:rp(),...r?{dedupeKey:`desktop:${r}`}:{}})},o=async w=>{if(!w.ok)return null;const E=await w.json().catch(()=>null);return(typeof E?.clientToken=="string"?E.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((w,E)=>(w.type==="relay"?1:0)-(E.type==="relay"?1:0));for(const w of a){if(w.type==="relay"){const k=ai({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const U=await o(await k.fetch("/api/client-auth/pairing/redeem",s));if(U){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:U};break}}catch{}finally{k.close()}continue}const E=ke(w.url);if(E)try{const k=await o(await fetch(`${E}/api/client-auth/pairing/redeem`,s));if(k){i={directUrl:E,token:k};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(w=>w.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),u=n.candidates.filter(w=>w.type!=="relay").map(w=>ke(w.url)).find(w=>!!w),d=i.directUrl||u,f=d||(l?tp(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const p=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&ke(w.apiUrl||w.url)===f),y=p?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),b={...p||{},id:y,label:n.label||p?.label||Al(f),url:f,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:y,hosts:p?t.map(w=>w.id===y?b:w):[b,...t]}},sp=/^(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}},YT=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"}},Al=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)sp.test(s)&&n.searchParams.set(s,"[REDACTED]");return n.toString()}catch{return t}},Dr=(e,t)=>{const n=ke(e),r=ke(t);if(!n||!r)return!1;try{const s=new URL(n),o=new URL(r);if(s.origin!==o.origin||o.search&&s.search!==o.search)return!1;const i=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname,a=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},ve=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},da=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},op=e=>{if(!An(e))return null;const t=ve(e,"id"),n=ve(e,"label"),r=ve(e,"url"),s=ve(e,"apiUrl")||ve(e,"api_url"),o=ve(e,"clientToken")||ve(e,"client_token"),i=ep(e.requestHeaders),a=np(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...s?{apiUrl:s}:{},...o?{clientToken:o}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Zn=e=>ke(e.apiUrl||e.url)||e.apiUrl||e.url,sn=()=>Ae()?(e,t)=>re(e,t):null,mi=async()=>{const e=sn();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!An(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(op).filter(a=>!!a):[],s=ve(t,"defaultHostId")||ve(t,"default_host_id")||ve(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=ve(t,"localOrigin")||ve(t,"local_origin");return{hosts:r,defaultHostId:s,initialHostChoiceCompleted:o,localOrigin:i}},ip=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})},ap=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},cp=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},lp=8e3,up=15e3,dp=400,fp=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)}},fa=async(e,t,n,r)=>{for(;;){const s=n-Date.now();if(s<=0)throw new Error("relay probe deadline exceeded");try{return await fp(e,t,Math.min(lp,s),r)}catch(o){if(e.getStatus().state==="error"||Date.now()>=n)throw o;await new Promise(i=>window.setTimeout(i,dp))}}},pp=async(e,t)=>{const n=ai({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),s=r+up;let o=!1;try{if(!(await fa(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 fa(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()}},gi=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(!An(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=da(r,"latencyMs")??da(r,"latency_ms")??0;return{status:o,latencyMs:i}},QT=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})},XT=async e=>{const t=sn();t&&await t("desktop_new_window_for_host",{hostId:e})},Mt="local",hp=e=>({id:Mt,label:"Local",url:e||Il()}),Il=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,mp=e=>e.id===Mt?"local":`host:${e.id}`,ZT=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Mt)?.url||Il(),r=Pn(),s=ke(n)||n,o=ke(t)||t,i=W(),a=e.find(u=>u.relay&&mp(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Dr(r,n))return{id:Mt,label:"Local",url:s};const c=e.find(u=>r?Dr(r,Zn(u)):!1);if(c)return{id:c.id,label:c.label,url:ke(Zn(c))||Zn(c)};if(t&&Dr(t,n))return{id:Mt,label:"Local",url:s};const l=e.find(u=>t?Dr(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:Al(o||"Instance"),url:o}},hs=new Map;let xl=0;const ms=new Map;let Ro=0,Rl={byHostId:{},isProbing:!1};const Co=new Set,gs=()=>{Rl={byHostId:Object.fromEntries(hs),isProbing:Ro>0};for(const e of Co)try{e()}catch{}},ev=e=>(Co.add(e),()=>{Co.delete(e)}),tv=()=>Rl,Cl=(e,t)=>{hs.set(e,t),gs()},nv=(e,t)=>{ms.set(e,++xl),Cl(e,t)},gp=e=>{const t=new Set([Mt,...e]);let n=!1;for(const r of Array.from(hs.keys()))t.has(r)||(hs.delete(r),ms.delete(r),n=!0);n&&gs()},yp=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",wp=async()=>rn()?ap().catch(()=>""):"",bp=async(e,t)=>{const n=e.id===Mt?t:e.clientToken||"",r=async()=>{const i=await pp(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()?Zn(e):e.url);if(!s)return{status:"unreachable",latencyMs:0};const o=await gi(s,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(yp(o.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:o.status,latencyMs:o.latencyMs}},Sp=async e=>{if(!Be())return;const t=++xl;for(const n of e)ms.set(n.id,t);Ro+=1,gs();try{const n=await wp();await Promise.all(e.map(async r=>{const s=await bp(r,n);ms.get(r.id)===t&&Cl(r.id,s)}))}finally{Ro-=1,gs()}};let pa=!1;const Tp=async()=>{if(pa||!Be())return;pa=!0;const e=await mi().catch(()=>null);e&&(gp(e.hosts.map(t=>t.id)),await Sp([hp(e.localOrigin),...e.hosts]))},vp=5e3,kp=1500;let Vs=!1;const Ep=async e=>{if(!rn()||Vs)return;const t=`host:${e}`;if(W()===t){Vs=!0;try{const n=await mi().catch(()=>null),r=n?.hosts.find(d=>d.id===e);if(!n||!r?.relay)return;const s=r.apiUrl?ke(r.apiUrl):null;if(s&&s.startsWith("https://"))return;const o=await g("/api/client-auth/connection/candidates").catch(()=>null);if(!o?.ok)return;const i=await o.json().catch(()=>null);if(!i||i.serverId!==r.relay.serverId)return;const a=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const d of a){if(!d||typeof d!="object")continue;const f=d;if(f.type!=="lan"||typeof f.url!="string")continue;const p=ke(f.url);p&&!c.includes(p)&&c.push(p)}if(c.length===0)return;const l=s&&c.includes(s)?s:c[0];l!==s&&await ip({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await gi(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"||W()!==t)return;us({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{Vs=!1}}},Pp=e=>{typeof window>"u"||window.setTimeout(()=>{Ep(e).catch(()=>{})},vp)},Ap=async e=>{if(!rn())return;const t=await mi().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(W()===s)return;const o=d=>{us({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:s})},i=()=>{us({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:s,relay:r.relay??void 0}),Pp(r.id)},a=r.apiUrl?ke(Zn(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=gi(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),kp))]);if(u){if(c(u)){o(a);return}i();return}i(),l.then(d=>{c(d)&&W()===s&&o(a)})};class Zt extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const rv=e=>e instanceof Zt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),ys=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},ha=500,Ol=()=>{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}},sv=()=>Ol(),Ge=(e,t)=>{if(!Ol())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>ha&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-ha)},Ip=()=>{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__=Ip);const ov=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}},xp=3,Rp=3e4,Cp=32e3,Op=3600*1e3,Mp=600*1e3,Dp=200,_p=new Set([429,502,503,504]),ft=new Map,yi=e=>JSON.stringify([W(),e]);function Lp(){const e=Date.now();for(const[t,n]of ft){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>Op&&ft.delete(t)}}typeof setInterval<"u"&&setInterval(Lp,Mp).unref?.();function Fp(e){const t=yi(e);let n=ft.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Rp},ft.set(t,n);ft.size>Dp;){const r=ft.keys().next().value;if(!r)break;ft.delete(r)}return n}function Up(e){e&&ft.delete(yi(e))}function jp(e,t){if(!e)return;const n=Fp(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Np(t)&&n.consecutiveErrors>=xp&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Np(e){return e!==void 0&&_p.has(e)}function Bp(e){const t=ft.get(yi(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Cp*4),!1):!0:!1}function Hp(e){if(!(!e||!Bp(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const Ml=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,ma=/^(?:\/\/\?\/)?[A-Za-z]:$/u,zp=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/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==="/"?"/":Ml.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},$p=e=>{if(e==="/"||Ml.test(e)||ma.test(e)||zp.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},Wp=e=>Ye(e)??"",Gp="openchamber",qp="auto",Kp=(e,t)=>e===Gp&&t===qp,Vp=it(m().min(1),v({type:N("running")})),Jp=v({id:m().min(1),sessionID:m().min(1),action:m(),resources:G(m())}),Yp=v({id:m().min(1),sessionID:m().min(1),title:m()}),Qp=v({sessions:it(m().min(1),v({status:m(),lastUpdateAt:R()})),pending:it(m().min(1),v({permissions:G(Jp),forms:G(Yp)})).optional(),serverTime:R()});function K(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const vn={text:(e,t)=>`${e}:text:${t}`,reasoning:(e,t)=>`${e}:reasoning:${t}`,tool:e=>e,userText:e=>`${e}:text:0`,userFile:(e,t)=>`${e}:file:${t}`,userAgent:(e,t)=>`${e}:agent:${t}`},iv=e=>e==="completed"||e==="error",Dl=e=>e.role==="user"||e.role==="assistant",av=e=>e==="user"||e==="assistant",cv=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&Dl(n))return n}},lv=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.info&&Dl(n.info))return n}},uv=e=>e?.role==="assistant"&&e.time.completed===void 0,ga="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Xp=14;let ya=0,Js=0;const Zp=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+=ga[t[r]%ga.length];return n},wa=e=>{const t=Date.now();t!==ya&&(ya=t,Js=0),Js+=1;const n=BigInt(t)*BigInt(4096)+BigInt(Js),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}${Zp(Xp)}`};function _r(e){return K({id:e.id,parentID:e.parentID,projectID:e.projectID,directory:e.location.directory,subpath:e.subpath,title:e.title??"",agent:e.agent,model:e.model,cost:e.cost,tokens:e.tokens,outcome:e.outcome,time:K({...e.time}),metadata:e.metadata,permissions:e.permissions,revert:e.revert,fork:e.fork})}function eh(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 th(e){return K({branch:e.branch.current,defaultBranch:e.branch.default})}function ba(e){return!e||e.length===0?"":e.filter(t=>t.type==="text").map(t=>t.text).join(`
3
+ `)}function nh(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 rh(e){return e.message||e.type}function sh(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:ba(e.state.content),metadata:e.state.metadata,time:{start:n,end:r},attachments:nh(e.state.content,s)});break;case"error":o=K({status:"error",input:e.state.input,error:rh(e.state.error),output:ba(e.state.content)||void 0,metadata:e.state.metadata,time:{start:n,end:r}});break}return K({id:vn.tool(e.id),sessionID:t.sessionID,messageID:t.messageID,type:"tool",callID:e.id,tool:e.name,state:o,executed:e.executed})}function oh(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:vn.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:vn.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(sh(o,t));break}return n}function ih(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 ah(e){return e.source.type==="uri"?e.source.uri:`data:${e.mime};base64,${e.data}`}function ch(e,t){const n=[];return e.text.length>0&&n.push({id:vn.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:vn.userFile(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name,url:ah(r)}))}),e.agents?.forEach((r,s)=>{n.push({id:vn.userAgent(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"agent",name:r.name})}),n}function lh(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:ch(e,{sessionID:t,messageID:e.id,created:e.time.created})};case"assistant":return{message:ih(e,t),parts:oh(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:uh(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 uh(e){return e==="Infinity"||e==="-Infinity"||e==="NaN"?void 0:e}function Sa(e,t){return e.map(n=>lh(n,t))}const dh=e=>e.type==="document";function fh(e){const t={};for(const n of e)if(dh(n))for(const[r,s]of Object.entries(n.info)){if(s===void 0)continue;const o=t[r];t[r]=Ta(o)&&Ta(s)?{...o,...s}:s}return t}function Ta(e){return Object.prototype.toString.call(e)==="[object Object]"}const ph=e=>({...e,name:e.id,displayName:e.name}),va="/api",hh=1e4,mh=4e3,gh=100,yh=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 ut 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 wh=v({_tag:m(),message:m().optional(),ref:m().optional()});function bh(e,t){if(t instanceof ut)return t;if(t instanceof ed){if(t.reason==="UnexpectedStatus"){const s=t.cause?.status;return new ut(e,"unexpected status",{status:typeof s=="number"?s:void 0,cause:t})}const r=new ut(e,t.reason==="Transport"?"transport failure":t.reason,{cause:t.cause??t});return t.reason==="Transport"&&Yi(t.cause)&&To(r),r}const n=wh.safeParse(t);if(n.success)return new ut(e,n.data.message??n.data._tag,{status:yh.get(n.data._tag),tag:n.data._tag,ref:n.data.ref,cause:t});if(t instanceof Error){const r=new ut(e,t.message,{cause:t});return Yi(t)&&To(r),r}return new ut(e,String(t),{cause:t})}const Sh=e=>e.tag==="InvalidRequestError"&&e.detail.startsWith("Skill not found"),Th=e=>e instanceof ut&&e.status===404;async function O(e,t){try{return await t()}catch(n){throw bh(e,n)}}const vh=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ka=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(vh.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}},Ea=()=>{try{return Pe().api("/api")}catch{return null}},_l=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)}},kh=3e4,Eh=e=>e.pathname.endsWith("/event")||e.pathname.endsWith("/log"),Ph="x-opencode-directory",Ah=e=>e.replace(/\/api\/*$/,"")||"/",Ys=e=>{const t=e.requestTimeoutMs??kh;return Zu.make({baseUrl:Ah(e.baseUrl),headers:e.directory?{[Ph]: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(Eh(s)||o==="POST")return g(n,r);const i=_l(t),a=r?.signal!==void 0?r.signal:n instanceof Request?n.signal:void 0,c=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let l,u=null;if(a&&c)l=AbortSignal.any([a,i.signal]);else if(a){const p=new AbortController,y=()=>p.abort(a.reason),b=()=>p.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=p.signal}else l=i.signal;const d=()=>{u?.(),i.cleanup()};let f=!1;try{const p=await g(n,{...r,signal:l});return f=p.body!==null,p}catch(p){throw i.signal.aborted&&!a?.aborted?new Error(`OpenCode request timed out after ${t}ms`):p}finally{!f||l.aborted?d():l.addEventListener("abort",d,{once:!0})}}})},Ih=v({reason:m().optional(),isDirectory:Ne().optional()}),ln=e=>e.replace(/\\/g,"/"),Pa=400,Aa=()=>{const e=xs();return e&&e.runtime?.isDesktop&&e.files?e.files:null},Lr=m().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),xh=v({home:Lr,chatsRoot:Lr.optional(),canonicalChatsRoot:Lr.optional(),canonicalLegacyChatsRoot:Lr.optional()}),Qs=e=>JSON.parse(JSON.stringify(e)),Ia=e=>K({previous:e.previous??void 0,next:e.next??void 0}),xa=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 Rh{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;providerCatalogInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;constructor(t=va){const r=Ea()||t;this.baseUrl=ka(r),this.client=Ys({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==W())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=Ea(),n=ka(t||va);this.baseUrl=n,this.client=Ys({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=Ys({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(eh)}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=>th(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=Ih.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&s?.isDirectory===!0)return"available";const o=ys(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??gh,order:t.order,search:t.search,cursor:t.cursor,parentID:t.parentID}));return{sessions:s.data.map(_r),cursor:Ia(s.cursor)}}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&&Kp(t.model.providerID,t.model.id)?void 0:t?.model,location:r?{directory:r}:void 0,metadata:t?.metadata}));return _r(s)}async getSession(t,n){const r=await O("session.get",()=>this.clientFor(n).session.get({sessionID:t}));return _r(r)}async deleteSession(t,n){return await O("session.remove",()=>this.clientFor(n).session.remove({sessionID:t})),!0}async renameSession(t,n,r){await O("session.update",()=>this.clientFor(r).session.update({sessionID:t,title:n}))}async moveSession(t,n,r){const s=this.normalizeCandidatePath(n)??n;await O("session.move",()=>this.client.session.move({sessionID:t,directory:s,delivery:r?.delivery}))}async switchSessionModel(t,n,r){await O("session.switchModel",()=>this.clientFor(r).session.switchModel({sessionID:t,model:n}))}async switchSessionAgent(t,n,r){await O("session.switchAgent",()=>this.clientFor(r).session.switchAgent({sessionID:t,agent:n}))}async getSessionMessages(t,n,r){const s=await O("message.list",()=>this.clientFor(r).message.list({sessionID:t,limit:n?.limit,cursor:n?.cursor,order:n?.cursor?void 0:n?.order})),o=Sa(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:Ia({...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]=Sa([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 ri(async()=>{const{default:d}=await import("./vendor-heic2any-CEam9pDc.js").then(f=>f.h);return{default:d}},__vite__mapDeps([0,1,2]))).default,r=t.url.indexOf(",");if(r===-1)return t;const s=t.url.substring(r+1),o=atob(s),i=new Uint8Array(o.length);for(let d=0;d<o.length;d++)i[d]=o.charCodeAt(d);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((d,f)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=f,p.readAsDataURL(c)});let u=t.filename;return u&&(u=u.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:u,url:l}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let n=t.url;if(t.url.startsWith("data:")){const r=t.url.indexOf(",");if(r!==-1){const s=t.url.substring(5,r),o=t.url.substring(r);n=`data:${s.replace(/^[^;,]+/,"text/plain")}${o}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toPromptFile(t){const n=await this.normalizeFilePart(t);return{uri:n.url,name:n.filename}}async applySendSelection(t,n,r,s){n.model&&(this.assertRuntimeUnchanged(s),await this.switchSessionModel(t,n.model,r)),n.agent&&(this.assertRuntimeUnchanged(s),await this.switchSessionAgent(t,n.agent,r))}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??wa("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)");Hp(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?Qs(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 ut)||!Sh(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 jp(t.providerID,a instanceof ut?a.status:void 0),a}return Up(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?Qs(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??wa("msg");return await O("session.shell",()=>this.clientFor(t.directory).session.shell({sessionID:t.sessionId,id:n,command:t.command})),n}async stageRevert(t,n,r){return O("session.revert.stage",()=>this.clientFor(r?.directory).session.revert.stage({sessionID:t,messageID:n,files:r?.files}))}async commitRevert(t,n){await O("session.revert.commit",()=>this.clientFor(n).session.revert.commit({sessionID:t}))}async clearRevert(t,n){await O("session.revert.clear",()=>this.clientFor(n).session.revert.clear({sessionID:t}))}async compactSession(t,n){await O("session.compact",()=>this.clientFor(n).session.compact({sessionID:t}))}async forkSession(t,n){const r=await O("session.fork",()=>this.clientFor(n?.directory).session.fork({sessionID:t,before:n?.before}));return _r(r)}async getActiveSessionStatuses(){try{const t=Vp.parse(await O("session.active",()=>this.client.session.active())),n={};for(const r of Object.keys(t))n[r]={type:"busy"};return n}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=Qp.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?Qs(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 Th(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 xa(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 xa(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=fh(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()+hh}),u})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const n=this.resolveDirectory(t),r=n??"",s=this.providerCatalogInFlight.get(r);if(s)return s;const o=(async()=>{const i=this.clientFor(n),[a,c,l]=await Promise.all([O("provider.list",()=>i.provider.list().then(u=>u.data)),O("model.list",()=>i.model.list().then(u=>u.data)),O("model.default",()=>i.model.default().then(u=>u.data)).catch(()=>{})]);return K({providers:a,models:c,default:l?{id:l.modelID,providerID:l.providerID}:void 0})})();this.providerCatalogInFlight.set(r,o);try{return await o}finally{this.providerCatalogInFlight.get(r)===o&&this.providerCatalogInFlight.delete(r)}}async listAgents(t){const n=this.resolveDirectory(t),r=n??"",s=this.listAgentsInFlight.get(r);if(s)return s;const o=O("agent.list",()=>this.clientFor(n).agent.list().then(i=>i.data.map(ph)));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=_l(mh);r=await g(n,{signal:s.signal}).finally(s.cleanup)}catch{return"unreachable"}if(Ge("opencodeClient.checkHealth:response",{status:r.status}),r.status===502||r.status===504)return"unreachable";if(!r.ok)return"unhealthy";try{const s=await r.json();return Ge("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0?"healthy":"unhealthy"}catch{return"unhealthy"}}async createDirectory(t,n){const r=Aa();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"?ln(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=Aa();try{if(u){const w=await u.listDirectory(t||"",n);if(!w||!Array.isArray(w.entries))throw new Zt("Directory listing returned an invalid response",{reason:"invalid-response"});const E=w.entries.map(k=>({name:k.name,path:ln(k.path),isDirectory:!!k.isDirectory,isFile:!k.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(s,{entries:E,expiresAt:Date.now()+Pa}),E}const d=new URLSearchParams;t&&t.trim().length>0&&d.set("path",t),n?.respectGitignore&&d.set("respectGitignore","true");const f=d.toString(),p=await g(`${this.baseUrl}/fs/list${f?`?${f}`:""}`);if(!p.ok){const w=await p.json().catch(()=>({})),E=typeof w.error=="string"?w.error:"Failed to list directory";throw new Zt(E,{reason:ys(w.reason),status:p.status})}const y=await p.json();if(!y||!Array.isArray(y.entries))throw new Zt("Directory listing returned an invalid response",{reason:"invalid-response"});const b=y.entries;return this.listDirectoryCache.set(s,{entries:b,expiresAt:Date.now()+Pa}),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?ln(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=ln(i.path),c=a.split("/").filter(Boolean).pop()||a,l=ln(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=W();if(!t||t==="local"){const n=await nl();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 xh.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 Rh;let Xs=null,Zs=null,eo=null;const Ra=new Set;let Ca=!1;const Ll=e=>{if(Ra.add(e),Ca||typeof window>"u")return;Ca=!0;const t=()=>{for(const n of Ra)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{}},Ch=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,s=new Set;let o;const i=()=>{if(o=void 0,r.size===0&&s.size===0)return;const c=Array.from(r.entries()),l=Array.from(s);r.clear(),s.clear();for(const[u,d]of c)try{n.setItem(u,JSON.stringify(d,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!r.has(u)&&!s.has(u)&&r.set(u,d)}for(const u of l)try{n.removeItem(u)}catch(d){console.error("Failed to remove deferred storage value",d),r.has(u)||s.add(u)}},a=()=>{o===void 0&&(o=setTimeout(i,0))};return Ll(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()}}},wi=e=>Ch(()=>jl(),e),Oh=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 Ll(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}}},Fl=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},bi=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},Ul=e=>{const t=bi(),n=new Set,r=new Set,s=l=>{if(r.has(l))return null;if(n.has(l))return t.getItem(l);try{return e.getItem(l)}catch{return null}},o=(l,u)=>{try{e.setItem(l,u),t.removeItem(l),n.delete(l),r.delete(l);return}catch{try{e.removeItem(l)}catch{}}t.setItem(l,u),n.add(l),r.delete(l)},i=l=>{try{e.removeItem(l),r.delete(l)}catch{r.add(l)}t.removeItem(l),n.delete(l)},a=()=>{const l=[];try{for(let u=0;u<e.length;u+=1){const d=e.key(u);d&&l.push(d)}}catch{}try{e.clear(),r.clear()}catch{for(const u of l)r.add(u)}t.clear(),n.clear()},c=()=>{const l=new Set;try{for(let u=0;u<e.length;u+=1){const d=e.key(u);d&&!r.has(d)&&!n.has(d)&&l.add(d)}}catch{}for(const u of n)l.add(u);return[...l]};return{getItem:s,setItem:o,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},Mh=()=>{const e=Fl("localStorage");return e?Ul(e):bi()},jl=()=>(Xs||(Xs=Mh()),Xs),yr=()=>(eo||(eo=Oh(jl())),eo),Dh=()=>{const e=Fl("sessionStorage");return e?Ul(e):bi()},_h=()=>(Zs||(Zs=Dh()),Zs),Lh={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.84375rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},dv={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function Oa(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Fr={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)"}}},to={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Fr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:to.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Fr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:to.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Fr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:to.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Fr.tool.inline})},Fh=[{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'}],Uh=[{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'}],Nl=e=>Object.fromEntries(e.map(t=>[t.id,t])),jh=Nl(Fh),Nh=Nl(Uh),Bh="system",Hh="system-mono",zh=e=>typeof e=="string"&&e in jh,$h=e=>typeof e=="string"&&e in Nh,Oo="openchamber.mobileKeyboardMode",Wh='meta[name="viewport"]',Ma="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",fv=()=>!0;function Ds(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const Gh=e=>Ds(e)==="resize-content"?`${Ma}, interactive-widget=resizes-content`:Ma,qh=()=>{if(typeof window>"u")return"resize-content";try{return Ds(localStorage.getItem(Oo))}catch{return"resize-content"}},Bl=e=>{const t=Ds(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Oo):localStorage.setItem(Oo,t)}catch{}return t},pv=e=>{const t=Bl(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(Wh);if(n instanceof HTMLMetaElement){const r=Gh(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},no=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Kh=new Set(["starting","running","stopping"]),Vh=e=>!!e?.tabs.some(t=>wn(t.purpose)&&t.lifecycle!=="exited"),Mo=512*1024,Jh=new TextEncoder,Yh=new TextDecoder,ro=e=>{const t=Jh.encode(e);if(t.byteLength<=Mo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Mo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Yh.decode(r),byteLength:r.byteLength}},Xe=(e,t)=>`${e}\0${t}`,un=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Qh="terminal-store";let Da=!1,_a=0;const Xh=v({type:N("project-action"),actionId:m()}),Gn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(_a+=1,`tab-${Date.now().toString(36)}-${_a.toString(36)}`),so=e=>typeof e=="object"&&e!==null,wn=e=>e.type==="project-action",Ur=(e,t)=>wn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,Zh=()=>Gn().replace(/^tab-/,"exec-"),La=e=>e==="running"?"running":"exited",em=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),tm=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()]},oo={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},nm=e=>e.trim()||"Action",rm=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},te=Wp,ws=(e,t)=>`${e}\0${t}`,Bn=(e,t,n,r)=>{e.set(ws(t,n),r)},Fa=(e,t,n,r)=>{if(!r)return!1;const s=ws(t,n),o=e.actionMutationRevisions.get(s)??0,i=r.get(s)??0;return o>i},sm=/^Terminal(?: (\d+))?$/,Ua=e=>{let t=0;for(const n of e){const r=sm.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}`},hv=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&Kh.has(e.lifecycle),om=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),jr=(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}),io=e=>({tabs:[e],activeTabId:e.id}),xe=(e,t)=>e.tabs.findIndex(n=>n.id===t);let ao=null,co=null;const im=e=>{if(co&&ao?.sessions===e.sessions&&ao.nextTabId===e.nextTabId)return co;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 ao={sessions:e.sessions,nextTabId:e.nextTabId},co=t,t},am=()=>{const e=Xu(()=>_h());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))}},Zr=yt()(Cn(hr((e,t)=>({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=te(n);r&&e(s=>{if(s.sessions.has(r))return s;const o=new Map(s.sessions),i=Gn(),a=jr(i,"Terminal");return o.set(r,io(a)),{sessions:o,nextTabId:s.nextTabId+1}})},getDirectoryState:n=>{const r=te(n);return t().sessions.get(r)},getActiveTab:n=>{const r=te(n),s=t().sessions.get(r);if(!s)return;const o=s.activeTabId;return o?s.tabs.find(i=>i.id===o)??s.tabs[0]:s.tabs[0]},getBuffer:(n,r)=>t().buffers.get(Xe(te(n),r))??no,matchesActionExecution:(n,r,s)=>{const o=t().sessions.get(te(n))?.tabs.find(i=>i.id===r);return!!(o&&wn(o.purpose)&&o.purpose.executionId===s)},captureStartedActionMutationRevisions:n=>{const r=te(n),s=ws(r,""),o=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(s)&&o.set(i,a);return o},createTab:n=>{const r=te(n);if(!r)return"tab-invalid";const s=Gn();return e(o=>{const i=new Map(o.sessions),a=i.get(r),c=o.nextTabId+1,l=Ua(a?.tabs??[]),u=jr(s,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,io(u)),{sessions:i,nextTabId:c}}),s},reconcileServerSessions:(n,r,s)=>{const o=te(n);o&&e(i=>{const a=i.sessions.get(o);if(!a&&r.length===0)return i;const c=[...a?.tabs??[]];let l=i.buffers,u=!1,d=null;const f=new Set,p=new Set,y=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(Xe(o,c[0].id))?c[0]:null;y&&r.length>0&&(c.length=0);for(const C of tm(r)){let Te=c.findIndex(F=>F.terminalSessionId===C.sessionId||F.id===C.sessionId);const ae=C.purpose,js=ae?.type==="project-action"&&Fa(i,o,ae.actionId,s?.startedActionMutationRevisions);if(ae?.type==="project-action"){f.add(ae.actionId);const F=c.findIndex(Qe=>wn(Qe.purpose)&&Qe.purpose.actionId===ae.actionId);if(js){F>=0&&p.add(c[F].id);continue}Te<0&&(Te=F)}const Ie=ae?.type==="project-action"?em(ae,C.status):{type:"terminal"};if(Te>=0){const F=c[Te];let Qe=F.purpose.type==="project-action"||ae?.type==="project-action"?La(C.status):C.status;F.lifecycle==="stopping"&&C.status==="running"&&F.purpose.type==="project-action"&&Ie.type==="project-action"&&F.purpose.executionId===Ie.executionId&&(Qe="stopping");const an=C.createdAt??F.createdAt,vr=ae?.type==="project-action"&&(F.terminalSessionId!==C.sessionId||Ie.type==="project-action"&&Ie.executionId!==null&&(F.purpose.type!=="project-action"||F.purpose.executionId!==Ie.executionId));if(vr){const wt=Xe(o,F.id);l=un(l,Ns=>Ns===wt)??l}const Fn=ae?.type==="project-action"&&C.status==="running"&&(F.terminalSessionId!==C.sessionId||F.lifecycle!=="running"),kr=F.purpose.type!==Ie.type||F.purpose.type==="project-action"&&Ie.type==="project-action"&&(F.purpose.actionId!==Ie.actionId||F.purpose.executionId!==Ie.executionId);if((F.terminalSessionId!==C.sessionId||F.lifecycle!==Qe||F.isConnecting!==!1||F.createdAt!==an||kr)&&(c[Te]={...F,terminalSessionId:C.sessionId,lifecycle:Qe,purpose:Ie,isConnecting:!1,createdAt:an},vr&&Object.assign(c[Te],oo),u=!0),Fn){const wt={tabId:F.id,createdAt:an,index:Te};(!d||wt.createdAt>d.createdAt||wt.createdAt===d.createdAt&&wt.index>d.index)&&(d=wt)}p.add(F.id);continue}const _n=ae?.type==="project-action"?nm(ae.actionId):y&&c.length===0?y.label:Ua(c),Ln=ae?.type==="project-action"?"play":null,jt={...jr(C.sessionId,_n),terminalSessionId:C.sessionId,lifecycle:ae?.type==="project-action"?La(C.status):C.status,purpose:Ie,iconKey:Ln,createdAt:C.createdAt??Date.now()};if(c.push(jt),u=!0,ae?.type==="project-action"&&C.status==="running"){const F={tabId:jt.id,createdAt:jt.createdAt,index:c.length-1};(!d||F.createdAt>d.createdAt||F.createdAt===d.createdAt&&F.index>d.index)&&(d=F)}p.add(jt.id)}let b=u||!!(y&&r.length>0);const w=c.map(C=>!wn(C.purpose)||f.has(C.purpose.actionId)||p.has(C.id)||C.lifecycle==="starting"||Fa(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}})),E=a?.activeTabId??null,k=E&&w.some(C=>C.id===E)?E:w[0]?.id??null,U=k?w.find(C=>C.id===k):w[0],D=d&&!om(U)?d.tabId:k;if(!b&&a&&D===a.activeTabId&&w.length===a.tabs.length&&w.every((C,Te)=>C===a.tabs[Te]))return i;const J=new Map(i.sessions);return J.set(o,{tabs:w,activeTabId:D}),{sessions:J,buffers:l}})},setActiveTab:(n,r)=>{const s=te(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);return!a||a.activeTabId===r||xe(a,r)<0?o:(i.set(s,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,s)=>{const o=te(n),i=s.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const u=xe(l,r);if(u<0||l.tabs[u]?.label===i)return a;const d=[...l.tabs];return d[u]={...d[u],label:i},c.set(o,{...l,tabs:d}),{sessions:c}})},setTabIconKey:(n,r,s)=>{const o=te(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const l=xe(c,r);if(l<0)return i;const u=s?.trim()||null;if(c.tabs[l]?.iconKey===u)return i;const d=[...c.tabs];return d[l]={...d[l],iconKey:u},a.set(o,{...c,tabs:d}),{sessions:a}})},closeTab:(n,r)=>{const s=te(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=xe(a,r);if(c<0)return o;const l=a.tabs[c].purpose;let u=o.actionMutationRevisions,d=o.nextActionMutationRevision;l.type==="project-action"&&(u=new Map(u),Bn(u,s,l.actionId,d),d+=1);const f={actionMutationRevisions:u,nextActionMutationRevision:d},p=a.tabs.filter(k=>k.id!==r),y=Xe(s,r),b=o.buffers.has(y)?un(o.buffers,k=>k===y):null;if(p.length===0){const k=Gn(),U=jr(k,"Terminal");i.set(s,io(U));const D={sessions:i,nextTabId:o.nextTabId+1};return b&&(D.buffers=b),{...D,...f}}let w=a.activeTabId;a.activeTabId===r&&(w=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),i.set(s,{...a,tabs:p,activeTabId:w});const E={sessions:i};return b&&(E.buffers=b),{...E,...f}})},setTabPurpose:(n,r,s)=>{const o=te(n);e(i=>{const a=i.sessions.get(o);if(!a)return i;const c=xe(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(s))return i;const u=[...a.tabs],d=s.type==="project-action"&&s.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==s.executionId);u[c]={...l,purpose:s},d&&Object.assign(u[c],oo);const f=Xe(o,r),p=d?un(i.buffers,w=>w===f)??i.buffers:i.buffers,y=new Map(i.sessions);if(y.set(o,{...a,tabs:u}),s.type!=="project-action")return{sessions:y};const b=new Map(i.actionMutationRevisions);return Bn(b,o,s.actionId,i.nextActionMutationRevision),{sessions:y,buffers:p,actionMutationRevisions:b,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,s)=>{const o=te(n),i=t().sessions.get(o);if(!i||xe(i,r)<0)return null;const a=Zh();return e(c=>{const l=c.sessions.get(o);if(!l)return c;const u=xe(l,r);if(u<0)return c;const d=[...l.tabs];d[u]={...d[u],purpose:{type:"project-action",actionId:s,executionId:a},lifecycle:"starting",terminalSessionId:null,...oo,isConnecting:!1};const f=new Map(c.sessions);f.set(o,{...l,tabs:d});const p=new Map(c.actionMutationRevisions);Bn(p,o,s,c.nextActionMutationRevision);const y=Xe(o,r),b=un(c.buffers,w=>w===y)??c.buffers;return{sessions:f,buffers:b,actionMutationRevisions:p,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,s,o)=>{const i=te(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0)return a;const d=l.tabs[u];if(!Ur(d,o?.expectedExecutionId))return a;const f=s!==null&&d.terminalSessionId!==s,p=s?"running":d.terminalSessionId?"exited":d.lifecycle,y={...d,terminalSessionId:s,lifecycle:p,isConnecting:!1},b=Xe(i,r),w=f&&a.buffers.has(b)?un(a.buffers,U=>U===b):null,E=[...l.tabs];E[u]=y,c.set(i,{...l,tabs:E});const k={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(wn(d.purpose)){const U=new Map(a.actionMutationRevisions);Bn(U,i,d.purpose.actionId,a.nextActionMutationRevision),k.actionMutationRevisions=U,k.nextActionMutationRevision=a.nextActionMutationRevision+1}return w&&(k.buffers=w),k})},setTabLifecycle:(n,r,s,o)=>{const i=te(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0||!Ur(l.tabs[u],o?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===s&&!d.isConnecting)return a;const f=[...l.tabs];if(f[u]={...d,lifecycle:s,isConnecting:!1},c.set(i,{...l,tabs:f}),d.purpose.type!=="project-action"||d.lifecycle===s)return{sessions:c};const p=new Map(a.actionMutationRevisions);return Bn(p,i,d.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:p,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,s,o)=>{const i=te(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0||!Ur(l.tabs[u],o?.expectedExecutionId))return a;const d=[...l.tabs];return d[u]={...d[u],isConnecting:s},c.set(i,{...l,tabs:d}),{sessions:c}})},replaceBuffer:(n,r,s,o,i)=>{const a=te(n);e(c=>{const l=c.sessions.get(a);if(!l||xe(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??no;if(d.lastSequence>o)return c;const f=ro(s),p=d.chunks[0]?.size;if(d.lastSequence===o&&d.byteLength===f.byteLength&&d.chunks.map(w=>w.data).join("")===f.text&&p?.cols===i?.cols&&p?.rows===i?.rows)return c;const y=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:f.text?[{id:y,data:f.text,byteLength:f.byteLength,...i?{size:i}:{}}]:[],byteLength:f.byteLength,lastSequence:o}),{buffers:b,nextChunkId:f.text?y+1:y}})},appendToBuffer:(n,r,s,o,i)=>{if(!s)return;const a=te(n);e(c=>{const l=c.sessions.get(a);if(!l||xe(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??no;if(o!==void 0&&o<=d.lastSequence)return c;const f=c.nextChunkId,p=ro(s),y=i!==void 0&&i!==s?ro(i).text:void 0,b={id:f,data:p.text,...y!==void 0?{replayData:y}:{},byteLength:p.byteLength},w=[...d.chunks,b];let E=d.byteLength+b.byteLength;for(;E>Mo&&w.length>1;){const U=w.shift();if(!U)break;E-=U.byteLength}const k=new Map(c.buffers);return k.set(u,{chunks:w,byteLength:E,lastSequence:o??d.lastSequence}),{buffers:k,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,s,o={})=>{const i=te(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0)return a;const d=l.tabs[u];if(!Ur(d,o.expectedExecutionId))return a;const f=o.autoOpened??d.previewAutoOpened,p=o.locked??d.previewUrlLocked;if(d.previewUrl===s&&d.previewAutoOpened===f&&d.previewUrlLocked===p)return a;const y=[...l.tabs];return y[u]={...d,previewUrl:s,previewAutoOpened:f,previewUrlLocked:p},c.set(i,{...l,tabs:y}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const s=te(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=xe(a,r);if(c<0)return o;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return o;const u=[...a.tabs];return u[c]={...l,previewAutoOpened:!0},i.set(s,{...a,tabs:u}),{sessions:i}})},removeDirectory:n=>{const r=te(n);e(s=>{const o=new Map(s.sessions);o.delete(r);const i=Xe(r,""),a=un(s.buffers,d=>d.startsWith(i)),c=ws(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:Qh,storage:am(),partialize:im,merge:(e,t)=>{if(!so(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"||!so(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],f=new Map;for(const w of u){if(!so(w))continue;const E=typeof w.id=="string"?w.id:null;if(!E)continue;const k=rm(E);k!==null&&(s=Math.max(s,k));const U=k===null?E:Gn();f.set(E,U);const D=Xh.safeParse(w.purpose).data,J=D?{type:"project-action",actionId:D.actionId,executionId:null}:{type:"terminal"};d.push({id:U,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:J,createdAt:typeof w.createdAt=="number"?w.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(d.length===0)continue;const p=typeof l.activeTabId=="string"?l.activeTabId:null,y=p?f.get(p)??p:null,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"&&!Da){Da=!0;const e=Zr.persist,t=()=>{Zr.getState().hasHydrated||Zr.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Ze=20,cm=8,ja=4096,lm=2160*60*6e4,Q=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const s=r==="/",o=/^[A-Za-z]:\/$/.test(r);return!s&&!o&&(r=r.replace(/\/+$/,"")),r},It=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Rt=(e,t)=>{const n=Q(t),r=Q(e);if(!n||!r)return!1;const s=It(n),o=It(r);return o===s||o.startsWith(`${s}/`)},Hn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=Q(r);if(!o||!s||typeof s!="object")continue;const i=s,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(p=>typeof p=="string").map(p=>Q(p)).filter(p=>p.length<=ja&&Rt(p,o)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(p=>typeof p=="string").map(p=>Q(p)).filter(p=>p.length<=ja&&Rt(p,o)))).slice(-500):[],l=typeof i.selectedPath=="string"?Q(i.selectedPath):null,u=l&&Rt(l,o)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>lm)continue;const f=n[o];if(f){const p=Array.from(new Set([...f.openPaths,...a])),y=Array.from(new Set([...f.expandedPaths,...c])),b=f.selectedPath??u??p[0]??null;n[o]={openPaths:p,selectedPath:b,expandedPaths:y,touchedAt:Math.max(f.touchedAt,d)};continue}n[o]={openPaths:a,selectedPath:u,expandedPaths:c,touchedAt:d}}return et(n,Ze)},et=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((s,o)=>(o[1]?.touchedAt??0)-(s[1]?.touchedAt??0));const r={};for(const[s,o]of n.slice(0,t))r[s]=o;return r},dn=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},um=yt()(Cn(hr((e,t)=>({byRoot:{},activeRuntimeKey:W(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const s={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Hn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:s,byRoot:Hn(s[n]?.byRoot)}})},addOpenPath:(n,r,s)=>{const o=Q((n||"").trim()),i=Q((r||"").trim());!o||!i||!s?.allowOutsideRoot&&!Rt(i,o)||e(a=>{const c=a.byRoot[o],l=dn(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&u&&c.selectedPath===f)return a;const p={...a.byRoot,[o]:{...l,openPaths:d,selectedPath:f}};return{byRoot:et(p,Ze)}})},removeOpenPath:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=It(o),l=y=>It(y)===c,u=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!u)return i;const d=a.openPaths.filter(y=>!l(y)),f=u?d[0]??null:a.selectedPath,p={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeOpenPathsByPrefix:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=It(o),l=c.endsWith("/")?c:`${c}/`,u=y=>{const b=It(y);return b===c||b.startsWith(l)},d=a.openPaths.filter(y=>!u(y));if(d.length===a.openPaths.length)return i;const f=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,p={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeExpandedPathsByPrefix:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=It(o),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(f=>{const p=It(f);return p!==c&&!p.startsWith(l)});if(u.length===a.expandedPaths.length)return i;const d={...i.byRoot,[s]:{...a,expandedPaths:u,touchedAt:Date.now()}};return{byRoot:et(d,Ze)}})},setSelectedPath:(n,r,s)=>{const o=Q((n||"").trim()),i=r?Q(r.trim()):null;!o||i&&!s?.allowOutsideRoot&&!Rt(i,o)||e(a=>{const c=a.byRoot[o],l=dn(c),u=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&u===c.openPaths)return a;const d={...a.byRoot,[o]:{...l,openPaths:u,selectedPath:i}};return{byRoot:et(d,Ze)}})},ensureSelectedPath:n=>{const r=Q((n||"").trim());if(!r)return;const s=t().byRoot[r];if(!s||s.selectedPath)return;const o=s.openPaths[0]??null;o&&t().setSelectedPath(r,o)},toggleExpandedPath:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||!Rt(o,s)||e(i=>{const a=i.byRoot[s],c=dn(a),u=c.expandedPaths.includes(o)?c.expandedPaths.filter(f=>f!==o):[...c.expandedPaths,o];if(a&&a.expandedPaths===u&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:u}};return{byRoot:et(d,Ze)}})},collapseAllExpandedPaths:n=>{const r=Q((n||"").trim());r&&e(s=>{const o=s.byRoot[r];if(!o||o.expandedPaths.length===0)return s;const i={...s.byRoot,[r]:{...dn(o),expandedPaths:[]}};return{byRoot:et(i,Ze)}})},expandPath:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||!Rt(o,s)||e(i=>{const a=i.byRoot[s],c=dn(a);if(c.expandedPaths.includes(o)&&a)return i;const u={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,o]}};return{byRoot:et(u,Ze)}})},expandPaths:(n,r)=>{const s=Q((n||"").trim());if(!s||!r||r.length===0)return;const o=r.map(i=>Q((i||"").trim())).filter(i=>i&&Rt(i,s));o.length!==0&&e(i=>{const a=i.byRoot[s],c=dn(a),l=new Set(c.expandedPaths),u=o.filter(f=>!l.has(f));if(u.length===0)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:et(d,Ze)}})}}),{name:"files-view-tabs-store",version:3,storage:wi(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:W(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Hn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,cm).map(([r,s])=>[r,{byRoot:Hn(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=W();return{...t,activeRuntimeKey:s,runtimeSnapshots:r,byRoot:Hn(r[s]?.byRoot)}}}),{name:"files-view-tabs-store"})),dm=["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"],fm=/^plugin:[a-z][a-z0-9-]*$/,pm=new Set(dm),hm=e=>fm.test(e),mm=e=>pm.has(e)||hm(e),mv=e=>e.slice(7),gv=e=>`plugin:${e}`,Si=["session","repository","usage","telemetry","subagents","mcp","pinned","contextSources"],yv={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"},gm=/^ext:[a-z][a-z0-9-]*$/,wv=e=>`ext:${e}`,ym=e=>gm.test(e),wm=_t([Se(Si),Qu(["ext:",m().regex(/^[a-z][a-z0-9-]*$/)])]),Hl=e=>{const t=wm.safeParse(e);return t.success?t.data:null},bs=e=>{const t=new Set;if(Array.isArray(e))for(const n of e){const r=Hl(n);r&&t.add(r)}for(const n of Si)t.add(n);return[...t]},bv=(e,t)=>{const n=new Set(t),r=bs(e).filter(o=>!ym(o)||n.has(o)),s=new Set(r);for(const o of t)s.has(o)||r.push(o);return r},Sv=(e,t)=>!e?.includes(t),Tv=(e,t=[])=>e!=null&&Si.every(n=>e.includes(n))&&t.every(n=>e.includes(n)),vv=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),zl=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e){const s=Hl(r);s&&n.add(s)}return t||n.delete("telemetry"),[...n]},bm=e=>Math.min(480,Math.max(200,Math.round(e))),Sm=Se(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),Tm=v({widthByMode:it(m(),R().finite().optional().catch(void 0)).catch({}),widthFractionByMode:it(m(),R().positive().max(1).optional().catch(void 0)).catch({})}),$l="ask",Na=e=>e==="attach"||e==="inline"||e==="ask"?e:$l;function Ba(e){return e==="vim"?"vim":"default"}const pt="all";function Ha(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function za(e){return e==="me"||e==="any"?e:"any"}function Wl(e){return typeof e!="string"?pt:e.trim()||pt}function $a(e,t){const n=W();if(Jc(n))return e;const r={...e};return t===pt?delete r[n]:r[n]=t,r}function vm(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=Wl(r);s!==pt&&(t[n]=s)}return t}function Wa(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const Nr={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:""}},Br=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,km=e=>{if(!e||typeof e!="object")return!1;const t=e;return Br(t.completion,Nr.completion)&&Br(t.error,Nr.error)&&Br(t.question,Nr.question)&&Br(t.subtask,Nr.subtask)},Em=380,Pm=320,Am=1e4,Gl=12,Ga=120,Im=280;let Hr=0;const xm=e=>ue(e),ue=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?t.startsWith("/")?"/":"":r},ql=e=>Number.isFinite(e)?Math.min(Am,Math.max(Pm,Math.round(e))):Em,ur=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Ss=e=>{const t=ur(e);return t&&xm(t)||null},Ts=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>Ga?t.slice(0,Ga):t:null},Ti=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,Kl=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},Rm=(e,t)=>(e==="file"||e==="browser")&&t||e,Vl=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return Rm(e,t)},vi=(e,t)=>t===e?e:`${e}:${t}`,ki=e=>{const t=ur(e.targetPath),n=e.mode==="terminal"?Ss(e.targetDirectory):null,r=Vl(e.mode,t,e.dedupeKey);return{id:vi(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Kl(e.projectPlanRef),dedupeKey:r,label:Ts(e.label),sessionTitleFallback:Ts(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:Ti(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Jl=(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))},Yl=e=>{if(!Array.isArray(e))return[];const t=Ce(),n=[],r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s;if(typeof o.mode!="string"||!mm(o.mode)||t&&o.mode==="browser")continue;const i=ur(typeof o.targetPath=="string"?o.targetPath:null),a=o.mode==="terminal"?Ss(o.targetDirectory):null,c=typeof o.projectPlanId=="string"&&o.projectPlanId.trim()?o.projectPlanId.trim():null,l=Kl(o.projectPlanRef);if(o.mode==="plan"&&c!==null!=(l!==null))continue;const u=Vl(o.mode,i,typeof o.dedupeKey=="string"?o.dedupeKey:null),d=vi(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:Ts(typeof o.label=="string"?o.label:null),sessionTitleFallback:Ts(typeof o.sessionTitleFallback=="string"?o.sessionTitleFallback:null),readOnly:o.readOnly===!0,stagedDiff:o.stagedDiff===!0,diffScope:Ti(o.diffScope)??(o.stagedDiff===!0?"staged":"working"),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return n},In=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,zt=e=>{if(e){const t=Yl(e.tabs),n=In(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()}},Cm=(e,t,n)=>{const r=n?.reveal!==!1,s=ki(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=Jl(a,Gl,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:In(l,c),touchedAt:Date.now()}},Om=(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:In(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=ki({mode:"file"});return{...e,tabs:[...s,l],activeTabId:l.id,isOpen:e.isOpen,touchedAt:Date.now()}}return{...e,tabs:s,activeTabId:c?.id??In(s,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},Mm=(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},Dm=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),lo=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=ue(r);if(!o||!s||typeof s!="object")continue;const i=s;let a=Yl(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=[ki({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=In(a,c),u=Jl(a,Gl,l),d={},f={},p=Tm.parse(s);for(const y of Sm.options){const b=p.widthByMode[y],w=p.widthFractionByMode[y];b!==void 0&&(d[y]=ql(b)),w!==void 0&&(f[y]=w)}n[o]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:In(u,l),widthByMode:d,widthFractionByMode:f,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},$t=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((s,o)=>(o[1]?.touchedAt??0)-(s[1]?.touchedAt??0));const r={};for(const[s,o]of n.slice(0,t))r[s]=o;return r},T=yt()(Cn(hr((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:Im,contextPanelByDirectory:{},contextRailOrder:[],contextRailHiddenSurfaces:[],contextEditorTreeVisible:!0,contextEditorVisible:!0,contextEditorTreeWidth:240,notesPanelHeight:112,workStatusExpandedSections:{},messageQueueExpanded:!0,workStatusScrollTop:0,workStatusPanelEnabled:!0,workStatusPanelVisible:!1,workStatusPanelFits:!1,workStatusOverlayOpen:!1,workStatusHiddenSections:[],workStatusSectionOrder:bs([]),workStatusHiddenSectionsExplicit:!1,isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,openGuestPageId:null,worktreesPageProjectId:null,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsProjectPath:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,streamingAutoFollowEnabled:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionGoalEnabled:!0,sessionGoalDefaultBudgetEnabled:!1,sessionGoalDefaultBudget:2e5,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",sessionRetentionOnlyArchived:!1,autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:Bh,monoFont:Hh,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:qh(),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:pt,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,agentMemoryFeatureAvailable:!1,routingFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:$l,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:bm(n)})},openContextSurface:(n,r)=>{const s=ue((n||"").trim());if(!s)return;const o=t(),i=o.contextPanelByDirectory[s],a=i?.tabs??[],c=a.find(d=>d.id===i?.activeTabId)??null,l=()=>{if(r==="terminal"){const f=(a.find(p=>p.mode==="terminal")??null)?.targetDirectory??null;if(f){const p=Zr.getState().getDirectoryState(f);if(Vh(p))return}o.openContextPanelTab(s,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),o.closeContextPanel(s);return}r==="file"&&!o.contextEditorTreeVisible&&e({contextEditorTreeVisible:!0});const u=a.filter(d=>d.mode===r);if(u.length>0){l();const d=u.reduce((f,p)=>p.touchedAt>=f.touchedAt?p:f);o.setActiveContextPanelTab(s,d.id);return}r!=="chat"&&o.openContextPanelTab(s,{mode:r})},openContextPanelTab:(n,r,s)=>{const o=ue((n||"").trim());if(!o)return;const i=r.mode==="terminal"?{...r,targetDirectory:Ss(r.targetDirectory)===o?null:Ss(r.targetDirectory)}:r,a=i.mode==="file"&&!!i.targetPath&&s?.reveal!==!1;e(c=>{const l=c.contextPanelByDirectory[o],u=zt(l),d={...c.contextPanelByDirectory,[o]:Cm(u,i,s)};return{contextPanelByDirectory:$t(d,20),contextEditorVisible:a||c.contextEditorVisible}})},openContextDiff:(n,r,s=!1,o=null)=>{const i=ue((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=Ti(o)??(s?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const s=ue((n||"").trim()),o=ur(r);!s||!o||(t().openContextPanelTab(s,{mode:"file",targetPath:o}),t().setPendingFileFocusPath(o),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,s,o)=>{const i=ue((n||"").trim()),a=ur(r),c=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1,l=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:n=>{const r=ue((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const s=ue((n||"").trim()),o=(r||"").trim();!s||!o||Ce()||t().openContextPanelTab(s,{mode:"browser",targetPath:o,dedupeKey:o,label:null})},openAgentBrowserTab:(n,r)=>{const s=ue((n||"").trim());if(!s||Ce())return null;Hr+=1;const o=`browser:agent:${Date.now()}-${Hr}`;return t().openContextPanelTab(s,{mode:"browser",targetPath:r.trim(),dedupeKey:o,label:null},{reveal:!1}),vi("browser",o)},openNewContextBrowserTab:n=>{const r=ue((n||"").trim());!r||Ce()||(Hr+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${Hr}`,label:null}))},openContextBrowser:(n,r="",s)=>{const o=ue((n||"").trim());if(!o||Ce())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(o,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},s)},setContextPanelTabTargetPath:(n,r,s)=>{const o=ue((n||"").trim()),i=(r||"").trim();!o||!i||e(a=>{const c=a.contextPanelByDirectory[o];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[o]:Dm(c,i,s)}}:a})},setActiveContextPanelTab:(n,r)=>{const s=ue((n||"").trim()),o=(r||"").trim();!s||!o||e(i=>{const a=i.contextPanelByDirectory[s],c=zt(a),l=c.tabs.find(f=>f.id===o);if(!l)return i;const u=l.mode==="file"&&!!l.targetPath;if(c.activeTabId===o&&c.isOpen)return u?{contextEditorVisible:!0}:i;const d={...i.contextPanelByDirectory,[s]:{...c,isOpen:!0,activeTabId:o,touchedAt:Date.now(),tabs:c.tabs.map(f=>f.id===o?{...f,touchedAt:Date.now()}:f)}};return{contextPanelByDirectory:$t(d,20),contextEditorVisible:u||i.contextEditorVisible}})},reorderContextPanelTabs:(n,r,s)=>{const o=ue((n||"").trim()),i=(r||"").trim(),a=(s||"").trim();!o||!i||!a||e(c=>{const l=c.contextPanelByDirectory[o],u=zt(l);if(!u.tabs.some(p=>p.id===i)||!u.tabs.some(p=>p.id===a))return c;const d=Mm(u,i,a);if(d.tabs===u.tabs)return c;const f={...c.contextPanelByDirectory,[o]:d};return{contextPanelByDirectory:$t(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const s=ue((n||"").trim()),o=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!s||o.length===0)return;const i=o.map(a=>t().contextPanelByDirectory[s]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[s],l=zt(c);if(!l.tabs.some(y=>o.includes(y.id)))return a;const u=Om(l,o),d=u.tabs.find(y=>y.id===u.activeTabId),f=u.isOpen&&d?.mode==="file"&&!d.targetPath,p={...a.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:$t(p,20),contextEditorTreeVisible:f||a.contextEditorTreeVisible}});for(const a of i)a.mode==="file"&&a.targetPath&&um.getState().removeOpenPath(s,a.targetPath)},closeContextPanel:n=>{const r=ue((n||"").trim());r&&e(s=>{const o=s.contextPanelByDirectory[r];if(!o||!o.isOpen)return s;const i={...s.contextPanelByDirectory,[r]:{...zt(o),isOpen:!1}};return{contextPanelByDirectory:$t(i,20)}})},toggleContextPanelExpanded:n=>{const r=ue((n||"").trim());r&&e(s=>{const o=s.contextPanelByDirectory[r],i=zt(o),a={...s.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:$t(a,20)}})},setContextPanelWidth:(n,r,s,o)=>{const i=ue((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=zt(c),u=ql(s),d={...l.widthFractionByMode};o!==void 0&&Number.isFinite(o)&&o>0?d[r]=Math.min(1,u/o):delete d[r];const f={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:$t(f,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(s=>s.workStatusExpandedSections[n]===r?s:{workStatusExpandedSections:{...s.workStatusExpandedSections,[n]:r}})},setMessageQueueExpanded:n=>{e(r=>r.messageQueueExpanded===n?r:{messageQueueExpanded:n})},setWorkStatusScrollTop:n=>{e({workStatusScrollTop:Math.max(0,n)})},setWorkStatusPanelEnabled:n=>{e({workStatusPanelEnabled:n})},setWorkStatusPanelVisible:n=>{e(r=>r.workStatusPanelVisible===n?r:{workStatusPanelVisible:n})},setWorkStatusPanelFits:n=>{e(r=>r.workStatusPanelFits===n?r:n?{workStatusPanelFits:!0,workStatusOverlayOpen:!1}:{workStatusPanelFits:!1})},setWorkStatusOverlayOpen:n=>{e(r=>r.workStatusOverlayOpen===n?r:{workStatusOverlayOpen:n})},setWorkStatusSectionVisible:(n,r)=>{e(s=>{const o=s.workStatusHiddenSections,i=o.includes(n);return r===!i?s:{workStatusHiddenSectionsExplicit:!0,workStatusHiddenSections:r?o.filter(a=>a!==n):[...o,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)],workStatusHiddenSectionsExplicit:!0})},setWorkStatusSectionOrder:n=>{e({workStatusSectionOrder:bs(n)})},setContextRailSurfaceVisible:(n,r)=>{e(s=>{const o=s.contextRailHiddenSurfaces,i=o.includes(n);return r===!i?s:{contextRailHiddenSurfaces:r?o.filter(a=>a!==n):[...o,n]}})},setContextRailHiddenSurfaces:n=>{e({contextRailHiddenSurfaces:[...new Set(n)]})},setSessionSwitcherOpen:n=>{t().isSessionSwitcherOpen!==n&&e({isSessionSwitcherOpen:n})},setSessionDropdownOpen:n=>{t().isSessionDropdownOpen!==n&&e({isSessionDropdownOpen:n})},setPendingDiffFile:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?s:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:s})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=t();return n&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),n},setIsMobile:n=>{e({isMobile:n})},toggleCommandPalette:()=>{e(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{e({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{e(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{e({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{e({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{e({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{e({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{e({isSessionCreateDialogOpen:n})},setScheduledTasksDialogOpen:n=>{e(n?{isScheduledTasksDialogOpen:!0,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isUsageStatsPageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isArchivePageOpen:!1})},setUsageStatsPageOpen:n=>{e(n?{isUsageStatsPageOpen:!0,isArchivePageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isUsageStatsPageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{worktreesPageProjectId:null})},setOpenGuestPage:n=>{e(n?{openGuestPageId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{openGuestPageId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.isUsageStatsPageOpen&&!n.worktreesPageProjectId&&!n.isMultiRunLauncherOpen&&!n.openGuestPageId||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",openGuestPageId:null})},setSettingsDialogOpen:n=>{e(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:n=>{e({isNewWorktreeDialogOpen:n})},setModelSelectorOpen:n=>{e({isModelSelectorOpen:n})},setSidebarSection:n=>{e({sidebarSection:n})},setSettingsPage:n=>{e({settingsPage:n})},setSettingsProjectPath:n=>{const r=n?.trim();e({settingsProjectPath:r||null})},setSettingsProjectsSelectedId:n=>{e({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{e({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{e({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{e({showReasoningTraces:n})},setStreamingAutoFollowEnabled:n=>{e({streamingAutoFollowEnabled:n})},setSessionRecapEnabled:n=>{e({sessionRecapEnabled:n})},setSessionSuggestionEnabled:n=>{e({sessionSuggestionEnabled:n})},setSessionGoalEnabled:n=>{e({sessionGoalEnabled:n})},setSessionGoalDefaultBudgetEnabled:n=>{e({sessionGoalDefaultBudgetEnabled:n})},setSessionGoalDefaultBudget:n=>{e({sessionGoalDefaultBudget:n})},setCollapsibleThinkingBlocks:n=>{e({collapsibleThinkingBlocks:n})},setChatRenderMode:n=>{e({chatRenderMode:n})},setActivityRenderMode:n=>{e({activityRenderMode:n})},setShowDeletionDialog:n=>{e({showDeletionDialog:n})},setAutoDeleteEnabled:n=>{e({autoDeleteEnabled:n})},setAutoSaveEnabled:n=>{e({autoSaveEnabled:n})},setAutoDeleteAfterDays:n=>{const r=Math.max(1,Math.min(365,n));e({autoDeleteAfterDays:r})},setSessionRetentionAction:n=>{e(r=>({sessionRetentionAction:r.sessionRetentionOnlyArchived?"delete":n}))},setSessionRetentionOnlyArchived:n=>{e(r=>({sessionRetentionOnlyArchived:n,sessionRetentionAction:n?"delete":r.sessionRetentionAction}))},setAutoDeleteLastRunAt:n=>{e({autoDeleteLastRunAt:n})},setMessageLimit:n=>{const r=Math.max(10,Math.min(500,Math.round(n)));e({messageLimit:r})},setFontSize:n=>{const r=Math.max(50,Math.min(200,n));e({fontSize:r}),t().applyTypography()},setGlobalDraftStarters:n=>{e({globalDraftStarters:n})},setDraftStartersVisible:n=>{e({draftStartersVisible:n})},setTerminalFontSize:n=>{const r=Math.round(n),s=Math.max(9,Math.min(52,r));e({terminalFontSize:s})},setTerminalShell:n=>{e({terminalShell:n})},setTerminalLoginShells:n=>{e({terminalLoginShells:[...new Set(n)]})},setEditorFontSize:n=>{const r=Math.round(n),s=Math.max(9,Math.min(32,r));e({editorFontSize:s})},setUiFont:n=>{e({uiFont:n})},setMonoFont:n=>{e({monoFont:n})},setPadding:n=>{const r=Math.max(50,Math.min(200,n));e({padding:r}),t().applyPadding()},setCornerRadius:n=>{e({cornerRadius:n})},applyTypography:()=>{const{fontSize:n}=t(),r=document.documentElement,s=n/100,o=Object.entries(Lh);if(s===1){r.style.removeProperty("font-size");for(const[i]of o)r.style.removeProperty(Oa(i));return}r.style.fontSize=`${s*100}%`;for(const[i]of o)r.style.removeProperty(Oa(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:Ha(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:za(n)})},setLinearIssueListTeamId:n=>{const r=Wl(n);e(s=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:$a(s.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=W();e(r=>({linearIssueListTeamId:Jc(n)?pt:r.linearIssueListTeamIdByRuntime[n]??pt}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:Wa(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:pt,linearIssueListTeamIdByRuntime:$a(n.linearIssueListTeamIdByRuntime,pt),linearIssueListPriority:"all"}))},setLinearIssueFocus:n=>{const r=n?.trim()??"";e({linearIssueFocus:r||null})},setInputBarOffset:n=>{e({inputBarOffset:n})},setMobileKeyboardMode:n=>{e(r=>r.mobileKeyboardMode===n?r:{mobileKeyboardMode:n})},toggleFavoriteModel:(n,r)=>{e(s=>s.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:s.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...s.favoriteModels]})},reorderFavoriteModel:(n,r,s,o)=>{e(i=>{const a=i.favoriteModels.findIndex(d=>d.providerID===n&&d.modelID===r),c=i.favoriteModels.findIndex(d=>d.providerID===s&&d.modelID===o);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[u]=l.splice(a,1);return u?(l.splice(c,0,u),{favoriteModels:l}):i})},setProviderOrder:n=>{e(r=>{const s=n.filter(i=>typeof i=="string"&&i.length>0),o=r.providerOrder;return o.length===s.length&&o.every((i,a)=>i===s[a])?r:{providerOrder:s}})},toggleHiddenModel:(n,r)=>{e(s=>s.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:s.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...s.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},hideAllModels:(n,r)=>{e(s=>{const o=s.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...o]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(s=>s.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>s.collapsedModelProviders.includes(r)?{collapsedModelProviders:s.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...s.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const s=Array.from(new Set(n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)));s.length!==0&&e(o=>{const i=new Set(s),a=o.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...s]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},addRecentModel:(n,r)=>{e(s=>{const o=s.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...o].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>{if(s.recentAgents.includes(r))return s;const o=s.recentAgents;return{recentAgents:[r,...o].slice(0,5)}})},addRecentEffort:(n,r,s)=>{const o=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!o||!i)return;const a=`${o}/${i}`,c=typeof s=="string"&&s.trim().length>0?s.trim():"default";e(l=>{const u=l.recentEfforts[a]??[];if(u.includes(c))return l;const d=u;return{recentEfforts:{...l.recentEfforts,[a]:[c,...d].slice(0,5)}}})},applyTheme:()=>{const{theme:n}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(s)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{e(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:"",...n?{isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,openGuestPageId:null}:{}}))},openMultiRunLauncher:()=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null})},openMultiRunLauncherWithPrompt:n=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null})},setTimelineDialogOpen:n=>{e({isTimelineDialogOpen:n})},setPromptNavigatorPanelOpen:n=>{e({isPromptNavigatorPanelOpen:n})},togglePromptNavigatorPanel:()=>{e(n=>({isPromptNavigatorPanelOpen:!n.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:n=>{e({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{e({nativeNotificationsEnabled:n})},setNotificationMode:n=>{e({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{e({showTerminalQuickKeysOnDesktop:n})},setSessionTabsEnabled:n=>{e({sessionTabsEnabled:n})},setNotifyOnSubtasks:n=>{e({notifyOnSubtasks:n})},setDockBadgeEnabled:n=>{e({dockBadgeEnabled:n})},setAlwaysShowScrollbars:n=>{e({alwaysShowScrollbars:n})},setNotifyOnCompletion:n=>{e({notifyOnCompletion:n})},setNotifyOnError:n=>{e({notifyOnError:n})},setNotifyOnQuestion:n=>{e({notifyOnQuestion:n})},setNotificationTemplates:n=>{e(r=>({notificationTemplates:typeof n=="function"?n(r.notificationTemplates):n}))},setSummarizeLastMessage:n=>{e({summarizeLastMessage:n})},setSummaryThreshold:n=>{e({summaryThreshold:n})},setSummaryLength:n=>{e({summaryLength:n})},setMaxLastMessageLength:n=>{e({maxLastMessageLength:n})},setPersistChatDraft:n=>{e({persistChatDraft:n})},setShowOpenCodeUpdateNotifications:n=>{e({showOpenCodeUpdateNotifications:n})},setAgentControlToolEnabled:n=>{e({agentControlToolEnabled:n})},setAgentWebToolEnabled:n=>{e({agentWebToolEnabled:n})},setBrowserProvider:n=>{e({browserProvider:n})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},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:Na(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:Ba(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:wi(),version:21,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<21&&n.workStatusHiddenSectionsExplicit!==!0&&(n.workStatusHiddenSections=Array.isArray(n.workStatusHiddenSections)?n.workStatusHiddenSections.filter(r=>r!=="telemetry"):[],n.workStatusHiddenSectionsExplicit=!1),t<16&&(delete n.activeMainTab,delete n.activeSurface),t<17&&delete n.expandedEditorToolbar,t<18&&delete n.shortcutOverrides,t<14){const r=n.contextPanelByDirectory;if(r&&typeof r=="object")for(const s of Object.values(r)){if(!s||typeof s!="object")continue;const o=s,i=o.widthByMode;if(i&&typeof i=="object"){const l=i;l.preview!==void 0&&(l.browser===void 0&&(l.browser=l.preview),delete l.preview)}if(!Array.isArray(o.tabs))continue;const a=new Set,c=[];for(const l of o.tabs){if(!l||typeof l!="object")continue;const u=l;if(u.mode!=="preview"){typeof u.id=="string"&&a.add(u.id),c.push(u);continue}const d=typeof u.targetPath=="string"?u.targetPath:"",f=typeof u.dedupeKey=="string"&&u.dedupeKey.trim()?u.dedupeKey.trim():d||"browser",p=f==="browser"?"browser":`browser:${f}`;a.has(p)||(a.add(p),c.push({...u,mode:"browser",id:p,dedupeKey:f}))}if(o.tabs=c,typeof o.activeTabId=="string"&&o.activeTabId.startsWith("preview")){const l=c.find(u=>typeof u.id=="string");o.activeTabId=l&&typeof l.id=="string"?l.id:null}}}if(t<13&&typeof n.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const s=localStorage.getItem("openchamber:files:auto-save-enabled");s!==null&&(r=s!=="false",localStorage.removeItem("openchamber:files:auto-save-enabled"))}}catch{r=!0}n.autoSaveEnabled=r}if(t<12&&(n.desktopWindowControlsPosition==="auto"||n.desktopWindowControlsPosition==null)&&(n.desktopWindowControlsPosition="right"),t<11&&n.terminalFontSize===13&&(n.terminalFontSize=14),t<10&&delete n.diffViewMode,t<9&&((!n.workStatusExpandedSections||typeof n.workStatusExpandedSections!="object")&&(n.workStatusExpandedSections={}),(typeof n.workStatusScrollTop!="number"||!Number.isFinite(n.workStatusScrollTop))&&(n.workStatusScrollTop=0),typeof n.workStatusPanelEnabled!="boolean"&&(n.workStatusPanelEnabled=!0),Array.isArray(n.workStatusHiddenSections)||(n.workStatusHiddenSections=[]),(typeof n.notesPanelHeight!="number"||!Number.isFinite(n.notesPanelHeight))&&(n.notesPanelHeight=112)),t<1&&km(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=lo(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=lo(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=lo(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Ha(n.linearIssueListStatus),n.linearIssueListAssignee=za(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=vm(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=Wa(n.linearIssueListPriority),n.fileEditorKeymap=Ba(n.fileEditorKeymap),n.largeTextPasteBehavior=Na(n.largeTextPasteBehavior),n.toolJsonViewMode!=="summary"&&n.toolJsonViewMode!=="formatted"&&n.toolJsonViewMode!=="raw"&&(n.toolJsonViewMode="summary"),typeof n.autoSaveEnabled!="boolean"&&(n.autoSaveEnabled=!0),n.contextRailHiddenSurfaces=Array.isArray(n.contextRailHiddenSurfaces)?n.contextRailHiddenSurfaces.filter(r=>typeof r=="string"&&r.trim()!==""):[],n.contextRailOrder=Array.isArray(n.contextRailOrder)?n.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""):[],n},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextRailHiddenSurfaces:e.contextRailHiddenSurfaces,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorVisible:e.contextEditorVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,notesPanelHeight:e.notesPanelHeight,workStatusExpandedSections:e.workStatusExpandedSections,messageQueueExpanded:e.messageQueueExpanded,workStatusScrollTop:e.workStatusScrollTop,workStatusPanelEnabled:e.workStatusPanelEnabled,workStatusHiddenSections:e.workStatusHiddenSections,workStatusSectionOrder:e.workStatusSectionOrder,workStatusHiddenSectionsExplicit:e.workStatusHiddenSectionsExplicit,isSessionSwitcherOpen:e.isSessionSwitcherOpen,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,streamingAutoFollowEnabled:e.streamingAutoFollowEnabled,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,sessionGoalEnabled:e.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:e.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:e.sessionGoalDefaultBudget,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,chatRenderMode:e.chatRenderMode,activityRenderMode:e.activityRenderMode,showDeletionDialog:e.showDeletionDialog,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,sessionRetentionOnlyArchived:e.sessionRetentionOnlyArchived,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,providerOrder:e.providerOrder,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,diffWrapLines:e.diffWrapLines,diffFileListMode:e.diffFileListMode,diffFileTreeWidth:e.diffFileTreeWidth,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,toolJsonViewMode:e.toolJsonViewMode,linearIssueListStatus:e.linearIssueListStatus,linearIssueListAssignee:e.linearIssueListAssignee,linearIssueListTeamIdByRuntime:e.linearIssueListTeamIdByRuntime,linearIssueListPriority:e.linearIssueListPriority,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,sessionTabsEnabled:e.sessionTabsEnabled,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,alwaysShowScrollbars:e.alwaysShowScrollbars,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,agentControlToolEnabled:e.agentControlToolEnabled,agentWebToolEnabled:e.agentWebToolEnabled,browserProvider:e.browserProvider,agentMemoryToolEnabled:e.agentMemoryToolEnabled,agentNotifyToolEnabled:e.agentNotifyToolEnabled,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"})),_m=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},Lm=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Fm=e=>{const t=T.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Um=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=Lm(t);return _m(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},jm=768,Nm=800,Bm=()=>{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},Hm=()=>{if(typeof window>"u")return!1;const e=new URLSearchParams(window.location.search).get("surface");return e==="mobile"||e==="desktop"},Ql=()=>{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<=jm&&Bm()},Xl=()=>{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:mr()?"mobile":Be()||Ce()?"desktop":Ql()?"mobile":"desktop"},kv=()=>{const e=Xl();return typeof window<"u"&&(window.__OPENCHAMBER_SURFACE__=e),e},zm=()=>Xl()==="mobile",Ev=()=>{if(typeof window>"u")return()=>{};if(mr()||Be()||Ce())return()=>{};if(Hm())return()=>{};let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null;const n=window.__OPENCHAMBER_SURFACE__,r=Ql()?"mobile":"desktop";n&&n!==r&&(window.__OPENCHAMBER_SURFACE__=void 0,window.location.reload())},Nm)};return window.addEventListener("resize",t),()=>{e&&clearTimeout(e),window.removeEventListener("resize",t)}},Zl="surface",Ei=()=>{try{if(Ce())return"vscode";if(Be())return"desktop";if(mr()||zm())return"mobile"}catch{}return"web"},$m=()=>Ei()==="mobile"?"timeline":"projects",Wm=(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},Do=yt()(hr(e=>({animatedActivityIndicators:!1,setAnimatedActivityIndicators:t=>e({animatedActivityIndicators:t}),projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sidebarViewMode:$m(),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:Wm})),eu="directoryTreeShowHidden",_o="directory-show-hidden-change",Lo=()=>{if(typeof window>"u")return!0;try{const e=yr().getItem(eu);return e===null?!0:e==="true"}catch{return!0}},Gm=()=>{typeof window>"u"||window.dispatchEvent(new Event(_o))},qm=()=>Lo(),Km=(e,t={})=>{if(!(typeof window>"u")){try{yr().setItem(eu,e?"true":"false"),Gm()}catch{}t.persist!==!1&&ht({directoryShowHidden:e})}},Pv=()=>{const e=Mc.c(2),[t,n]=os.useState(Lo);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(Lo())};return window.addEventListener("storage",o),window.addEventListener(_o,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(_o,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),os.useEffect(r,s),t},tu=[{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"}],Vm=new Map(tu.map(e=>[e.name,e])),Av=e=>Vm.get(e),Iv=tu.map(e=>({type:"command",name:e.name})),xv="terminal-box",Rv="book-open",Cv=e=>`${e.type}:${e.name}`,Ov=(e,t)=>e.type===t.type&&e.name===t.name,Mv=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Jm=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},nu="filesViewShowGitignored",Fo="files-view-show-gitignored-change",Uo=()=>{if(typeof window>"u")return!1;try{return yr().getItem(nu)==="true"}catch{return!1}},Ym=()=>{typeof window>"u"||window.dispatchEvent(new Event(Fo))},Qm=()=>Uo(),Xm=(e,t={})=>{if(!(typeof window>"u")){try{yr().setItem(nu,e?"true":"false"),Ym()}catch{}t.persist!==!1&&ht({filesViewShowGitignored:e})}},Dv=()=>{const e=Mc.c(2),[t,n]=os.useState(Uo);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(Uo())};return window.addEventListener("storage",o),window.addEventListener(Fo,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(Fo,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),os.useEffect(r,s),t},ru="session",su=40,Zm=1,eg=100,ou=e=>e==="global"||e==="session",Pi=e=>e!=null&&Number.isInteger(e)&&e>=Zm&&e<=eg,tg=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Ai=e=>e==="auto"||typeof e=="string"&&tg.includes(e),bn="openchamber-input-history.v1",ng=8,rg=50,sg=[40,25,10,5,1],uo=Object.freeze([]);let dt=null,qa=0;const er=(e=ru,t=su)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),iu=()=>(qa+=1,Date.now()*1e3+qa),au=e=>JSON.stringify([e]),jo=(e,t,n)=>JSON.stringify([e,t,n]),Ii=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},og=()=>{const e=Ii(),t=qe?JSON.stringify(ts(qe.base)):dt;if(!e)return t;try{return e.getItem(bn)??(qe?null:dt)}catch{return t}},Ka=it(m(),me()),ig=v({key:m().min(1),source:_t([N("file-url"),N("vscode-file")]),filename:m().min(1),mimeType:m().min(1),size:R().finite().nonnegative(),reference:m().min(1)}),ag=v({text:m(),attachmentKeys:G(m()),restorableAttachments:G(ig),submittedAt:R().finite().nonnegative()}),cg=v({touchedAt:R().finite().nonnegative(),entries:G(me())}),lg=(e,t)=>{try{const n=JSON.parse(e),s=(t===1?Gi([m().trim().min(1)]):Gi([m().trim().min(1),m().trim().min(1),m().trim().min(1)])).safeParse(n);if(!s.success)return null;if(t===3){const o=Ye(s.data[1]);if(!o||o!==s.data[1])return null}return s.data}catch{return null}},Va=(e,t)=>{const n=[];for(const[r,s]of Object.entries(e)){if(!lg(r,t))continue;const o=cg.safeParse(s);if(!o.success)continue;const i=o.data.entries.map(a=>ag.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:o.data.touchedAt,entries:i}])}return Object.fromEntries(n)},ug=()=>{const e=og();if(e===null)return er();try{const t=JSON.parse(e),n=v({version:N(1),entryLimit:R().int().optional(),scope:_t([N("global"),N("session")]).optional(),global:Ka.default({}),session:Ka.default({})}).safeParse(t);return n.success?{entryLimit:Pi(n.data.entryLimit)?n.data.entryLimit:su,scope:n.data.scope??ru,globalBuckets:Va(n.data.global,1),sessionBuckets:Va(n.data.session,3)}:er()}catch{const t=Ii();if(t)try{t.removeItem(bn)}catch{}return dt=null,er()}};let qe=null,es=er();const Ja=(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},qn=()=>{const e=ug();if(es=e,!qe)return e;const{base:t,value:n}=qe;return No({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:Ja(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:Ja(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},cu=(e,t)=>e.slice(Math.max(0,e.length-t)),Ya=(e,t,n)=>{const r=Object.entries(e).map(([s,o])=>[s,{touchedAt:o.touchedAt,entries:cu(o.entries,n)}]).sort((s,o)=>o[1].touchedAt-s[1].touchedAt).slice(0,t);return Object.fromEntries(r)},No=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Ya(e.globalBuckets,ng,t),sessionBuckets:Ya(e.sessionBuckets,rg,t)}),ts=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Qa=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Kn=e=>{const t=No(e),n=JSON.stringify(ts(t));qe={base:es,value:t};const r=Ii();if(!r)return dt=n,t;try{return r.setItem(bn,n),qe=null,dt=n,t}catch(i){if(!(i instanceof Error)||!Qa(i))return dt=n,t}try{r.removeItem(bn)}catch{}for(const i of sg){const a=No(t,i),c=JSON.stringify(ts(a));try{return r.setItem(bn,c),qe=null,dt=c,a}catch(l){if(!(l instanceof Error)||!Qa(l))return qe={base:es,value:a},dt=c,a}}const s=er(t.scope,t.entryLimit),o=JSON.stringify(ts(s));try{r.setItem(bn,o),qe=null}catch{qe={base:es,value:s}}return dt=o,s},dg=(e,t,n)=>{const r=e.trim(),s=Ye(t),o=n.trim();return!r||!s||!o?null:{runtimeKey:r,directory:s,sessionId:o}},lu=e=>e.source==="vscode"&&e.vscodeSource==="file"?Ye(e.vscodePath??null):e.dataUrl.trim()||null,fg=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Bo=e=>{const t=lu(e),n=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),n].join("|")},pg=e=>{const t=lu(e);return!t||!fg(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Bo(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Bo(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},hg=(e,t)=>({text:e,attachmentKeys:t.map(Bo),restorableAttachments:t.map(pg).filter(n=>n!==null)}),mg=(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}),gg=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&mg(e.restorableAttachments,t.restorableAttachments),Xa=(e,t,n,r)=>{const s=e?[...e.entries]:[];for(const o of t){const i=s.at(-1);gg(i,o)||s.push({text:o.text,attachmentKeys:[...o.attachmentKeys],restorableAttachments:o.restorableAttachments.map(a=>({...a})),submittedAt:iu()})}return{touchedAt:n,entries:cu(s,r)}},yg=Kn(qn()),Vn=yt(e=>({...yg,applyEntryLimit:t=>{Pi(t)&&e(n=>{const r=qn();if(r.entryLimit===t)return{...n,...r};const s=Kn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},applyScope:t=>{ou(t)&&e(n=>{const r=qn();if(r.scope===t)return{...n,...r};const s=Kn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const s=qn(),o=iu(),i=au(t.runtimeKey),a=jo(t.runtimeKey,t.directory,t.sessionId),c=Kn({entryLimit:s.entryLimit,scope:s.scope,globalBuckets:{...s.globalBuckets,[i]:Xa(s.globalBuckets[i],n,o,s.entryLimit)},sessionBuckets:{...s.sessionBuckets,[a]:Xa(s.sessionBuckets[a],n,o,s.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=qn(),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=Kn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:o});return{...n,...i}})}})),_v=(e,t)=>t?e.scope==="session"?e.sessionBuckets[jo(t.runtimeKey,t.directory,t.sessionId)]?.entries??uo:e.globalBuckets[au(t.runtimeKey)]?.entries??uo:uo,wg=v({text:m(),prefix:m(),suffix:m(),start:R()}),Za=32,bg=200,Sg="[data-chat-quote-root]";function Lv(e,t){return e.querySelector(`[data-message-id="${CSS.escape(t)}"]`)?.querySelector(Sg)??null}function ec(e,t,n){const r=e.ownerDocument.createRange();return r.setStart(e,0),r.setEnd(t,n),r.toString().length}function Fv(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))return null;const n=e.textContent??"",r=ec(e,t.startContainer,t.startOffset),s=ec(e,t.endContainer,t.endOffset),o=n.slice(r,s);return o.trim()?{text:o,prefix:n.slice(Math.max(0,r-Za),r),suffix:n.slice(s,s+Za),start:r}:null}function Tg(e,t){if(!t.text)return null;const n=[];for(let s=e.indexOf(t.text);s!==-1&&n.length<bg;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 uu(e,t){for(let n=e.firstChild;n;n=n.nextSibling)n.nodeType===3?t.push(n):uu(n,t);return t}function Uv(e,t){const n=Tg(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 uu(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 jv(e){return{text:e.trim(),prefix:"",suffix:"",start:0}}const vg=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,kg=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
4
+ `).replace(/^\n+|\n+$/g,"");if(!t||!n||!r)return null;const s=Math.max(1,Math.floor(e.startLine));return{terminalId:t,terminalLabel:n,startLine:s,endLine:Math.max(s,Math.floor(e.endLine)),text:r}},Eg=(e,t)=>{const n=t.map(kg).filter(o=>o!==null);if(n.length===0)return e;const s=["<terminal_context>",...n.flatMap((o,i)=>[`- ${o.terminalLabel} lines ${o.startLine}-${o.endLine}:`,...o.text.split(`
5
+ `).map((a,c)=>` ${o.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
6
+ `);return e.trim()?`${e.trim()}
7
+
8
+ ${s}`:s},Nv=e=>{const t=vg.exec(e);if(!t)return{visibleText:e,contexts:[]};const n=[];let r=null;for(const s of(t[1]??"").split(`
9
+ `)){const o=/^- (.+) lines (\d+)-(\d+):$/.exec(s);if(o){r&&n.push(r),r={terminalLabel:o[1],startLine:Number(o[2]),endLine:Number(o[3]),text:""};continue}const i=/^\s{2}\d+ \| ?(.*)$/.exec(s);r&&i&&(r.text+=`${r.text?`
10
+ `:""}${i[1]}`)}return r&&n.push(r),{visibleText:e.slice(0,t.index).trimEnd(),contexts:n}},xi="openchamberContext",Ri="opencodeComment";function Pg(e){switch(e.kind){case"code-comment":{const t=`lines ${e.startLine}-${e.endLine}`,n=e.source==="diff"&&e.side?` (${e.side})`:"";return`Comment on \`${e.fileLabel}\` ${t}${n}:
11
+ \`\`\`${e.language}
12
+ ${e.code}
13
+ \`\`\`
14
+
15
+ ${e.text}`}case"terminal":return Eg("",[{terminalId:e.terminalId,terminalLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,text:e.output}]);case"browser-annotation":return e.text?`${e.prompt}
16
+
17
+ ${e.text}`:e.prompt;case"pr-comment":return`Attached GitHub PR comment (${e.label}):
18
+
19
+ ${e.body}${e.text?`
20
+
21
+ ${e.text}`:""}`;case"file-quote":{const t=e.startLine!=null&&e.endLine!=null?` lines ${e.startLine}-${e.endLine}`:"",n=e.quote.split(`
22
+ `).map(r=>`> ${r}`).join(`
23
+ `);return`Comment on this fragment of \`${e.fileLabel}\`${t}:
24
+ ${n}${e.text?`
25
+
26
+ ${e.text}`:""}`}case"chat-quote":return`Comment on this fragment of an earlier message in this conversation:
27
+ ${e.quote.split(`
28
+ `).map(n=>`> ${n}`).join(`
29
+ `)}${e.text?`
30
+
31
+ ${e.text}`:""}`;case"pr-check":return`Attached failed GitHub PR check (${e.label}):
32
+ \`\`\`
33
+ ${e.output}
34
+ \`\`\`${e.text?`
35
+
36
+ ${e.text}`:""}`;case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return""}}function Bv(e,t){const n=t??Pg(e),r={[xi]:e};return e.kind==="code-comment"&&(r[Ri]={path:e.fileLabel,selection:{startLine:e.startLine,endLine:e.endLine,startChar:0,endChar:0},comment:e.text,preview:e.code,origin:e.source==="diff"?"review":"file"}),{text:n,metadata:r}}function Hv(e){switch(e.source){case"terminal":return{kind:"terminal",terminalId:e.terminalId??"",terminalLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,output:e.code};case"preview-annotation":return{kind:"browser-annotation",pageUrl:e.fileLabel,prompt:e.code,text:e.text};case"pr-comment":return{kind:"pr-comment",label:e.fileLabel,body:e.code,text:e.text};case"pr-check":return{kind:"pr-check",label:e.fileLabel,output:e.code,text:e.text};case"file-quote":{const t={kind:"file-quote",fileLabel:e.fileLabel,quote:e.code,text:e.text};return e.startLine>0&&e.endLine>0&&(t.startLine=e.startLine,t.endLine=e.endLine),t}case"chat-quote":{const t={kind:"chat-quote",quote:e.code,text:e.text};return e.fileLabel&&(t.messageId=e.fileLabel),e.anchor&&(t.anchor=e.anchor),t}case"diff":case"file":case"plan":{const t={kind:"code-comment",source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,language:e.language,code:e.code,text:e.text};return e.source==="diff"&&e.side&&(t.side=e.side),t}}}const du=As("kind",[v({kind:N("code-comment"),source:Se(["diff","file","plan"]),fileLabel:m(),startLine:R(),endLine:R(),side:Se(["original","modified"]).optional(),language:m(),code:m(),text:m()}),v({kind:N("terminal"),terminalId:m(),terminalLabel:m(),startLine:R(),endLine:R(),output:m()}),v({kind:N("browser-annotation"),pageUrl:m(),prompt:m(),text:m()}),v({kind:N("pr-comment"),label:m(),body:m(),text:m()}),v({kind:N("pr-check"),label:m(),output:m(),text:m()}),v({kind:N("file-quote"),fileLabel:m(),startLine:R().optional(),endLine:R().optional(),quote:m(),text:m()}),v({kind:N("chat-quote"),messageId:m().optional(),anchor:wg.optional(),quote:m(),text:m()}),v({kind:N("github-issue"),number:R().int().positive(),title:m(),url:m()}),v({kind:N("github-pr"),number:R().int().positive(),title:m(),url:m()}),v({kind:N("linear-issue"),identifier:m().min(1),title:m(),url:m()}),v({kind:N("guest-issue"),providerId:m().min(1),id:m().min(1),title:m(),url:m(),data:qi().optional()}),v({kind:N("guest-pr"),providerId:m().min(1),id:m().min(1),title:m(),url:m(),data:qi().optional()})]),fu=v({path:m(),selection:v({startLine:R().finite(),endLine:R().finite(),startChar:R().finite().optional(),endChar:R().finite().optional()}).optional(),comment:m(),preview:m().optional(),origin:Se(["file","review"]).optional()}),Ag=v({[xi]:du,[Ri]:fu.optional()});function zv(e){if(e.type!==void 0&&e.type!=="text")return null;const t=du.safeParse(e.metadata?.[xi]);if(t.success)return t.data;const n=fu.safeParse(e.metadata?.[Ri]);if(n.success){const r=n.data;return r.selection?{kind:"code-comment",source:r.origin==="review"?"diff":"file",fileLabel:r.path,startLine:r.selection.startLine,endLine:r.selection.endLine,language:"",code:r.preview??"",text:r.comment}:{kind:"file-quote",fileLabel:r.path,quote:r.preview??"",text:r.comment}}return null}function $v(e){switch(e.kind){case"code-comment":{const t={source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,code:e.code,language:e.language,text:e.text};return e.side&&(t.side=e.side),t}case"terminal":return{source:"terminal",fileLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,code:e.output,language:"",text:"",terminalId:e.terminalId};case"browser-annotation":return{source:"preview-annotation",fileLabel:e.pageUrl,startLine:0,endLine:0,code:e.prompt,language:"",text:e.text};case"pr-comment":return{source:"pr-comment",fileLabel:e.label,startLine:0,endLine:0,code:e.body,language:"",text:e.text};case"pr-check":return{source:"pr-check",fileLabel:e.label,startLine:0,endLine:0,code:e.output,language:"",text:e.text};case"file-quote":return{source:"file-quote",fileLabel:e.fileLabel,startLine:e.startLine??0,endLine:e.endLine??0,code:e.quote,language:"",text:e.text};case"chat-quote":return{source:"chat-quote",fileLabel:e.messageId??"",startLine:0,endLine:0,code:e.quote,language:"",text:e.text,anchor:e.anchor};case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return null}}function Ig(e){switch(e.kind){case"code-comment":return e.text.trim()||e.code.trim()||e.fileLabel;case"chat-quote":case"file-quote":return e.text.trim()||e.quote;case"browser-annotation":return e.text.trim()||e.prompt.trim()||e.pageUrl;case"pr-comment":return e.text.trim()||e.body.trim()||e.label;case"pr-check":return e.text.trim()||e.label.trim()||e.output;case"terminal":return e.output.trim()||e.terminalLabel;case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return e.title.trim()||e.url}}function xg(e){let t=e.content.trim()||e.contextPreview?.trim()||"";if(!t){for(const r of e.context??[])if(r.kind!=="instruction"&&(t=(r.kind==="context"?Ig(r.metadata.openchamberContext):r.text).trim(),t))break}t||=e.attachments?.[0]?.filename??"";const n=t.split(`
37
+ `,1)[0];return n.slice(0,100)+(t.length>n.length||n.length>100?"...":"")}const pu="queue",Rg=e=>e==="steer"||e==="queue",Cg=(e,t)=>e==="immediate"?"steer":Rg(e)?e:t===!1?"steer":t===!0?"queue":pu,Pt=()=>!Ce(),tc=50,Ho=(e,t,n=W())=>{const r=Ye(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},Ue=e=>`${e.runtimeKey}
38
+ ${e.directory}
39
+ ${e.sessionId}`,Yt=e=>{const[t,n,...r]=e.split(`
40
+ `);return Ho(r.join(`
41
+ `),n,t)},Og=v({providerID:m().min(1),modelID:m().min(1),agent:m().optional(),variant:m().optional()}),Mg=v({id:m(),filename:m(),mimeType:m(),size:R(),source:Se(["local","server","vscode"]),serverPath:m().optional(),dataUrl:m().optional()}),Dg=As("kind",[v({kind:N("context"),text:m(),metadata:Ag,instructions:m().optional()}),v({kind:N("instruction"),text:m()}),v({kind:N("synthetic"),text:m()})]),Ci=v({id:m().min(1),createdAt:R(),content:m(),text:m(),agentMention:m().optional(),attachments:G(Mg),context:G(Dg).optional(),contextPreview:m().optional(),sendConfig:Og}),Oi=v({sessionId:m().min(1),directory:m(),items:G(Ci),sendingId:m().nullable()}),nc=v({revision:R(),sessions:G(Oi)}),tr=v({revision:R(),session:Oi}),_g=tr.extend({item:Ci}),Lg=tr.extend({items:G(Ci)}),Fg=e=>{const t=e.indexOf(",");if(!e.startsWith("data:")||t===-1)return null;const n=e.slice(5,t),r=e.slice(t+1);try{if(n.endsWith(";base64")){const i=atob(r),a=new ArrayBuffer(i.length),c=new Uint8Array(a);for(let l=0;l<i.length;l+=1)c[l]=i.charCodeAt(l);return a}const s=new TextEncoder().encode(decodeURIComponent(r)),o=new ArrayBuffer(s.byteLength);return new Uint8Array(o).set(s),o}catch{return null}},Ug=e=>{const t=e.dataUrl??"",n=t?Fg(t):null,r={id:e.id,file:new File(n?[n]:[],e.filename,{type:e.mimeType}),dataUrl:t,mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source};return e.serverPath&&(r.serverPath=e.serverPath),r},zr=e=>{const t={id:e.id,content:e.content,text:e.text,createdAt:e.createdAt,sendConfig:{...e.sendConfig}};return e.agentMention&&(t.agentMention=e.agentMention),e.attachments.length>0&&(t.attachments=e.attachments.map(Ug)),e.context&&(t.context=e.context),e.contextPreview&&(t.contextPreview=e.contextPreview),t},jg=e=>{const t={id:e.id,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source,dataUrl:e.dataUrl};return e.serverPath&&(t.serverPath=e.serverPath),t},rc=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(s=>!!s.dataUrl).map(jg),context:e.context??[],sendConfig:t};e.agentMention&&(n.agentMention=e.agentMention);const r=xg({content:"",context:e.context});return r&&(n.contextPreview=r),n},Wt=async(e,t,n)=>{const r=await g(t,n);if(!r.ok){const o=new Error(`Message queue request failed (${r.status})`);throw o.status=r.status,o}const s=e.safeParse(await r.json());if(!s.success)throw new Error("Invalid message queue response");return s.data},vt=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},kt=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,fo=new Set,sc=new Map,tt=new Map,$r=new Map;let po=0;const oc=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),Ng=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:oc(n.queuedMessages??{}),quarantinedLegacyMessages:oc({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:Cg(n.followUpBehavior,n.queueModeEnabled??null)}},nt=(e,t)=>{const{[t]:n,...r}=e;return r},Wr=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(s=>s.id!==n);return r.length===0?{queuedMessages:nt(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},Bg=(e,t,n,r)=>{let s=e.queuedMessages,o=e.sendingIds;for(const i of new Set([...Object.keys(s),...Object.keys(o)])){const a=Yt(i);a?.runtimeKey!==t||a.sessionId!==n||(tt.get(i)??-1)>r||(tt.set(i,r),s=nt(s,i),o=nt(o,i))}return{queuedMessages:s,sendingIds:o}},zo=yt()(Cn(hr((e,t)=>{let n=null,r=!1;const s=(a,c,l)=>{if(l!==W()||($r.get(l)??-1)>c)return;const u=Ho(a.sessionId,a.directory,l);if(!u){if(a.items.length>0)return;e(f=>Bg(f,l,a.sessionId,c));return}const d=Ue(u);(tt.get(d)??-1)>c||(tt.set(d,c),e(f=>{const p=a.items.map(zr),y=p.length>0?{...f.queuedMessages,[d]:p}:nt(f.queuedMessages,d),b=a.sendingId?{...f.sendingIds,[d]:[a.sendingId]}:nt(f.sendingIds,d);return{queuedMessages:y,sendingIds:b}}))},o=async a=>{try{const c=await Wt(nc,"/api/message-queue"),l=c.sessions.find(u=>u.sessionId===a.sessionId)??{sessionId:a.sessionId,directory:a.directory,items:[],sendingId:null};s(l,c.revision,a.runtimeKey)}catch{}},i=async(a,c,l)=>{try{const u=await Wt(tr,c,l);s(u.session,u.revision,a.runtimeKey)}catch(u){console.warn("[queue] server update failed:",u),await o(a)}};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:pu,sendingIds:{},addToQueue:async(a,c)=>{const l=Ue(a),u=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,d={id:u,content:c.content,text:c.text??c.content,createdAt:Date.now(),sendConfig:c.sendConfig};if(c.agentMention&&(d.agentMention=c.agentMention),c.attachments&&c.attachments.length>0&&(d.attachments=c.attachments),c.context&&c.context.length>0&&(d.context=c.context),e(y=>{const b=y.queuedMessages[l]??[],w={...y.queuedMessages,[l]:[...b,d].slice(-20)},E=Object.keys(w);if(E.length>tc){E.sort((k,U)=>(w[k]?.[0]?.createdAt??0)-(w[U]?.[0]?.createdAt??0));for(const k of E.slice(0,E.length-tc))delete w[k]}return{queuedMessages:w}}),!Pt())return;if(!c.sendConfig)throw e(y=>Wr(y,l,u)),new Error("A queued message needs a provider and model to be delivered later.");const f=dg(a.runtimeKey,a.directory,a.sessionId),p=hg(c.content,c.attachments??[]);try{const y=await Wt(tr,`${kt(a.sessionId)}/items`,vt("POST",{directory:a.directory,item:rc(c,c.sendConfig)}));e(b=>Wr(b,l,u)),s(y.session,y.revision,a.runtimeKey),f&&Vn.getState().appendSubmissions(f,[p])}catch(y){throw e(b=>Wr(b,l,u)),y}},removeFromQueue:(a,c)=>{const l=Ue(a);e(u=>Wr(u,l,c)),Pt()&&i(a,`${kt(a.sessionId)}/items/${encodeURIComponent(c)}`,vt("DELETE"))},reorderQueue:(a,c,l)=>{if(c===l)return;const u=Ue(a),d=t().queuedMessages[u];if(!d)return;const f=d.findIndex(w=>w.id===c),p=d.findIndex(w=>w.id===l);if(f===-1||p===-1)return;const y=d.slice(),[b]=y.splice(f,1);if(y.splice(p,0,b),e(w=>({queuedMessages:{...w.queuedMessages,[u]:y}})),Pt()){const w=y.map(E=>E.id);i(a,`${kt(a.sessionId)}/order`,vt("PUT",{itemIds:w}))}},popToInput:async(a,c)=>{const[l]=await t().takeForSend(a,c);return l??null},takeForSend:async(a,c)=>{const l=Ue(a);if(Pt())try{if(c){const b=await Wt(_g,`${kt(a.sessionId)}/items/${encodeURIComponent(c)}/take`,vt("POST"));return s(b.session,b.revision,a.runtimeKey),[zr(b.item)]}const y=await Wt(Lg,`${kt(a.sessionId)}/take`,vt("POST"));return s(y.session,y.revision,a.runtimeKey),y.items.map(zr)}catch(y){throw await o(a),y}const u=t(),d=u.sendingIds[l]??[],f=(u.queuedMessages[l]??[]).filter(y=>(c?y.id===c:!0)&&!d.includes(y.id));if(f.length===0)return[];const p=new Set(f.map(y=>y.id));return e(y=>{const b=(y.queuedMessages[l]??[]).filter(w=>!p.has(w.id));return b.length===0?{queuedMessages:nt(y.queuedMessages,l)}:{queuedMessages:{...y.queuedMessages,[l]:b}}}),f},clearQueue:a=>{const c=Ue(a);e(l=>{const u=l.sendingIds[c]??[],d=(l.queuedMessages[c]??[]).filter(f=>u.includes(f.id));return d.length>0?{queuedMessages:{...l.queuedMessages,[c]:d}}:{queuedMessages:nt(l.queuedMessages,c)}}),Pt()&&i(a,kt(a.sessionId),vt("DELETE"))},forgetQueue:a=>{const c=Ue(a);tt.delete(c),e(l=>({queuedMessages:nt(l.queuedMessages,c),sendingIds:nt(l.sendingIds,c)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(a,c)=>{const l=Ue(a);e(u=>{const d=u.sendingIds[l]??[];return d.includes(c)?u:{sendingIds:{...u.sendingIds,[l]:[...d,c]}}})},clearSending:(a,c)=>{const l=Ue(a);e(u=>{const d=u.sendingIds[l];if(!d||!d.includes(c))return u;const f=d.filter(p=>p!==c);return f.length===0?{sendingIds:nt(u.sendingIds,l)}:{sendingIds:{...u.sendingIds,[l]:f}}})},getSendableQueue:a=>{const c=Ue(a),l=t(),u=l.queuedMessages[c]??[],d=l.sendingIds[c];return!d||d.length===0?u:u.filter(f=>!d.includes(f.id))},setFollowUpBehavior:a=>{e({followUpBehavior:a}),ht({followUpBehavior:a})},getQueueForTarget:a=>t().queuedMessages[Ue(a)]??[],hydrate:()=>{if(!Pt())return Promise.resolve();const a=W();if(n?.runtimeKey===a)return n.promise;const c=++po,l=()=>c===po&&a===W(),u=(async()=>{let p=sc.get(a);for(p||(p={items:Object.entries(t().queuedMessages).flatMap(([b,w])=>{const E=Yt(b);return!E||E.runtimeKey!==a?[]:w.map(k=>({target:E,message:k}))}),pending:null},sc.set(a,p));p.pending||p.items.length>0;){if(!l())return;if(p.pending){await p.pending;continue}const y=p.items.shift();if(!y?.message.sendConfig)continue;const{target:b,message:w}=y,E=Wt(tr,`${kt(b.sessionId)}/items`,vt("POST",{directory:b.directory,item:rc(w,y.message.sendConfig)})).then(()=>{}).catch(U=>{console.warn("[queue] failed to migrate a locally queued message to the server:",U)});p.pending=E;const k=p;E.then(()=>{k.pending===E&&(k.pending=null)}),await E}if(l())do{r=!1;let y;try{y=await Wt(nc,"/api/message-queue",{signal:AbortSignal.timeout(15e3)})}catch(b){if(!l())return;if(r)continue;throw b}if(!l())return;fo.add(a),!(($r.get(a)??-1)>y.revision)&&($r.set(a,y.revision),e(b=>{const w=D=>(tt.get(D)??-1)>y.revision,E=D=>Yt(D)?.runtimeKey!==a||w(D),k={},U={};for(const[D,J]of Object.entries(b.queuedMessages))E(D)&&(k[D]=J);for(const[D,J]of Object.entries(b.sendingIds))E(D)&&(U[D]=J);for(const D of y.sessions){const J=Ho(D.sessionId,D.directory,a);if(!J)continue;const C=Ue(J);w(C)||(tt.set(C,y.revision),D.items.length>0&&(k[C]=D.items.map(zr)),D.sendingId&&(U[C]=[D.sendingId]))}return{queuedMessages:k,sendingIds:U}}))}while(r&&l())})(),d={runtimeKey:a,promise:u};n=d;const f=()=>{n===d&&(n=null)};return u.then(f,f),u},resync:()=>(n?.runtimeKey===W()&&(r=!0),t().hydrate()),applyServerSession:s,setServerHold:async(a,c)=>{if(!Pt())return;const l=await g(`${kt(a)}/hold`,vt("PUT",{held:c}));if(!l.ok)throw new Error(`Message queue hold request failed (${l.status})`)},resetForRuntimeSwitch:a=>{if(po+=1,n=null,r=!1,a){$r.delete(a);for(const c of tt.keys())Yt(c)?.runtimeKey===a&&tt.delete(c)}!a||!fo.has(a)||e(c=>{const l={},u={};for(const[d,f]of Object.entries(c.queuedMessages))Yt(d)?.runtimeKey===a?tt.delete(d):l[d]=f;for(const[d,f]of Object.entries(c.sendingIds))Yt(d)?.runtimeKey!==a&&(u[d]=f);return{queuedMessages:l,sendingIds:u}})}}},{name:"message-queue-store",version:3,storage:wi(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=Yt(t)?.runtimeKey;return!n||!fo.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:Ng}),{name:"message-queue-store"})),Hg=v({type:N("openchamber:message-queue.updated"),properties:v({revision:R(),session:Oi})}),Wv=(e,t)=>{if(!Pt())return;const n=Hg.safeParse(e);if(!n.success)return;const{session:r,revision:s}=n.data.properties;zo.getState().applyServerSession(r,s,t)},zg=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const n=new TextEncoder().encode(t);let r="";for(const o of n)r+=String.fromCharCode(o);return`path_${typeof btoa=="function"?btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},L=e=>t=>{const n=e.safeParse(t);return n.success?n.data:void 0},Mn=R().refine(Number.isFinite),Fe=m().transform(e=>e.trim()),fe=Fe.pipe(m().min(1)),Ft=it(m(),me()),A=L(Ne()),je=L(m().min(1)),gn=L(Fe),fn=L(fe),ic=e=>L(m().max(e)),zn=e=>L(Fe.transform(t=>t.slice(0,e))),Z=e=>L(Fe.pipe(Se(e))),Gt=L(Mn),$g=(e,t)=>L(Mn.transform(n=>Math.max(e,Math.min(t,Math.round(n))))),ho=e=>L(Mn.transform(t=>Math.max(e,Math.round(t)))),Wg=L(Mn.positive().transform(Math.floor)),Gg=L(_t([sr(),Mn])),qg=L(_t([sr(),Fe.transform(e=>e.length>0?e:null)])),Kg=L(_t([sr(),Fe])),Mi=G(me()).transform(e=>e.filter(t=>m().min(1).safeParse(t).success)),Gr=L(Mi.transform(e=>Array.from(new Set(e.map(String))))),mo=L(Mi.transform(e=>e.map(String))),Vg=Ft.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=G(me()).safeParse(r);s.success&&(t[n]=s.data.filter(o=>m().safeParse(o).success).map(String))}return t}),go=L(Vg.pipe(it(m(),G(m())).refine(e=>Object.keys(e).length>0))),Jg=v({providerID:fe,modelID:fe}),yo=e=>L(G(me()).transform(t=>{const n=[],r=new Set;for(const s of t){const o=Jg.safeParse(s);if(!o.success)continue;const i=`${o.data.providerID}/${o.data.modelID}`;if(!r.has(i)&&(r.add(i),n.push(o.data),n.length>=e))break}return n})),Yg=L(Ft.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){if(!n)continue;const s=Mi.safeParse(r);if(!s.success)continue;const o=Array.from(new Set(s.data.map(String)));o.length>0&&(t[n]=o.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),Qg=L(Ft.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=fe.safeParse(r);!s||!o.success||(t[s]=o.data)}return t})),qr={completion:{title:"Task Complete",message:"Your task has finished."},error:{title:"Error Occurred",message:"An error occurred while processing your task."},question:{title:"Input Needed",message:"Please provide input to continue."},subtask:{title:"Subtask Complete",message:"A subtask has finished."}},Xg=v({title:m().catch(""),message:m().catch("")}),Zg=L(Ft.transform(e=>{const t=i=>{const a=Xg.safeParse(e[i]);return a.success?a.data:void 0},n=t("completion"),r=t("error"),s=t("question"),o=t("subtask");if(!(!n&&!r&&!s&&!o))return{completion:n??qr.completion,error:r??qr.error,question:s??qr.question,subtask:o??qr.subtask}}).pipe(Oc(e=>e!==void 0))),ac=Ft.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{const r=m().safeParse(n);return r.success?[[t,r.data]]:[]}))),ey=v({id:me().transform(e=>String(e??"")),label:me().transform(e=>String(e??"")),models:G(me()).transform(e=>e.filter(t=>m().safeParse(t).success).map(String)).catch([]),order:R().catch(0)}),ty=L(Ft.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=Ft.safeParse(r);if(!s.success)continue;const o={},i=G(me()).safeParse(s.data.customGroups);i.success&&(o.customGroups=i.data.flatMap(l=>{const u=ey.safeParse(l);return u.success?[u.data]:[]}));const a=ac.safeParse(s.data.modelAssignments);a.success&&(o.modelAssignments=a.data);const c=ac.safeParse(s.data.renamedGroups);c.success&&(o.renamedGroups=c.data),Object.keys(o).length>0&&(t[n]=o)}return t}).refine(e=>Object.keys(e).length>0)),ny=v({id:fe,name:fe,hostname:fe.transform(e=>e.toLowerCase())}),ry=L(G(me()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=ny.safeParse(s);o.success&&(n.has(o.data.id)||r.has(o.data.hostname)||(n.add(o.data.id),r.add(o.data.hostname),t.push(o.data)))}return t})),sy=L(Ft.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=fe.safeParse(r);!s||!o.success||(t[s]=o.data)}return t}).refine(e=>Object.keys(e).length>0)),oy=v({id:fe,label:fe,source:fe,subpath:Fe.optional().catch(void 0),gitIdentityId:Fe.optional().catch(void 0)}),iy=L(G(me()).transform(e=>{const t=[],n=new Set;for(const r of e){const s=oy.safeParse(r);if(!s.success||n.has(s.data.id))continue;n.add(s.data.id);const o={id:s.data.id,label:s.data.label,source:s.data.source};s.data.subpath&&(o.subpath=s.data.subpath),s.data.gitIdentityId&&(o.gitIdentityId=s.data.gitIdentityId),t.push(o)}return t})),ay=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,wo=Mn.nonnegative(),cy=v({path:fe,label:fe.optional().catch(void 0),icon:fe.optional().catch(void 0),iconImage:_t([sr(),v({mime:fe,updatedAt:wo.transform(Math.round).pipe(R().positive()),source:Se(["custom","auto"])})]).optional().catch(void 0),color:fe.optional().catch(void 0),iconBackground:_t([sr(),Fe.pipe(m().regex(ay)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:wo.optional().catch(void 0),lastOpenedAt:wo.optional().catch(void 0),sidebarCollapsed:Ne().optional().catch(void 0),defaultModel:fe.optional().catch(void 0),defaultAgent:fe.optional().catch(void 0),defaultVariant:fe.optional().catch(void 0)}),ly=L(G(me()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=cy.safeParse(s);if(!o.success)continue;const i=Ye(o.data.path);if(!i)continue;const a=zg(i);if(!a||n.has(a)||r.has(i))continue;n.add(a),r.add(i);const c={id:a,path:i};o.data.label&&(c.label=o.data.label),o.data.icon&&(c.icon=o.data.icon),o.data.iconImage!==void 0&&(c.iconImage=o.data.iconImage),o.data.color&&(c.color=o.data.color),o.data.iconBackground!==void 0&&(c.iconBackground=o.data.iconBackground),o.data.addedAt!==void 0&&(c.addedAt=o.data.addedAt),o.data.lastOpenedAt!==void 0&&(c.lastOpenedAt=o.data.lastOpenedAt),o.data.defaultModel&&(c.defaultModel=o.data.defaultModel),o.data.defaultAgent&&(c.defaultAgent=o.data.defaultAgent),o.data.defaultVariant&&(c.defaultVariant=o.data.defaultVariant),o.data.sidebarCollapsed!==void 0&&(c.sidebarCollapsed=o.data.sidebarCollapsed),t.push(c)}return t}).refine(e=>e.length>0)),uy=Se(["steer","queue"]),dy=(e,t)=>{const n=uy.safeParse(e);if(n.success)return n.data;if(e==="immediate")return"steer";const r=Ne().safeParse(t.queueModeEnabled);if(r.success)return r.data?"queue":"steer"},fy=L(Fe.pipe(Se(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),py=L(Fe.pipe(Se(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),hy=L(Fe.transform(e=>e.replace(/\s+/g," ").slice(0,64))),my=e=>L(G(me()).transform(t=>{const n=[];for(const r of t){const s=Fe.transform(o=>o.toLowerCase()).safeParse(r);s.success&&e(s.data)&&!n.includes(s.data)&&n.push(s.data)}return n})),Di=e=>L(Oc(e)),dr=(e,t)=>(n,r)=>{const s=e(n,r);return s===void 0?void 0:t(s)},h=e=>e,S=(e,t,n={})=>({read:()=>T.getState()[e],write:t,autoSave:n.autoSave??!0}),qt=e=>t=>{T.setState({[e]:t})},cc=()=>globalThis.window?.__zustand_config_store__??null,Kt=e=>({read:()=>cc()?.getState()[e],write:t=>{cc()?.setState({[e]:t})},autoSave:!1}),$n=e=>({read:()=>Do.getState()[e],write:t=>{Do.setState({[e]:t})},autoSave:!1}),gy=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],yy=Di(Ai),wy=Di(zh),by=Di($h),Sy=L(m().refine(ou)),Ty=L(R().refine(Pi)),vy=dr(gn,e=>Ds(e,void 0)),ky=dr(L(G(me())),Jm),Ey=dr(L(G(me())),e=>zl(e)),Py=Z(["ask","attach","inline"]),Ay=Z(["default","vim"]),Iy=(e,t)=>{let n=e;const r=(s,o)=>{if(n.some(c=>c.type==="command"&&c.name===s))return;const i=n.findIndex(c=>c.type==="command"&&c.name===o),a=i>=0?i+1:n.length;n=[...n.slice(0,a),{type:"command",name:s},...n.slice(a)]};return t.draftStartersCraftGoalAdded!==!0&&r("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==!0&&r("schedule-task","craft-goal"),n},wr={themeId:h({scope:"profile",perSurface:!0,parse:je}),useSystemTheme:h({scope:"profile",perSurface:!0,parse:A}),themeVariant:h({scope:"profile",derived:!0,parse:Z(["light","dark"])}),lightThemeId:h({scope:"profile",perSurface:!0,parse:je}),darkThemeId:h({scope:"profile",perSurface:!0,parse:je}),lastDirectory:h({scope:"instance",adopt:"bootstrap-only",parse:je}),homeDirectory:h({scope:"instance",parse:je}),opencodeBinary:h({scope:"instance",parse:gn}),projects:h({scope:"instance",parse:ly}),activeProjectId:h({scope:"instance",adopt:"bootstrap-only",parse:je}),securityScopedBookmarks:h({scope:"instance",surfaces:["desktop"],parse:mo}),pinnedDirectories:h({scope:"instance",parse:Gr}),desktopLanAccessEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopKeepAwakeEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopMinimizeToTrayEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopMacMenuBarEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopUiPassword:h({scope:"instance",secret:!0,surfaces:["desktop"],parse:gn}),hasDesktopUiPassword:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessActive:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessBlockedReason:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:gn}),githubClientId:h({scope:"instance",parse:fn}),githubScopes:h({scope:"instance",parse:fn}),skillCatalogs:h({scope:"instance",parse:iy}),defaultGitIdentityId:h({scope:"instance",parse:gn}),permissionAutoAccept:h({scope:"instance",parse:L(v({sessions:it(m().min(1),Ne()).catch({}),revision:R().int().nonnegative().catch(0)}))}),agentControlToolEnabled:h({scope:"instance",parse:A,ui:S("agentControlToolEnabled",e=>T.getState().setAgentControlToolEnabled(e))}),agentWebToolEnabled:h({scope:"instance",parse:A,ui:S("agentWebToolEnabled",e=>T.getState().setAgentWebToolEnabled(e))}),browserProvider:h({scope:"instance",parse:je,ui:S("browserProvider",e=>T.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:h({scope:"instance",parse:A,ui:S("agentNotifyToolEnabled",e=>T.getState().setAgentNotifyToolEnabled(e))}),agentMemoryToolEnabled:h({scope:"instance",parse:A,ui:S("agentMemoryToolEnabled",e=>T.getState().setAgentMemoryToolEnabled(e))}),agentMemoryFeatureAvailable:h({scope:"instance",computed:!0,parse:A,ui:S("agentMemoryFeatureAvailable",e=>T.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),routingFeatureAvailable:h({scope:"instance",computed:!0,parse:A,ui:S("routingFeatureAvailable",e=>T.getState().setRoutingFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:h({scope:"instance",parse:zn(128)}),autoDeleteEnabled:h({scope:"instance",parse:A,ui:S("autoDeleteEnabled",e=>T.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:h({scope:"instance",parse:$g(1,365),ui:S("autoDeleteAfterDays",e=>T.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:h({scope:"instance",parse:A,ui:S("sessionRetentionOnlyArchived",e=>T.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionAction:h({scope:"instance",parse:Z(["archive","delete"]),ui:S("sessionRetentionAction",e=>T.getState().setSessionRetentionAction(e))}),terminalShell:h({scope:"instance",parse:yy,ui:S("terminalShell",e=>T.getState().setTerminalShell(e))}),terminalLoginShells:h({scope:"instance",parse:my(Ai),ui:S("terminalLoginShells",e=>T.getState().setTerminalLoginShells(e))}),openInAppId:h({scope:"instance",parse:fn}),dictationEnabled:h({scope:"profile",parse:A,ui:Kt("dictationEnabled")}),sttProvider:h({scope:"instance",parse:fy,ui:Kt("sttProvider")}),sttServerUrl:h({scope:"instance",parse:zn(2048),ui:Kt("sttServerUrl")}),sttModel:h({scope:"instance",parse:zn(256),ui:Kt("sttModel")}),sttLocalModel:h({scope:"instance",parse:zn(256),ui:Kt("sttLocalModel")}),sttLanguage:h({scope:"profile",parse:zn(64),ui:Kt("sttLanguage")}),tunnelProvider:h({scope:"instance",parse:dr(fn,e=>e.toLowerCase())}),tunnelMode:h({scope:"instance",parse:L(m().transform(e=>e.trim().toLowerCase()).pipe(Se(["quick","managed-remote","managed-local"])))}),tunnelBootstrapTtlMs:h({scope:"instance",parse:Gg}),tunnelSessionTtlMs:h({scope:"instance",parse:Gt}),managedLocalTunnelConfigPath:h({scope:"instance",parse:qg}),managedRemoteTunnelHostname:h({scope:"instance",parse:gn}),managedRemoteTunnelToken:h({scope:"instance",secret:!0,parse:Kg}),hasManagedRemoteTunnelToken:h({scope:"instance",computed:!0,parse:A}),managedRemoteTunnelPresets:h({scope:"instance",parse:ry}),managedRemoteTunnelSelectedPresetId:h({scope:"instance",parse:fn}),managedRemoteTunnelPresetTokens:h({scope:"instance",secret:!0,parse:sy}),sidebarProjectDisplayMode:h({scope:"profile",parse:Z(["all","single"]),ui:$n("projectDisplayMode")}),sidebarViewMode:h({scope:"profile",perSurface:!0,parse:Z(["projects","timeline"]),ui:$n("sidebarViewMode")}),sidebarProjectSortOrder:h({scope:"profile",parse:Z(["manual","a-z","z-a","date-added","recent"]),ui:$n("projectSortOrder")}),sidebarWorktreeSortOrder:h({scope:"profile",parse:Z(["recent","manual","a-z"]),ui:$n("worktreeSortOrder")}),sidebarShowRecentSection:h({scope:"profile",parse:A,ui:$n("showRecentSection")}),workStatusSectionOrder:h({scope:"profile",parse:dr(mo,bs),ui:S("workStatusSectionOrder",e=>T.getState().setWorkStatusSectionOrder(e))}),workStatusPanelEnabled:h({scope:"profile",parse:A,ui:S("workStatusPanelEnabled",e=>T.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:h({scope:"profile",parse:Ey,ui:{read:()=>T.getState().workStatusHiddenSections,write:(e,t)=>{const n=t.workStatusHiddenSectionsExplicit===!0;T.setState({workStatusHiddenSections:zl(e,n),workStatusHiddenSectionsExplicit:n})},autoSave:!0}}),workStatusHiddenSectionsExplicit:h({scope:"profile",parse:A,ui:S("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:h({scope:"profile",parse:A,ui:S("showReasoningTraces",e=>T.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:S("streamingAutoFollowEnabled",e=>T.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:h({scope:"profile",parse:A,ui:S("collapsibleThinkingBlocks",e=>T.getState().setCollapsibleThinkingBlocks(e))}),showTextJustificationActivity:h({scope:"profile",parse:A}),chatRenderMode:h({scope:"profile",parse:Z(["sorted","live"]),ui:S("chatRenderMode",e=>T.getState().setChatRenderMode(e))}),activityRenderMode:h({scope:"profile",parse:Z(["collapsed","summary"]),ui:S("activityRenderMode",e=>T.getState().setActivityRenderMode(e))}),mermaidRenderingMode:h({scope:"profile",parse:Z(["svg","ascii"]),ui:S("mermaidRenderingMode",e=>T.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:h({scope:"profile",parse:Z(["markdown","plain"]),ui:S("userMessageRenderingMode",e=>T.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:h({scope:"profile",parse:A,ui:S("collapsibleUserMessages",e=>T.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:h({scope:"profile",perSurface:!0,parse:A,ui:S("stickyUserHeader",e=>T.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:S("promptNavigatorEnabled",e=>T.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:S("wideChatLayoutEnabled",e=>T.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:h({scope:"profile",parse:A,ui:S("showSplitAssistantMessageActions",e=>T.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:h({scope:"profile",parse:A,ui:S("showToolFileIcons",e=>T.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:h({scope:"profile",parse:A,ui:S("codeBlockLineWrap",e=>T.getState().setCodeBlockLineWrap(e))}),showTurnChangedFiles:h({scope:"profile",parse:A,ui:S("showTurnChangedFiles",e=>T.getState().setShowTurnChangedFiles(e))}),showExpandedBashTools:h({scope:"profile",parse:A,ui:S("showExpandedBashTools",e=>T.getState().setShowExpandedBashTools(e))}),showExpandedEditTools:h({scope:"profile",parse:A,ui:S("showExpandedEditTools",e=>T.getState().setShowExpandedEditTools(e))}),toolJsonViewMode:h({scope:"profile",parse:Z(["summary","formatted","raw"]),ui:S("toolJsonViewMode",e=>T.getState().setToolJsonViewMode(e))}),timeFormatPreference:h({scope:"profile",parse:Z(["auto","12h","24h"]),ui:S("timeFormatPreference",e=>T.getState().setTimeFormatPreference(e))}),weekStartPreference:h({scope:"profile",parse:Z(["auto","sunday","monday"]),ui:S("weekStartPreference",e=>T.getState().setWeekStartPreference(e))}),messageStreamTransport:h({scope:"profile",parse:Z(["auto","ws","sse"]),ui:Kt("settingsMessageStreamTransport")}),diffLayoutPreference:h({scope:"profile",parse:Z(["dynamic","inline","side-by-side"]),ui:S("diffLayoutPreference",e=>T.getState().setDiffLayoutPreference(e))}),diffWrapLines:h({scope:"profile",parse:A,ui:S("diffWrapLines",e=>T.getState().setDiffWrapLines(e))}),gitChangesViewMode:h({scope:"profile",parse:Z(["flat","tree"]),ui:S("gitChangesViewMode",e=>T.getState().setGitChangesViewMode(e))}),gitmojiEnabled:h({scope:"profile",parse:A}),defaultFileViewerPreview:h({scope:"profile",parse:A}),directoryShowHidden:h({scope:"profile",parse:A,ui:{read:qm,write:e=>Km(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:h({scope:"profile",parse:A,ui:{read:Qm,write:e=>Xm(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:h({scope:"profile",parse:Ay,ui:S("fileEditorKeymap",e=>T.getState().setFileEditorKeymap(e))}),autoSaveEnabled:h({scope:"profile",parse:A,ui:S("autoSaveEnabled",e=>T.getState().setAutoSaveEnabled(e))}),autoCreateWorktree:h({scope:"profile",parse:A}),sessionTabsEnabled:h({scope:"profile",surfaces:["web","desktop","vscode"],parse:A,ui:S("sessionTabsEnabled",e=>T.getState().setSessionTabsEnabled(e))}),allowPromptingSubagentSessions:h({scope:"profile",parse:A,ui:S("allowPromptingSubagentSessions",e=>T.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:h({scope:"profile",parse:A,ui:S("inputSpellcheckEnabled",e=>T.getState().setInputSpellcheckEnabled(e))}),enterToSend:h({scope:"profile",parse:A,ui:S("enterToSend",e=>T.getState().setEnterToSend(e))}),enterToSendConfigured:h({scope:"profile",parse:A,ui:S("enterToSendConfigured",e=>T.getState().setEnterToSendConfigured(e))}),persistChatDraft:h({scope:"profile",parse:A,ui:S("persistChatDraft",e=>T.getState().setPersistChatDraft(e))}),largeTextPasteBehavior:h({scope:"profile",parse:Py,ui:S("largeTextPasteBehavior",e=>T.getState().setLargeTextPasteBehavior(e))}),followUpBehavior:h({scope:"profile",parse:dy,ui:{read:()=>zo.getState().followUpBehavior,write:e=>zo.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:h({scope:"profile",parse:A}),inputHistoryScope:h({scope:"profile",parse:Sy,ui:{read:()=>Vn.getState().scope,write:e=>Vn.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:h({scope:"profile",parse:Ty,ui:{read:()=>Vn.getState().entryLimit,write:e=>Vn.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:h({scope:"profile",parse:ky,ui:{read:()=>T.getState().globalDraftStarters??void 0,write:(e,t)=>T.getState().setGlobalDraftStarters(Iy(e,t)),autoSave:!1}}),draftStartersVisible:h({scope:"profile",parse:A,ui:S("draftStartersVisible",e=>T.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:h({scope:"profile",parse:A}),draftStartersScheduleTaskAdded:h({scope:"profile",parse:A}),fontSize:h({scope:"profile",perSurface:!0,parse:Gt,ui:S("fontSize",e=>T.getState().setFontSize(e))}),terminalFontSize:h({scope:"profile",perSurface:!0,parse:Gt,ui:S("terminalFontSize",e=>T.getState().setTerminalFontSize(e))}),editorFontSize:h({scope:"profile",perSurface:!0,parse:Gt,ui:S("editorFontSize",e=>T.getState().setEditorFontSize(e))}),uiFont:h({scope:"profile",parse:wy,ui:S("uiFont",e=>T.getState().setUiFont(e))}),monoFont:h({scope:"profile",parse:by,ui:S("monoFont",e=>T.getState().setMonoFont(e))}),padding:h({scope:"profile",perSurface:!0,parse:Gt,ui:S("padding",e=>T.getState().setPadding(e))}),cornerRadius:h({scope:"profile",perSurface:!0,parse:Gt,ui:S("cornerRadius",e=>T.getState().setCornerRadius(e))}),shortcutOverrides:h({scope:"profile",parse:Qg,ui:S("shortcutOverrides",qt("shortcutOverrides"))}),defaultModel:h({scope:"profile",parse:je}),defaultVariant:h({scope:"profile",parse:je}),defaultAgent:h({scope:"profile",parse:je}),smallModelUseDefault:h({scope:"profile",parse:A}),smallModelOverride:h({scope:"profile",parse:je}),walkthroughModelOverride:h({scope:"profile",parse:je}),zenModel:h({scope:"profile",parse:fn}),favoriteModels:h({scope:"profile",parse:yo(64),ui:S("favoriteModels",qt("favoriteModels"),{autoSave:!1})}),hiddenModels:h({scope:"profile",parse:yo(1024),ui:S("hiddenModels",qt("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:h({scope:"profile",parse:Gr,ui:S("collapsedModelProviders",qt("collapsedModelProviders"),{autoSave:!1})}),recentModels:h({scope:"profile",parse:yo(16),ui:S("recentModels",qt("recentModels"),{autoSave:!1})}),recentAgents:h({scope:"profile",parse:Gr,ui:S("recentAgents",qt("recentAgents"),{autoSave:!1})}),recentEfforts:h({scope:"profile",parse:Yg,ui:S("recentEfforts",qt("recentEfforts"),{autoSave:!1})}),providerOrder:h({scope:"profile",parse:Gr,ui:S("providerOrder",e=>T.getState().setProviderOrder(e))}),sessionRecapEnabled:h({scope:"profile",parse:A,ui:S("sessionRecapEnabled",e=>T.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:h({scope:"profile",parse:A,ui:S("sessionSuggestionEnabled",e=>T.getState().setSessionSuggestionEnabled(e))}),sessionGoalEnabled:h({scope:"profile",parse:A,ui:S("sessionGoalEnabled",e=>T.getState().setSessionGoalEnabled(e))}),sessionGoalDefaultBudgetEnabled:h({scope:"profile",parse:A,ui:S("sessionGoalDefaultBudgetEnabled",e=>T.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:h({scope:"profile",parse:Wg,ui:S("sessionGoalDefaultBudget",e=>T.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:h({scope:"profile",parse:A,ui:S("summarizeLastMessage",e=>T.getState().setSummarizeLastMessage(e))}),summaryThreshold:h({scope:"profile",parse:ho(0),ui:S("summaryThreshold",e=>T.getState().setSummaryThreshold(e))}),summaryLength:h({scope:"profile",parse:ho(10),ui:S("summaryLength",e=>T.getState().setSummaryLength(e))}),maxLastMessageLength:h({scope:"profile",parse:ho(10),ui:S("maxLastMessageLength",e=>T.getState().setMaxLastMessageLength(e))}),showDeletionDialog:h({scope:"profile",parse:A,ui:S("showDeletionDialog",e=>T.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:h({scope:"profile",parse:A,ui:S("nativeNotificationsEnabled",e=>T.getState().setNativeNotificationsEnabled(e))}),notificationMode:h({scope:"profile",parse:Z(["always","hidden-only"]),ui:S("notificationMode",e=>T.getState().setNotificationMode(e))}),notifyOnSubtasks:h({scope:"profile",parse:A,ui:S("notifyOnSubtasks",e=>T.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:h({scope:"profile",parse:A,ui:S("notifyOnCompletion",e=>T.getState().setNotifyOnCompletion(e))}),notifyOnError:h({scope:"profile",parse:A,ui:S("notifyOnError",e=>T.getState().setNotifyOnError(e))}),notifyOnQuestion:h({scope:"profile",parse:A,ui:S("notifyOnQuestion",e=>T.getState().setNotifyOnQuestion(e))}),notificationTemplates:h({scope:"profile",parse:Zg,ui:S("notificationTemplates",e=>T.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:h({scope:"profile",parse:A,ui:S("showOpenCodeUpdateNotifications",e=>T.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:h({scope:"profile",parse:A,ui:S("reportUsage",e=>T.getState().setReportUsage(e))}),usageDisplayMode:h({scope:"profile",parse:Z(["usage","remaining"])}),usageDropdownProviders:h({scope:"profile",parse:mo}),usageSelectedModels:h({scope:"profile",parse:go}),usageCollapsedFamilies:h({scope:"profile",parse:go}),usageExpandedFamilies:h({scope:"profile",parse:go}),usageModelGroups:h({scope:"profile",parse:ty}),globalBehaviorPrompt:h({scope:"profile",parse:ic(1024*1024)}),responseStyleEnabled:h({scope:"profile",parse:A}),responseStylePreset:h({scope:"profile",parse:Z(gy)}),responseStyleCustomInstructions:h({scope:"profile",parse:ic(5e4)}),pwaAppName:h({scope:"instance",surfaces:["web"],parse:hy}),pwaOrientation:h({scope:"instance",surfaces:["web"],parse:Z(["system","portrait","landscape"])}),mobileKeyboardMode:h({scope:"device",surfaces:["mobile"],parse:vy,ui:S("mobileKeyboardMode",e=>T.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:h({scope:"device",surfaces:["desktop"],parse:py,ui:S("desktopWindowControlsPosition",e=>T.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:h({scope:"device",surfaces:["desktop"],parse:Z(["classic","traffic-lights"]),ui:S("desktopWindowControlsStyle",e=>T.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:h({scope:"device",surfaces:["mobile","web"],parse:Gt,ui:S("inputBarOffset",e=>T.getState().setInputBarOffset(e))})},xy=e=>Object.prototype.hasOwnProperty.call(wr,e),br=Object.keys(wr).filter(xy),hu=e=>wr[e].scope==="device",Sr=e=>wr[e],Ry=e=>!wr[e].computed&&!hu(e),Cy=it(m(),me()),Oy=e=>{const t=Cy.safeParse(e);if(!t.success)return null;const n=t.data,r={};for(const s of br){const i=Sr(s).parse(n[s],n);i!==void 0&&Object.assign(r,{[s]:i})}return r},My=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),Dy=e=>{for(const t of br){const n=Sr(t);if(!n.ui)continue;const r=e[t];r!==void 0&&(My(n.ui.read(),r)||n.ui.write(r,e))}},_y=br.filter(e=>Sr(e).ui?.autoSave===!0),Gv=()=>{const e={};for(const t of _y){const r=Sr(t).ui?.read();r!==void 0&&Object.assign(e,{[t]:r})}return e},Ly=br.filter(e=>{const t=Sr(e);return t.scope!=="device"&&!t.secret&&!t.computed}),Fy=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},lc="openchamber.settingsMirror.v2.index",Uy="openchamber.deviceSeeded.v1:",jy=e=>`${Uy}${encodeURIComponent(e)}`,Ny=(e,t)=>{const n=jy(t);let r=!1;try{r=localStorage.getItem(n)===null,r&&localStorage.setItem(n,String(Date.now()))}catch{r=!1}if(r)return e;const s={};for(const o of br)e[o]===void 0||hu(o)||Object.assign(s,{[o]:e[o]});return s},By="openchamber.settingsMirror.v2:",Hy=5,uc=e=>`${By}${encodeURIComponent(e)}`,pn=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},zy=(e,t)=>{const n={};for(const o of Ly)e[o]!==void 0&&Object.assign(n,{[o]:e[o]});localStorage.setItem(uc(t),JSON.stringify(n));let r=[];try{const o=JSON.parse(localStorage.getItem(lc)??"[]");Array.isArray(o)&&(r=o.filter(i=>typeof i=="string"))}catch{r=[]}const s=[t,...r.filter(o=>o!==t)].slice(0,Hy);for(const o of r)s.includes(o)||localStorage.removeItem(uc(o));localStorage.setItem(lc,JSON.stringify(s))},$y=e=>{if(!(typeof window>"u")){if(zy(e,W()),pn("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),Fy(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(n=>n.sidebarCollapsed===!0).map(n=>n.id).filter(n=>typeof n=="string"&&n.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(e.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof e.directoryShowHidden=="boolean"?localStorage.setItem("directoryTreeShowHidden",e.directoryShowHidden?"true":"false"):localStorage.removeItem("directoryTreeShowHidden"),typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),pn("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}else localStorage.removeItem("openchamber.pwaName");if(Bl(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion=="string"){const t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem("opencode-update-toast-dismissed-version",t):localStorage.removeItem("opencode-update-toast-dismissed-version")}else localStorage.removeItem("opencode-update-toast-dismissed-version");typeof e.dictationEnabled=="boolean"?localStorage.setItem("dictationEnabled",String(e.dictationEnabled)):localStorage.removeItem("dictationEnabled"),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),pn("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),pn("sttModel",typeof e.sttModel=="string"?e.sttModel:null),pn("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),pn("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null)}},$o=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let Wo="idle",Kr=null;const Go=new Set,qv=()=>Wo,Kv=e=>(Go.add(e),()=>Go.delete(e)),Vv=e=>{Ls(),Ke(e)},Ke=e=>{Kr&&(clearTimeout(Kr),Kr=null);const t=e==="saved"?"idle":e;t!==Wo&&(Wo=t,Go.forEach(n=>n())),t==="error"&&(Kr=setTimeout(()=>Ke("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},mu=()=>{const e=T.persist;if(e&&typeof e=="object")return e},gu=()=>xs()?.settings??null,yu=()=>`/api/config/settings?${Zl}=${Ei()}`,Wy=e=>{Dy(e)},vs=e=>Oy(e);class Gy{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const n=this.mutations.at(-1),r=n?[...this.operations].some(s=>s.revision>=n.revision):!0;n&&!r?(n.revision=this.revision,n.changes={...n.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const n={revision:t};return this.operations.add(n),n}reconcile(t,n){let r=t;for(const s of this.mutations)s.revision<=n.revision||(r={...r,...s.changes});return r}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const n=Math.min(...[...this.operations].map(({revision:r})=>r));this.mutations=this.mutations.filter(r=>r.revision>n)}reset(){this.mutations=[],this.operations.clear()}}let _i=0,Ct=null,xn={},qo=!1;const Jv=()=>qo,Ko=e=>{qo=!0;try{Wy(e)}finally{qo=!1}};let Qt=null,Je=null,st=null,Re=null,nr=[],dc=!1,ks=0,ns=[];const Le=new Gy,qy=2e3,Ky=200,Li=()=>({runtimeKey:W(),generation:_i}),_s=e=>Object.keys(e),wu=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),rs=e=>{xn={...xn,...e}},Vy=e=>{const t={...xn};for(const n of e)delete t[n];xn=t},Jy=e=>{const t={};for(const n of _s(e))wu(e[n],xn[n])||Object.assign(t,{[n]:e[n]});return t},fr=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,bu=e=>{let t=null;for(const n of ns)fr(n.context,e)&&(t={...t??{},...n.changes});return Je&&st&&fr(st,e)&&(t={...t??{},...Je}),t},fc=(e,t)=>{const n=bu(t);return e&&n?{...e,...n}:e},ie=e=>e.generation===_i&&e.runtimeKey===W(),Wn=()=>{Je&&(Re&&(clearTimeout(Re),Re=null),Es({keepalive:!0}))},Ls=()=>{if(!(dc||typeof window>"u")){dc=!0,Qd(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Re&&clearTimeout(Re),Je&&Es())}),Zc(e=>{e.runtimeKey!==e.previousRuntimeKey&&(_i+=1,Le.reset(),ks=0,Ct=null,Qt=null,xn={},Ke("saved"))});try{window.addEventListener("pagehide",Wn,{capture:!0}),window.addEventListener("beforeunload",Wn,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Wn()}),document.addEventListener("freeze",Wn)),mr()&&ri(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||Wn()})).catch(()=>{})}catch{}}},Su=async(e=Li())=>{if(Ls(),Ct&&fr(Ct.context,e)&&Date.now()-Ct.at<qy)return fc(Ct.value,e);if(Qt&&fr(Qt.context,e))return Qt.promise;const t=Le.begin(),n=bu(e),r=o=>{if(!ie(e)||!o)return null;const i=fc(Le.reconcile({...o,...n},t),e);Ct={value:i,at:Date.now(),context:e};const a={};for(const c of _s(o))wu(o[c],i?.[c])&&Object.assign(a,{[c]:o[c]});return rs(a),i},s={context:e,promise:(async()=>{const o=gu();if(o)try{const i=await o.load();if(!ie(e))return null;const a=vs(i.settings);return r(a)}catch(i){if(!ie(e))return null;console.warn("Failed to load shared settings from runtime settings API:",i)}if(!ie(e))return null;try{const i=await g(yu(),{method:"GET",headers:{Accept:"application/json"}});if(!ie(e)||!i.ok)return null;const a=await i.json().catch(()=>null);if(!ie(e))return null;const c=vs(a);return r(c)}catch(i){return ie(e)&&console.warn("Failed to load shared settings from server:",i),null}})()};return Qt=s,s.promise.finally(()=>{Le.finish(t),Qt===s&&(Qt=null)}),s.promise},Yv=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;Ls();const r=Li(),s=Le.begin(),o=[mu(),Do.persist],i=u=>!u?.hasHydrated||u.hasHydrated()||!u.onFinishHydration?Promise.resolve():new Promise(d=>{let f=!1;const p=()=>{f||(f=!0,d())},y=u.onFinishHydration(()=>{y?.(),p()});u.hasHydrated?.()&&p()}),a=()=>Promise.all(o.map(i)).then(()=>{}),c=u=>!Je||!st||!ie(st)?u:{...u,...Je},l=async u=>{if(!ie(r))return;let d=c(Le.reconcile(u,s));if(await a(),!!ie(r)){d=Ny(c(Le.reconcile(u,s)),r.runtimeKey);try{$y(d)}catch(f){console.warn("persistToLocalStorage failed:",f)}try{Ko(d)}catch(f){console.warn("applyDesktopUiPreferences failed:",f)}$o(d,t,n)}};try{const u=await Su(r);u&&ie(r)?await l(u):ie(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(u){ie(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",u)}finally{Le.finish(s)}};async function Es({keepalive:e=!1}={}){let t=!1;const n=Je,r=st,s=ks,o=nr;Je=null,st=null,ks=0,Re=null,nr=[];try{if(!n||!r||Object.keys(n).length===0||!ie(r)){t=!0,Ke("saved");return}const i=Le.begin(s),a={context:r,changes:{...n}};ns.push(a),rs(n);const c=()=>Vy(_s(n));try{const l=gu();if(l)try{const u=vs(await l.save(n));if(!ie(r))return;if(u){rs(u);const d=Le.reconcile(u,i);Ko(d),$o(d,!1),Ct=null}u||c(),t=!!u,Ke(u?"saved":"error");return}catch(u){if(!ie(r))return;console.warn("Failed to update settings via runtime settings API:",u)}if(!ie(r))return;try{const u=await g(yu(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:e});if(!ie(r))return;if(!u.ok){console.warn("Failed to update shared settings via API:",u.status,u.statusText),c(),Ke("error");return}const d=vs(await u.json().catch(()=>null));if(!ie(r))return;if(d){rs(d);const f=Le.reconcile(d,i);Ko(f),$o(f,!1),t=!0,Ke("saved"),Ct=null}else c(),Ke("error")}catch(u){ie(r)&&(console.warn("Failed to update shared settings via API:",u),c(),Ke("error"))}}finally{ns=ns.filter(l=>l!==a),Le.finish(i)}}finally{o.forEach(i=>i({ok:t}))}}const Qv=()=>Su(),ht=async e=>{if(typeof window>"u")return{ok:!1};Ls();const t=Li();st&&!fr(st,t)&&(Re&&clearTimeout(Re),Es());const n={};for(const i of _s(e))Ry(i)&&Object.assign(n,{[i]:e[i]});const r=Le.record(n),s=Jy({...Je??{},...n});if(Object.keys(s).length===0){Je=null,st=null,Re&&(clearTimeout(Re),Re=null);const i=nr;return nr=[],i.forEach(a=>a({ok:!0})),Ke("saved"),{ok:!0}}Je=s,st=t,ks=r,Ke("saving"),Re&&clearTimeout(Re);const o=new Promise(i=>{nr.push(i)});return Re=setTimeout(()=>{Es()},Ky),o},Xv=async()=>{if(typeof window>"u")return;const e=mu();try{const t=await Um();if(!t)return;const n=()=>Fm(t);if(e?.hasHydrated?.()){n();return}if(n(),e?.onFinishHydration){const r=e.onFinishHydration(()=>{r?.(),n()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},Yy=3e4,Qy=40,Xy=60,Zy=(e,t,n,r,s,o,i)=>{const a=t.trim(),c=n.trim().toLowerCase();return JSON.stringify([e,a,c,r,s,o,i])},pc=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},ew=yt()(Cn((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,s=Xy,o){if(!n||n.trim().length===0)return[];const i=n.trim(),a=W(),c=typeof r=="string"?r.trim():"",l=!!o?.includeHidden,u=o?.respectGitignore??!0,d=o?.type==="directory"?"directory":"file",f=Zy(a,i,c,s,l,u,d),p=Date.now(),y=t().cache[f];if(y&&p-y.timestamp<Yy)return y.files;const b=t().inFlight[f];if(b)return b;const w=rt.searchFiles(c,{directory:i,limit:s,type:d}).then(E=>(e(k=>{if(k.inFlight[f]!==w)return k;const U={...k.cache,[f]:{files:E,timestamp:Date.now()}},D=k.cacheKeys.filter(J=>J!==f);for(D.push(f);D.length>Qy;){const J=D.shift();J&&delete U[J]}return{cache:U,cacheKeys:D}}),E)).finally(()=>{e(E=>{if(E.inFlight[f]!==w)return E;const k={...E.inFlight};return delete k[f],{inFlight:k}})});return e(E=>({inFlight:{...E.inFlight,[f]:w}})),w},invalidateDirectory(n){if(!n||n.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const r=n.trim();e(s=>{const o={...s.cache},i=s.cacheKeys.filter(l=>pc(l,r)?(delete o[l],!1):!0),a=Object.entries(s.inFlight).filter(([l])=>!pc(l,r)),c=Object.fromEntries(a);return{cache:o,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),tw=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Vo="openchamber_stream_perf",nw=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Vo)==="1"}catch{return!1}};let Tu=nw(),vu=!1;const on=()=>Tu||vu,ku=()=>{on()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},hc=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Eu=()=>{if(!on()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},Pu=e=>Array.from(e.entries()).map(([t,n])=>({metric:t,count:n.count,avg:n.count>0?Number((n.total/n.count).toFixed(3)):0,max:Number(n.max.toFixed(3)),total:Number(n.total.toFixed(3)),last:Number(n.last.toFixed(3))})).sort((t,n)=>n.total-t.total||n.count-t.count),Fi=(e,t)=>{const n=Eu();if(!n)return;const r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},rw=e=>{if(Tu=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(Vo,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Vo),ku()}catch{}},Zv=e=>{if(vu=e,!(typeof window>"u")){if(e){Eu();return}ku()}},sw=()=>{typeof window>"u"||(on()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},ow=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!on()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:Pu(e.counters)}},ek=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!on()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,n=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:n,durationMs:t?Math.max(0,Date.now()-t):0,entries:Pu(e.counters)}},tk=(e,t=1)=>{Fi(e,t)},nk=(e,t)=>{Fi(e,t)},rk=e=>{!on()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},sk=(e,t)=>{if(!on())return t();const n=hc();try{return t()}finally{Fi(e,hc()-n)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:rw,reset:sw,getSnapshot:ow});var iw={};let ot=null,mc=0;const Ve=yr(),gc=Ve.getItem("lastDirectory"),aw=typeof gc=="string"&&gc.length>0,Vr=e=>{try{ew.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Rn=e=>Ye(e)??"",cw=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},ss=(e,t)=>{const n=cw(e,t);return Rn(n)},lw=()=>{const e=Ve.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Rn(e);return t.length>0?t:null},uw=()=>{const e=Ve.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Rn(e);return t.length>0?t:null},dw=()=>{if(typeof process>"u")return null;const e=iw,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const r=Rn(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=Rn(n);return r.length>0?r:null}return null},Ui=()=>{if(typeof window<"u"){if(ot)return ot;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ot=t,Ve.setItem("homeDirectory",t),t;const n=lw();if(n&&!Ce())return ot=n,n}const e=dw();return e||"/"},fw=e=>{const t=Ye(e);return t&&t!=="/"?t:null},pw=e=>(ot=e,typeof window<"u"&&Ve.setItem("homeDirectory",e),ht({homeDirectory:e}),e),Jo=async()=>{const e=r=>{const s=fw(r);return s?pw(s):null};try{const r=await rt.getFilesystemHome(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await rt.getSystemInfo(),s=e(r?.homeDirectory);if(s)return s}catch(r){console.warn("Failed to get home directory from system info:",r)}try{const r=await nl(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=Ui(),n=e(t);return n||t},hw=()=>{if(!Ce())return null;const e=el()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Rn(e);return t.length>0?t:null},pr=hw()||Ui(),Ps=(()=>{const e=uw();return e&&!Ce()?ss(e,pr):pr})();Ps&&rt.setDirectory(Ps);const mw=!!(pr&&pr!=="/"),Yo=yt()(Cn((e,t)=>({currentDirectory:Ps,directoryHistory:[Ps],historyIndex:0,homeDirectory:pr,hasPersistedDirectory:aw,isHomeReady:mw,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const s=ot||t().homeDirectory||Ve.getItem("homeDirectory"),o=ss(n,s);tw()&&console.log("[DirectoryStore] setDirectory called with path:",o),rt.setDirectory(o),Vr(),e(i=>{const a=i.directoryHistory[i.historyIndex]===o,c=a?i.directoryHistory:[...i.directoryHistory.slice(0,i.historyIndex+1),o];return Ve.setItem("lastDirectory",o),ht({lastDirectory:o}),{currentDirectory:o,directoryHistory:c,historyIndex:a?i.historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const n=t();if(n.historyIndex>0){const r=n.historyIndex-1,s=n.directoryHistory[r];rt.setDirectory(s),Vr(),Ve.setItem("lastDirectory",s),ht({lastDirectory:s}),e({currentDirectory:s,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const n=t();if(n.historyIndex<n.directoryHistory.length-1){const r=n.historyIndex+1,s=n.directoryHistory[r];rt.setDirectory(s),Vr(),Ve.setItem("lastDirectory",s),ht({lastDirectory:s}),e({currentDirectory:s,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=t(),s=ot||t().homeDirectory||Ui();if(n===s)return;const o=$p(n);o&&r(o)},goHome:async()=>{const n=ot||t().homeDirectory||await Jo();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),s=n;ot=s;const o=r.homeDirectory!==s,i=Ve.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!o&&!c){r.isHomeReady||e({isHomeReady:!0});return}const l=typeof s=="string"&&s!==""&&s!=="/",u=r.currentDirectory?ss(r.currentDirectory,s):r.currentDirectory,d=r.directoryHistory.map(b=>ss(b,s)),f=d.some((b,w)=>b!==r.directoryHistory[w]),p=!!(u&&u!==r.currentDirectory),y={homeDirectory:s,hasPersistedDirectory:a,isHomeReady:l};if(c?(y.currentDirectory=s,y.directoryHistory=[s],y.historyIndex=0,y.isSwitchingDirectory=!1):(p||f)&&(y.currentDirectory=u,y.directoryHistory=d,y.historyIndex=Math.min(r.historyIndex,d.length-1),y.isSwitchingDirectory=!1),e(()=>y),(c||p)&&l){const b=c?s:u;rt.setDirectory(b),Vr(),Ve.setItem("lastDirectory",b),ht({lastDirectory:b})}ht({homeDirectory:s})}}),{name:"directory-store"}));typeof window<"u"&&(Jo().then(e=>{Yo.getState().synchronizeHomeDirectory(e)}),Zc(()=>{ot=null;const e=++mc;Jo().then(t=>{e===mc&&Yo.getState().synchronizeHomeDirectory(t)})}));const gw=(e,t)=>{const n=Rs();return n?n.openWebSocket(Dd(e),t):ff(new WebSocket(e))},Au=1,yc=512*1024,yw=0,hn=1,ww=15e3,ji=new TextEncoder,Iu=new TextDecoder,Ni=Se(["interactive","command"]),xu=Se(["running","exited","error"]),bw=Se(["node","bun"]),Bi=As("type",[v({type:N("terminal")}),v({type:N("project-action"),actionId:m(),executionId:m()})]),Sw=v({sessionId:m(),cols:R(),rows:R(),status:xu,mode:Ni.optional(),purpose:Bi.optional()}),Tw=v({sessionId:m(),cwd:m(),status:Se(["running","exited"]),createdAt:R().nullable().optional().transform(e=>e??null),mode:Ni.optional(),purpose:Bi.optional()}),wc={mode:Ni.optional(),purpose:Bi.optional()},vw=As("t",[v({t:N("hello")}),v({t:N("pong")}),v({t:N("error"),s:m().optional(),message:m().optional(),code:m().optional(),fatal:Ne().optional()}),v({t:N("snapshot"),s:m(),q:R().int().nonnegative().default(0),history:m().default(""),status:xu,cols:R().int().positive().optional(),rows:R().int().positive().optional(),exitCode:R().nullish().transform(e=>e??void 0),signal:R().nullable().optional(),runtime:bw.optional(),ptyBackend:m().optional(),...wc}),v({t:N("output"),s:m(),q:R().int().nonnegative(),d:m(),r:m().optional()}),v({t:N("exit"),s:m(),q:R().int().nonnegative(),exitCode:R().nullish().transform(e=>e??void 0),signal:R().nullable().optional()}),v({t:N("restarted"),s:m(),q:R().int().nonnegative(),history:m().default(""),...wc})]),kw=e=>{const t=ji.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=Au,n.set(t,1),n},Ew=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):ji.encode(e);t[0]===Au&&(t=t.subarray(1));try{return vw.safeParse(JSON.parse(Iu.decode(t))).data??null}catch{return null}};class Pw extends Error{code;constructor(t,n){super(t),this.name="TerminalRequestError",this.code=n}}const ok=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,Aw=v({error:m().optional(),code:m().optional()}),Fs=async(e,t)=>{const n=Aw.safeParse(await e.json().catch(()=>null)).data;return new Pw(n?.error??t,n?.code??null)},Iw=e=>{const t=ji.encode(e);if(t.byteLength<=yc)return e;let n=t.byteLength-yc;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return Iu.decode(t.subarray(n))},xw=v({sessions:G(me())});class Ru{constructor(t={refreshAuth:Ms,openSocket:()=>gw(Pe().websocket("/api/terminal/ws")),clearUrlAuthToken:gr}){this.dependencies=t}socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=!1;subscribe(t,n){this.cancelIdleClose();const r={handlers:n,lastSequence:-1},s=this.subscribers.get(t)??new Set,o=s.size===0;s.add(r),this.subscribers.set(t,s);const i=this.projections.get(t);i&&(r.lastSequence=i.sequence,n.onEvent({type:"snapshot",sequence:i.sequence,data:i.history,cols:i.cols,rows:i.rows,status:i.status,mode:i.mode,purpose:i.purpose,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend}));const a=this.socket?.readyState===hn;return this.ensureConnected().then(()=>{const c=this.subscribers.get(t);o&&a&&c===s&&c.size>0&&this.send({t:"attach",v:3,s:t})}).catch(c=>{s.has(r)&&(n.onError?.(c,!1),this.scheduleReconnect())}),()=>{const c=this.subscribers.get(t);if(c?.delete(r),c?.size===0&&(this.subscribers.delete(t),this.projections.delete(t),this.send({t:"detach",v:3,s:t})),this.subscribers.size===0){if(this.cancelReconnect(),this.failures=0,this.socket?.readyState===hn){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,n){if(n&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n}))))throw new Error("Terminal connection is unavailable")}dispose(){this.disposed=!0,this.generation+=1,this.opening=null,this.subscribers.clear(),this.projections.clear(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.cancelIdleClose(),this.wakeCleanup?.(),this.wakeCleanup=null,this.closeSocket()}forget(t){this.projections.delete(t)}noteResize(t,n,r){const s=this.projections.get(t);s&&this.projections.set(t,{...s,cols:n,rows:r})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===hn)return;if(this.opening)return await this.opening,this.socket?.readyState===hn?void 0:this.ensureConnected();const t=this.generation,n=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((r,s)=>{let o=!1,i=!1,a=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,u=()=>{a||i||!l()||(a=!0,this.dependencies.clearUrlAuthToken?.())},d=p=>{o||(o=!0,clearTimeout(f),p?s(p):r())},f=setTimeout(()=>{u(),c?.close(),d(new Error("Terminal connection timed out"))},1e4);try{const p=this.dependencies.openSocket();c=p,p.binaryType="arraybuffer",this.socket=p,p.onopen=()=>{if(!l()){p.close(),d(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const y of this.subscribers.keys())this.send({t:"attach",v:3,s:y});this.startKeepalive(),d()},p.onmessage=y=>{this.handleMessage(y.data)},p.onerror=()=>{const y=l();y&&u(),d(new Error("Terminal WebSocket failed")),y&&this.subscribers.size>0&&this.scheduleReconnect()},p.onclose=()=>{const y=l();y&&(this.stopKeepalive(),u()),this.socket===p&&(this.socket=null),d(new Error("Terminal WebSocket closed")),y&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(p){d(p instanceof Error?p:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=n;try{await n}finally{this.opening===n&&(this.opening=null)}}handleMessage(t){const n=Ew(t);if(!n||n.t==="hello"||n.t==="pong")return;if(n.t==="error"){const o=new Error(n.message??"Terminal error");o.code=n.code;const i=n.s?[n.s]:[...this.subscribers.keys()];for(const a of i)for(const c of this.subscribers.get(a)??[])c.handlers.onError?.(o,n.fatal===!0);return}if(!n.s)return;const r=this.subscribers.get(n.s);if(!r)return;if(n.t==="snapshot"){const o={sequence:n.q??0,history:n.history??"",cols:n.cols,rows:n.rows,status:n.status,mode:n.mode,purpose:n.purpose,exitCode:n.exitCode,signal:n.signal??null,runtime:n.runtime,ptyBackend:n.ptyBackend};this.projections.set(n.s,o);for(const i of r)i.lastSequence=o.sequence,i.handlers.onEvent({type:"snapshot",sequence:o.sequence,data:o.history,cols:o.cols,rows:o.rows,status:o.status,mode:o.mode,purpose:o.purpose,exitCode:o.exitCode,signal:o.signal,runtime:o.runtime,ptyBackend:o.ptyBackend});return}const s=this.projections.get(n.s);s&&n.q>s.sequence&&(n.t==="output"?this.projections.set(n.s,{...s,sequence:n.q,history:Iw(s.history+(n.r??n.d))}):n.t==="exit"?this.projections.set(n.s,{...s,sequence:n.q,status:"exited",exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&this.projections.set(n.s,{...s,sequence:n.q,history:n.history??"",status:"running",mode:n.mode??s.mode,purpose:n.purpose??s.purpose,exitCode:void 0,signal:null}));for(const o of r)n.q<=o.lastSequence||(o.lastSequence=n.q,n.t==="output"?o.handlers.onEvent({type:"data",sequence:n.q,data:n.d,replayData:n.r}):n.t==="exit"?o.handlers.onEvent({type:"exit",sequence:n.q,exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&o.handlers.onEvent({type:"snapshot",sequence:n.q,data:n.history??"",status:"running",mode:n.mode??s?.mode,purpose:n.purpose??s?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==hn)return!1;try{return this.socket.send(kw(t)),!0}catch{return!1}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const n=typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine?6e4:Math.min(500*2**Math.min(this.failures-1,10),8e3);for(const s of this.subscribers.values())for(const o of s)o.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const r=()=>{typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null,this.ensureConnected().catch(()=>this.scheduleReconnect()))};typeof window<"u"&&window.addEventListener("online",r),typeof document<"u"&&document.addEventListener("visibilitychange",r),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",r),typeof document<"u"&&document.removeEventListener("visibilitychange",r)},this.reconnectTimer=setTimeout(r,n)}scheduleIdleClose(){this.idleCloseTimer||this.disposed||(this.idleCloseTimer=setTimeout(()=>{this.idleCloseTimer=null,!(this.disposed||this.subscribers.size>0)&&(this.generation+=1,this.opening=null,this.closeSocket())},ww))}cancelIdleClose(){this.idleCloseTimer&&(clearTimeout(this.idleCloseTimer),this.idleCloseTimer=null)}startKeepalive(){this.stopKeepalive(),this.keepaliveTimer=setInterval(()=>this.send({t:"ping",v:3}),45e3)}stopKeepalive(){this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null}cancelReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null}closeSocket(){this.stopKeepalive();const t=this.socket;this.socket=null,t&&(t.readyState===yw||t.readyState===hn)&&t.close()}}let Ut=new Ru;async function Rw(e){const t=await g("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await Fs(t,"Failed to create terminal session");const n=await t.json().catch(()=>null),r=Sw.safeParse(n).data;if(!r)throw new Error("Failed to create terminal session");return r}async function Cw(e){const t=await g(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`);if(!t.ok)throw await Fs(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=xw.safeParse(n).data?.sessions;if(!Array.isArray(r))throw new Error("Failed to list terminal sessions");const s=[];for(const o of r){const i=Tw.safeParse(o).data;i&&s.push(i)}return s}async function Ow(e){e.length!==0&&await Dn("/api/terminal/touch","POST",{sessionIds:e})}async function Mw(){const e=await g("/api/terminal/shells");if(!e.ok)throw await Fs(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&Ai(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function Dw(e,t,n){return Ut.subscribe(e,{onEvent:t,onError:n})}async function _w(e,t){await Ut.write(e,t)}async function Dn(e,t,n){const r={method:t};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const s=await g(e,r);if(!s.ok)throw await Fs(s,"Terminal command failed");return s}async function Lw(e,t,n){await Dn(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n}),Ut.noteResize(e,t,n)}async function Fw(e,t){await Dn(`/api/terminal/${e}/appearance`,"POST",t)}async function Uw(e){await Dn(`/api/terminal/${e}`,"DELETE"),Ut.forget(e)}async function jw(e,t){return(await Dn(`/api/terminal/${e}/restart`,"POST",t)).json()}async function Nw(e){const n=await(await Dn("/api/terminal/force-kill","POST",e)).json().catch(()=>null);if(Array.isArray(n?.killedSessionIds))for(const r of n.killedSessionIds)typeof r=="string"&&Ut.forget(r);else e.sessionId&&Ut.forget(e.sessionId)}function ik(){Ut.dispose(),Ut=new Ru}const Bw=()=>({async listShells(){return Mw()},async listSessions(e){return Cw(e)},async touchSessions(e){await Ow(e)},async createSession(e){return Rw(e)},connect(e,t){const n=Dw(e,t.onEvent,t.onError);return{close:()=>n()}},async sendInput(e,t){await _w(e,t)},async resize(e){await Lw(e.sessionId,e.cols,e.rows)},async updateAppearance(e,t){await Fw(e,t)},async close(e){await Uw(e)},async restartSession(e,t){return jw(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows,themeMode:t.themeMode,terminalBackground:t.terminalBackground,terminalForeground:t.terminalForeground,shell:t.shell,loginShell:t.loginShell})},async forceKill(e){await Nw(e)}}),Qo=new Set,Hw=e=>(Qo.add(e),()=>{Qo.delete(e)}),zw=e=>{for(const t of Qo)t(e)},Xo=new Set,$w=(e,t)=>JSON.stringify([t,Ye(e)]);function ak(e){return Xo.add(e),()=>{Xo.delete(e)}}function Ww(e,t){const n=$w(e,t);for(const r of Xo)r(n)}class Gw extends Error{reason;constructor(t,n){super(t),this.name="GitPathUnavailableError",this.reason=n}}const qw=v({error:m(),code:Se(["path_not_found","nested_repository","untracked_directory"])}),Cu=v({headCommit:m().nullable(),indexCommit:m().nullable(),worktreeCommit:m().nullable(),hasTrackedChanges:Ne(),hasUntrackedFiles:Ne(),hasConflict:Ne()}),P="/api/git",Ou=v({diff:m()}),Kw=v({files:G(v({path:m(),status:m()}))}),Vw=v({error:m()}),Jw=v({files:G(v({path:m(),previousPath:m().optional(),changeType:m(),insertions:R(),deletions:R(),isBinary:Ne()}))}),bc=v({hash:m(),date:m(),message:m(),refs:m(),body:m(),author_name:m(),author_email:m(),filesChanged:R(),insertions:R(),deletions:R(),parents:G(m())}),Yw=v({all:G(bc),latest:bc.nullable(),total:R()}),Qw=v({diff:m(),submodule:Cu.nullable().default(null)}),Xw=v({original:m(),modified:m(),path:m(),isBinary:Ne().optional(),submodule:Cu.nullable().default(null)});async function Mu(e,t){const n=qw.safeParse(await e.json().catch(()=>null));return n.success&&(e.status===404||e.status===422)?new Gw(n.data.error,n.data.code):new Error(`${t}: ${e.statusText}`)}async function Us(e,t){const n=Vw.safeParse(await e.json().catch(()=>null));return new Error(n.success?n.data.error:`${t}: ${e.statusText}`)}const Zw=1200,eb=5e3,Zo=new Map,Jn=new Map,Du=new Map,Sc=new Map,Jr=new Map,_u=e=>e.trim(),Hi=(e,t)=>JSON.stringify([e,_u(t)]),Lu=(e,t,n)=>JSON.stringify([e,_u(t),n??"full"]),ei=(e,t)=>Du.get(Hi(e,t))??0,Fu=(e,t)=>{const n=Hi(e,t);Du.set(n,ei(e,t)+1);for(const r of[void 0,"light"]){const s=Lu(e,t,r);Zo.delete(s),Jn.delete(s)}};Hw(e=>{Fu(W(),e)});const Tr=e=>{zw(e)},ne=async(e,t)=>{const n=await t.json();return Tr(e),n};function I(e,t,n){const r={...n};return t&&(r.directory=t),Pe().api(e,r)}async function tb(e){const t=Hi(W(),e),n=Date.now(),r=Sc.get(t);if(r&&r.expiresAt>n)return r.value;const s=Jr.get(t);if(s)return s;const o=(async()=>{const i=await g(I(`${P}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return Sc.set(t,{value:c,expiresAt:Date.now()+eb}),c})();Jr.set(t,o);try{return await o}finally{Jr.get(t)===o&&Jr.delete(t)}}class nb extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function ck(e){const t=await g("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new nb;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const n=await t.json();if(!Array.isArray(n?.repositories))throw new Error("Unexpected git directories response");return n.repositories.map(r=>Ye(r?.path??null)).filter(r=>r!==null)}async function rb(e,t){const n=t?.mode,r=W();t?.fresh&&Fu(r,e);const s=Lu(r,e,n),o=Date.now(),i=Zo.get(s);if(i&&i.expiresAt>o)return i.value;const a=Jn.get(s);if(a)return a;const c=(async()=>{const l=ei(r,e),u=await g(I(`${P}/status`,e,n?{mode:n}:void 0));if(!u.ok)throw new Error(`Failed to get git status: ${u.statusText}`);const d=await u.json();return ei(r,e)===l&&Zo.set(s,{value:d,expiresAt:Date.now()+Zw}),d})();Jn.set(s,c);try{return await c}finally{Jn.get(s)===c&&Jn.delete(s)}}async function lk(e){const t=await g(I(`${P}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function uk(e){const t=await g(I(`${P}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function dk(e,t){const n=await g(I(`${P}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!n.ok)throw new Error(`Failed to get git commit summaries: ${n.statusText}`);const r=await n.json().catch(()=>({}));return{commits:Array.isArray(r.commits)?r.commits.map(s=>({sha:typeof s.sha=="string"?s.sha:"",short:typeof s.short=="string"?s.short:"",subject:typeof s.subject=="string"?s.subject:""})).filter(s=>s.sha&&s.short):[]}}async function sb(e,t){const{path:n,staged:r,contextLines:s}=t;if(!n)throw new Error("path is required to fetch git diff");const o=await g(I(`${P}/diff`,e,{path:n,staged:r?"true":void 0,context:s}));if(!o.ok)throw await Mu(o,"Failed to get git diff");return Qw.parse(await o.json())}async function ob(e,t){const{base:n,head:r,path:s,contextLines:o,includeWorkingTree:i}=t;if(!n||!r)throw new Error("base and head are required to fetch git range diff");const a=await g(I(`${P}/range-diff`,e,{base:n,head:r,path:s||void 0,context:o,includeWorkingTree:i}));if(!a.ok)throw await Us(a,"Failed to get git range diff");return Ou.parse(await a.json())}async function ib(e,t){const n=await g(I(`${P}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!n.ok)throw await Us(n,"Failed to get commit diff");return Ou.parse(await n.json())}async function ab(e,t){const{base:n,head:r,includeWorkingTree:s}=t;if(!n||!r)throw new Error("base and head are required to fetch git range files");const o=await g(I(`${P}/range-files`,e,{base:n,head:r,includeWorkingTree:s}));if(!o.ok)throw await Us(o,"Failed to get git range files");return Kw.parse(await o.json()).files}async function cb(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await g(I(`${P}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function lb(e,t){const{path:n,staged:r}=t;if(!n)throw new Error("path is required to fetch git file diff");const s=await g(I(`${P}/file-diff`,e,{path:n,staged:r?"true":void 0}));if(!s.ok)throw await Mu(s,"Failed to get git file diff");return Xw.parse(await s.json())}async function ub(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await g(I(`${P}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to revert git changes")}Tr(e)}async function db(e,t){await Uu(e,[t])}async function Uu(e,t){const n=t.map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to stage git changes");const r=await g(I(`${P}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to stage git changes")}Tr(e)}async function fb(e,t){await ju(e,[t])}async function ju(e,t){const n=t.map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to unstage git changes");const r=await g(I(`${P}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to unstage git changes")}Tr(e)}async function pb(e,t,n){await zi(e,t,n,"stage")}async function hb(e,t,n){await zi(e,t,n,"unstage")}async function mb(e,t,n){await zi(e,t,n,"discard")}async function zi(e,t,n,r){if(!t)throw new Error("path is required to apply a git hunk");if(typeof n!="string"||!n.trim())throw new Error("patch is required to apply a git hunk");const s=await g(I(`${P}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:n,action:r})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error||"Failed to apply git hunk")}Tr(e)}async function gb(e){if(!e)return!1;const t=await g(I(`${P}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function yb(e){const t=await g(I(`${P}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function wb(e,t){const n=await g(I(`${P}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!n.ok)throw new Error(`Failed to get branch push status: ${n.statusText}`);return n.json()}async function bb(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await g(I(`${P}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete branch")}return ne(e,n)}async function Sb(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await g(I(`${P}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete remote branch")}return ne(e,n)}async function Tb(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await g(I(`${P}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to remove remote")}return ne(e,r)}async function vb(e,t,n){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);const s=await g(I(`${P}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));console.error("[git-generation][browser] http error",{status:s.status,statusText:s.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const o=await s.json();if(!o?.message||typeof o.message!="object")throw new Error("Malformed commit generation response");const i=typeof o.message.subject=="string"&&o.message.subject.trim().length>0?o.message.subject.trim():"",a=Array.isArray(o.message.highlights)?o.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:i,highlights:a}}}async function kb(e,t){const{base:n,head:r,context:s,zenModel:o,providerId:i,modelId:a}=t;if(!n||!r)throw new Error("base and head are required");const c={base:n,head:r};s?.trim()&&(c.context=s.trim()),o&&(c.zenModel=o),i&&(c.providerId=i),a&&(c.modelId=a);const l=await g(I(`${P}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const p=await l.json().catch(()=>({error:l.statusText}));throw new Error(p.error||"Failed to generate PR description")}const u=await l.json().catch(()=>null),d=typeof u?.title=="string"?u.title:"",f=typeof u?.body=="string"?u.body:"";if(!d&&!f)throw new Error("Malformed PR description response");return{title:d,body:f}}async function Tc(e){const t=await g(I(`${P}/worktrees`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list worktrees")}return t.json()}async function vc(e,t){const n=await g(I(`${P}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to validate worktree")}return n.json()}async function Eb(e){const t=await g(I(`${P}/worktrees/bootstrap-status`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to get worktree bootstrap status")}return t.json()}async function Pb(e,t){const n=await g(I(`${P}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to preview worktree")}return n.json()}async function kc(e,t){const n=await g(I(`${P}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to create worktree")}return n.json()}async function Ec(e,t){const n=await g(I(`${P}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete worktree")}return n.json()}async function Ab(e,t,n={}){const r=await g(I(`${P}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create commit")}return ne(e,r)}async function Ib(e,t={}){const n=W(),r=await g(I(`${P}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to push")}const s=await ne(e,r);return s.success&&Ww(e,n),s}async function xb(e,t={}){const n=await g(I(`${P}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to pull")}return ne(e,n)}async function Rb(e,t={}){const n=await g(I(`${P}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to fetch")}return ne(e,n)}async function Cb(e){const t=await g(I(`${P}/stashes`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list stashes")}return t.json()}async function Ob(e,t){const n=await g(I(`${P}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to count stash files")}return n.json()}async function Nu(e,t={}){const n=await g(I(`${P}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to stash changes")}return ne(e,n)}const $i=async(e,t,n)=>{const r=await g(I(`${P}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||`Failed to ${t}`)}return ne(e,r)},Mb=(e,t)=>$i(e,"stash/apply",t),Bu=(e,t)=>$i(e,"stash/pop",t),Db=(e,t)=>$i(e,"stash/drop",t);async function _b(e,t){const n=await g(I(`${P}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout branch")}return ne(e,n)}async function Lb(e,t,n){const r=await g(I(`${P}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create branch")}return ne(e,r)}async function Fb(e,t,n){const r=await g(I(`${P}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to rename branch")}return ne(e,r)}async function Ub(e,t={}){const n=await g(I(`${P}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(`Failed to get git log: ${r.error||n.statusText}`)}return Yw.parse(await n.json())}async function jb(e,t){const n=await g(I(`${P}/commit-files`,e,{hash:t}));if(!n.ok)throw await Us(n,"Failed to get commit files");return Jw.parse(await n.json())}async function fk(e,t,n,r){const s=await g(I(`${P}/commit-file-diff`,e,{hash:t,path:n,binary:r?"true":void 0}));if(!s.ok)throw new Error(`Failed to get commit file diff: ${s.statusText}`);return s.json()}async function Nb(){const e=await g(I(`${P}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Bb(e){const t=await g(I(`${P}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to create git identity")}return t.json()}async function Hb(e,t){const n=await g(I(`${P}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to update git identity")}return n.json()}async function zb(e){const t=await g(I(`${P}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to delete git identity")}}async function $b(e){if(!e)return null;const t=await g(I(`${P}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function Wb(e){if(!e)return!1;const t=await g(I(`${P}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function pk(){const e=await g(I(`${P}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function Gb(e,t){const n=await g(I(`${P}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to set git identity")}return n.json()}async function hk(){const e=await g(I(`${P}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function mk(e,t){if(!e)return null;const n=await g(I(`${P}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function qb(e){const t=await g(I(`${P}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function Kb(e,t){const n=await g(I(`${P}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to rebase")}return ne(e,n)}async function Vb(e){const t=await g(I(`${P}/rebase/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort rebase")}return ne(e,t)}async function Jb(e,t){const n=await g(I(`${P}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to merge")}return ne(e,n)}async function Yb(e,t){const n=await g(I(`${P}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout commit")}return ne(e,n)}async function Qb(e,t){const n=await g(I(`${P}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to cherry-pick")}return ne(e,n)}async function Xb(e,t){const n=await g(I(`${P}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to revert commit")}return ne(e,n)}async function Zb(e,t,n,r){const s=await g(I(`${P}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:n,force:r})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error||"Failed to reset")}return ne(e,s)}async function eS(e){const t=await g(I(`${P}/merge/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort merge")}return ne(e,t)}async function tS(e){const t=await g(I(`${P}/rebase/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue rebase")}return ne(e,t)}async function nS(e){const t=await g(I(`${P}/merge/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue merge")}return ne(e,t)}async function rS(e,t){return await Nu(e,{message:t?.message}),{success:!0}}async function sS(e){return await Bu(e,{ref:"stash@{0}"}),{success:!0}}async function oS(e){const t=await g(I(`${P}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function iS(e,t){const n=await g(`${P}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw new Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function aS(e){const t=await g(`${P}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const cS=()=>({checkIsGitRepository:tb,getGitStatus:rb,getGitDiff:sb,getGitFileDiff:lb,getGitRangeDiff:ob,getGitRangeFiles:ab,getBranchBase:cb,revertGitFile:ub,stageGitFile:db,stageGitFiles:Uu,unstageGitFile:fb,unstageGitFiles:ju,stageGitHunk:pb,unstageGitHunk:hb,revertGitHunk:mb,isLinkedWorktree:gb,getGitBranches:yb,getGitUnpushedBranchCounts:wb,deleteGitBranch:bb,deleteRemoteBranch:Sb,removeRemote:Tb,generateCommitMessage:vb,generatePullRequestDescription:kb,listGitWorktrees:Tc,validateGitWorktree:vc,createGitWorktree:kc,deleteGitWorktree:Ec,validateWorktreeDirectory:iS,canonicalizeWorktreeState:aS,createGitCommit(e,t,n){return Ab(e,t,n)},gitPush:Ib,gitPull:xb,gitFetch:Rb,listGitStashes:Cb,countGitStashFiles:Ob,stashGitChanges:Nu,applyGitStash:Mb,popGitStash:Bu,dropGitStash:Db,checkoutBranch:_b,createBranch:Lb,renameBranch:Fb,getGitLog(e,t){return Ub(e,t)},getCommitFiles:jb,getGitCommitDiff:ib,getCurrentGitIdentity:$b,hasLocalIdentity:Wb,setGitIdentity:Gb,getGitIdentities:Nb,createGitIdentity:Bb,updateGitIdentity:Hb,deleteGitIdentity:zb,getRemotes:qb,rebase:Kb,abortRebase:Vb,continueRebase:tS,merge:Jb,abortMerge:eS,continueMerge:nS,checkoutCommit:Yb,cherryPick:Qb,revertCommit:Xb,resetToCommit:Zb,stash:rS,stashPop:sS,getConflictDetails:oS,worktree:{list:Tc,validate:vc,bootstrapStatus:Eb,preview:Pb,create:kc,remove:Ec}}),de=e=>e.replace(/\\/g,"/"),lS=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Zt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:de(t?.directory||t?.path||e),entries:t.entries.filter(r=>!!(r&&typeof r.name=="string"&&typeof r.path=="string")).map(r=>({name:r.name,path:de(r.path),isDirectory:!!r.isDirectory}))}},$e=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},uS=({getDirectory:e})=>({async listDirectory(t,n){const r=de(t),s=new URLSearchParams;r&&s.set("path",r),n?.respectGitignore&&s.set("respectGitignore","true");const o=await g("/api/fs/list",{query:s,headers:$e(e)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Zt(a.error||"Failed to list directory",{reason:ys(a.reason),status:o.status})}const i=await o.json();return lS(r,i)},async search(t){const n=new URLSearchParams,r=de(t.directory);r&&n.set("directory",r),n.set("query",t.query),n.set("dirs","false"),n.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&n.set("limit",String(t.maxResults));const s=await g("/api/find/file",{query:n,headers:$e(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to search files")}const o=await s.json();return(Array.isArray(o)?o:[]).map(a=>({path:de(`${r}/${a}`),preview:[de(a)]}))},async createDirectory(t){const n=de(t),r=await g("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create directory")}const s=await r.json();return{success:!!s?.success,path:typeof s?.path=="string"?de(s.path):n}},async statFile(t,n){const r=de(t),s=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&s.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&s.set("outsideFileGrant",n.outsideFileGrant);const o=await g("/api/fs/stat",{query:s,signal:AbortSignal.timeout(3e4),headers:$e(e,n?.directory)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to stat file")}const i=await o.json().catch(()=>({}));return{path:typeof i.path=="string"?de(i.path):r,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,n){const r=de(t),s=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&s.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&s.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&s.set("optional","true");const o=await g("/api/fs/read",{query:s,signal:AbortSignal.timeout(3e4),cache:n?.optional||n?.fresh?"no-store":"default",headers:$e(e,n?.directory)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await o.text(),path:r}},async writeFile(t,n){const r=de(t),s=await g("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:r,content:n})});if(!s.ok){const i=await s.json().catch(()=>({error:s.statusText}));throw new Error(i.error||"Failed to write file")}const o=await s.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?de(o.path):r}},async uploadFile(t,n,r){const s=de(t),o=await g("/api/fs/upload",{method:"POST",query:{path:s,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...$e(e,r?.directory)},body:n});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Zt(a.error||"Failed to upload file",{reason:ys(a.reason),status:o.status})}const i=await o.json().catch(()=>({}));return{success:!!i.success,path:i.path?de(i.path):s}},async delete(t){const n=de(t),r=await g("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete file")}return{success:!!(await r.json().catch(()=>({}))).success}},async rename(t,n){const r=await g("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({oldPath:t,newPath:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rename file")}const s=await r.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?de(s.path):n}},async revealPath(t){const n=await g("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:de(t)})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(t){const n=de(t),r=await g("/api/fs/raw",{query:{path:n,download:!0},headers:$e(e)});if(!r.ok)throw new Error(`Download failed (${r.status})`);const s=await r.blob(),o=n.split("/").pop()||"file",i=window.Capacitor,a=new File([s],o,{type:s.type||"application/octet-stream"});if(i?.isNativePlatform?.()===!0&&navigator.canShare?.({files:[a]})){await navigator.share({files:[a]});return}const c=URL.createObjectURL(s),l=document.createElement("a");l.href=c,l.download=o,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),100)}}),dS="/api/config/settings",Pc=()=>`${dS}?${Zl}=${Ei()}`,fS="/api/config/reload",Ac=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},pS=()=>({async load(){const e=await g(Pc(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:Ac(await e.json()),source:"web"}},async save(e){const t=await g(Pc(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to save settings")}return Ac(await t.json())},async restartOpenCode(){const e=await g(fS,{method:"POST"});if(!e.ok){const t=await e.json().catch(()=>({error:e.statusText}));throw new Error(t.error||"Failed to restart OpenCode")}return{restarted:!0}}}),hS=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),mS=1500,ti=5e3,gS="openchamber-notification-claim:",rr=new Map,yS=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),wS=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim()).join("|")},bS=e=>{for(const[t,n]of rr)e-n>ti&&rr.delete(t)},SS=e=>{const t=wS(e);if(!t)return!0;const n=Date.now();bS(n);const r=rr.get(t)??0;if(n-r<ti)return!1;try{if(typeof window<"u"&&window.localStorage){const s=`${gS}${t}`,o=Number(window.localStorage.getItem(s)??"0");if(Number.isFinite(o)&&n-o<ti)return rr.set(t,o),!1;Number.isFinite(o)&&o>0&&window.localStorage.removeItem(s),window.localStorage.setItem(s,String(n))}}catch{}return rr.set(t,n),!0},Hu=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{setTimeout(()=>n(null),mS)})])??e}catch{return e}},TS=async e=>{const t=await Hu();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(n){return console.warn("Failed to send notification via service worker",n),!1}},vS=async()=>{const e=await Hu();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},kS=async e=>{if(e?.requireHidden&&typeof document<"u"&&document.hasFocus())return!0;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",e),!1;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),!1;if(!yS()&&await vS()||!SS(e))return!0;try{return await TS(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},ES=async e=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,requireHidden:e?.requireHidden}}),!0}catch(n){return console.warn("Failed to send native notification (desktop)",n),!1}},PS=()=>({async notifyAgentCompletion(e){return await ES(e)||await kS(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),mn=async(e,t)=>{try{const n=await g(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},AS=()=>({async getVapidPublicKey(){return mn("/api/push/vapid-public-key")},async subscribe(e){return mn("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return mn("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return mn("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return mn("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return mn("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),le=async e=>await e.json().catch(()=>null),IS=({urls:e})=>({async authStatus(){const t=await g("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await le(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to load GitHub status");return n},async authStart(){const t=await g("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),n=await le(t);if(!t.ok||!n||!("deviceCode"in n))throw new Error(n?.error||t.statusText||"Failed to start GitHub auth");return n},async authComplete(t){const n=await g("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to complete GitHub auth");return r},async authDisconnect(){const t=await g("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),n=await le(t);if(!t.ok)throw new Error(n?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!n?.removed}},async authActivate(t){const n=await g("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to activate GitHub account");return r},async authSetGhCliDisabled(t){const n=await g("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update gh CLI setting");return{disabled:!!r.disabled}},async me(){const t=await g("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),n=await le(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to fetch GitHub user");return n},async prStatus(t,n,r,s){const o=new URLSearchParams({directory:t,branch:n,...r?{remote:r}:{},...s?.force?{force:"true"}:{}}),i=await g(`/api/github/pr/status?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await le(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prCreate(t){const n=await g("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to create PR");return r},async prUpdate(t){const n=await g("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update PR");return r},async prMerge(t){const n=await g("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to merge PR");return r},async prReady(t){const n=await g("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to mark PR ready");return r},async repoUpstream(t){const n=await g(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to detect upstream repo");return r},async repoBranches(t,n){const r=await g(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(n)}`,{method:"GET",headers:{Accept:"application/json"}}),s=await le(r);if(!r.ok||!s)throw new Error(s?.error||r.statusText||"Failed to fetch repo branches");return s.branches??[]},async prsList(t,n){const r=n?.page??1,s=new URLSearchParams({directory:t,page:String(r)});n?.query&&s.set("query",n.query);const o=await g(`/api/github/pulls/list?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load pull requests");return i},async prContext(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.includeDiff&&s.set("diff","1"),r?.includeCheckDetails&&s.set("checkDetails","1"),r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/pulls/context",s),{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load pull request context");return i},async issuesList(t,n){const r=n?.page??1,s=new URLSearchParams({directory:t,page:String(r)});n?.query&&s.set("query",n.query);const o=await g(`/api/github/issues/list?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issues");return i},async issueGet(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/issues/get",s),{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issue");return i},async issueComments(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/issues/comments",s),{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issue comments");return i}});async function Me(e){try{return await e.json()}catch{return null}}function De(e,t){return e?.error?.trim()||t}function zu(e){return Number.isFinite(e)?e??null:null}function $u(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function Wu(e){const t=e?.id?.trim();return t?{id:t,name:e?.name?.trim()||null,displayName:e?.displayName?.trim()||null,email:e?.email?.trim()||null,avatarUrl:e?.avatarUrl?.trim()||null}:null}function xS(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function RS(e){const t=e?.id?.trim();if(!t)return null;const n=e?.authorizedAt;return{id:t,name:e?.name?.trim()||null,urlKey:e?.urlKey?.trim()||null,current:e?.current===!0,user:Wu(e?.user),authorizedAt:zu(n)}}function Ic(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(RS).filter(n=>n!=null):[];return{connected:e.connected,user:Wu(e.user),organization:xS(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function CS(e){const t=e?.authorizationUrl?.trim(),n=e?.expiresIn,r=e?.scope?.trim();return!t||!Number.isFinite(n)||n==null||!r?null:{authorizationUrl:t,expiresIn:n,scope:r}}function OS(e){const t=e?.id?.trim()||null,n=e?.name?.trim()||null,r=e?.type?.trim()||null;return!t&&!n&&!r?null:{id:t,name:n,type:r}}function MS(e){const t=e?.id?.trim(),n=e?.name?.trim();if(!t||!n)return null;const r=e?.position;return{id:t,name:n,type:e?.type?.trim()||null,position:zu(r)??0}}function DS(e){const t=e?.name?.trim()||null,n=e?.displayName?.trim()||null,r=e?.avatarUrl?.trim()||null;return!t&&!n&&!r?null:{name:t,displayName:n,avatarUrl:r}}function _S(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();return!t||!n||!r?null:{id:t,key:n,name:r}}function LS(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function FS(e){const t=e?.trim();if(!t)return null;const n=t.startsWith("#")?t.slice(1):t;return/^[0-9A-Fa-f]{6}$/.test(n)?`#${n.toLowerCase()}`:null}function US(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:FS(e.color)}}function jS(e){return Array.isArray(e)?e.map(US).filter(t=>t!=null):[]}function Gu(e){if(!e)return null;const t=e?.id?.trim(),n=e?.identifier?.trim(),r=e?.title?.trim(),s=e?.url?.trim();return!t||!n||!r||!s?null:{id:t,identifier:n,title:r,url:s,state:OS(e.state),assignee:DS(e.assignee),team:_S(e.team),priority:LS(e.priority),labels:jS(e.labels)}}function NS(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:$u(n)??"",createdAt:e?.createdAt?.trim()||null,user:e?.user?{name:e.user.name?.trim()||null,displayName:e.user.displayName?.trim()||null,avatarUrl:e.user.avatarUrl?.trim()||null}:null}}function qu(e){const t=Gu(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map(NS).filter(s=>s!=null):[],r=e?.description;return{...t,description:$u(r),comments:n}}function BS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(Gu).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function HS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:qu(e.issue)}}function zS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(MS).filter(n=>n!=null):[]}}function $S(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:qu(e.issue)}}function WS(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();if(!t||!n||!r)return null;const s=e?.projectPath?.trim()||null;return{id:t,key:n,name:r,projectPath:s}}function xc(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};const t=Array.isArray(e.teams)?e.teams.map(WS).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const GS=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function qS(e){return GS.find(t=>t===e)??null}function Rc(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function KS(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};if(e.posted===!0)return{connected:!0,posted:!0,commentId:e.commentId?.trim()||null};const t=qS(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const VS=()=>({async authStatus(){const e=await g("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await Me(e),n=Ic(t);if(!e.ok||!n)throw new Error(De(t,e.statusText||"Failed to load Linear status"));return n},async authStart(e){const t=await g("/api/linear/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{origin:e}:{})}),n=await Me(t),r=CS(n);if(!t.ok||!r)throw new Error(De(n,t.statusText||"Failed to start Linear auth"));return r},async authDisconnect(){const e=await g("/api/linear/auth",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Me(e);if(!e.ok)throw new Error(De(t,e.statusText||"Failed to disconnect Linear"));return{removed:t?.removed===!0}},async authActivate(e){const t=await g("/api/linear/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({organizationId:e})}),n=await Me(t),r=Ic(n);if(!t.ok||!r)throw new Error(De(n,t.statusText||"Failed to switch Linear workspace"));return r},async issuesList(e){const t=new URLSearchParams,n=e?.query?.trim(),r=e?.cursor?.trim(),s=e?.status?.trim(),o=e?.assignee?.trim(),i=e?.teamId?.trim(),a=e?.priority?.trim();n&&t.set("query",n),r&&t.set("cursor",r),s&&t.set("status",s),o&&t.set("assignee",o),i&&t.set("teamId",i),a&&t.set("priority",a);const c=t.toString(),l=c?`?${c}`:"",u=await g(`/api/linear/issues/list${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await Me(u),f=BS(d);if(!u.ok||!f)throw new Error(De(d,u.statusText||"Failed to load Linear issues"));return f},async issueGet(e){const t=new URLSearchParams({id:e}),n=await g(`/api/linear/issues/get?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Me(n),s=HS(r);if(!n.ok||!s)throw new Error(De(r,n.statusText||"Failed to load Linear issue"));return s},async issueStates(e){const t=new URLSearchParams({teamId:e}),n=await g(`/api/linear/issues/states?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Me(n),s=zS(r);if(!n.ok||!s)throw new Error(De(r,n.statusText||"Failed to load Linear workflow states"));return s},async issueUpdate(e){const t=await g("/api/linear/issues/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:e.id,stateId:e.stateId})}),n=await Me(t),r=$S(n);if(!t.ok||!r)throw new Error(De(n,t.statusText||"Failed to update Linear issue"));return r},async mappingGet(){const e=await g("/api/linear/mapping",{method:"GET",headers:{Accept:"application/json"}}),t=await Me(e),n=xc(t);if(!e.ok||!n)throw new Error(De(t,e.statusText||"Failed to load Linear mapping"));return n},async mappingSet(e){const t=await g("/api/linear/mapping",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({defaultProjectPath:e.defaultProjectPath,teamProjectPaths:e.teamProjectPaths})}),n=await Me(t),r=xc(n);if(!t.ok||!r)throw new Error(De(n,t.statusText||"Failed to save Linear mapping"));return r},async sessionStatusPost(e){const t=await g("/api/linear/session-status",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({kind:e.kind,sessionId:e.sessionId,issueIdentifier:e.issueIdentifier,sessionOrigin:e.sessionOrigin})}),n=await Me(t),r=KS(n);if(!t.ok||!r)throw new Error(De(n,t.statusText||"Failed to post Linear session status"));return r},async preferencesGet(){const e=await g("/api/linear/preferences",{method:"GET",headers:{Accept:"application/json"}}),t=await Me(e),n=Rc(t);if(!e.ok||!n)throw new Error(De(t,e.statusText||"Failed to load Linear preferences"));return n},async preferencesSet(e){const t=await g("/api/linear/preferences",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({sessionComments:e.sessionComments})}),n=await Me(t),r=Rc(n);if(!t.ok||!r)throw new Error(De(n,t.statusText||"Failed to save Linear preferences"));return r}}),Et=async e=>await e.json().catch(()=>null),JS=()=>({async listClients(){const e=await g("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Et(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load remote clients");return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){const t=await g("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),n=await Et(t);if(!t.ok||!n?.client||typeof n.token!="string")throw new Error(n?.error||t.statusText||"Failed to create remote client token");return n},async createPairingSession(e={}){const t=await g("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),n=await Et(t);if(!t.ok||typeof n?.pairing?.secret!="string"||!n?.server)throw new Error(n?.error||t.statusText||"Failed to create pairing session");return n},async listPendingPairings(){const e=await g("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Et(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pending pairings");return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){const e=await g("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Et(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pairing transports");return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable!==!1}},async cancelPairing(e){const t=await g(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await Et(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to cancel pairing");return{cancelled:n.cancelled===!0}},async revokeClient(e){const t=await g(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await Et(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to revoke remote client");return n},async purgeRevokedClients(){const e=await g("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Et(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),YS=()=>({api:(...e)=>Pe().api(...e),authenticatedAsset:(...e)=>Pe().authenticatedAsset(...e),assetWithUrlToken:(...e)=>Pe().assetWithUrlToken(...e),auth:(...e)=>Pe().auth(...e),health:(...e)=>Pe().health(...e),rawFile:(...e)=>Pe().rawFile(...e),sse:(...e)=>Pe().sse(...e),websocket:(...e)=>Pe().websocket(...e)}),QS=(e={})=>{const t=e.urls??oi();Kd(t);const n=YS();return{themeFiles:nf(),runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Bw(),git:cS(),files:uS({getDirectory:()=>Yo.getState().currentDirectory}),settings:pS(),permissions:hS(),notifications:PS(),github:IS({urls:n}),linear:VS(),push:AS(),clientAuth:JS()}},XS=3e3,Cc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ZS=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__OPENCHAMBER_API_BASE_URL__),clientToken:e(window.__OPENCHAMBER_CLIENT_TOKEN__),localOrigin:e(window.__OPENCHAMBER_LOCAL_ORIGIN__),runtimeHeaders:window.__OPENCHAMBER_RUNTIME_HEADERS__,relayHostId:e(window.__OPENCHAMBER_RELAY_HOST_ID__)}};let ni=Promise.resolve();const gk=()=>ni,yk=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:s,relayHostId:o,relay:i}=e??ZS(),a=e?null:qc(),c=o||(a?.target==="remote"?a.hostId:""),l=Vc({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return Yd({apiBaseUrl:t,runtimeKey:Cc(t,r)?"local":c?`host:${c}`:null}),ul(n||null),dl(s||null),i&&us({apiBaseUrl:t,clientToken:n||null,requestHeaders:s||null,runtimeKey:o?`host:${o}`:null,relay:i}),rt.reconnectToRuntimeBaseUrl(),Ms(t||void 0).catch(()=>{}),r&&!Cc(t,r)&&Object.keys(Os()).length>0&&wl(r).catch(()=>{}),El(),ni=i?Promise.resolve():Promise.race([Ap(o||void 0).catch(()=>{}),new Promise(u=>{window.setTimeout(u,1e4)})]).then(()=>{rt.reconnectToRuntimeBaseUrl()}),ni.then(()=>{window.setTimeout(()=>{Tp().catch(()=>{})},XS)}),QS({urls:l})};export{ew as $,cT as A,rt as B,Xv as C,Yv as D,Be as E,Ee as F,Gw as G,LT as H,af as I,Zr as J,ok as K,tk as L,Vd as M,On as N,Ce as O,mi as P,Il as Q,ZT as R,hp as S,Mt as T,Al as U,re as V,fl as W,TT as X,kT as Y,Pv as Z,Dv as _,W as a,ov as a$,wi as a0,Rs as a1,Ms as a2,Pe as a3,gw as a4,Os as a5,xm as a6,hm as a7,mv as a8,bm as a9,RT as aA,rn as aB,Vv as aC,Qv as aD,AT as aE,IT as aF,rv as aG,ut as aH,$p as aI,zv as aJ,Qd as aK,bh as aL,PT as aM,Kh as aN,Nh as aO,Hh as aP,ik as aQ,zo as aR,lT as aS,uT as aT,dT as aU,gv as aV,Xd as aW,el as aX,fn as aY,zg as aZ,tw as a_,NT as aa,vT as ab,hv as ac,Wp as ad,rk as ae,tl as af,ET as ag,ow as ah,ek as ai,sw as aj,Dr as ak,Zn as al,_h as am,Ge as an,sv as ao,Bd as ap,qc as aq,oT as ar,Zv as as,pv as at,iT as au,aT as av,OT as aw,fT as ax,CT as ay,xT as az,rl as b,rb as b$,Gp as b0,qp as b1,Kp as b2,jl as b3,wg as b4,iv as b5,zw as b6,uv as b7,cv as b8,zm as b9,nS as bA,tS as bB,Ob as bC,Lb as bD,Ab as bE,Bb as bF,kc as bG,bb as bH,zb as bI,Ec as bJ,Sb as bK,hk as bL,Db as bM,cb as bN,fk as bO,jb as bP,oS as bQ,$b as bR,yb as bS,ib as bT,dk as bU,sb as bV,lb as bW,Nb as bX,Ub as bY,ob as bZ,ab as b_,Ho as ba,Pt as bb,dg as bc,Vn as bd,Yi as be,$v as bf,wa as bg,vn as bh,Eb as bi,Jm as bj,K as bk,ba as bl,rh as bm,nh as bn,ch as bo,gr as bp,Hg as bq,Wv as br,eS as bs,Vb as bt,Mb as bu,aS as bv,tb as bw,_b as bx,Yb as by,Qb as bz,yk as c,to as c$,wb as c0,pk as c1,mk as c2,qb as c3,vc as c4,Tc as c5,Rb as c6,xb as c7,Ib as c8,Wb as c9,Ae as cA,dv as cB,Lh as cC,Jc as cD,Gv as cE,Jv as cF,_y as cG,jT as cH,ev as cI,tv as cJ,ke as cK,ip as cL,gp as cM,Sp as cN,mp as cO,gi as cP,pp as cQ,nv as cR,YT as cS,XT as cT,QT as cU,ap as cV,Pp as cW,GT as cX,jv as cY,Nv as cZ,Fr as c_,gb as ca,Cb as cb,Jb as cc,Bu as cd,Pb as ce,Kb as cf,Tb as cg,Fb as ch,Zb as ci,lk as cj,uk as ck,Xb as cl,ub as cm,mb as cn,Gb as co,db as cp,Uu as cq,pb as cr,rS as cs,Nu as ct,sS as cu,fb as cv,ju as cw,hb as cx,Hb as cy,iS as cz,yr as d,gT as d$,nk as d0,ck as d1,nb as d2,Hw as d3,Fv as d4,_T as d5,DT as d6,Dl as d7,lv as d8,xg as d9,vv as dA,Yt as dB,jh as dC,Bh as dD,Kv as dE,qv as dF,cp as dG,tp as dH,qT as dI,KT as dJ,MT as dK,Xm as dL,bT as dM,ST as dN,Pi as dO,fv as dP,Fh as dQ,Uh as dR,Ai as dS,eg as dT,Zm as dU,Km as dV,Ds as dW,pT as dX,mT as dY,yT as dZ,hT as d_,Ue as da,Av as db,xv as dc,Mv as dd,Rv as de,Iv as df,Cv as dg,tu as dh,Ov as di,Zt as dj,Bv as dk,Hv as dl,hg as dm,_v as dn,xi as dp,sk as dq,Lv as dr,Uv as ds,av as dt,wv as du,bv as dv,Tv as dw,ym as dx,yv as dy,Sv as dz,Pn as e,wT as e0,mm as e1,zT as e2,$w as e3,ak as e4,UT as e5,$T as e6,WT as e7,FT as e8,JT as e9,pt as ea,BT as f,gk as g,g as h,mr as i,HT as j,ai as k,At as l,VT as m,Yo as n,Ye as o,Xf as p,Do as q,kv as r,us as s,ht as t,T as u,um as v,Ev as w,xs as x,Zc as y,fs as z};