@vantran-se/openchamber-web 1.24.3 → 1.24.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-BjJHrzmU.js → CodeMirrorCommentWidgets-B4a0JkUz.js} +1 -1
  2. package/dist/assets/{DiffView-COVQhWGd.js → DiffView-B2CD9wC8.js} +1 -1
  3. package/dist/assets/{FilesView-B1V5JxFX.js → FilesView-C4vMFclc.js} +1 -1
  4. package/dist/assets/{GitView-CDOJy5Ay.js → GitView-Byu2DY7s.js} +1 -1
  5. package/dist/assets/{GuestAttachDialog-D3S0Rjic.js → GuestAttachDialog-B808E0-d.js} +1 -1
  6. package/dist/assets/{JsonTreeView-D0C9nU7K.js → JsonTreeView-VW_7czo3.js} +1 -1
  7. package/dist/assets/{LinearIssuesView-D7FKg1XJ.js → LinearIssuesView-EzGNCGrd.js} +1 -1
  8. package/dist/assets/{MarkdownImageGallery-BrFjAVEf.js → MarkdownImageGallery-B2YUDFaB.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-DWepTafh.js → MarkdownRendererImpl-B4ikIzR3.js} +1 -1
  10. package/dist/assets/{OnboardingScreen-Dyxxiqdt.js → OnboardingScreen-CQHBSTEi.js} +1 -1
  11. package/dist/assets/{PatchDiff-DnEhjXcC.js → PatchDiff-DCjGhlYV.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-DyxZVVVR.js → PierreDiffViewer-CEDZNkU2.js} +1 -1
  13. package/dist/assets/{PlanView-LW2z_EAP.js → PlanView-D3x-pTkZ.js} +1 -1
  14. package/dist/assets/{PluginPane-B4tKno2h.js → PluginPane-DEcgDQ9h.js} +1 -1
  15. package/dist/assets/{SettingsView-DEaMulN9.js → SettingsView-CSinuH-1.js} +1 -1
  16. package/dist/assets/{SettingsWindow-FLDJXOgQ.js → SettingsWindow-B5CHoJFZ.js} +1 -1
  17. package/dist/assets/{SubmoduleDiffSummary-CvVwD-Vi.js → SubmoduleDiffSummary-oxeACCWs.js} +1 -1
  18. package/dist/assets/{ToolOutputDialog-BiP0x2Rw.js → ToolOutputDialog-tLNWmfcW.js} +1 -1
  19. package/dist/assets/{ToolPartDiffPreview-CkR4msKP.js → ToolPartDiffPreview-CflzmK-x.js} +1 -1
  20. package/dist/assets/{VirtualizedFileDiff-0pyr_mHY.js → VirtualizedFileDiff-NU0FHFhT.js} +1 -1
  21. package/dist/assets/{WalkthroughView-yNj4nOP5.js → WalkthroughView-BZyjhqHv.js} +1 -1
  22. package/dist/assets/{appThemeRegistry-BuUKhbYQ.js → appThemeRegistry-DLicw4dH.js} +1 -1
  23. package/dist/assets/{commitAndPush-DvJKa3Ks.js → commitAndPush-BDftrjr6.js} +1 -1
  24. package/dist/assets/{computeVirtualFileMetrics-DxTBMuu-.js → computeVirtualFileMetrics-DlWlEM3x.js} +1 -1
  25. package/dist/assets/{de-DgxgFyGG.js → de-Bro6_zyl.js} +1 -1
  26. package/dist/assets/{es-BFsZj5F_.js → es-Bb9XQZvd.js} +1 -1
  27. package/dist/assets/{fr-jdZ5KKQi.js → fr-Dgfzn-IL.js} +1 -1
  28. package/dist/assets/{index-CKHjPKbq.js → index-CtQNmqUL.js} +1 -1
  29. package/dist/assets/{index-Cbci4i1W.js → index-Dqc6USl3.js} +1 -1
  30. package/dist/assets/{isDiffPlainText-D7FkBMP6.js → isDiffPlainText-CO4e5J_S.js} +1 -1
  31. package/dist/assets/{isFilePlainText-CL2vsrIZ.js → isFilePlainText-ue6kCou7.js} +1 -1
  32. package/dist/assets/{ja-C5kKrhO4.js → ja-BYsakGFh.js} +1 -1
  33. package/dist/assets/{ko-DXDTT_0O.js → ko-BSaQz9aN.js} +1 -1
  34. package/dist/assets/{main-CgXMBNvG.js → main-B62_pjL5.js} +2 -2
  35. package/dist/assets/{main-CZALtVek.js → main-BEdcOI2P.js} +4 -4
  36. package/dist/assets/{markdownCore-Dh7WEsdM.js → markdownCore-CK48LG0z.js} +1 -1
  37. package/dist/assets/{miniChat-CwTmDixi.js → miniChat-LT8Rqofr.js} +2 -2
  38. package/dist/assets/{mobile-CLf2vCtO.js → mobile-CqarEynh.js} +2 -2
  39. package/dist/assets/{patchFileDiff-Bsba8KFp.js → patchFileDiff-D7QVlovD.js} +1 -1
  40. package/dist/assets/{pl-D-7x4Y8Q.js → pl-OIviPdoj.js} +1 -1
  41. package/dist/assets/{pt-BR-CSBZrHa8.js → pt-BR-Cltg-E6s.js} +1 -1
  42. package/dist/assets/{renderElectronMiniChatApp-C5gAFBk0.js → renderElectronMiniChatApp-COyLTtZx.js} +2 -2
  43. package/dist/assets/{renderMobileApp-V4hYd32H.js → renderMobileApp-BC1MHg6g.js} +3 -3
  44. package/dist/assets/{runtimeEndpointReset-DhlHCn-2.js → runtimeEndpointReset-DdrazOVH.js} +3 -3
  45. package/dist/assets/{scheduledTasksApi-DzjbLd8P.js → scheduledTasksApi-B2SWMGEU.js} +1 -1
  46. package/dist/assets/{shikiHighlight-8_3csmr6.js → shikiHighlight-BPu3JiQs.js} +1 -1
  47. package/dist/assets/{textMateThemeFromAppTheme-CHo2fCgW.js → textMateThemeFromAppTheme-DWqRPo9A.js} +1 -1
  48. package/dist/assets/{tr-Dr-oJ22L.js → tr-CQI-KPre.js} +1 -1
  49. package/dist/assets/{uk-9Nx83UcI.js → uk-CqW7R4DA.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-khZXpFL_.js → useAppFontEffects-ne84JBVL.js} +9 -9
  51. package/dist/assets/{useInlineCommentController-DkQ_gqpn.js → useInlineCommentController-CgS0fnw_.js} +1 -1
  52. package/dist/assets/{useRootScrollLock-DdvHf9Pt.js → useRootScrollLock-Cpf1qoGp.js} +2 -2
  53. package/dist/assets/{vendor-codemirror-language-data-CdzUmUyZ.js → vendor-codemirror-language-data-Bx2EHc1O.js} +2 -2
  54. package/dist/assets/{web-components-B8IcVQAA.js → web-components-DxX8bZ1o.js} +1 -1
  55. package/dist/assets/{zh-CN-Bxy_Hj3r.js → zh-CN-CVZG_o_J.js} +1 -1
  56. package/dist/assets/{zh-TW-0BB4gpHM.js → zh-TW-D5ZxzCZp.js} +1 -1
  57. package/dist/index.html +2 -2
  58. package/dist/mini-chat.html +2 -2
  59. package/dist/mobile.html +2 -2
  60. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
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 C,r as Ve,d as dr,l as U,a as N,b as Fe,u as ue,_ as Te,c as Qt,t as ji,j as Ni,e as tr,f as wc}from"./vendor-zod-CgAdXWZO.js";import{_ as Xs}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as gt,d as xn,p as fr,a as Bu}from"./vendor-zustand-BAGL70zf.js";import{c as Hu}from"./vendor-opencode-sdk-BJ73u-bH.js";import{f as bc,R as no}from"./vendor-react-BUCujlKS.js";const Kn=1,zu="openchamber-relay-v1",Sc=1,Tc=12,Vn=1+Tc,nr=64*1024,rr=5,ro=128,vc=0,kc=1,vn=4,$u=1+vn,hs=nr-rr-$u,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},Gu=new Set(Object.values(H)),Wu=e=>Gu.has(e),Jt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},pt=globalThis.crypto.subtle,Ec={name:"ECDH",namedCurve:"P-256"},Pc=16,jo=32,qu=16,ms=4,Ac=8;class Rt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Ku=()=>pt.generateKey(Ec,!0,["deriveBits"]),Vu=async e=>{const t=await pt.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Ju=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Rt("invalid ECDH public key JWK");try{return await pt.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Ec,!0,[])}catch{throw new Rt("invalid ECDH public key JWK")}},Yu=()=>{const e=new Uint8Array(Pc);return globalThis.crypto.getRandomValues(e),e},Qu=async(e,t,n)=>{if(n.length!==Pc)throw new Rt("invalid handshake nonce length");const r=await pt.deriveBits({name:"ECDH",public:t},e,256),o=await pt.importKey("raw",r,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await pt.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(zu)},o,jo*2*8)),i=(a,c)=>pt.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(s.slice(0,jo),["encrypt","decrypt"]),hostToClient:await i(s.slice(jo),["encrypt","decrypt"])}},Xu=(e,t,n)=>{for(let r=Ac-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Zu=(e,t)=>{let n=0n;for(let r=0;r<Ac;r+=1)n=n<<8n|BigInt(e[t+r]);return n},ed=e=>{const t=new Uint8Array(ms);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>nr)throw new Rt("plaintext frame exceeds maximum size");n+=1n;const o=new Uint8Array(Tc);o.set(t,0),Xu(o,ms,n);const s=new Uint8Array(await pt.encrypt({name:"AES-GCM",iv:o},e,r)),i=new Uint8Array(Vn+s.length);return i[0]=Sc,i.set(o,1),i.set(s,Vn),i}}},td=e=>{let t=0n;return{async decrypt(n){if(n.length<Vn+qu)throw new Rt("encrypted frame too short");if(n[0]!==Sc)throw new Rt("unsupported encrypted frame version");const r=n.slice(1,Vn),o=Zu(r,ms);if(o<=t)throw new Rt("frame counter regression");let s;try{s=await pt.decrypt({name:"AES-GCM",iv:r},e,n.slice(Vn))}catch{throw new Rt("frame decryption failed")}return t=o,new Uint8Array(s)}}},kr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",nd=e=>{let t="";for(let n=0;n<e.length;n+=3){const r=e[n],o=n+1<e.length?e[n+1]:void 0,s=n+2<e.length?e[n+2]:void 0;t+=kr[r>>2],t+=kr[(r&3)<<4|(o??0)>>4],o!==void 0&&(t+=kr[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=kr[s&63])}return t},Bi=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!==Kn)return null;const r=n.batch===!0,o=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:Kn,batch:r,flowControl:o}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:Kn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:o}:null},rd=e=>({type:"fail",closeCode:Jt.ChannelFailure,reason:e}),od=async(e,t={})=>{const n=t.batch!==!1,r=await Ju(e),o=await Ku(),s=Yu(),i={t:"hello",v:Kn,clientPubJwk:await Vu(o.publicKey),nonce:nd(s)};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 Bi(c)?.t==="ready"?{type:"ignore"}:rd("plaintext frame on established channel");const l=Bi(c);if(l?.t!=="ready")return{type:"ignore"};const u=await Qu(o.privateKey,r,s);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:ed(u.clientToHost),decryptor:td(u.hostToClient)}}}}},Ic=4294967295,sd=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 ye extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const ze=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>Ic)throw new ye("invalid stream id");if(n.length>hs)throw new ye("tunnel payload exceeds maximum size");const o=new Uint8Array(rr+n.length);return o[0]=r?e|ro:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(n,rr),o},id=e=>{if(e.length<rr)throw new ye("tunnel frame too short");const t=e[0],n=(t&ro)!==0,r=t&~ro;if(!Wu(r))throw new ye(`unknown tunnel frame type ${r}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:o,payload:e.slice(rr),hasMoreFragments:n}},ad=new TextEncoder,cd=new TextDecoder,Er=e=>ad.encode(JSON.stringify(e)),Pr=(e,t)=>{let n;try{n=JSON.parse(cd.decode(e))}catch{throw new ye("malformed JSON tunnel payload")}if(!t(n))throw new ye("unexpected JSON tunnel payload shape");return n},xc=(e,t=hs)=>{if(t<=0||t>hs)throw new ye("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},Hi=(e,t,n)=>{const r=xc(n);return r.map((o,s)=>ze(e,t,o,s<r.length-1))},ld=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,o=t.get(r);if(!n.hasMoreFragments&&!o)return n.payload;const s=o?.chunks??[],i=(o?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new ye("fragmented message exceeds maximum size");if(s.push(n.payload),n.hasMoreFragments)return t.set(r,{chunks:s,totalBytes:i}),null;t.delete(r);const a=new Uint8Array(i);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a},dropStream(n){for(const r of t.keys())r.startsWith(`${n}:`)&&t.delete(r)}}},ud=e=>{if(e.length===0)throw new ye("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=vc,s.set(o,1),s.length>nr)throw new ye("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=vn+o.length;if(t>nr)throw new ye("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=kc;let r=1;for(const o of e)n[r]=o.length>>>24&255,n[r+1]=o.length>>>16&255,n[r+2]=o.length>>>8&255,n[r+3]=o.length&255,r+=vn,n.set(o,r),r+=o.length;return n},dd=e=>{if(e.length<1)throw new ye("empty batch plaintext");const t=e[0];if(t===vc)return[e.slice(1)];if(t!==kc)throw new ye(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+vn>e.length)throw new ye("truncated batch frame length");const o=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=vn,r+o>e.length)throw new ye("truncated batch frame body");n.push(e.slice(r,r+o)),r+=o}if(n.length===0)throw new ye("empty frame batch");return n},fd=new Set([H.HttpBody,H.WsText,H.WsBinary]),Cc=150,pd=24*1024,hd=32,md=e=>{const t=e.windowMs??Cc,n=e.maxBatchBytes??pd,r=e.maxBatchFrames??hd,o=e.now??(()=>Date.now()),s=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=o(),e.sendBatch(ud(b))};return{enqueue:b=>{if(d)return;const w=b[0]&~ro;if(!fd.has(w)){a.push(b),p();return}const E=o();if(a.length===0&&E-u>=t){a.push(b),p();return}const k=vn+b.length;if(a.length>0&&1+c+k>nr&&p(),a.push(b),c+=k,c>=n||a.length>=r){p();return}l===null&&(l=s(p,t))},flush:p,dispose(){d=!0,f(),a=[],c=0}}},gd=()=>{let e=1;return{next(){if(e>Ic)throw new ye("stream id space exhausted");const t=e;return e+=2,t}}},ko=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yd=e=>ko(e)&&Object.values(e).every(t=>typeof t=="string"),wd=e=>ko(e)&&typeof e.status=="number"&&yd(e.headers),zi=e=>ko(e)&&typeof e.reason=="string",bd=e=>ko(e)&&typeof e.code=="number"&&typeof e.reason=="string",Rc=/^[a-z][a-z\d+.-]*:\/\//i,Zs="http://tunnel.invalid",Sd=e=>{try{const t=Rc.test(e)?new URL(e):new URL(e,Zs);return`${t.pathname}${t.search}`}catch{return e}},Ar=e=>({async*[Symbol.asyncIterator](){yield e}}),Td=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()}}}),vd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},kd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Td(e)};if(typeof e=="string")return{body:Ar(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Ar(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Ar(vd(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Ar(r),contentType:n}},Ed=async(e,t)=>{let n;const r=new Headers;let o="GET",s=null,i;e instanceof Request?(n=e.url,o=e.method,e.headers.forEach((d,f)=>r.set(f,d)),i=e.signal,s=e.body):n=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((d,f)=>r.set(f,d)),t.body!==void 0&&(s=t.body),t.signal&&(i=t.signal));const a=Rc.test(n)?new URL(n):new URL(n,Zs),{body:c,contentType:l}=await kd(s);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,f)=>{u[f]=d}),{method:o.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},Dc="__openchamberAmbiguousTransport",Oc=e=>(Object.defineProperty(e,Dc,{value:!0,enumerable:!1,configurable:!0}),e),Pd=e=>!e||typeof e!="object"?!1:e[Dc]===!0,Ad=["local","remote",null],Id=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Mc(e){if(!e||typeof e!="object")return{valid:!1};const t=e,n=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,o=t.status;if(r!==null&&(typeof r!="string"||!Ad.includes(r)))return{valid:!1};if(typeof o!="string"||!Id.includes(o))return{valid:!1};if(r==="remote"||r==="local"){if(o==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok",...n}};if(o==="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(o==="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(o==="incompatible"||o==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:o,hostId:t.hostId,url:t.url,...n}};if(o==="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(o==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...n}};if(o==="missing")return{valid:!1}}return{valid:!1}}function wS(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 bS(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function SS(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function _c(){if(xd()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=Mc(t);return n.valid?n.outcome:null}function xd(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Mc(e).valid?"valid":"malformed"}const oo=/^[a-z][a-z\d+.-]*:\/\//i,Cd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},so=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Rd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return so(e)},Dd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return so(e)},Od=()=>Object.keys(xo()).length>0,Md=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},gs=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},_d=(e,t)=>{if(!t)return e;const n=new URLSearchParams;gs({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},$i=(e,t,n)=>{if(oo.test(t)){const s=new URL(t);return gs(s,n),s.toString()}const r=Cd(t);if(!e)return _d(r,n);const o=new URL(r,`${e}/`);return gs(o,n),o.toString()},Ir=(e,t=pf())=>{if(!t)return e;const n=oo.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),oo.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},Lc=(e,t)=>{const n=oo.test(e)?new URL(e):new URL(e,Md(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},Gi=(e,t,n)=>{if(!Od())return null;const r=Dd();if(!r)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${r}/`);o.searchParams.set("url",t);const s=hf(r);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Lc(o.toString(),n)):o.toString()}catch{return null}},ei=(e={})=>{const t=so(e.apiBaseUrl),n=so(e.realtimeBaseUrl),r=()=>t||Rd(),o=()=>n||r(),s=(a,c)=>$i(r(),a,c),i=(a,c)=>$i(o(),a,c);return{api:s,authenticatedAsset:(a,c)=>Ir(s(a,c)),assetWithUrlToken:(a,c,l)=>Ir(s(a,l),c),auth:s,health:a=>s("/health",a),rawFile:(a,c)=>s("/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=Ir(i(a,c));return Gi("sse",l,e)||l},websocket:(a,c)=>{const l=Lc(Ir(i(a,c)),e);return Gi("ws",l,e)||l}}};let io=ei();const Ee=()=>io,Ld=e=>{io=e},Fc=e=>(io=ei(e),io),ys="openchamber:runtime-endpoint-changed",ws="openchamber:runtime-endpoint-will-change";let kn="",or="";const No=(e,t,n)=>{try{e[t]=n}catch{}},ti=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"}`}},Fd="mobile-disconnected",Ud="url:default",Uc=e=>e===""||e===Ud||e===Fd,jc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Nc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Bc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Eo=()=>kn||jc();let Bo="",Wi=null,qi,Ki;const Vi=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},G=()=>{if(or)return or;const e=Vi("__OPENCHAMBER_API_BASE_URL__"),t=Vi("__OPENCHAMBER_LOCAL_ORIGIN__");if(Wi===kn&&qi===e&&Ki===t)return Bo;const n=Eo();return Bo=Bc(n,Nc())?"local":ti(n),Wi=kn,qi=e,Ki=t,Bo},jd=(e={})=>{if(kn||or)return;const t=e.apiBaseUrl?.trim()||jc(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const o=Nc(),s=o&&(!t||Bc(t,o));kn=t,or=e.runtimeKey?.trim()||(s?"local":ti(t||r))},ao=e=>{const t=e.apiBaseUrl.trim(),n=Eo(),r=G(),o=e.runtimeKey?.trim()||ti(t),s={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:o,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(ws,{detail:s})),kn=t,or=o,typeof window<"u"){const i=window;No(i,"__OPENCHAMBER_API_BASE_URL__",t),No(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),No(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Fc({apiBaseUrl:t,realtimeBaseUrl:t}),Zc(e.requestHeaders||null),Xc(e.clientToken||null),e.relay?sf(e.relay):af(),Co(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ys,{detail:s}))},Nd=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(ws,t),()=>window.removeEventListener(ws,t)},Hc=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(ys,t),()=>window.removeEventListener(ys,t)};let bs=null;const TS=e=>{bs=e},Po=()=>bs||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),zc=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Bd=(e=zc())=>!!e,Hd=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,mt=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,tn=()=>Hd()?.runtime==="electron",zd=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},$d="right",vS=()=>{if(!tn())return!1;const e=zd();return e==="win32"||e==="linux"},kS=e=>e==="left"?"left":$d,ES=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],ve=()=>typeof mt()?.invoke=="function",Cn=()=>tn()&&ve(),Gd=()=>{if(mt()?.pickThemeFile)return{async pick(){const e=mt()?.pickThemeFile;return e?{status:"picked",file:v({name:m(),size:C().nonnegative(),text:m()}).nullable().parse(await e())}:{status:"unsupported"}}}},oe=async(e,t)=>{const n=mt();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},PS=async()=>{if(!Cn()||!ke())return null;try{const e=await oe("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}},AS=async e=>{if(!Cn()||!ke())return null;try{const t=await oe("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}},IS=async()=>{if(!Cn()||!ke())return null;try{const e=await oe("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}},xS=async e=>{if(!Cn()||!ke())return null;try{const t=await oe("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}},CS=async()=>{if(!Cn()||!ke())return null;try{const e=await oe("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}},RS=async e=>{if(!Cn()||!ke())return null;try{const t=await oe("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}},Ji=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}}},Ho=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}}},Wd=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Un=e=>{const t=Wd(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},ke=()=>{if(typeof window>"u"||!Je())return!1;if(G()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Ho(e),n=Ho(Eo());if(!n&&t&&_c()?.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&&Un(t.hostname)&&Un(n.hostname)}const r=Ho(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&&Un(t.hostname)&&Un(r.hostname)}const o=Ji(e),s=Ji(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(r&&Un(r.hostname))},Je=()=>typeof window>"u"?!1:tn(),DS=async()=>{if(!Je())return!1;try{return!!await oe("desktop_focus_window")}catch{return!1}},$c=()=>Je()&&ve()&&ke(),qd=m().min(1),OS=e=>{if(!$c())return null;try{const t=qd.safeParse(mt()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},MS=async()=>{if(!Je())return!1;try{return await oe("desktop_start_window_drag"),!0}catch{return!1}},Me=()=>Bd()?!0:Po()?.runtime?.isVSCode===!0,_S=()=>{const t=Po()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Me()},LS=(e,t=Je())=>e==="web"&&!t,Gc=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},FS=async e=>{if($c())try{const t=await mt()?.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"}},Kd=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vd=v({path:m().min(1),outsideFileGrant:m().min(1),expiresAt:C().finite()}),US=async e=>{if(ve()&&ke())try{const t=await mt()?.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(!Kd(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"}},jS=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!ve()||!ke())return{success:!1,error:"Native file access not available"};try{const n=await mt()?.grantFileAccess?.(t),r=Vd.safeParse(n);return r.success?{success:!0,...r.data}:{success:!1,error:"File access was not granted"}}catch(n){return console.warn("Failed to request existing file access",n),{success:!1,error:n instanceof Error?n.message:String(n)}}},NS=async e=>({success:!0}),BS=async e=>({success:!0}),HS=async()=>ve()?await oe("desktop_check_for_updates"):null,zS=async e=>{if(!ve())return!1;const t=mt();let n=null,r=0,o;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("openchamber:update-progress",s=>{const i=s?.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,o=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:o});return}if(c==="Progress"){const u=l?.downloaded,d=l?.total;typeof u=="number"&&(r=u),typeof d=="number"&&(o=d),e({downloaded:r,total:o});return}c==="Finished"&&e({downloaded:r,total:o})})),await oe("desktop_download_and_install_update"),!0}catch(s){throw s instanceof Error?s:new Error(String(s))}finally{if(n)try{const s=n();s instanceof Promise&&await s}catch{}}},$S=async()=>ve()?(await oe("desktop_restart"),!0):!1,GS=async()=>{if(!ve())return!1;try{return await oe("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},WS=async()=>{if(!ve()||!ke())return null;try{const e=await oe("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}},Jd=async(e,t)=>{if(!ve()||!ke())return!1;const n=e?.trim();if(!n)return!1;try{return await oe("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}},qS=async e=>{if(!ve()||!ke())return!1;const t=e?.trim();if(!t)return!1;try{return await oe("desktop_reveal_path",{path:t}),!0}catch{return Jd(t)}},KS=async(e,t)=>{if(!ve()||!ke())return null;const n=e?.trim();if(!n)return null;try{const r=await oe("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}},VS=async(e,t,n)=>{if(!ve()||!ke())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await oe("desktop_open_in_app",{projectPath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},JS=async(e,t,n)=>{if(!ve()||!ke())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await oe("desktop_open_file_in_app",{filePath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},YS=async(e,t)=>{if(!ve()||!ke())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 oe("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 o=r;return o.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(o.apps)?{apps:o.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:o.hasCache===!0,isCacheStale:o.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},pr=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",Yd=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_ELECTRON__?.arch?.toLowerCase?.();if(e==="arm64"||e==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const t=window.__VSCODE_CONFIG__?.arch?.toLowerCase?.();if(t==="arm64"||t==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const n=navigator.userAgentData;if(n?.architecture?.toLowerCase?.()==="arm64"||n?.architecture?.toLowerCase?.()==="aarch64")return(n.platform||navigator.platform||"").toLowerCase().includes("win");const r=navigator.userAgent.toLowerCase();return!!((r.includes("aarch64")||r.includes("arm64")||r.includes("armv"))&&r.includes("windows"))},QS=()=>{if(typeof window>"u"||!pr()||Wc()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Wc=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Me()?"vscode":Je()?"desktop":"web"},Qd="1.24.3",xr=new Uint8Array(0),Xd=new TextEncoder,Zd=new TextDecoder,je=e=>e instanceof Error?e:new Error(String(e)),Cr=()=>new DOMException("The operation was aborted.","AbortError"),ef=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},tf=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},Yi=0,zo=1,Qi=2,Xi=3,nf=new Set([Jt.AuthFailed,Jt.DuplicateClient,Jt.LimitExceeded]),rf={[Jt.AuthFailed]:"relay authentication failed",[Jt.DuplicateClient]:"relay connection replaced by another client",[Jt.LimitExceeded]:"relay connection limit reached"},Zi=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ni=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??Cc,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(x=>ef(new WebSocket(x)));let d=!1,f=null,p={state:"idle"};const g=new Set;let b=null,w=null,E=null,k=0,F=0,O=null,K=[],R=!1;const we=x=>{if(!(p.state===x.state&&p.lastError===x.lastError)){p=x;for(const $ of g)try{$(p)}catch{}}},se=x=>{const $=K;K=[];for(const D of $)D.reject(x)},Lo=x=>{const $=K;K=[];for(const D of $)D.resolve(x)},Pe=(x,$)=>{x.dead=!0;const D=Array.from(x.streams.values());x.streams.clear();for(const M of D)try{M.fail($)}catch{}},On=()=>{O!==null&&(clearTimeout(O),O=null)},Mn=()=>{d||O===null||Zi()||(On(),Qe(),_n())},Lt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Mn()},L=()=>{R||typeof window>"u"||(R=!0,window.addEventListener("online",Mn),typeof document<"u"&&document.addEventListener("visibilitychange",Lt))},Qe=()=>{!R||typeof window>"u"||(R=!1,window.removeEventListener("online",Mn),typeof document<"u"&&document.removeEventListener("visibilitychange",Lt))},on=()=>{if(d||O!==null)return;const x=Math.max(0,F-1),$=a*2**Math.min(x,10),D=Zi()?l:c,M=Math.min(D,$);L(),O=setTimeout(()=>{O=null,Qe(),_n()},M)},Sr=()=>{const x=new URL(e.relayUrl);return x.searchParams.set("v",String(Kn)),x.searchParams.set("role","client"),x.searchParams.set("serverId",e.serverId),x.searchParams.set("appId","openchamber"),x.searchParams.set("appVersion",Qd),x.searchParams.set("platform",Wc()),e.grant&&x.searchParams.set("grant",e.grant),x.toString()},_n=async()=>{if(d)return;On(),k+=1;const x=k;we({state:F>0?"reconnecting":"connecting",lastError:p.lastError});let $;try{$=await od(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(V){if(x!==k||d)return;Ui(x,je(V),!0);return}if(x!==k||d)return;let D;try{D=u(Sr())}catch(V){Ui(x,je(V));return}w=D;let M=!1,j=null,W=null,xe=null,he=null,B=Promise.resolve(),z=null,te=null,it=!1,de=!1,fe=0,me=0,ge=null,at=null,Q=Date.now();const wt=()=>{ge!==null&&(clearTimeout(ge),ge=null),j!==null&&(clearInterval(j),j=null),W!==null&&(clearTimeout(W),W=null),xe!==null&&(clearInterval(xe),xe=null),he!==null&&(clearTimeout(he),he=null),at!==null&&(at.dispose(),at=null)};E=wt;function q(V,ne=!1,Y=!1){if(!(M||x!==k)){M=!0,Y&&(f=V),wt(),z&&(b=null,Pe(z,new Error(`relay tunnel reset: ${V.message}`))),se(V);try{D.close()}catch{}if(w===D&&(w=null),!d){if(F+=1,Y){we({state:"error",lastError:V.message});return}we({state:ne?"error":"reconnecting",lastError:V.message}),on()}}}const Ln=()=>{try{D.send($.helloText)}catch{}},vr=(V,ne,Y)=>{te=V,it=ne,de=Y,j!==null&&(clearInterval(j),j=null),W!==null&&(clearTimeout(W),W=null);const ie=new Map,Ft=gd(),Ue=ld();let Ut=Promise.resolve();const bt=Fn=>{Ut=Ut.then(async()=>{if(jt.dead)return;const Nu=await V.encryptor.encrypt(Fn);jt.dead||D.send(Nu)}).catch(()=>{q(new Error("relay encrypt/send failed"))})},Uo=ne?md({windowMs:s,sendBatch:bt}):null;at=Uo;const jt={streams:ie,assembler:Ue,nextStreamId:()=>Ft.next(),dead:!1,send(Fn){jt.dead||(Uo?Uo.enqueue(Fn):bt(Fn))}};z=jt,b=jt,F=0,Q=Date.now(),we({state:"connected"}),Lo(jt),xe=setInterval(()=>{Date.now()-Q<r||(jt.send(ze(H.Ping,0,xr)),he===null&&(he=setTimeout(()=>{he=null,q(new Error("relay keepalive timeout"))},o)))},r)},sn=()=>{ge!==null&&clearTimeout(ge),ge=null,!(!z||z.dead||fe===me)&&(me=fe,z.send(ze(H.DeliveryAck,0,sd(fe))))},ju=(V,ne)=>{let Y;try{Y=id(ne)}catch(Ue){q(je(Ue));return}if(Y.frameType===H.DeliveryAck){q(new Error("unexpected downstream delivery acknowledgement"));return}if(de&&Y.streamId!==0&&(fe+=ne.length,ge===null&&(ge=setTimeout(sn,10))),Q=Date.now(),he!==null&&(clearTimeout(he),he=null),Y.frameType===H.Ping){V.send(ze(H.Pong,Y.streamId,xr));return}if(Y.frameType===H.Pong)return;let ie=Y.payload;if(Y.frameType===H.WsText||Y.frameType===H.WsBinary){let Ue;try{Ue=V.assembler.push(Y)}catch(Ut){q(je(Ut));return}if(Ue===null)return;ie=Ue}else if(Y.hasMoreFragments){q(new Error("unexpected fragmented tunnel frame"));return}const Ft=V.streams.get(Y.streamId);Ft&&Ft.handleFrame(Y.frameType,ie)};D.onopen=()=>{M||x!==k||(Ln(),j=setInterval(Ln,t))},D.onmessage=V=>{if(M||x!==k)return;const ne=V.data;if(typeof ne=="string"){B=B.then(async()=>{if(M||x!==k)return;const ie=await $.handleText(ne);if(ie.type==="established"){if(te)return;vr(ie.channel,ie.batch,ie.flowControl)}else ie.type==="fail"&&q(new Error(`relay handshake failed: ${ie.reason}`))}).catch(ie=>{q(je(ie))});return}const Y=ne instanceof ArrayBuffer?new Uint8Array(ne):ne instanceof Uint8Array?ne:null;Y&&(B=B.then(async()=>{if(M||x!==k)return;const ie=z,Ft=te;if(!ie||!Ft){q(new Error("encrypted frame before handshake completed"));return}let Ue;try{Ue=await Ft.decryptor.decrypt(Y)}catch(bt){q(je(bt));return}let Ut;try{Ut=it?dd(Ue):[Ue]}catch(bt){q(je(bt));return}for(const bt of Ut){if(M||x!==k||ie.dead)return;ju(ie,bt)}de&&fe-me>=16*1024&&sn()}).catch(ie=>{q(je(ie))}))},D.onclose=V=>{const ne=nf.has(V.code);q(new Error(rf[V.code]??`relay socket closed (code ${V.code})`),ne,ne)},D.onerror=()=>{},W=setTimeout(()=>{W=null,q(new Error("relay handshake timeout"),!0)},n);function Ui(V,ne,Y=!1){V!==k||d||(se(ne),F+=1,we({state:Y?"error":"reconnecting",lastError:ne.message}),on())}},Tr=x=>d?Promise.reject(new Error("relay tunnel closed")):x?.aborted?Promise.reject(Cr()):f?Promise.reject(f):b&&!b.dead?Promise.resolve(b):new Promise(($,D)=>{let M=null;const j={resolve(W){M&&x&&x.removeEventListener("abort",M),$(W)},reject(W){M&&x&&x.removeEventListener("abort",M),D(W)}};x&&(M=()=>{K=K.filter(W=>W!==j),D(Cr())},x.addEventListener("abort",M,{once:!0})),K.push(j)}),yt=async(x,$)=>{const D=await Ed(x,$),M=D.signal;if(M?.aborted)throw Cr();const j=await Tr(M),W=j.nextStreamId();return await new Promise((xe,he)=>{let B=!1,z=!1,te=null,it=null;const de=()=>{j.streams.delete(W),j.assembler.dropStream(W),it&&M&&M.removeEventListener("abort",it)},fe=Q=>{if(!z){if(z=!0,de(),!B){he(Q);return}try{te?.error(Q)}catch{}}},me=Q=>{j.dead||j.send(ze(H.StreamAbort,W,Er({reason:Q})))},ge=Q=>Oc(new Error(Q));it=()=>{me("aborted"),fe(Cr())},j.streams.set(W,{handleFrame(Q,wt){if(Q===H.HttpResponse){if(B||z)return;let q;try{q=Pr(wt,wd)}catch(sn){me("malformed response head"),fe(ge(je(sn).message));return}const Ln=q.status===204||q.status===205||q.status===304;let vr=null;Ln||(vr=new ReadableStream({start(sn){te=sn},cancel(){z||(z=!0,de(),me("response body cancelled"))}})),B=!0,xe(new Response(vr,{status:q.status,headers:q.headers})),Ln&&(z=!0,de());return}if(Q===H.HttpBody){if(!B||z)return;try{te?.enqueue(wt)}catch{}return}if(Q===H.StreamEnd){if(z)return;if(!B){fe(ge("tunnel stream ended before response head"));return}z=!0,de();try{te?.close()}catch{}return}if(Q===H.StreamAbort){let q="stream aborted by host";try{q=Pr(wt,zi).reason}catch{}fe(ge(q))}},fail(Q){fe(ge(Q.message))}}),M&&M.addEventListener("abort",it,{once:!0});const at={method:D.method,path:D.path,query:D.query,headers:D.headers,hasBody:D.body!==null};j.send(ze(H.HttpRequest,W,Er(at))),(async()=>{try{let Q=!1;if(D.body)for await(const wt of D.body){if(z||j.dead)return;for(const q of xc(wt))j.send(ze(H.HttpBody,W,q)),Q=!0}!z&&!j.dead&&(D.body&&!Q&&j.send(ze(H.HttpBody,W,xr)),j.send(ze(H.StreamEnd,W,xr)))}catch(Q){me("request body failed"),fe(ge(je(Q).message))}})()})},Fo=x=>{const $=x.indexOf("?");return $===-1?{path:x,query:""}:{path:x.slice(0,$),query:x.slice($+1)}},Fu=(x,$)=>{let D=Yi,M=null,j=0,W=!1;const xe={get readyState(){return D},onopen:null,onmessage:null,onerror:null,onclose:null,send(B){if(D!==zo||!M||M.dead)throw new Error("relay tunnel socket is not open");if(typeof B=="string"){for(const te of Hi(H.WsText,j,Xd.encode(B)))M.send(te);return}const z=B instanceof ArrayBuffer?new Uint8Array(B.slice(0)):(()=>{const te=new Uint8Array(B.byteLength);return te.set(new Uint8Array(B.buffer,B.byteOffset,B.byteLength)),te})();for(const te of Hi(H.WsBinary,j,z))M.send(te)},close(B=1e3,z=""){D===Xi||D===Qi||(D===zo&&M&&!M.dead&&(D=Qi,M.send(ze(H.WsClose,j,Er({code:B,reason:z})))),he(B,z))}},he=(B,z,te=!1)=>{if(!W){if(W=!0,M&&(M.streams.delete(j),M.assembler.dropStream(j)),D=Xi,te)try{xe.onerror?.()}catch{}try{xe.onclose?.({code:B,reason:z})}catch{}}};return(async()=>{let B;try{B=await Tr()}catch(de){he(1006,je(de).message,!0);return}if(W)return;M=B,j=B.nextStreamId(),B.streams.set(j,{handleFrame(de,fe){if(de===H.WsOpened){if(D===Yi){D=zo;try{xe.onopen?.()}catch{}}return}if(de===H.WsText){try{xe.onmessage?.({data:Zd.decode(fe)})}catch{}return}if(de===H.WsBinary){const me=new ArrayBuffer(fe.byteLength);new Uint8Array(me).set(fe);try{xe.onmessage?.({data:me})}catch{}return}if(de===H.WsClose){let me=1e3,ge="";try{const at=Pr(fe,bd);me=at.code,ge=at.reason}catch{}he(me,ge);return}if(de===H.StreamAbort){let me="stream aborted";try{me=Pr(fe,zi).reason}catch{}he(1006,me,!0)}},fail(de){he(1012,de.message,!0)}});const{path:z,query:te}=Fo(x),it=$&&$.length>0?{path:z,query:te,protocols:$}:{path:z,query:te};B.send(ze(H.WsOpen,j,Er(it)))})(),xe},Uu=()=>{if(d)return;d=!0,k+=1,On(),Qe(),E?.(),E=null;const x=b;b=null;const $=new Error("relay tunnel closed");x&&Pe(x,$),se($);try{w?.close()}catch{}w=null,we({state:"idle"})};return _n(),{fetch:yt,openWebSocket:Fu,getStatus:()=>p,subscribeStatus(x){return g.add(x),()=>{g.delete(x)}},close:Uu}};let De=null,ht=null;const of=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Ao=()=>De,XS=()=>!De||!ht?null:{relayUrl:ht.relayUrl,serverId:ht.serverId,hostEncPubJwk:{...ht.hostEncPubJwk}},ZS=()=>De!==null,sf=e=>(De&&ht&&of(ht,e)||(De?.close(),ht=e,De=ni(e)),De),eT=(e,t)=>{De!==t&&(De?.close(),ht=e,De=t)},af=()=>{De?.close(),De=null,ht=null};let qc=()=>null,Kc="",co={},Xt="",sr=0,Wt=null,Sn="",ir=0,Zt="",qt=null,It="",Kr=0,Vr=0;const ri=1e4,cf=e=>e.toLowerCase()==="authorization",Vc=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const o=n.trim(),s=r.trim();o&&s&&!cf(o)&&(t[o]=s)}return t},lf=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,o])=>t[r]===o)},Io=e=>typeof e!="string"?"":e.trim(),uf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Io(e)},df=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Jc=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():df();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},oi=e=>{try{return new URL(e).origin}catch{return""}},Yc=()=>{Sn="",ir=0,Zt="",qt=null,It="",Kr+=1},hr=()=>{Xt="",sr=0,Yc()},Qc=()=>{Vr+=1,Wt=null,hr(),si()},Xc=e=>{const t=Io(e);Kc=t,Qc(),qc=()=>t?{type:"bearer",token:t}:null},Zc=e=>{const t=Vc(e);lf(co,t)||(co=t,Qc())},xo=()=>{if(Object.keys(co).length>0)return co;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Vc(e):{}},el=()=>Kc||uf(),ff=(e,t)=>{const n=Io(e);if(!n||typeof t!="number"||!Number.isFinite(t)){hr();return}const r=Xt;Xt=n,sr=t,r&&r!==n&&wf()},tl=()=>!Xt||sr<=Date.now()+ri?(hr(),""):Xt,nl=e=>{const t=oi(e);return!t||Zt!==t?"":!Sn||ir<=Date.now()+ri?(Sn="",ir=0,Zt="",""):Sn},pf=()=>{const e=tl();return!e&&(el()||typeof window<"u")&&Co().catch(()=>{}),e},hf=e=>{const t=e?nl(e):"";return!t&&e&&typeof window<"u"&&il(e).catch(()=>{}),t},rl=async()=>{const e=await qc(),t=e?.type==="bearer"?Io(e.token):el();return t?{type:"bearer",token:t}:null},mf=v({token:m(),expiresAt:C()}),ol=async(e,t)=>{const n=await rl(),r=new Headers;for(const[c,l]of Object.entries(xo()))r.set(c,l);n?.type==="bearer"&&r.set("Authorization",`Bearer ${n.token}`);const o=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",s=Ao(),i=s?await s.fetch(o,{method:"POST",headers:r}):await fetch(Jc(e,o),{method:"POST",headers:r,credentials:"include"});if(!i.ok)throw new Error(`Failed to mint runtime URL auth token (${i.status})`);const a=mf.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},tT=async e=>{const t=await ol(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},sl=e=>{if(Wt)return Wt;const t=Vr,r=(async()=>{let o;try{o=await ol(e)}catch(s){throw t===Vr&&hr(),s}if(t!==Vr)throw new Error("Runtime URL auth token response is stale");if(ff(o.token,o.expiresAt),!Xt)throw new Error("Runtime URL auth token response was invalid");return Xt})().finally(()=>{Wt===r&&(Wt=null)});return Wt=r,Wt},gf=e=>{const t=oi(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(qt&&It===t)return qt;const n=Kr,o=(async()=>{const s=await fetch(Jc(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!s.ok)throw n===Kr&&t===It&&(Sn="",ir=0,Zt=""),new Error(`Failed to mint local runtime URL auth token (${s.status})`);const i=await s.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!==Kr||t!==It)throw new Error("Local runtime URL auth token response is stale");return Sn=a,ir=c,Zt=t,a})().finally(()=>{qt===o&&(qt=null,It="")});return qt=o,It=t,qt},Co=async e=>{const t=tl();return t||sl(e)},il=async e=>{const t=oi(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=nl(t);return n||((Zt&&Zt!==t||It&&It!==t)&&Yc(),gf(t))};let gn=0,Jn=null,al=null;const Ss=new Set,yf=5e3,wf=()=>{for(const e of Ss)try{e()}catch{}},cl=()=>{Jn!==null&&(clearTimeout(Jn),Jn=null)},si=()=>{if(cl(),gn<=0||typeof window>"u")return;const e=sr-ri-yf,t=sr>0?Math.max(0,e-Date.now()):0;Jn=setTimeout(()=>{Jn=null,!(gn<=0)&&sl(al).catch(()=>{}).finally(()=>{si()})},t)},nT=e=>{typeof e=="string"&&e.trim()&&(al=e.trim()),gn+=1,si();let t=!1;return()=>{t||(t=!0,gn=Math.max(0,gn-1),gn===0&&cl())}},rT=e=>(Ss.add(e),()=>{Ss.delete(e)}),bf=async e=>{const t=new Headers(e);for(const[r,o]of Object.entries(xo()))t.has(r)||t.set(r,o);if(t.has("Authorization"))return t;const n=await rl();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},lo=gt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Sf=15e3,Tf=5*6e4;let Ts=0,$o=!1;const vf=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),kf=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!vf(t)},ll=async()=>{if(!$o){$o=!0;try{const{runtimeFetch:e}=await Xs(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>Lf);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){lo.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=lo.getState();n==="expired"&&r()}}catch{}finally{$o=!1}}},Ef=(e,t)=>{if(t!==401||lo.getState().state==="expired"||!kf(e))return;const n=Date.now();n-Ts<Sf||(Ts=n,ll())};let ea=!1;const oT=()=>{if(ea)return;ea=!0;let e=Date.now();const t=()=>{if(lo.getState().state!=="ok")return;const n=Date.now();n-e<Tf||(e=n,Ts=n,ll())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},en=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Pf=()=>typeof window>"u"?"":window.location.origin||"",ii=e=>{if(typeof window>"u")return!1;const t=Pf();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}},ai=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Af=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),Pt=(e,t)=>{try{Af(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},ci=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},Jr=e=>{try{const t=Ee().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:en(e.pathname)}catch{return!1}},Go=e=>{if(en(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ii(t)&&en(t.pathname)}catch{return!1}},If=(e,t)=>{try{const n=new URL(e);if(!ii(n))return e;const r=Ot(`${n.pathname}${n.search}`,t);return!ai(r)&&(n.protocol==="http:"||n.protocol==="https:")?(ci(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},Ot=(e,t)=>e==="/health"?Ee().health(t):e.startsWith("/auth/")||e==="/auth"?Ee().auth(e,t):en(e)?Ee().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?If(e,t):e,xf=e=>{const t=e instanceof Request?e.url:e.toString();if(!ai(t))return en(t);try{return Jr(new URL(t))}catch{return!1}},ul=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Cf=(e,t)=>!ul(t),vs=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,o=!1;for(const[s,i]of t)Cf(s,i)?(n.push([s,encodeURIComponent(i)]),r=!0,s.toLowerCase()==="x-opencode-directory"&&(o=!0)):n.push([s,i]);return o&&n.push(["x-opencode-directory-encoding","uri"]),r?n:void 0},ct=async(e,t,n=!0)=>{const r=new Headers(vs(e)??e);return t&&new Headers(vs(t)??t).forEach((o,s)=>r.set(s,o)),n?bf(r):r},Rf=(e,t)=>{if(!t)return e;const n=new URL(e,Zs);return ci(n,t),`${n.pathname}${n.search}`},dl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!ai(n))return en(n)?Rf(n,t):null;try{const r=new URL(n);return!ii(r)||!en(r.pathname)?null:(ci(r,t),`${r.pathname}${r.search}`)}catch{return null}},Df=async(e,t,n)=>{const r=Ao();if(!r)return null;const o=dl(e,n);if(o===null)return null;const s=e instanceof Request?e.headers:void 0,i=await ct(s,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(o,{...t,headers:i})},Of=(e,t)=>{if(typeof e=="string")return Ot(e,t);if(e instanceof URL)return Ot(e.toString(),t);const n=Ot(e.url,t);return n===e.url?e:new Request(n,e)},Mf=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Rr=new Map,_f=(e,t,n)=>n||e!=="GET"||t.includes("/event")||!Mf.test(t)?null:`GET ${t}`,y=async(e,t={})=>{const{query:n,...r}=t,o=Ao(),s=o?dl(e,n):null;let i,a,c;if(o&&s!==null){const g=e instanceof Request?e.headers:void 0,b=await ct(g,r.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...r,headers:b}):()=>o.fetch(s,{...r,headers:b}),a=s,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const g=Of(e,n),b=g instanceof Request?g.headers:void 0,w=await ct(b,r.headers,xf(g)),E=g instanceof Request?g.url:g instanceof URL?g.toString():String(g);Pt(E,w),i=g instanceof Request?()=>fetch(new Request(g,{...r,headers:w})):()=>fetch(g,{...r,headers:w}),a=E,c=String(r.method??(g instanceof Request?g.method:"GET")).toUpperCase()}const l=i;i=()=>l().then(g=>(Ef(a,g.status),g));const u=r.signal!=null||e instanceof Request,d=_f(c,a,u);if(!d)return i();const f=Rr.get(d);if(f)return f.then(g=>g.clone());const p=i();return Rr.set(d,p),p.then(()=>Rr.delete(d),()=>Rr.delete(d)),p.then(g=>g.clone())};let ta=!1;const fl=()=>{if(ta||typeof window>"u")return;ta=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await Df(t,n??{});if(r)return r;if(typeof t=="string"){if(!Go(t)){try{const i=new URL(t);if(Jr(i)){const a=await ct(void 0,n?.headers);return Pt(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const o=await ct(void 0,n?.headers),s=Ot(t);return Pt(s,o),e(s,{...n,headers:o})}if(t instanceof URL){const o=t.toString();if(!Go(o)){if(Jr(t)){const a=await ct(void 0,n?.headers);return Pt(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const s=await ct(void 0,n?.headers),i=Ot(o);return Pt(i,s),e(i,{...n,headers:s})}if(t instanceof Request){if(!Go(t.url)){try{const a=new URL(t.url);if(Jr(a)){const c=await ct(t.headers,n?.headers);return Pt(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const o=await ct(t.headers,n?.headers),s=Ot(t.url);Pt(s,o);const i=s===t.url?t:new Request(s,t);return e(new Request(i,{...n,headers:o}))}return e(t,n)}},Lf=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:Pt,buildRuntimeFetchUrl:Ot,installRuntimeFetchBridge:fl,isLatin1Safe:ul,runtimeFetch:y,sanitizeHeadersForBrowser:vs},Symbol.toStringTag,{value:"Module"})),Tn=16384,uo=globalThis,Ff=e=>{if(uo.Buffer)return uo.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(uo.Buffer)return uo.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 o=0;o<n.length;o+=1)r[o]=n.charCodeAt(o);return new TextDecoder().decode(r)}catch{return null}},Uf=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}},jf=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}},na=e=>typeof e=="string"&&e.length>0,Nf=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!na(t.x)||!na(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Bf=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Hf=e=>{if(!e||typeof e!="object")return null;const t=e,n=Bf(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=Uf(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=jf(t.relayUrl);if(!r)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const s=Nf(t.hostEncPubJwk);if(!s)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:r,serverId:o,hostEncPubJwk:s,...i?{grant:i}:{},...n===void 0?{}:{priority:n}}}return null},li=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 o=Array.isArray(t.candidates)?t.candidates.map(Hf).filter(c=>!!c):[];if(o.length===0)return null;const s=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(s){const c=Date.parse(s);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}:{},...s?{expiresAt:s}:{},candidates:o}},sT=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}),iT=e=>{const t=li(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",Ff(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},zf=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 o=pl(r);return!o||o.length>Tn?null:li(JSON.parse(o))}catch{return null}},aT=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,o=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"&&(o=l)}if(r!=="2"||!o||o.length>Tn)return null;const s=pl(o);if(!s||s.length>Tn)return null;try{return li(JSON.parse(s))}catch{return null}},En=e=>typeof e=="object"&&e!==null,$f=e=>e.trim().toLowerCase()==="authorization",Gf=e=>{if(!En(e))return;const t={};for(const[n,r]of Object.entries(e)){const o=n.trim(),s=typeof r=="string"?r.trim():"";!o||!s||/[\r\n:]/.test(o)||/[\r\n]/.test(s)||$f(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},Wf=e=>`relay://${e}`,qf=e=>{if(!En(e))return null;const t=be(e,"relayUrl")||be(e,"relay_url"),n=be(e,"serverId")||be(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!En(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Kf=()=>{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"},cT=async(e,t)=>{const n=zf(e);if(!n)throw new Error("invalid-connect-link");const r=await Xf().catch(()=>""),o={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:Kf(),...r?{dedupeKey:`desktop:${r}`}:{}})},s=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=ni({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const F=await s(await k.fetch("/api/client-auth/pairing/redeem",o));if(F){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:F};break}}catch{}finally{k.close()}continue}const E=Se(w.url);if(E)try{const k=await s(await fetch(`${E}/api/client-auth/pairing/redeem`,o));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=>Se(w.url)).find(w=>!!w),d=i.directUrl||u,f=d||(l?Wf(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const p=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&Se(w.apiUrl||w.url)===f),g=p?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),b={...p||{},id:g,label:n.label||p?.label||hl(f),url:f,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:g,hosts:p?t.map(w=>w.id===g?b:w):[b,...t]}},Vf=/^(t|.*(?:token|auth|secret|api).*)$/i,Se=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}},lT=e=>{const t=Se(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"}},hl=e=>{const t=Se(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 o of r)Vf.test(o)&&n.searchParams.set(o,"[REDACTED]");return n.toString()}catch{return t}},Dr=(e,t)=>{const n=Se(e),r=Se(t);if(!n||!r)return!1;try{const o=new URL(n),s=new URL(r);if(o.origin!==s.origin||s.search&&o.search!==s.search)return!1;const i=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname,a=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},be=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},ra=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},Jf=e=>{if(!En(e))return null;const t=be(e,"id"),n=be(e,"label"),r=be(e,"url"),o=be(e,"apiUrl")||be(e,"api_url"),s=be(e,"clientToken")||be(e,"client_token"),i=Gf(e.requestHeaders),a=qf(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...o?{apiUrl:o}:{},...s?{clientToken:s}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Yn=e=>Se(e.apiUrl||e.url)||e.apiUrl||e.url,nn=()=>ve()?(e,t)=>oe(e,t):null,ui=async()=>{const e=nn();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!En(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(Jf).filter(a=>!!a):[],o=be(t,"defaultHostId")||be(t,"default_host_id")||be(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=be(t,"localOrigin")||be(t,"local_origin");return{hosts:r,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},Yf=async e=>{const t=nn();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})},Qf=async()=>{const e=nn();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Xf=async()=>{const e=nn();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Zf=8e3,ep=15e3,tp=400,np=async(e,t,n,r)=>{const o=new AbortController,s=window.setTimeout(()=>o.abort(),n);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(s)}},oa=async(e,t,n,r)=>{for(;;){const o=n-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await np(e,t,Math.min(Zf,o),r)}catch(s){if(e.getStatus().state==="error"||Date.now()>=n)throw s;await new Promise(i=>window.setTimeout(i,tp))}}},rp=async(e,t)=>{const n=ni({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),o=r+ep;let s=!1;try{if(!(await oa(n,"/health",o)).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 oa(n,"/auth/session",o,{headers:a});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:l.ok?(s=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...s?{tunnel:n}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{s||n.close()}},di=async(e,t)=>{const n=nn();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(!En(r))return{status:"unreachable",latencyMs:0};const o=r.status,s=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",i=ra(r,"latencyMs")??ra(r,"latency_ms")??0;return{status:s,latencyMs:i}},uT=async(e,t)=>{const n=nn();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},dT=async e=>{const t=nn();t&&await t("desktop_new_window_for_host",{hostId:e})},Dt="local",op=e=>({id:Dt,label:"Local",url:e||ml()}),ml=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,sp=e=>e.id===Dt?"local":`host:${e.id}`,fT=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Dt)?.url||ml(),r=Eo(),o=Se(n)||n,s=Se(t)||t,i=G(),a=e.find(u=>u.relay&&sp(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Dr(r,n))return{id:Dt,label:"Local",url:o};const c=e.find(u=>r?Dr(r,Yn(u)):!1);if(c)return{id:c.id,label:c.label,url:Se(Yn(c))||Yn(c)};if(t&&Dr(t,n))return{id:Dt,label:"Local",url:o};const l=e.find(u=>t?Dr(t,u.url):!1);return l?{id:l.id,label:l.label,url:Se(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:Dt,label:"Local",url:o}:{id:"custom",label:hl(s||"Instance"),url:s}},fo=new Map;let gl=0;const po=new Map;let ks=0,yl={byHostId:{},isProbing:!1};const Es=new Set,ho=()=>{yl={byHostId:Object.fromEntries(fo),isProbing:ks>0};for(const e of Es)try{e()}catch{}},pT=e=>(Es.add(e),()=>{Es.delete(e)}),hT=()=>yl,wl=(e,t)=>{fo.set(e,t),ho()},mT=(e,t)=>{po.set(e,++gl),wl(e,t)},ip=e=>{const t=new Set([Dt,...e]);let n=!1;for(const r of Array.from(fo.keys()))t.has(r)||(fo.delete(r),po.delete(r),n=!0);n&&ho()},ap=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",cp=async()=>tn()?Qf().catch(()=>""):"",lp=async(e,t)=>{const n=e.id===Dt?t:e.clientToken||"",r=async()=>{const i=await rp(e.relay,{clientToken:n,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),a={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(a.via="relay"),a};if(e.relay&&!e.apiUrl)return r();const o=Se(tn()?Yn(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const s=await di(o,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(ap(s.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:s.status,latencyMs:s.latencyMs}},up=async e=>{if(!Je())return;const t=++gl;for(const n of e)po.set(n.id,t);ks+=1,ho();try{const n=await cp();await Promise.all(e.map(async r=>{const o=await lp(r,n);po.get(r.id)===t&&wl(r.id,o)}))}finally{ks-=1,ho()}};let sa=!1;const dp=async()=>{if(sa||!Je())return;sa=!0;const e=await ui().catch(()=>null);e&&(ip(e.hosts.map(t=>t.id)),await up([op(e.localOrigin),...e.hosts]))},fp=5e3,pp=1500;let Wo=!1;const hp=async e=>{if(!tn()||Wo)return;const t=`host:${e}`;if(G()===t){Wo=!0;try{const n=await ui().catch(()=>null),r=n?.hosts.find(d=>d.id===e);if(!n||!r?.relay)return;const o=r.apiUrl?Se(r.apiUrl):null;if(o&&o.startsWith("https://"))return;const s=await y("/api/client-auth/connection/candidates").catch(()=>null);if(!s?.ok)return;const i=await s.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=Se(f.url);p&&!c.includes(p)&&c.push(p)}if(c.length===0)return;const l=o&&c.includes(o)?o:c[0];l!==o&&await Yf({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await di(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(u.status==="unreachable"||u.status==="wrong-service"||u.status==="incompatible"||G()!==t)return;ao({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{Wo=!1}}},mp=e=>{typeof window>"u"||window.setTimeout(()=>{hp(e).catch(()=>{})},fp)},gp=async e=>{if(!tn())return;const t=await ui().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 o=`host:${r.id}`;if(G()===o)return;const s=d=>{ao({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:o})},i=()=>{ao({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:o,relay:r.relay??void 0}),mp(r.id)},a=r.apiUrl?Se(Yn(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=di(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),pp))]);if(u){if(c(u)){s(a);return}i();return}i(),l.then(d=>{c(d)&&G()===o&&s(a)})};class Yt extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const gT=e=>e instanceof Yt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),mo=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},bl=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,ia=/^(?:\/\/\?\/)?[A-Za-z]:$/u,yp=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/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]):/,(o,s)=>s.toUpperCase()+":");return n==="/"?"/":bl.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},wp=e=>{if(e==="/"||bl.test(e)||ia.test(e)||yp.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const n=e.slice(0,t);return ia.test(n)?`${n}/`:n},bp=e=>Ye(e)??"",Sp=Ve(m().min(1),dr("type",[v({type:U("idle")}),v({type:U("busy")}),v({type:U("retry"),attempt:C(),message:m(),next:C()})])),Sl=v({messageID:m(),callID:m()}).optional(),Tp=v({id:m().min(1),sessionID:m().min(1),permission:m(),patterns:N(m()),metadata:Ve(m(),ue()),always:N(m()),tool:Sl}),vp=v({id:m().min(1),sessionID:m().min(1),questions:N(v({question:m(),header:m(),options:N(v({label:m(),description:m()})),multiple:Fe().optional()})),tool:Sl}),kp=v({sessions:Ve(m().min(1),v({status:m(),lastUpdateAt:C()})),pending:Ve(m().min(1),v({permissions:N(Tp),questions:N(vp)})).optional(),serverTime:C()}),aa=500,Tl=()=>{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}},yT=()=>Tl(),$e=(e,t)=>{if(!Tl())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>aa&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-aa)},Ep=()=>{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__=Ep);const wT=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();$e(`${e}:start`,n);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return $e(`${e}:end`,{durationMs:Math.round(s-r)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw $e(`${e}:error`,{durationMs:Math.round(s-r),error:o instanceof Error?o.message:String(o)}),o}},Pp=3,Ap=3e4,Ip=32e3,xp=3600*1e3,Cp=600*1e3,Rp=200,Dp=new Set([429,502,503,504]),ut=new Map,fi=e=>JSON.stringify([G(),e]);function Op(){const e=Date.now();for(const[t,n]of ut){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>xp&&ut.delete(t)}}typeof setInterval<"u"&&setInterval(Op,Cp).unref?.();function Mp(e){const t=fi(e);let n=ut.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Ap},ut.set(t,n);ut.size>Rp;){const r=ut.keys().next().value;if(!r)break;ut.delete(r)}return n}function _p(e){e&&ut.delete(fi(e))}function ca(e,t){if(!e)return;const n=Mp(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Lp(t)&&n.consecutiveErrors>=Pp&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Lp(e){return e!==void 0&&Dp.has(e)}function Fp(e){const t=ut.get(fi(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Ip*4),!1):!0:!1}function Up(e){if(!(!e||!Fp(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const la="/api",jp=1e4,Np=4e3;function yn(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object"&&"message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}const Bp=v({reason:m().optional(),isDirectory:Fe().optional()});function Ne(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${yn(e.error)}`);throw n!==void 0&&(r.status=n),r}if(e.data===void 0||e.data===null)throw new Error(`${t} failed: empty response`);return e.data}function an(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${yn(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}const Hp=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ua="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",zp=14;let da=0,qo=0;const $p=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+=ua[t[r]%ua.length];return n},fa=e=>{const t=Date.now();t!==da&&(da=t,qo=0),qo+=1;const n=BigInt(t)*BigInt(4096)+BigInt(qo),r=new Uint8Array(6);for(let s=0;s<6;s+=1)r[s]=Number(n>>BigInt(40-8*s)&BigInt(255));const o=Array.from(r,s=>s.toString(16).padStart(2,"0")).join("");return`${e}_${o}${$p(zp)}`},pa=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(Hp.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}},ha=()=>{try{return Ee().api("/api")}catch{return null}},vl=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)}},Gp=3e4,Wp=e=>(typeof e=="string"?e:e instanceof URL?e.toString():e.url).includes("/event"),Ko=e=>{const t=e.requestTimeoutMs??Gp;return Hu({...e,fetch:async(n,r)=>{const o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(Wp(n)||o==="POST")return y(n,r);const s=vl(t),i=r?.signal!==void 0?r.signal:n instanceof Request?n.signal:void 0,a=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let c,l=null;if(i&&a)c=AbortSignal.any([i,s.signal]);else if(i){const f=new AbortController,p=()=>f.abort(i.reason),g=()=>f.abort(s.signal.reason);i.aborted?p():s.signal.aborted?g():(i.addEventListener("abort",p,{once:!0}),s.signal.addEventListener("abort",g,{once:!0}),l=()=>{i.removeEventListener("abort",p),s.signal.removeEventListener("abort",g)}),c=f.signal}else c=s.signal;const u=()=>{l?.(),s.cleanup()};let d=!1;try{const f=await y(n,{...r,signal:c});return d=f.body!==null,f}catch(f){throw s.signal.aborted&&!i?.aborted?new Error(`OpenCode request timed out after ${t}ms`):f}finally{!d||c.aborted?u():c.addEventListener("abort",u,{once:!0})}}})},cn=e=>e.replace(/\\/g,"/"),ma=400,ga=()=>{const e=Po();return e&&e.runtime?.isDesktop&&e.files?e.files:null},Or=m().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),qp=v({home:Or,chatsRoot:Or.optional(),canonicalChatsRoot:Or.optional(),canonicalLegacyChatsRoot:Or.optional()});class Kp{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;constructor(t=la){const r=ha()||t;this.baseUrl=pa(r),this.client=Ko({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==G())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=ha(),n=pa(t||la);this.baseUrl=n,this.client=Ko({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear()}getSdkClient(){return this.client}getScopedSdkClient(t){return this.getScopedApiClient(t)}getScopedApiClient(t){const n=this.normalizeCandidatePath(t)??t,r=n||"",o=this.scopedClients.get(r);if(o)return o;const s=Ko({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,s),s}normalizeCandidatePath(t){return Ye(t)}deriveHomeDirectory(t){const n=t.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const s=n[1],a=t.slice(s.length+(t.charAt(s.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${s}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${s}/${a[0]}`,username:a[0]}:{homeDirectory:`${s}/`,username:void 0}}const r=t.startsWith("/"),o=t.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const n=this.normalizeCandidatePath(t)??t;this.currentDirectory!==n&&$e("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 s=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await n()}finally{this.currentDirectory===i&&(this.currentDirectory=s)}},o=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const t=new Set,n=o=>{const s=this.normalizeCandidatePath(o);s&&t.add(s)};try{const s=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;s&&(n(s.directory),n(s.worktree),n(s.state))}catch(o){console.debug("Failed to load path info:",o)}if(!t.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);n(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!t.size)try{(await this.listSessions()).forEach(s=>n(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}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 y("/api/fs/directory-stat",{query:{path:n}}),o=Bp.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&o?.isDirectory===!0)return"available";const s=mo(o?.reason);return s==="not-found"||s==="not-directory"?"missing":"unknown"}catch{return"unknown"}}async listSessions(){const t=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(t.data)?t.data:[]}async createSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.create({...r?{directory:r}:{},parentID:t?.parentID,title:t?.title,metadata:t?.metadata});return Ne(o,"session.create")}async getSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.get({sessionID:t,...r?{directory:r}:{}});return Ne(o,"session.get")}async deleteSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.delete({sessionID:t,...r?{directory:r}:{}});return an(o,"session.delete")===!0}async updateSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s={...n.title!==void 0?{title:n.title}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},...n.time?.archived!==void 0&&n.time.archived!==null?{time:{archived:n.time.archived}}:{}},i=await this.client.session.update({sessionID:t,...o?{directory:o}:{},...s});return Ne(i,"session.update")}async getSessionMessages(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.messages({sessionID:t,...o?{directory:o}:{},...typeof n=="number"?{limit:n}:{}});return Ne(s,"session.messages")}async getSessionTodos(t){try{const n=await this.client.session.todo({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(n.error)return[];const r=n.data;return!r||!Array.isArray(r)?[]:r}catch{return[]}}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 Xs(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 o=t.url.substring(r+1),s=atob(o),i=new Uint8Array(s.length);for(let d=0;d<s.length;d++)i[d]=s.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 o=t.url.substring(5,r),s=t.url.substring(r);n=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toNormalizedFilePartInput(t){const n=await this.normalizeFilePart(t);return{...t.id?{id:t.id}:{},type:"file",mime:n.mime,filename:n.filename,url:n.url}}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??fa("msg"),r=[];if(t.prefaceText&&t.prefaceText.trim()&&r.push({type:"text",text:t.prefaceText,synthetic:t.prefaceTextSynthetic!==!1}),t.text&&t.text.trim()){const l={type:"text",text:t.text};r.push(l)}if(t.files&&t.files.length>0)for(const l of t.files){const u=await this.toNormalizedFilePartInput(l);r.push(u)}if(t.additionalParts&&t.additionalParts.length>0)for(const l of t.additionalParts){if(l.text&&l.text.trim()){const u={type:"text",text:l.text};l.synthetic&&(u.synthetic=!0),l.metadata&&(u.metadata=l.metadata),r.push(u)}if(l.files&&l.files.length>0)for(const u of l.files){const d=await this.toNormalizedFilePartInput(u);r.push(d)}}if(t.agentMentions&&t.agentMentions.length>0)for(const l of t.agentMentions)l?.name&&r.push({type:"agent",name:l.name,...l.source?{source:l.source}:{}});if(r.length===0)throw new Error("Message must have at least one part (text or file)");const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;t.format&&console.info("[git-generation][browser] send structured message",{sessionId:t.id,providerID:t.providerID,modelID:t.modelID,agent:t.agent,variant:t.variant,directory:o,baseUrl:this.baseUrl,formatType:t.format.type}),Up(t.providerID),this.assertRuntimeUnchanged(t.runtimeKey);let s;try{const l=await this.client.session.promptAsync({sessionID:t.id,...o?{directory:o}:{},model:{providerID:t.providerID,modelID:t.modelID},agent:t.agent,variant:t.variant,messageID:n,...t.delivery?{delivery:t.delivery}:{},...t.format?{format:t.format}:{},parts:r});if(l.response instanceof Response)s=l.response;else if(l.error){const u=l.response?.status;if(!u){const d=new Error(`Message send transport failure: ${yn(l.error)}`);throw Pd(l.error)?Oc(d):d}s=new Response(JSON.stringify(l.error),{status:u})}else s=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){throw ca(t.providerID),l}if(s.ok)return _p(t.providerID),n;let i="";try{i=await s.text()}catch{}const a=i&&i.trim().length>0?`: ${i.trim()}`:"",c=new Error(`Failed to send message (${s.status})${a}`);throw c.status=s.status,ca(t.providerID,s.status),c}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??fa("msg"),r=[];if(t.files&&t.files.length>0)for(const i of t.files)r.push(await this.toNormalizedFilePartInput(i));const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;this.assertRuntimeUnchanged(t.runtimeKey);const s=await this.client.session.command({sessionID:t.id,...o?{directory:o}:{},command:t.command,arguments:t.arguments??"",model:`${t.providerID}/${t.modelID}`,agent:t.agent,variant:t.variant,...r.length>0?{parts:r}:{},messageID:n});return an(s,"session.command"),n}async abortSession(t){return!!(await this.client.session.abort({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,r=await this.client.session.shell({sessionID:t.sessionId,...n?{directory:n}:{},messageID:t.messageId,agent:t.agent,model:t.model,command:t.command});return Ne(r,"session.shell")}async revertSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.revert({sessionID:t,...s?{directory:s}:{},messageID:n,partID:r});return Ne(i,"session.revert")}async summarizeSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.summarize({sessionID:t,...s?{directory:s}:{},providerID:n,modelID:r});return an(i,"session.summarize")===!0}async unrevertSession(t){const n=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Ne(n,"session.unrevert")}async forkSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.fork({sessionID:t,...o?{directory:o}:{},messageID:n});return Ne(s,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(t){try{const n=this.normalizeCandidatePath(t),r=await this.client.session.status(n?{directory:n}:void 0);if(r.error)return null;const o=Sp.safeParse(r.data);return o.success?o.data:null}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getHostSessionStatusSnapshot(){try{const t=await y("/api/sessions/status",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=kp.safeParse(await t.json().catch(()=>null));return n.success?n.data:null}catch{return null}}async getWebServerSessionActivity(){try{const t=await y("/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 listToolIds(t){try{const n=typeof t?.directory=="string"?t.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(n?{directory:n}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(t,n,r){const o=this.normalizeCandidatePath(r?.directory??null)??this.currentDirectory,s=await this.client.permission.reply({requestID:t,...o?{directory:o}:{},reply:n,...r?.message?{message:r.message}:{}});return an(s,"permission.reply")===!0}async createPermission(t,n,r,o){try{const s=await this.client.v2.session.permission.create({sessionID:t,action:n,resources:r,...o?.id?{id:o.id}:{},...o?.save?{save:o.save}:{},...o?.metadata?{metadata:o.metadata}:{},...o?.source?{source:o.source}:{},...o?.agent?{agent:o.agent}:{}});if(s.error!==void 0)return null;const i=s.data?.data;return i===void 0?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(t,n,r){try{const s=await(r?this.getScopedSdkClient(r):this.client).v2.session.permission.get({sessionID:t,requestID:n});if(s.error===void 0){const i=s.data?.data;if(i!==void 0)return{state:"ok",permission:i}}return s.response?.status===404?{state:"resolved"}:{state:"unknown"}}catch{return{state:"unknown"}}}async listPendingPermissions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",u=await this.client.permission.list(l?{directory:l}:void 0);if(u.error)throw new Error(`permission.list failed: ${yn(u.error)}`);return u.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const u=l.id;typeof u!="string"||u.length===0||a.has(u)||(a.add(u),i.push(l))}return i}async replyToQuestion(t,n,r){const o=!Array.isArray(n)||n.length===0?[]:Array.isArray(n[0])?n:[n],s=this.normalizeCandidatePath(r)??this.currentDirectory,i=await this.client.question.reply({requestID:t,...s?{directory:s}:{},answers:o});return an(i,"question.reply")===!0}async rejectQuestion(t){const n=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return an(n,"question.reject")===!0}async listPendingQuestions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",u=await this.client.question.list(l?{directory:l}:void 0);if(u.error)throw new Error(`question.list failed: ${yn(u.error)}`);return u.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const u=l.id;typeof u!="string"||u.length===0||a.has(u)||(a.add(u),i.push(l))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configCache.get(r);if(o&&o.expiresAt>Date.now())return $e("opencodeClient.getConfig:cacheHit",{directory:n??null}),o.config;const s=this.configInFlight.get(r);if(s)return $e("opencodeClient.getConfig:deduped",{directory:n??null}),s;const i=this.configCacheGeneration,a=(async()=>{$e("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),u=await(n?this.getScopedApiClient(n):this.client).config.get();if(!u.data)throw new Error("Failed to get config");const d=typeof performance<"u"?performance.now():Date.now();return $e("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(d-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:u.data,expiresAt:Date.now()+jp}),u.data})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async updateConfig(t){const n=await this.client.config.update({config:t}),r=Ne(n,"global.config.update");return this.clearConfigCache(),r}async updateConfigPartial(t){const n=await this.getConfig(),r=t(n);return await this.updateConfig(r)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configProvidersInFlight.get(r);if(o)return o;const s=(async()=>{const i=await this.client.config.providers(n?{directory:n}:void 0);return Ne(i,"config.providers")})();this.configProvidersInFlight.set(r,s);try{return await s}finally{this.configProvidersInFlight.get(r)===s&&this.configProvidersInFlight.delete(r)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.listAgentsInFlight.get(r);if(o)return o;const s=(async()=>{const i=n?{directory:n}:void 0,a=await this.client.app.agents(i);if(!a.error&&Array.isArray(a.data)&&a.data.length>0)return a.data;const c=await y("/api/agent",{...n?{query:{directory:n}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${yn(a.error)}`):new Error(`agent.list failed (${c.status})`);const l=await c.json().catch(()=>null);if(!Array.isArray(l))throw new Error("agent.list failed: invalid response");return l})();this.listAgentsInFlight.set(r,s);try{return await s}finally{this.listAgentsInFlight.get(r)===s&&this.listAgentsInFlight.delete(r)}}async listCommandsWithDetails(t,n){const r=this.normalizeCandidatePath(t??null)??this.currentDirectory,o=await this.client.command.list(r?{directory:r}:void 0,{signal:n});return(Ne(o,"command.list")||[]).map(i=>({name:i.name,description:i.description,agent:i.agent,model:i.model,source:i.source,template:i.template}))}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,n=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;$e("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});const r=vl(Np),o=await y(n,{signal:r.signal}).finally(r.cleanup);if($e("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return $e("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,n){const r=ga();if(r?.createDirectory)try{return await r.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}if(n?.asProject){const a=await y(`${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 o={path:t,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await y(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const a=await s.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await s.json()}async cloneRepository(t){const n=await y(`${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 o=`${typeof t=="string"?cn(t.trim()):""}|${n?.respectGitignore?"1":"0"}`,s=Date.now(),i=this.listDirectoryCache.get(o);if(i&&i.expiresAt>s)return i.entries;const a=this.listDirectoryInFlight.get(o);if(a)return a;const l=(async()=>{const u=ga();try{if(u){const w=await u.listDirectory(t||"",n);if(!w||!Array.isArray(w.entries))throw new Yt("Directory listing returned an invalid response",{reason:"invalid-response"});const E=w.entries.map(k=>({name:k.name,path:cn(k.path),isDirectory:!!k.isDirectory,isFile:!k.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:E,expiresAt:Date.now()+ma}),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 y(`${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 Yt(E,{reason:mo(w.reason),status:p.status})}const g=await p.json();if(!g||!Array.isArray(g.entries))throw new Yt("Directory listing returned an invalid response",{reason:"invalid-response"});const b=g.entries;return this.listDirectoryCache.set(o,{entries:b,expiresAt:Date.now()+ma}),b}catch(d){throw console.error("Failed to list directory contents:",d),d}})().finally(()=>{this.listDirectoryInFlight.get(o)===l&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,l),l}async searchFiles(t,n){const r=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():this.currentDirectory,o=r?cn(r):null,s=r?this.getScopedApiClient(r):this.client;try{const i=await s.find.files({query:t,limit:typeof n?.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0,dirs:n?.dirs===!1||n?.type==="file"?"false":"true",type:n?.type});return(Array.isArray(i?.data)?i.data:[]).map(c=>{const l=cn(c),u=l.split("/").filter(Boolean).pop()||l,d=cn(o?`${o}/${l}`:l);return{name:u,path:d,relativePath:l,extension:u.includes(".")?u.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const t=G();if(!t||t==="local"){const n=await Gc();if(n)return n}try{const n=await y(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const o=await n.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}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 y(`${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 qp.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`;console.log("[OpencodeClient] POST",n,"with path:",t);try{const r=await y(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),o=await r.json().catch(()=>null);if(!r.ok){const s=o??{},i=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:t}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const rt=new Kp;let Vo=null,Jo=null,Yo=null;const ya=new Set;let wa=!1;const kl=e=>{if(ya.add(e),wa||typeof window>"u")return;wa=!0;const t=()=>{for(const n of ya)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{}},Vp=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,o=new Set;let s;const i=()=>{if(s=void 0,r.size===0&&o.size===0)return;const c=Array.from(r.entries()),l=Array.from(o);r.clear(),o.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)&&!o.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)||o.add(u)}},a=()=>{s===void 0&&(s=setTimeout(i,0))};return kl(i),{getItem:c=>{if(r.has(c))return r.get(c)??null;if(o.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),o.delete(c),a()},removeItem:c=>{r.delete(c),o.add(c),a()}}},pi=e=>Vp(()=>Al(),e),Jp=e=>{const t=new Map,n=new Set;let r;const o=()=>{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)}},s=()=>{r===void 0&&(r=setTimeout(o,0))};return kl(o),{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),s()},removeItem:i=>{t.delete(i),n.add(i),s()},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}}},El=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},hi=()=>{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}}},Pl=e=>{const t=hi(),n=new Set,r=new Set,o=l=>{if(r.has(l))return null;if(n.has(l))return t.getItem(l);try{return e.getItem(l)}catch{return null}},s=(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:o,setItem:s,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},Yp=()=>{const e=El("localStorage");return e?Pl(e):hi()},Al=()=>(Vo||(Vo=Yp()),Vo),mr=()=>(Yo||(Yo=Jp(Al())),Yo),Qp=()=>{const e=El("sessionStorage");return e?Pl(e):hi()},Xp=()=>(Jo||(Jo=Qp()),Jo),Zp={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.84375rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},bT={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function ba(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Mr={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)"}}},Qo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Mr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Mr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Mr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Mr.tool.inline})},eh=[{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'}],th=[{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'}],Il=e=>Object.fromEntries(e.map(t=>[t.id,t])),nh=Il(eh),rh=Il(th),oh="system",sh="system-mono",ih=e=>typeof e=="string"&&e in nh,ah=e=>typeof e=="string"&&e in rh,Ps="openchamber.mobileKeyboardMode",ch='meta[name="viewport"]',Sa="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",ST=()=>!0;function Ro(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const lh=e=>Ro(e)==="resize-content"?`${Sa}, interactive-widget=resizes-content`:Sa,uh=()=>{if(typeof window>"u")return"resize-content";try{return Ro(localStorage.getItem(Ps))}catch{return"resize-content"}},xl=e=>{const t=Ro(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Ps):localStorage.setItem(Ps,t)}catch{}return t},TT=e=>{const t=xl(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(ch);if(n instanceof HTMLMetaElement){const r=lh(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},Xo=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),dh=new Set(["starting","running","stopping"]),fh=e=>!!e?.tabs.some(t=>wn(t.purpose)&&t.lifecycle!=="exited"),As=512*1024,ph=new TextEncoder,hh=new TextDecoder,Zo=e=>{const t=ph.encode(e);if(t.byteLength<=As)return{text:e,byteLength:t.byteLength};let n=t.byteLength-As;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:hh.decode(r),byteLength:r.byteLength}},Xe=(e,t)=>`${e}\0${t}`,ln=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},mh="terminal-store";let Ta=!1,va=0;const gh=v({type:U("project-action"),actionId:m()}),zn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(va+=1,`tab-${Date.now().toString(36)}-${va.toString(36)}`),es=e=>typeof e=="object"&&e!==null,wn=e=>e.type==="project-action",_r=(e,t)=>wn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,yh=()=>zn().replace(/^tab-/,"exec-"),ka=e=>e==="running"?"running":"exited",wh=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),bh=e=>{const t=new Map,n=[];for(const r of e){if(r.purpose?.type!=="project-action"){n.push(r);continue}const o=t.get(r.purpose.actionId);(!o||r.status==="running"&&o.status!=="running"||r.status===o.status&&((r.createdAt??0)>(o.createdAt??0)||r.createdAt===o.createdAt&&r.sessionId>o.sessionId))&&t.set(r.purpose.actionId,r)}return[...n,...t.values()]},ts={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},Sh=e=>e.trim()||"Action",Th=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},X=bp,go=(e,t)=>`${e}\0${t}`,jn=(e,t,n,r)=>{e.set(go(t,n),r)},Ea=(e,t,n,r)=>{if(!r)return!1;const o=go(t,n),s=e.actionMutationRevisions.get(o)??0,i=r.get(o)??0;return s>i},vh=/^Terminal(?: (\d+))?$/,Pa=e=>{let t=0;for(const n of e){const r=vh.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},vT=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&dh.has(e.lifecycle),kh=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),Lr=(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}),ns=e=>({tabs:[e],activeTabId:e.id}),Ae=(e,t)=>e.tabs.findIndex(n=>n.id===t);let rs=null,os=null;const Eh=e=>{if(os&&rs?.sessions===e.sessions&&rs.nextTabId===e.nextTabId)return os;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt,purpose:o.purpose.type==="project-action"?{type:"project-action",actionId:o.purpose.actionId}:{type:"terminal"}}))}]),nextTabId:e.nextTabId};return rs={sessions:e.sessions,nextTabId:e.nextTabId},os=t,t},Ph=()=>{const e=Bu(()=>Xp());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))}},Yr=gt()(xn(fr((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=X(n);r&&e(o=>{if(o.sessions.has(r))return o;const s=new Map(o.sessions),i=zn(),a=Lr(i,"Terminal");return s.set(r,ns(a)),{sessions:s,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=X(n);return t().sessions.get(r)},getActiveTab:n=>{const r=X(n),o=t().sessions.get(r);if(!o)return;const s=o.activeTabId;return s?o.tabs.find(i=>i.id===s)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(Xe(X(n),r))??Xo,matchesActionExecution:(n,r,o)=>{const s=t().sessions.get(X(n))?.tabs.find(i=>i.id===r);return!!(s&&wn(s.purpose)&&s.purpose.executionId===o)},captureStartedActionMutationRevisions:n=>{const r=X(n),o=go(r,""),s=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(o)&&s.set(i,a);return s},createTab:n=>{const r=X(n);if(!r)return"tab-invalid";const o=zn();return e(s=>{const i=new Map(s.sessions),a=i.get(r),c=s.nextTabId+1,l=Pa(a?.tabs??[]),u=Lr(o,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,ns(u)),{sessions:i,nextTabId:c}}),o},reconcileServerSessions:(n,r,o)=>{const s=X(n);s&&e(i=>{const a=i.sessions.get(s);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,g=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(Xe(s,c[0].id))?c[0]:null;g&&r.length>0&&(c.length=0);for(const R of bh(r)){let we=c.findIndex(L=>L.terminalSessionId===R.sessionId||L.id===R.sessionId);const se=R.purpose,Lo=se?.type==="project-action"&&Ea(i,s,se.actionId,o?.startedActionMutationRevisions);if(se?.type==="project-action"){f.add(se.actionId);const L=c.findIndex(Qe=>wn(Qe.purpose)&&Qe.purpose.actionId===se.actionId);if(Lo){L>=0&&p.add(c[L].id);continue}we<0&&(we=L)}const Pe=se?.type==="project-action"?wh(se,R.status):{type:"terminal"};if(we>=0){const L=c[we];let Qe=L.purpose.type==="project-action"||se?.type==="project-action"?ka(R.status):R.status;L.lifecycle==="stopping"&&R.status==="running"&&L.purpose.type==="project-action"&&Pe.type==="project-action"&&L.purpose.executionId===Pe.executionId&&(Qe="stopping");const on=R.createdAt??L.createdAt,Sr=se?.type==="project-action"&&(L.terminalSessionId!==R.sessionId||Pe.type==="project-action"&&Pe.executionId!==null&&(L.purpose.type!=="project-action"||L.purpose.executionId!==Pe.executionId));if(Sr){const yt=Xe(s,L.id);l=ln(l,Fo=>Fo===yt)??l}const _n=se?.type==="project-action"&&R.status==="running"&&(L.terminalSessionId!==R.sessionId||L.lifecycle!=="running"),Tr=L.purpose.type!==Pe.type||L.purpose.type==="project-action"&&Pe.type==="project-action"&&(L.purpose.actionId!==Pe.actionId||L.purpose.executionId!==Pe.executionId);if((L.terminalSessionId!==R.sessionId||L.lifecycle!==Qe||L.isConnecting!==!1||L.createdAt!==on||Tr)&&(c[we]={...L,terminalSessionId:R.sessionId,lifecycle:Qe,purpose:Pe,isConnecting:!1,createdAt:on},Sr&&Object.assign(c[we],ts),u=!0),_n){const yt={tabId:L.id,createdAt:on,index:we};(!d||yt.createdAt>d.createdAt||yt.createdAt===d.createdAt&&yt.index>d.index)&&(d=yt)}p.add(L.id);continue}const On=se?.type==="project-action"?Sh(se.actionId):g&&c.length===0?g.label:Pa(c),Mn=se?.type==="project-action"?"play":null,Lt={...Lr(R.sessionId,On),terminalSessionId:R.sessionId,lifecycle:se?.type==="project-action"?ka(R.status):R.status,purpose:Pe,iconKey:Mn,createdAt:R.createdAt??Date.now()};if(c.push(Lt),u=!0,se?.type==="project-action"&&R.status==="running"){const L={tabId:Lt.id,createdAt:Lt.createdAt,index:c.length-1};(!d||L.createdAt>d.createdAt||L.createdAt===d.createdAt&&L.index>d.index)&&(d=L)}p.add(Lt.id)}let b=u||!!(g&&r.length>0);const w=c.map(R=>!wn(R.purpose)||f.has(R.purpose.actionId)||p.has(R.id)||R.lifecycle==="starting"||Ea(i,s,R.purpose.actionId,o?.startedActionMutationRevisions)||R.lifecycle==="exited"&&!R.isConnecting?R:(b=!0,{...R,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:R.purpose.actionId,executionId:null}})),E=a?.activeTabId??null,k=E&&w.some(R=>R.id===E)?E:w[0]?.id??null,F=k?w.find(R=>R.id===k):w[0],O=d&&!kh(F)?d.tabId:k;if(!b&&a&&O===a.activeTabId&&w.length===a.tabs.length&&w.every((R,we)=>R===a.tabs[we]))return i;const K=new Map(i.sessions);return K.set(s,{tabs:w,activeTabId:O}),{sessions:K,buffers:l}})},setActiveTab:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);return!a||a.activeTabId===r||Ae(a,r)<0?s:(i.set(o,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,o)=>{const s=X(n),i=o.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(s);if(!l)return a;const u=Ae(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(s,{...l,tabs:d}),{sessions:c}})},setTabIconKey:(n,r,o)=>{const s=X(n);e(i=>{const a=new Map(i.sessions),c=a.get(s);if(!c)return i;const l=Ae(c,r);if(l<0)return i;const u=o?.trim()||null;if(c.tabs[l]?.iconKey===u)return i;const d=[...c.tabs];return d[l]={...d[l],iconKey:u},a.set(s,{...c,tabs:d}),{sessions:a}})},closeTab:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=Ae(a,r);if(c<0)return s;const l=a.tabs[c].purpose;let u=s.actionMutationRevisions,d=s.nextActionMutationRevision;l.type==="project-action"&&(u=new Map(u),jn(u,o,l.actionId,d),d+=1);const f={actionMutationRevisions:u,nextActionMutationRevision:d},p=a.tabs.filter(k=>k.id!==r),g=Xe(o,r),b=s.buffers.has(g)?ln(s.buffers,k=>k===g):null;if(p.length===0){const k=zn(),F=Lr(k,"Terminal");i.set(o,ns(F));const O={sessions:i,nextTabId:s.nextTabId+1};return b&&(O.buffers=b),{...O,...f}}let w=a.activeTabId;a.activeTabId===r&&(w=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),i.set(o,{...a,tabs:p,activeTabId:w});const E={sessions:i};return b&&(E.buffers=b),{...E,...f}})},setTabPurpose:(n,r,o)=>{const s=X(n);e(i=>{const a=i.sessions.get(s);if(!a)return i;const c=Ae(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(o))return i;const u=[...a.tabs],d=o.type==="project-action"&&o.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==o.executionId);u[c]={...l,purpose:o},d&&Object.assign(u[c],ts);const f=Xe(s,r),p=d?ln(i.buffers,w=>w===f)??i.buffers:i.buffers,g=new Map(i.sessions);if(g.set(s,{...a,tabs:u}),o.type!=="project-action")return{sessions:g};const b=new Map(i.actionMutationRevisions);return jn(b,s,o.actionId,i.nextActionMutationRevision),{sessions:g,buffers:p,actionMutationRevisions:b,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,o)=>{const s=X(n),i=t().sessions.get(s);if(!i||Ae(i,r)<0)return null;const a=yh();return e(c=>{const l=c.sessions.get(s);if(!l)return c;const u=Ae(l,r);if(u<0)return c;const d=[...l.tabs];d[u]={...d[u],purpose:{type:"project-action",actionId:o,executionId:a},lifecycle:"starting",terminalSessionId:null,...ts,isConnecting:!1};const f=new Map(c.sessions);f.set(s,{...l,tabs:d});const p=new Map(c.actionMutationRevisions);jn(p,s,o,c.nextActionMutationRevision);const g=Xe(s,r),b=ln(c.buffers,w=>w===g)??c.buffers;return{sessions:f,buffers:b,actionMutationRevisions:p,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0)return a;const d=l.tabs[u];if(!_r(d,s?.expectedExecutionId))return a;const f=o!==null&&d.terminalSessionId!==o,p=o?"running":d.terminalSessionId?"exited":d.lifecycle,g={...d,terminalSessionId:o,lifecycle:p,isConnecting:!1},b=Xe(i,r),w=f&&a.buffers.has(b)?ln(a.buffers,F=>F===b):null,E=[...l.tabs];E[u]=g,c.set(i,{...l,tabs:E});const k={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(wn(d.purpose)){const F=new Map(a.actionMutationRevisions);jn(F,i,d.purpose.actionId,a.nextActionMutationRevision),k.actionMutationRevisions=F,k.nextActionMutationRevision=a.nextActionMutationRevision+1}return w&&(k.buffers=w),k})},setTabLifecycle:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0||!_r(l.tabs[u],s?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===o&&!d.isConnecting)return a;const f=[...l.tabs];if(f[u]={...d,lifecycle:o,isConnecting:!1},c.set(i,{...l,tabs:f}),d.purpose.type!=="project-action"||d.lifecycle===o)return{sessions:c};const p=new Map(a.actionMutationRevisions);return jn(p,i,d.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:p,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0||!_r(l.tabs[u],s?.expectedExecutionId))return a;const d=[...l.tabs];return d[u]={...d[u],isConnecting:o},c.set(i,{...l,tabs:d}),{sessions:c}})},replaceBuffer:(n,r,o,s,i)=>{const a=X(n);e(c=>{const l=c.sessions.get(a);if(!l||Ae(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??Xo;if(d.lastSequence>s)return c;const f=Zo(o),p=d.chunks[0]?.size;if(d.lastSequence===s&&d.byteLength===f.byteLength&&d.chunks.map(w=>w.data).join("")===f.text&&p?.cols===i?.cols&&p?.rows===i?.rows)return c;const g=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:f.text?[{id:g,data:f.text,byteLength:f.byteLength,...i?{size:i}:{}}]:[],byteLength:f.byteLength,lastSequence:s}),{buffers:b,nextChunkId:f.text?g+1:g}})},appendToBuffer:(n,r,o,s,i)=>{if(!o)return;const a=X(n);e(c=>{const l=c.sessions.get(a);if(!l||Ae(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??Xo;if(s!==void 0&&s<=d.lastSequence)return c;const f=c.nextChunkId,p=Zo(o),g=i!==void 0&&i!==o?Zo(i).text:void 0,b={id:f,data:p.text,...g!==void 0?{replayData:g}:{},byteLength:p.byteLength},w=[...d.chunks,b];let E=d.byteLength+b.byteLength;for(;E>As&&w.length>1;){const F=w.shift();if(!F)break;E-=F.byteLength}const k=new Map(c.buffers);return k.set(u,{chunks:w,byteLength:E,lastSequence:s??d.lastSequence}),{buffers:k,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,s={})=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0)return a;const d=l.tabs[u];if(!_r(d,s.expectedExecutionId))return a;const f=s.autoOpened??d.previewAutoOpened,p=s.locked??d.previewUrlLocked;if(d.previewUrl===o&&d.previewAutoOpened===f&&d.previewUrlLocked===p)return a;const g=[...l.tabs];return g[u]={...d,previewUrl:o,previewAutoOpened:f,previewUrlLocked:p},c.set(i,{...l,tabs:g}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=Ae(a,r);if(c<0)return s;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return s;const u=[...a.tabs];return u[c]={...l,previewAutoOpened:!0},i.set(o,{...a,tabs:u}),{sessions:i}})},removeDirectory:n=>{const r=X(n);e(o=>{const s=new Map(o.sessions);s.delete(r);const i=Xe(r,""),a=ln(o.buffers,d=>d.startsWith(i)),c=go(r,"");let l;for(const d of o.actionMutationRevisions.keys())d.startsWith(c)&&(l??=new Map(o.actionMutationRevisions),l.delete(d));const u={sessions:s};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:mh,storage:Ph(),partialize:Eh,merge:(e,t)=>{if(!es(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const a of n){if(!Array.isArray(a)||a.length!==2)continue;const[c,l]=a;if(typeof c!="string"||!es(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],f=new Map;for(const w of u){if(!es(w))continue;const E=typeof w.id=="string"?w.id:null;if(!E)continue;const k=Th(E);k!==null&&(o=Math.max(o,k));const F=k===null?E:zn();f.set(E,F);const O=gh.safeParse(w.purpose).data,K=O?{type:"project-action",actionId:O.actionId,executionId:null}:{type:"terminal"};d.push({id:F,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:K,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,g=p?f.get(p)??p:null,b=g?d.some(w=>w.id===g):!1;r.set(c,{tabs:d,activeTabId:b?g:d[0].id})}const s=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,i=Math.max(t.nextTabId,s,o+1);return{...t,sessions:r,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:i,hasHydrated:!0}}})));if(typeof window<"u"&&!Ta){Ta=!0;const e=Yr.persist,t=()=>{Yr.getState().hasHydrated||Yr.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Ze=20,Ah=8,Aa=4096,Ih=2160*60*6e4,J=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",s=/^[A-Za-z]:\/$/.test(r);return!o&&!s&&(r=r.replace(/\/+$/,"")),r},At=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,xt=(e,t)=>{const n=J(t),r=J(e);if(!n||!r)return!1;const o=At(n),s=At(r);return s===o||s.startsWith(`${o}/`)},Nn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=J(r);if(!s||!o||typeof o!="object")continue;const i=o,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(p=>typeof p=="string").map(p=>J(p)).filter(p=>p.length<=Aa&&xt(p,s)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(p=>typeof p=="string").map(p=>J(p)).filter(p=>p.length<=Aa&&xt(p,s)))).slice(-500):[],l=typeof i.selectedPath=="string"?J(i.selectedPath):null,u=l&&xt(l,s)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>Ih)continue;const f=n[s];if(f){const p=Array.from(new Set([...f.openPaths,...a])),g=Array.from(new Set([...f.expandedPaths,...c])),b=f.selectedPath??u??p[0]??null;n[s]={openPaths:p,selectedPath:b,expandedPaths:g,touchedAt:Math.max(f.touchedAt,d)};continue}n[s]={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((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},un=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},xh=gt()(xn(fr((e,t)=>({byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const o={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Nn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:o,byRoot:Nn(o[n]?.byRoot)}})},addOpenPath:(n,r,o)=>{const s=J((n||"").trim()),i=J((r||"").trim());!s||!i||!o?.allowOutsideRoot&&!xt(i,s)||e(a=>{const c=a.byRoot[s],l=un(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&u&&c.selectedPath===f)return a;const p={...a.byRoot,[s]:{...l,openPaths:d,selectedPath:f}};return{byRoot:et(p,Ze)}})},removeOpenPath:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=At(s),l=g=>At(g)===c,u=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!u)return i;const d=a.openPaths.filter(g=>!l(g)),f=u?d[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeOpenPathsByPrefix:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=At(s),l=c.endsWith("/")?c:`${c}/`,u=g=>{const b=At(g);return b===c||b.startsWith(l)},d=a.openPaths.filter(g=>!u(g));if(d.length===a.openPaths.length)return i;const f=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeExpandedPathsByPrefix:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=At(s),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(f=>{const p=At(f);return p!==c&&!p.startsWith(l)});if(u.length===a.expandedPaths.length)return i;const d={...i.byRoot,[o]:{...a,expandedPaths:u,touchedAt:Date.now()}};return{byRoot:et(d,Ze)}})},setSelectedPath:(n,r,o)=>{const s=J((n||"").trim()),i=r?J(r.trim()):null;!s||i&&!o?.allowOutsideRoot&&!xt(i,s)||e(a=>{const c=a.byRoot[s],l=un(c),u=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&u===c.openPaths)return a;const d={...a.byRoot,[s]:{...l,openPaths:u,selectedPath:i}};return{byRoot:et(d,Ze)}})},ensureSelectedPath:n=>{const r=J((n||"").trim());if(!r)return;const o=t().byRoot[r];if(!o||o.selectedPath)return;const s=o.openPaths[0]??null;s&&t().setSelectedPath(r,s)},toggleExpandedPath:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||!xt(s,o)||e(i=>{const a=i.byRoot[o],c=un(a),u=c.expandedPaths.includes(s)?c.expandedPaths.filter(f=>f!==s):[...c.expandedPaths,s];if(a&&a.expandedPaths===u&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:u}};return{byRoot:et(d,Ze)}})},collapseAllExpandedPaths:n=>{const r=J((n||"").trim());r&&e(o=>{const s=o.byRoot[r];if(!s||s.expandedPaths.length===0)return o;const i={...o.byRoot,[r]:{...un(s),expandedPaths:[]}};return{byRoot:et(i,Ze)}})},expandPath:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||!xt(s,o)||e(i=>{const a=i.byRoot[o],c=un(a);if(c.expandedPaths.includes(s)&&a)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,s]}};return{byRoot:et(u,Ze)}})},expandPaths:(n,r)=>{const o=J((n||"").trim());if(!o||!r||r.length===0)return;const s=r.map(i=>J((i||"").trim())).filter(i=>i&&xt(i,o));s.length!==0&&e(i=>{const a=i.byRoot[o],c=un(a),l=new Set(c.expandedPaths),u=s.filter(f=>!l.has(f));if(u.length===0)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:et(d,Ze)}})}}),{name:"files-view-tabs-store",version:3,storage:pi(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Nn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,o])=>o.updatedAt-r.updatedAt).slice(0,Ah).map(([r,o])=>[r,{byRoot:Nn(o.byRoot),updatedAt:o.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:{},o=G();return{...t,activeRuntimeKey:o,runtimeSnapshots:r,byRoot:Nn(r[o]?.byRoot)}}}),{name:"files-view-tabs-store"})),Ch=["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"],Rh=/^plugin:[a-z][a-z0-9-]*$/,Dh=new Set(Ch),Oh=e=>Rh.test(e),Mh=e=>Dh.has(e)||Oh(e),kT=e=>e.slice(7),ET=e=>`plugin:${e}`,mi=["session","repository","usage","telemetry","subagents","tasks","mcp","pinned","contextSources"],PT={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",tasks:"chat.workStatus.section.tasks",mcp:"chat.workStatus.section.mcp",pinned:"chat.workStatus.section.pinned",contextSources:"chat.workStatus.section.contextBreakdown"},_h=new Set(mi),Cl=e=>typeof e=="string"&&_h.has(e),Is=e=>{const t=new Set;if(Array.isArray(e))for(const n of e)Cl(n)&&t.add(n);for(const n of mi)t.add(n);return[...t]},AT=(e,t)=>!e?.includes(t),IT=e=>e!=null&&mi.every(t=>e.includes(t)),xT=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),Rl=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e)Cl(r)&&n.add(r);return t||n.delete("telemetry"),[...n]},Lh=e=>Math.min(480,Math.max(200,Math.round(e))),Fh=Te(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),Uh=v({widthByMode:Ve(m(),C().finite().optional().catch(void 0)).catch({}),widthFractionByMode:Ve(m(),C().positive().max(1).optional().catch(void 0)).catch({})}),Dl="ask",Ia=e=>e==="attach"||e==="inline"||e==="ask"?e:Dl;function xa(e){return e==="vim"?"vim":"default"}const dt="all";function Ca(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function Ra(e){return e==="me"||e==="any"?e:"any"}function Ol(e){return typeof e!="string"?dt:e.trim()||dt}function Da(e,t){const n=G();if(Uc(n))return e;const r={...e};return t===dt?delete r[n]:r[n]=t,r}function jh(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 o=Ol(r);o!==dt&&(t[n]=o)}return t}function Oa(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const Fr={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}"}},St={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Ur=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,Nh=e=>{if(!e||typeof e!="object")return!1;const t=e;return Ur(t.completion,Fr.completion)&&Ur(t.error,Fr.error)&&Ur(t.question,Fr.question)&&Ur(t.subtask,Fr.subtask)},Bh=380,Hh=320,zh=1e4,Ml=12,Ma=120,$h=280;let _a=0;const Gh=e=>pe(e),pe=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},_l=e=>Number.isFinite(e)?Math.min(zh,Math.max(Hh,Math.round(e))):Bh,ar=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},yo=e=>{const t=ar(e);return t&&Gh(t)||null},wo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>Ma?t.slice(0,Ma):t:null},gi=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,Ll=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},Wh=(e,t)=>(e==="file"||e==="browser")&&t||e,Fl=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return Wh(e,t)},Ul=(e,t)=>t===e?e:`${e}:${t}`,yi=e=>{const t=ar(e.targetPath),n=e.mode==="terminal"?yo(e.targetDirectory):null,r=Fl(e.mode,t,e.dedupeKey);return{id:Ul(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Ll(e.projectPlanRef),dedupeKey:r,label:wo(e.label),sessionTitleFallback:wo(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:gi(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 o=[...r.entries()].filter(([,i])=>i>t);if(o.length===0)return e;const s=new Set;for(const[i,a]of o){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))s.add(u.id)}return s.size===0?e:e.filter(i=>!s.has(i.id))},Nl=e=>{if(!Array.isArray(e))return[];const t=Me(),n=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o;if(typeof s.mode!="string"||!Mh(s.mode)||t&&s.mode==="browser")continue;const i=ar(typeof s.targetPath=="string"?s.targetPath:null),a=s.mode==="terminal"?yo(s.targetDirectory):null,c=typeof s.projectPlanId=="string"&&s.projectPlanId.trim()?s.projectPlanId.trim():null,l=Ll(s.projectPlanRef);if(s.mode==="plan"&&c!==null!=(l!==null))continue;const u=Fl(s.mode,i,typeof s.dedupeKey=="string"?s.dedupeKey:null),d=Ul(s.mode,u);!d||r.has(d)||(r.add(d),n.push({id:d,mode:s.mode,targetPath:i,targetDirectory:a,projectPlanId:c,projectPlanRef:l,dedupeKey:u,label:wo(typeof s.label=="string"?s.label:null),sessionTitleFallback:wo(typeof s.sessionTitleFallback=="string"?s.sessionTitleFallback:null),readOnly:s.readOnly===!0,stagedDiff:s.stagedDiff===!0,diffScope:gi(s.diffScope)??(s.stagedDiff===!0?"staged":"working"),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}))}return n},Pn=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,Nt=e=>{if(e){const t=Nl(e.tabs),n=Pn(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()}},qh=(e,t,n)=>{const r=n?.reveal!==!1,o=yi(t),s=o.mode==="file"&&o.targetPath?e.tabs.filter(u=>!(u.mode==="file"&&!u.targetPath)):e.tabs,i=s.findIndex(u=>u.id===o.id),a=i===-1?[...s,o]:s.map((u,d)=>d===i?{...u,mode:o.mode,targetPath:o.targetPath||u.targetPath,targetDirectory:o.targetDirectory,projectPlanId:o.projectPlanId??u.projectPlanId,projectPlanRef:o.projectPlanRef??u.projectPlanRef,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||u.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:u),c=r?o.id:e.activeTabId??o.id,l=jl(a,Ml,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:Pn(l,c),touchedAt:Date.now()}},Kh=(e,t)=>{const n=new Set(t),r=e.tabs.filter(l=>n.has(l.id)),o=e.tabs.filter(l=>!n.has(l.id));if(o.length===e.tabs.length)return e;if(!(e.activeTabId?n.has(e.activeTabId):!1))return{...e,tabs:o,activeTabId:Pn(o,e.activeTabId),isOpen:o.length>0?e.isOpen:!1,touchedAt:Date.now()};const i=r.find(l=>l.id===e.activeTabId)?.mode??null,a=i?o.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=yi({mode:"file"});return{...e,tabs:[...o,l],activeTabId:l.id,isOpen:e.isOpen,touchedAt:Date.now()}}return{...e,tabs:o,activeTabId:c?.id??Pn(o,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},Vh=(e,t,n)=>{if(t===n)return e;const r=e.tabs.findIndex(a=>a.id===t),o=e.tabs.findIndex(a=>a.id===n);if(r===-1||o===-1)return e;const s=[...e.tabs],[i]=s.splice(r,1);return i?(s.splice(o,0,i),{...e,tabs:s,touchedAt:Date.now()}):e},Jh=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),ss=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=pe(r);if(!s||!o||typeof o!="object")continue;const i=o;let a=Nl(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=[yi({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=Pn(a,c),u=jl(a,Ml,l),d={},f={},p=Uh.parse(o);for(const g of Fh.options){const b=p.widthByMode[g],w=p.widthFractionByMode[g];b!==void 0&&(d[g]=_l(b)),w!==void 0&&(f[g]=w)}n[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:Pn(u,l),widthByMode:d,widthFractionByMode:f,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},Bt=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},T=gt()(xn(fr((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:$h,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:Is([]),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,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,showOpenCodeRestartConfirm:!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:oh,monoFont:sh,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:uh(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",toolJsonViewMode:"summary",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:dt,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:{...St.completion},error:{...St.error},question:{...St.question},subtask:{...St.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!Yd(),agentControlToolEnabled:!0,agentWebToolEnabled:!0,agentMemoryToolEnabled:!1,agentMemoryFeatureAvailable:!1,routingFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:Dl,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((o,s)=>typeof o=="string"&&o.trim()!==""&&n.indexOf(o)===s):[];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:Lh(n)})},openContextSurface:(n,r)=>{const o=pe((n||"").trim());if(!o)return;const s=t(),i=s.contextPanelByDirectory[o],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=Yr.getState().getDirectoryState(f);if(fh(p))return}s.openContextPanelTab(o,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),s.closeContextPanel(o);return}r==="file"&&!s.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);s.setActiveContextPanelTab(o,d.id);return}r!=="chat"&&s.openContextPanelTab(o,{mode:r})},openContextPanelTab:(n,r,o)=>{const s=pe((n||"").trim());if(!s)return;const i=r.mode==="terminal"?{...r,targetDirectory:yo(r.targetDirectory)===s?null:yo(r.targetDirectory)}:r,a=i.mode==="file"&&!!i.targetPath&&o?.reveal!==!1;e(c=>{const l=c.contextPanelByDirectory[s],u=Nt(l),d={...c.contextPanelByDirectory,[s]:qh(u,i,o)};return{contextPanelByDirectory:Bt(d,20),contextEditorVisible:a||c.contextEditorVisible}})},openContextDiff:(n,r,o=!1,s=null)=>{const i=pe((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=gi(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const o=pe((n||"").trim()),s=ar(r);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,s)=>{const i=pe((n||"").trim()),a=ar(r),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,l=Number.isFinite(s)?Math.max(1,Math.trunc(s)):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=pe((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const o=pe((n||"").trim()),s=(r||"").trim();!o||!s||Me()||t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:s,label:null})},openNewContextBrowserTab:n=>{const r=pe((n||"").trim());!r||Me()||(_a+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${_a}`,label:null}))},openContextBrowser:(n,r="",o)=>{const s=pe((n||"").trim());if(!s||Me())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(s,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},o)},setContextPanelTabTargetPath:(n,r,o)=>{const s=pe((n||"").trim()),i=(r||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:Jh(c,i,o)}}:a})},setActiveContextPanelTab:(n,r)=>{const o=pe((n||"").trim()),s=(r||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Nt(a),l=c.tabs.find(f=>f.id===s);if(!l)return i;const u=l.mode==="file"&&!!l.targetPath;if(c.activeTabId===s&&c.isOpen)return u?{contextEditorVisible:!0}:i;const d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:s,touchedAt:Date.now(),tabs:c.tabs.map(f=>f.id===s?{...f,touchedAt:Date.now()}:f)}};return{contextPanelByDirectory:Bt(d,20),contextEditorVisible:u||i.contextEditorVisible}})},reorderContextPanelTabs:(n,r,o)=>{const s=pe((n||"").trim()),i=(r||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],u=Nt(l);if(!u.tabs.some(p=>p.id===i)||!u.tabs.some(p=>p.id===a))return c;const d=Vh(u,i,a);if(d.tabs===u.tabs)return c;const f={...c.contextPanelByDirectory,[s]:d};return{contextPanelByDirectory:Bt(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const o=pe((n||"").trim()),s=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!o||s.length===0)return;const i=s.map(a=>t().contextPanelByDirectory[o]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[o],l=Nt(c);if(!l.tabs.some(g=>s.includes(g.id)))return a;const u=Kh(l,s),d=u.tabs.find(g=>g.id===u.activeTabId),f=u.isOpen&&d?.mode==="file"&&!d.targetPath,p={...a.contextPanelByDirectory,[o]:u};return{contextPanelByDirectory:Bt(p,20),contextEditorTreeVisible:f||a.contextEditorTreeVisible}});for(const a of i)a.mode==="file"&&a.targetPath&&xh.getState().removeOpenPath(o,a.targetPath)},closeContextPanel:n=>{const r=pe((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...Nt(s),isOpen:!1}};return{contextPanelByDirectory:Bt(i,20)}})},toggleContextPanelExpanded:n=>{const r=pe((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r],i=Nt(s),a={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Bt(a,20)}})},setContextPanelWidth:(n,r,o,s)=>{const i=pe((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=Nt(c),u=_l(o),d={...l.widthFractionByMode};s!==void 0&&Number.isFinite(s)&&s>0?d[r]=Math.min(1,u/s):delete d[r];const f={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:Bt(f,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(o=>o.workStatusExpandedSections[n]===r?o:{workStatusExpandedSections:{...o.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(o=>{const s=o.workStatusHiddenSections,i=s.includes(n);return r===!i?o:{workStatusHiddenSectionsExplicit:!0,workStatusHiddenSections:r?s.filter(a=>a!==n):[...s,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)],workStatusHiddenSectionsExplicit:!0})},setWorkStatusSectionOrder:n=>{e({workStatusSectionOrder:Is(n)})},setContextRailSurfaceVisible:(n,r)=>{e(o=>{const s=o.contextRailHiddenSurfaces,i=s.includes(n);return r===!i?o:{contextRailHiddenSurfaces:r?s.filter(a=>a!==n):[...s,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,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?o:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:o})},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,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isArchivePageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{worktreesPageProjectId:null})},setOpenGuestPage:n=>{e(n?{openGuestPageId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{openGuestPageId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.worktreesPageProjectId&&!n.isMultiRunLauncherOpen&&!n.openGuestPageId||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!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})},setShowOpenCodeRestartConfirm:n=>{e({showOpenCodeRestartConfirm: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),o=Math.max(9,Math.min(52,r));e({terminalFontSize:o})},setTerminalShell:n=>{e({terminalShell:n})},setTerminalLoginShells:n=>{e({terminalLoginShells:[...new Set(n)]})},setEditorFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(32,r));e({editorFontSize:o})},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,o=n/100,s=Object.entries(Zp);if(o===1){r.style.removeProperty("font-size");for(const[i]of s)r.style.removeProperty(ba(i));return}r.style.fontSize=`${o*100}%`;for(const[i]of s)r.style.removeProperty(ba(i))},applyPadding:()=>{const{padding:n}=t(),r=document.documentElement,o=n/100;if(o===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 s=Math.sqrt(o);r.style.setProperty("--padding-scale",s.toString());const i=1+(o-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(o=>({diffFileLayout:{...o.diffFileLayout,[n]:r}}))},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:Ca(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:Ra(n)})},setLinearIssueListTeamId:n=>{const r=Ol(n);e(o=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:Da(o.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=G();e(r=>({linearIssueListTeamId:Uc(n)?dt:r.linearIssueListTeamIdByRuntime[n]??dt}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:Oa(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:dt,linearIssueListTeamIdByRuntime:Da(n.linearIssueListTeamIdByRuntime,dt),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(o=>o.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...o.favoriteModels]})},reorderFavoriteModel:(n,r,o,s)=>{e(i=>{const a=i.favoriteModels.findIndex(d=>d.providerID===n&&d.modelID===r),c=i.favoriteModels.findIndex(d=>d.providerID===o&&d.modelID===s);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 o=n.filter(i=>typeof i=="string"&&i.length>0),s=r.providerOrder;return s.length===o.length&&s.every((i,a)=>i===o[a])?r:{providerOrder:o}})},toggleHiddenModel:(n,r)=>{e(o=>o.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...o.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},hideAllModels:(n,r)=>{e(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...s]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(o=>o.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>o.collapsedModelProviders.includes(r)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...o.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const o=Array.from(new Set(n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean)));o.length!==0&&e(s=>{const i=new Set(o),a=s.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...o]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},addRecentModel:(n,r)=>{e(o=>{const s=o.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...s].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>{if(o.recentAgents.includes(r))return o;const s=o.recentAgents;return{recentAgents:[r,...s].slice(0,5)}})},addRecentEffort:(n,r,o)=>{const s=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!s||!i)return;const a=`${s}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.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 o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{e(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:"",...n?{isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,openGuestPageId:null}:{}}))},openMultiRunLauncher:()=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},openMultiRunLauncherWithPrompt:n=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!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})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setAgentMemoryFeatureAvailable:n=>{e({agentMemoryFeatureAvailable:n})},setRoutingFeatureAvailable:n=>{e({routingFeatureAvailable:n})},setProjectContextSidebarWidth:n=>{e({projectContextSidebarWidth:n})},markAgentMemoryViewed:(n,r)=>{e(o=>({agentMemoryViewedAt:r>(o.agentMemoryViewedAt[n]??0)?{...o.agentMemoryViewedAt,[n]:r}:o.agentMemoryViewedAt}))},setProjectContextTab:n=>{e({projectContextTab:n})},setInputSpellcheckEnabled:n=>{e({inputSpellcheckEnabled:n})},setLargeTextPasteBehavior:n=>{e({largeTextPasteBehavior:Ia(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(o=>({shortcutOverrides:{...o.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{e(r=>{const o={...r.shortcutOverrides};return delete o[n],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:n=>{e({fileEditorKeymap:xa(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:pi(),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 o of Object.values(r)){if(!o||typeof o!="object")continue;const s=o,i=s.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(s.tabs))continue;const a=new Set,c=[];for(const l of s.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(s.tabs=c,typeof s.activeTabId=="string"&&s.activeTabId.startsWith("preview")){const l=c.find(u=>typeof u.id=="string");s.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 o=localStorage.getItem("openchamber:files:auto-save-enabled");o!==null&&(r=o!=="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&&Nh(n.notificationTemplates)&&(n.notificationTemplates={completion:{...St.completion},error:{...St.error},question:{...St.question},subtask:{...St.subtask}}),t<3){const r=new Set([90,120,180,220]),o=n.memoryLimitHistorical,s=n.memoryLimitActiveSession;typeof o=="number"&&!r.has(o)?n.messageLimit=o:typeof s=="number"&&!r.has(s)&&(n.messageLimit=s),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if(delete n.isRightSidebarOpen,delete n.rightSidebarWidth,delete n.rightSidebarTab,n.contextPanelByDirectory=ss(n.contextPanelByDirectory),t<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,o={};for(const[s,i]of Object.entries(r))typeof s=="string"&&typeof i=="string"&&(o[s]=i);n.shortcutOverrides=o}return t<6&&(n.contextPanelByDirectory=ss(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=ss(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Ca(n.linearIssueListStatus),n.linearIssueListAssignee=Ra(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=jh(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=Oa(n.linearIssueListPriority),n.fileEditorKeymap=xa(n.fileEditorKeymap),n.largeTextPasteBehavior=Ia(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,showOpenCodeRestartConfirm:e.showOpenCodeRestartConfirm,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,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,agentMemoryToolEnabled:e.agentMemoryToolEnabled,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"})),Yh=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},Qh=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Xh=e=>{const t=T.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Zh=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=Qh(t);return Yh(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},em=(e,t)=>{const n=e??{};return t<2&&(n.projectSortOrder="manual"),t<3&&n.projectSortOrder==="recent"&&(n.projectSortOrder="manual"),t<4&&delete n.displayMode,n},xs=gt()(fr(e=>({projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sessionGroupingMode:"by-worktree",setSessionGroupingMode:t=>e({sessionGroupingMode:t}),stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,projectSortOrder:"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})}),{name:"session-display-mode",version:5,migrate:em})),Bl="directoryTreeShowHidden",Cs="directory-show-hidden-change",Rs=()=>{if(typeof window>"u")return!0;try{const e=mr().getItem(Bl);return e===null?!0:e==="true"}catch{return!0}},tm=()=>{typeof window>"u"||window.dispatchEvent(new Event(Cs))},nm=()=>Rs(),rm=(e,t={})=>{if(!(typeof window>"u")){try{mr().setItem(Bl,e?"true":"false"),tm()}catch{}t.persist!==!1&&ft({directoryShowHidden:e})}},CT=()=>{const e=bc.c(2),[t,n]=no.useState(Rs);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(Rs())};return window.addEventListener("storage",s),window.addEventListener(Cs,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Cs,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),no.useEffect(r,o),t},Hl=[{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"}],om=new Map(Hl.map(e=>[e.name,e])),RT=e=>om.get(e),DT=Hl.map(e=>({type:"command",name:e.name})),OT="terminal-box",MT="book-open",_T=e=>`${e.type}:${e.name}`,LT=(e,t)=>e.type===t.type&&e.name===t.name,FT=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},sm=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=o.type==="command"||o.type==="skill"?o.type:null,i=typeof o.name=="string"?o.name.trim():"";if(!s||!i)continue;const a=`${s}:${i}`;n.has(a)||(n.add(a),t.push({type:s,name:i}))}return t},zl="filesViewShowGitignored",Ds="files-view-show-gitignored-change",Os=()=>{if(typeof window>"u")return!1;try{return mr().getItem(zl)==="true"}catch{return!1}},im=()=>{typeof window>"u"||window.dispatchEvent(new Event(Ds))},am=()=>Os(),cm=(e,t={})=>{if(!(typeof window>"u")){try{mr().setItem(zl,e?"true":"false"),im()}catch{}t.persist!==!1&&ft({filesViewShowGitignored:e})}},UT=()=>{const e=bc.c(2),[t,n]=no.useState(Os);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(Os())};return window.addEventListener("storage",s),window.addEventListener(Ds,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Ds,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),no.useEffect(r,o),t},$l="session",Gl=40,lm=1,um=100,Wl=e=>e==="global"||e==="session",wi=e=>e!=null&&Number.isInteger(e)&&e>=lm&&e<=um,dm=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],bi=e=>e==="auto"||typeof e=="string"&&dm.includes(e),bn="openchamber-input-history.v1",fm=8,pm=50,hm=[40,25,10,5,1],is=Object.freeze([]);let lt=null,La=0;const Qn=(e=$l,t=Gl)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),ql=()=>(La+=1,Date.now()*1e3+La),Kl=e=>JSON.stringify([e]),Ms=(e,t,n)=>JSON.stringify([e,t,n]),Si=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},mm=()=>{const e=Si(),t=Ge?JSON.stringify(Xr(Ge.base)):lt;if(!e)return t;try{return e.getItem(bn)??(Ge?null:lt)}catch{return t}},Fa=Ve(m(),ue()),gm=v({key:m().min(1),source:Qt([U("file-url"),U("vscode-file")]),filename:m().min(1),mimeType:m().min(1),size:C().finite().nonnegative(),reference:m().min(1)}),ym=v({text:m(),attachmentKeys:N(m()),restorableAttachments:N(gm),submittedAt:C().finite().nonnegative()}),wm=v({touchedAt:C().finite().nonnegative(),entries:N(ue())}),bm=(e,t)=>{try{const n=JSON.parse(e),o=(t===1?ji([m().trim().min(1)]):ji([m().trim().min(1),m().trim().min(1),m().trim().min(1)])).safeParse(n);if(!o.success)return null;if(t===3){const s=Ye(o.data[1]);if(!s||s!==o.data[1])return null}return o.data}catch{return null}},Ua=(e,t)=>{const n=[];for(const[r,o]of Object.entries(e)){if(!bm(r,t))continue;const s=wm.safeParse(o);if(!s.success)continue;const i=s.data.entries.map(a=>ym.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:s.data.touchedAt,entries:i}])}return Object.fromEntries(n)},Sm=()=>{const e=mm();if(e===null)return Qn();try{const t=JSON.parse(e),n=v({version:U(1),entryLimit:C().int().optional(),scope:Qt([U("global"),U("session")]).optional(),global:Fa.default({}),session:Fa.default({})}).safeParse(t);return n.success?{entryLimit:wi(n.data.entryLimit)?n.data.entryLimit:Gl,scope:n.data.scope??$l,globalBuckets:Ua(n.data.global,1),sessionBuckets:Ua(n.data.session,3)}:Qn()}catch{const t=Si();if(t)try{t.removeItem(bn)}catch{}return lt=null,Qn()}};let Ge=null,Qr=Qn();const ja=(e,t,n)=>{const r={...e};for(const o of new Set([...Object.keys(t),...Object.keys(n)])){if(JSON.stringify(t[o])===JSON.stringify(n[o]))continue;const s=n[o];if(!s){delete r[o];continue}const i=new Set((t[o]?.entries??[]).map(u=>JSON.stringify(u))),a=new Set(s.entries.map(u=>JSON.stringify(u))),c=(e[o]?.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 s.entries){const d=JSON.stringify(u);!i.has(d)&&!l.has(d)&&c.push(u)}c.sort((u,d)=>u.submittedAt-d.submittedAt),r[o]={touchedAt:Math.max(s.touchedAt,e[o]?.touchedAt??0),entries:c}}return r},$n=()=>{const e=Sm();if(Qr=e,!Ge)return e;const{base:t,value:n}=Ge;return _s({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)})},Vl=(e,t)=>e.slice(Math.max(0,e.length-t)),Na=(e,t,n)=>{const r=Object.entries(e).map(([o,s])=>[o,{touchedAt:s.touchedAt,entries:Vl(s.entries,n)}]).sort((o,s)=>s[1].touchedAt-o[1].touchedAt).slice(0,t);return Object.fromEntries(r)},_s=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Na(e.globalBuckets,fm,t),sessionBuckets:Na(e.sessionBuckets,pm,t)}),Xr=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Ba=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Gn=e=>{const t=_s(e),n=JSON.stringify(Xr(t));Ge={base:Qr,value:t};const r=Si();if(!r)return lt=n,t;try{return r.setItem(bn,n),Ge=null,lt=n,t}catch(i){if(!(i instanceof Error)||!Ba(i))return lt=n,t}try{r.removeItem(bn)}catch{}for(const i of hm){const a=_s(t,i),c=JSON.stringify(Xr(a));try{return r.setItem(bn,c),Ge=null,lt=c,a}catch(l){if(!(l instanceof Error)||!Ba(l))return Ge={base:Qr,value:a},lt=c,a}}const o=Qn(t.scope,t.entryLimit),s=JSON.stringify(Xr(o));try{r.setItem(bn,s),Ge=null}catch{Ge={base:Qr,value:o}}return lt=s,o},Tm=(e,t,n)=>{const r=e.trim(),o=Ye(t),s=n.trim();return!r||!o||!s?null:{runtimeKey:r,directory:o,sessionId:s}},Jl=e=>e.source==="vscode"&&e.vscodeSource==="file"?Ye(e.vscodePath??null):e.dataUrl.trim()||null,vm=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Ls=e=>{const t=Jl(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("|")},km=e=>{const t=Jl(e);return!t||!vm(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Ls(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Ls(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},Em=(e,t)=>({text:e,attachmentKeys:t.map(Ls),restorableAttachments:t.map(km).filter(n=>n!==null)}),Pm=(e,t)=>e.length===t.length&&e.every((n,r)=>{const o=t[r];return o!==void 0&&n.key===o.key&&n.source===o.source&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.size===o.size&&n.reference===o.reference}),Am=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&Pm(e.restorableAttachments,t.restorableAttachments),Ha=(e,t,n,r)=>{const o=e?[...e.entries]:[];for(const s of t){const i=o.at(-1);Am(i,s)||o.push({text:s.text,attachmentKeys:[...s.attachmentKeys],restorableAttachments:s.restorableAttachments.map(a=>({...a})),submittedAt:ql()})}return{touchedAt:n,entries:Vl(o,r)}},Im=Gn($n()),Wn=gt(e=>({...Im,applyEntryLimit:t=>{wi(t)&&e(n=>{const r=$n();if(r.entryLimit===t)return{...n,...r};const o=Gn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},applyScope:t=>{Wl(t)&&e(n=>{const r=$n();if(r.scope===t)return{...n,...r};const o=Gn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const o=$n(),s=ql(),i=Kl(t.runtimeKey),a=Ms(t.runtimeKey,t.directory,t.sessionId),c=Gn({entryLimit:o.entryLimit,scope:o.scope,globalBuckets:{...o.globalBuckets,[i]:Ha(o.globalBuckets[i],n,s,o.entryLimit)},sessionBuckets:{...o.sessionBuckets,[a]:Ha(o.sessionBuckets[a],n,s,o.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=$n(),o=Ms(t.runtimeKey,t.directory,t.sessionId);if(!(o in r.sessionBuckets))return{...n,...r};const s={...r.sessionBuckets};delete s[o];const i=Gn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:s});return{...n,...i}})}})),jT=(e,t)=>t?e.scope==="session"?e.sessionBuckets[Ms(t.runtimeKey,t.directory,t.sessionId)]?.entries??is:e.globalBuckets[Kl(t.runtimeKey)]?.entries??is:is,xm=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Cm=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
2
+ import{s as m,o as v,n as C,r as Ve,d as dr,l as U,a as N,b as Fe,u as ue,_ as Te,c as Qt,t as ji,j as Ni,e as tr,f as wc}from"./vendor-zod-CgAdXWZO.js";import{_ as Xs}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as gt,d as xn,p as fr,a as Bu}from"./vendor-zustand-BAGL70zf.js";import{c as Hu}from"./vendor-opencode-sdk-BJ73u-bH.js";import{f as bc,R as no}from"./vendor-react-BUCujlKS.js";const Kn=1,zu="openchamber-relay-v1",Sc=1,Tc=12,Vn=1+Tc,nr=64*1024,rr=5,ro=128,vc=0,kc=1,vn=4,$u=1+vn,hs=nr-rr-$u,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},Gu=new Set(Object.values(H)),Wu=e=>Gu.has(e),Jt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},pt=globalThis.crypto.subtle,Ec={name:"ECDH",namedCurve:"P-256"},Pc=16,jo=32,qu=16,ms=4,Ac=8;class Rt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Ku=()=>pt.generateKey(Ec,!0,["deriveBits"]),Vu=async e=>{const t=await pt.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Ju=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Rt("invalid ECDH public key JWK");try{return await pt.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Ec,!0,[])}catch{throw new Rt("invalid ECDH public key JWK")}},Yu=()=>{const e=new Uint8Array(Pc);return globalThis.crypto.getRandomValues(e),e},Qu=async(e,t,n)=>{if(n.length!==Pc)throw new Rt("invalid handshake nonce length");const r=await pt.deriveBits({name:"ECDH",public:t},e,256),o=await pt.importKey("raw",r,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await pt.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(zu)},o,jo*2*8)),i=(a,c)=>pt.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(s.slice(0,jo),["encrypt","decrypt"]),hostToClient:await i(s.slice(jo),["encrypt","decrypt"])}},Xu=(e,t,n)=>{for(let r=Ac-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Zu=(e,t)=>{let n=0n;for(let r=0;r<Ac;r+=1)n=n<<8n|BigInt(e[t+r]);return n},ed=e=>{const t=new Uint8Array(ms);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>nr)throw new Rt("plaintext frame exceeds maximum size");n+=1n;const o=new Uint8Array(Tc);o.set(t,0),Xu(o,ms,n);const s=new Uint8Array(await pt.encrypt({name:"AES-GCM",iv:o},e,r)),i=new Uint8Array(Vn+s.length);return i[0]=Sc,i.set(o,1),i.set(s,Vn),i}}},td=e=>{let t=0n;return{async decrypt(n){if(n.length<Vn+qu)throw new Rt("encrypted frame too short");if(n[0]!==Sc)throw new Rt("unsupported encrypted frame version");const r=n.slice(1,Vn),o=Zu(r,ms);if(o<=t)throw new Rt("frame counter regression");let s;try{s=await pt.decrypt({name:"AES-GCM",iv:r},e,n.slice(Vn))}catch{throw new Rt("frame decryption failed")}return t=o,new Uint8Array(s)}}},kr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",nd=e=>{let t="";for(let n=0;n<e.length;n+=3){const r=e[n],o=n+1<e.length?e[n+1]:void 0,s=n+2<e.length?e[n+2]:void 0;t+=kr[r>>2],t+=kr[(r&3)<<4|(o??0)>>4],o!==void 0&&(t+=kr[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=kr[s&63])}return t},Bi=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!==Kn)return null;const r=n.batch===!0,o=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:Kn,batch:r,flowControl:o}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:Kn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:o}:null},rd=e=>({type:"fail",closeCode:Jt.ChannelFailure,reason:e}),od=async(e,t={})=>{const n=t.batch!==!1,r=await Ju(e),o=await Ku(),s=Yu(),i={t:"hello",v:Kn,clientPubJwk:await Vu(o.publicKey),nonce:nd(s)};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 Bi(c)?.t==="ready"?{type:"ignore"}:rd("plaintext frame on established channel");const l=Bi(c);if(l?.t!=="ready")return{type:"ignore"};const u=await Qu(o.privateKey,r,s);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:ed(u.clientToHost),decryptor:td(u.hostToClient)}}}}},Ic=4294967295,sd=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 ye extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const ze=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>Ic)throw new ye("invalid stream id");if(n.length>hs)throw new ye("tunnel payload exceeds maximum size");const o=new Uint8Array(rr+n.length);return o[0]=r?e|ro:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(n,rr),o},id=e=>{if(e.length<rr)throw new ye("tunnel frame too short");const t=e[0],n=(t&ro)!==0,r=t&~ro;if(!Wu(r))throw new ye(`unknown tunnel frame type ${r}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:o,payload:e.slice(rr),hasMoreFragments:n}},ad=new TextEncoder,cd=new TextDecoder,Er=e=>ad.encode(JSON.stringify(e)),Pr=(e,t)=>{let n;try{n=JSON.parse(cd.decode(e))}catch{throw new ye("malformed JSON tunnel payload")}if(!t(n))throw new ye("unexpected JSON tunnel payload shape");return n},xc=(e,t=hs)=>{if(t<=0||t>hs)throw new ye("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},Hi=(e,t,n)=>{const r=xc(n);return r.map((o,s)=>ze(e,t,o,s<r.length-1))},ld=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,o=t.get(r);if(!n.hasMoreFragments&&!o)return n.payload;const s=o?.chunks??[],i=(o?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new ye("fragmented message exceeds maximum size");if(s.push(n.payload),n.hasMoreFragments)return t.set(r,{chunks:s,totalBytes:i}),null;t.delete(r);const a=new Uint8Array(i);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a},dropStream(n){for(const r of t.keys())r.startsWith(`${n}:`)&&t.delete(r)}}},ud=e=>{if(e.length===0)throw new ye("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=vc,s.set(o,1),s.length>nr)throw new ye("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=vn+o.length;if(t>nr)throw new ye("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=kc;let r=1;for(const o of e)n[r]=o.length>>>24&255,n[r+1]=o.length>>>16&255,n[r+2]=o.length>>>8&255,n[r+3]=o.length&255,r+=vn,n.set(o,r),r+=o.length;return n},dd=e=>{if(e.length<1)throw new ye("empty batch plaintext");const t=e[0];if(t===vc)return[e.slice(1)];if(t!==kc)throw new ye(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+vn>e.length)throw new ye("truncated batch frame length");const o=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=vn,r+o>e.length)throw new ye("truncated batch frame body");n.push(e.slice(r,r+o)),r+=o}if(n.length===0)throw new ye("empty frame batch");return n},fd=new Set([H.HttpBody,H.WsText,H.WsBinary]),Cc=150,pd=24*1024,hd=32,md=e=>{const t=e.windowMs??Cc,n=e.maxBatchBytes??pd,r=e.maxBatchFrames??hd,o=e.now??(()=>Date.now()),s=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=o(),e.sendBatch(ud(b))};return{enqueue:b=>{if(d)return;const w=b[0]&~ro;if(!fd.has(w)){a.push(b),p();return}const E=o();if(a.length===0&&E-u>=t){a.push(b),p();return}const k=vn+b.length;if(a.length>0&&1+c+k>nr&&p(),a.push(b),c+=k,c>=n||a.length>=r){p();return}l===null&&(l=s(p,t))},flush:p,dispose(){d=!0,f(),a=[],c=0}}},gd=()=>{let e=1;return{next(){if(e>Ic)throw new ye("stream id space exhausted");const t=e;return e+=2,t}}},ko=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yd=e=>ko(e)&&Object.values(e).every(t=>typeof t=="string"),wd=e=>ko(e)&&typeof e.status=="number"&&yd(e.headers),zi=e=>ko(e)&&typeof e.reason=="string",bd=e=>ko(e)&&typeof e.code=="number"&&typeof e.reason=="string",Rc=/^[a-z][a-z\d+.-]*:\/\//i,Zs="http://tunnel.invalid",Sd=e=>{try{const t=Rc.test(e)?new URL(e):new URL(e,Zs);return`${t.pathname}${t.search}`}catch{return e}},Ar=e=>({async*[Symbol.asyncIterator](){yield e}}),Td=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()}}}),vd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},kd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Td(e)};if(typeof e=="string")return{body:Ar(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Ar(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Ar(vd(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Ar(r),contentType:n}},Ed=async(e,t)=>{let n;const r=new Headers;let o="GET",s=null,i;e instanceof Request?(n=e.url,o=e.method,e.headers.forEach((d,f)=>r.set(f,d)),i=e.signal,s=e.body):n=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((d,f)=>r.set(f,d)),t.body!==void 0&&(s=t.body),t.signal&&(i=t.signal));const a=Rc.test(n)?new URL(n):new URL(n,Zs),{body:c,contentType:l}=await kd(s);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,f)=>{u[f]=d}),{method:o.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},Dc="__openchamberAmbiguousTransport",Oc=e=>(Object.defineProperty(e,Dc,{value:!0,enumerable:!1,configurable:!0}),e),Pd=e=>!e||typeof e!="object"?!1:e[Dc]===!0,Ad=["local","remote",null],Id=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Mc(e){if(!e||typeof e!="object")return{valid:!1};const t=e,n=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,o=t.status;if(r!==null&&(typeof r!="string"||!Ad.includes(r)))return{valid:!1};if(typeof o!="string"||!Id.includes(o))return{valid:!1};if(r==="remote"||r==="local"){if(o==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok",...n}};if(o==="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(o==="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(o==="incompatible"||o==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:o,hostId:t.hostId,url:t.url,...n}};if(o==="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(o==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...n}};if(o==="missing")return{valid:!1}}return{valid:!1}}function wS(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 bS(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function SS(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function _c(){if(xd()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=Mc(t);return n.valid?n.outcome:null}function xd(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Mc(e).valid?"valid":"malformed"}const oo=/^[a-z][a-z\d+.-]*:\/\//i,Cd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},so=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Rd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return so(e)},Dd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return so(e)},Od=()=>Object.keys(xo()).length>0,Md=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},gs=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},_d=(e,t)=>{if(!t)return e;const n=new URLSearchParams;gs({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},$i=(e,t,n)=>{if(oo.test(t)){const s=new URL(t);return gs(s,n),s.toString()}const r=Cd(t);if(!e)return _d(r,n);const o=new URL(r,`${e}/`);return gs(o,n),o.toString()},Ir=(e,t=pf())=>{if(!t)return e;const n=oo.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),oo.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},Lc=(e,t)=>{const n=oo.test(e)?new URL(e):new URL(e,Md(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},Gi=(e,t,n)=>{if(!Od())return null;const r=Dd();if(!r)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${r}/`);o.searchParams.set("url",t);const s=hf(r);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Lc(o.toString(),n)):o.toString()}catch{return null}},ei=(e={})=>{const t=so(e.apiBaseUrl),n=so(e.realtimeBaseUrl),r=()=>t||Rd(),o=()=>n||r(),s=(a,c)=>$i(r(),a,c),i=(a,c)=>$i(o(),a,c);return{api:s,authenticatedAsset:(a,c)=>Ir(s(a,c)),assetWithUrlToken:(a,c,l)=>Ir(s(a,l),c),auth:s,health:a=>s("/health",a),rawFile:(a,c)=>s("/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=Ir(i(a,c));return Gi("sse",l,e)||l},websocket:(a,c)=>{const l=Lc(Ir(i(a,c)),e);return Gi("ws",l,e)||l}}};let io=ei();const Ee=()=>io,Ld=e=>{io=e},Fc=e=>(io=ei(e),io),ys="openchamber:runtime-endpoint-changed",ws="openchamber:runtime-endpoint-will-change";let kn="",or="";const No=(e,t,n)=>{try{e[t]=n}catch{}},ti=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"}`}},Fd="mobile-disconnected",Ud="url:default",Uc=e=>e===""||e===Ud||e===Fd,jc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Nc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Bc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Eo=()=>kn||jc();let Bo="",Wi=null,qi,Ki;const Vi=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},G=()=>{if(or)return or;const e=Vi("__OPENCHAMBER_API_BASE_URL__"),t=Vi("__OPENCHAMBER_LOCAL_ORIGIN__");if(Wi===kn&&qi===e&&Ki===t)return Bo;const n=Eo();return Bo=Bc(n,Nc())?"local":ti(n),Wi=kn,qi=e,Ki=t,Bo},jd=(e={})=>{if(kn||or)return;const t=e.apiBaseUrl?.trim()||jc(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const o=Nc(),s=o&&(!t||Bc(t,o));kn=t,or=e.runtimeKey?.trim()||(s?"local":ti(t||r))},ao=e=>{const t=e.apiBaseUrl.trim(),n=Eo(),r=G(),o=e.runtimeKey?.trim()||ti(t),s={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:o,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(ws,{detail:s})),kn=t,or=o,typeof window<"u"){const i=window;No(i,"__OPENCHAMBER_API_BASE_URL__",t),No(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),No(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Fc({apiBaseUrl:t,realtimeBaseUrl:t}),Zc(e.requestHeaders||null),Xc(e.clientToken||null),e.relay?sf(e.relay):af(),Co(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ys,{detail:s}))},Nd=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(ws,t),()=>window.removeEventListener(ws,t)},Hc=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(ys,t),()=>window.removeEventListener(ys,t)};let bs=null;const TS=e=>{bs=e},Po=()=>bs||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),zc=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Bd=(e=zc())=>!!e,Hd=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,mt=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,tn=()=>Hd()?.runtime==="electron",zd=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},$d="right",vS=()=>{if(!tn())return!1;const e=zd();return e==="win32"||e==="linux"},kS=e=>e==="left"?"left":$d,ES=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],ve=()=>typeof mt()?.invoke=="function",Cn=()=>tn()&&ve(),Gd=()=>{if(mt()?.pickThemeFile)return{async pick(){const e=mt()?.pickThemeFile;return e?{status:"picked",file:v({name:m(),size:C().nonnegative(),text:m()}).nullable().parse(await e())}:{status:"unsupported"}}}},oe=async(e,t)=>{const n=mt();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},PS=async()=>{if(!Cn()||!ke())return null;try{const e=await oe("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}},AS=async e=>{if(!Cn()||!ke())return null;try{const t=await oe("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}},IS=async()=>{if(!Cn()||!ke())return null;try{const e=await oe("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}},xS=async e=>{if(!Cn()||!ke())return null;try{const t=await oe("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}},CS=async()=>{if(!Cn()||!ke())return null;try{const e=await oe("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}},RS=async e=>{if(!Cn()||!ke())return null;try{const t=await oe("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}},Ji=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}}},Ho=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}}},Wd=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Un=e=>{const t=Wd(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},ke=()=>{if(typeof window>"u"||!Je())return!1;if(G()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Ho(e),n=Ho(Eo());if(!n&&t&&_c()?.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&&Un(t.hostname)&&Un(n.hostname)}const r=Ho(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&&Un(t.hostname)&&Un(r.hostname)}const o=Ji(e),s=Ji(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(r&&Un(r.hostname))},Je=()=>typeof window>"u"?!1:tn(),DS=async()=>{if(!Je())return!1;try{return!!await oe("desktop_focus_window")}catch{return!1}},$c=()=>Je()&&ve()&&ke(),qd=m().min(1),OS=e=>{if(!$c())return null;try{const t=qd.safeParse(mt()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},MS=async()=>{if(!Je())return!1;try{return await oe("desktop_start_window_drag"),!0}catch{return!1}},Me=()=>Bd()?!0:Po()?.runtime?.isVSCode===!0,_S=()=>{const t=Po()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Me()},LS=(e,t=Je())=>e==="web"&&!t,Gc=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},FS=async e=>{if($c())try{const t=await mt()?.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"}},Kd=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vd=v({path:m().min(1),outsideFileGrant:m().min(1),expiresAt:C().finite()}),US=async e=>{if(ve()&&ke())try{const t=await mt()?.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(!Kd(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"}},jS=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!ve()||!ke())return{success:!1,error:"Native file access not available"};try{const n=await mt()?.grantFileAccess?.(t),r=Vd.safeParse(n);return r.success?{success:!0,...r.data}:{success:!1,error:"File access was not granted"}}catch(n){return console.warn("Failed to request existing file access",n),{success:!1,error:n instanceof Error?n.message:String(n)}}},NS=async e=>({success:!0}),BS=async e=>({success:!0}),HS=async()=>ve()?await oe("desktop_check_for_updates"):null,zS=async e=>{if(!ve())return!1;const t=mt();let n=null,r=0,o;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("openchamber:update-progress",s=>{const i=s?.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,o=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:o});return}if(c==="Progress"){const u=l?.downloaded,d=l?.total;typeof u=="number"&&(r=u),typeof d=="number"&&(o=d),e({downloaded:r,total:o});return}c==="Finished"&&e({downloaded:r,total:o})})),await oe("desktop_download_and_install_update"),!0}catch(s){throw s instanceof Error?s:new Error(String(s))}finally{if(n)try{const s=n();s instanceof Promise&&await s}catch{}}},$S=async()=>ve()?(await oe("desktop_restart"),!0):!1,GS=async()=>{if(!ve())return!1;try{return await oe("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},WS=async()=>{if(!ve()||!ke())return null;try{const e=await oe("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}},Jd=async(e,t)=>{if(!ve()||!ke())return!1;const n=e?.trim();if(!n)return!1;try{return await oe("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}},qS=async e=>{if(!ve()||!ke())return!1;const t=e?.trim();if(!t)return!1;try{return await oe("desktop_reveal_path",{path:t}),!0}catch{return Jd(t)}},KS=async(e,t)=>{if(!ve()||!ke())return null;const n=e?.trim();if(!n)return null;try{const r=await oe("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}},VS=async(e,t,n)=>{if(!ve()||!ke())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await oe("desktop_open_in_app",{projectPath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},JS=async(e,t,n)=>{if(!ve()||!ke())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await oe("desktop_open_file_in_app",{filePath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},YS=async(e,t)=>{if(!ve()||!ke())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 oe("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 o=r;return o.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(o.apps)?{apps:o.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:o.hasCache===!0,isCacheStale:o.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},pr=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",Yd=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_ELECTRON__?.arch?.toLowerCase?.();if(e==="arm64"||e==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const t=window.__VSCODE_CONFIG__?.arch?.toLowerCase?.();if(t==="arm64"||t==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const n=navigator.userAgentData;if(n?.architecture?.toLowerCase?.()==="arm64"||n?.architecture?.toLowerCase?.()==="aarch64")return(n.platform||navigator.platform||"").toLowerCase().includes("win");const r=navigator.userAgent.toLowerCase();return!!((r.includes("aarch64")||r.includes("arm64")||r.includes("armv"))&&r.includes("windows"))},QS=()=>{if(typeof window>"u"||!pr()||Wc()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Wc=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Me()?"vscode":Je()?"desktop":"web"},Qd="1.24.4",xr=new Uint8Array(0),Xd=new TextEncoder,Zd=new TextDecoder,je=e=>e instanceof Error?e:new Error(String(e)),Cr=()=>new DOMException("The operation was aborted.","AbortError"),ef=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},tf=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},Yi=0,zo=1,Qi=2,Xi=3,nf=new Set([Jt.AuthFailed,Jt.DuplicateClient,Jt.LimitExceeded]),rf={[Jt.AuthFailed]:"relay authentication failed",[Jt.DuplicateClient]:"relay connection replaced by another client",[Jt.LimitExceeded]:"relay connection limit reached"},Zi=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ni=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??Cc,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(x=>ef(new WebSocket(x)));let d=!1,f=null,p={state:"idle"};const g=new Set;let b=null,w=null,E=null,k=0,F=0,O=null,K=[],R=!1;const we=x=>{if(!(p.state===x.state&&p.lastError===x.lastError)){p=x;for(const $ of g)try{$(p)}catch{}}},se=x=>{const $=K;K=[];for(const D of $)D.reject(x)},Lo=x=>{const $=K;K=[];for(const D of $)D.resolve(x)},Pe=(x,$)=>{x.dead=!0;const D=Array.from(x.streams.values());x.streams.clear();for(const M of D)try{M.fail($)}catch{}},On=()=>{O!==null&&(clearTimeout(O),O=null)},Mn=()=>{d||O===null||Zi()||(On(),Qe(),_n())},Lt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Mn()},L=()=>{R||typeof window>"u"||(R=!0,window.addEventListener("online",Mn),typeof document<"u"&&document.addEventListener("visibilitychange",Lt))},Qe=()=>{!R||typeof window>"u"||(R=!1,window.removeEventListener("online",Mn),typeof document<"u"&&document.removeEventListener("visibilitychange",Lt))},on=()=>{if(d||O!==null)return;const x=Math.max(0,F-1),$=a*2**Math.min(x,10),D=Zi()?l:c,M=Math.min(D,$);L(),O=setTimeout(()=>{O=null,Qe(),_n()},M)},Sr=()=>{const x=new URL(e.relayUrl);return x.searchParams.set("v",String(Kn)),x.searchParams.set("role","client"),x.searchParams.set("serverId",e.serverId),x.searchParams.set("appId","openchamber"),x.searchParams.set("appVersion",Qd),x.searchParams.set("platform",Wc()),e.grant&&x.searchParams.set("grant",e.grant),x.toString()},_n=async()=>{if(d)return;On(),k+=1;const x=k;we({state:F>0?"reconnecting":"connecting",lastError:p.lastError});let $;try{$=await od(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(V){if(x!==k||d)return;Ui(x,je(V),!0);return}if(x!==k||d)return;let D;try{D=u(Sr())}catch(V){Ui(x,je(V));return}w=D;let M=!1,j=null,W=null,xe=null,he=null,B=Promise.resolve(),z=null,te=null,it=!1,de=!1,fe=0,me=0,ge=null,at=null,Q=Date.now();const wt=()=>{ge!==null&&(clearTimeout(ge),ge=null),j!==null&&(clearInterval(j),j=null),W!==null&&(clearTimeout(W),W=null),xe!==null&&(clearInterval(xe),xe=null),he!==null&&(clearTimeout(he),he=null),at!==null&&(at.dispose(),at=null)};E=wt;function q(V,ne=!1,Y=!1){if(!(M||x!==k)){M=!0,Y&&(f=V),wt(),z&&(b=null,Pe(z,new Error(`relay tunnel reset: ${V.message}`))),se(V);try{D.close()}catch{}if(w===D&&(w=null),!d){if(F+=1,Y){we({state:"error",lastError:V.message});return}we({state:ne?"error":"reconnecting",lastError:V.message}),on()}}}const Ln=()=>{try{D.send($.helloText)}catch{}},vr=(V,ne,Y)=>{te=V,it=ne,de=Y,j!==null&&(clearInterval(j),j=null),W!==null&&(clearTimeout(W),W=null);const ie=new Map,Ft=gd(),Ue=ld();let Ut=Promise.resolve();const bt=Fn=>{Ut=Ut.then(async()=>{if(jt.dead)return;const Nu=await V.encryptor.encrypt(Fn);jt.dead||D.send(Nu)}).catch(()=>{q(new Error("relay encrypt/send failed"))})},Uo=ne?md({windowMs:s,sendBatch:bt}):null;at=Uo;const jt={streams:ie,assembler:Ue,nextStreamId:()=>Ft.next(),dead:!1,send(Fn){jt.dead||(Uo?Uo.enqueue(Fn):bt(Fn))}};z=jt,b=jt,F=0,Q=Date.now(),we({state:"connected"}),Lo(jt),xe=setInterval(()=>{Date.now()-Q<r||(jt.send(ze(H.Ping,0,xr)),he===null&&(he=setTimeout(()=>{he=null,q(new Error("relay keepalive timeout"))},o)))},r)},sn=()=>{ge!==null&&clearTimeout(ge),ge=null,!(!z||z.dead||fe===me)&&(me=fe,z.send(ze(H.DeliveryAck,0,sd(fe))))},ju=(V,ne)=>{let Y;try{Y=id(ne)}catch(Ue){q(je(Ue));return}if(Y.frameType===H.DeliveryAck){q(new Error("unexpected downstream delivery acknowledgement"));return}if(de&&Y.streamId!==0&&(fe+=ne.length,ge===null&&(ge=setTimeout(sn,10))),Q=Date.now(),he!==null&&(clearTimeout(he),he=null),Y.frameType===H.Ping){V.send(ze(H.Pong,Y.streamId,xr));return}if(Y.frameType===H.Pong)return;let ie=Y.payload;if(Y.frameType===H.WsText||Y.frameType===H.WsBinary){let Ue;try{Ue=V.assembler.push(Y)}catch(Ut){q(je(Ut));return}if(Ue===null)return;ie=Ue}else if(Y.hasMoreFragments){q(new Error("unexpected fragmented tunnel frame"));return}const Ft=V.streams.get(Y.streamId);Ft&&Ft.handleFrame(Y.frameType,ie)};D.onopen=()=>{M||x!==k||(Ln(),j=setInterval(Ln,t))},D.onmessage=V=>{if(M||x!==k)return;const ne=V.data;if(typeof ne=="string"){B=B.then(async()=>{if(M||x!==k)return;const ie=await $.handleText(ne);if(ie.type==="established"){if(te)return;vr(ie.channel,ie.batch,ie.flowControl)}else ie.type==="fail"&&q(new Error(`relay handshake failed: ${ie.reason}`))}).catch(ie=>{q(je(ie))});return}const Y=ne instanceof ArrayBuffer?new Uint8Array(ne):ne instanceof Uint8Array?ne:null;Y&&(B=B.then(async()=>{if(M||x!==k)return;const ie=z,Ft=te;if(!ie||!Ft){q(new Error("encrypted frame before handshake completed"));return}let Ue;try{Ue=await Ft.decryptor.decrypt(Y)}catch(bt){q(je(bt));return}let Ut;try{Ut=it?dd(Ue):[Ue]}catch(bt){q(je(bt));return}for(const bt of Ut){if(M||x!==k||ie.dead)return;ju(ie,bt)}de&&fe-me>=16*1024&&sn()}).catch(ie=>{q(je(ie))}))},D.onclose=V=>{const ne=nf.has(V.code);q(new Error(rf[V.code]??`relay socket closed (code ${V.code})`),ne,ne)},D.onerror=()=>{},W=setTimeout(()=>{W=null,q(new Error("relay handshake timeout"),!0)},n);function Ui(V,ne,Y=!1){V!==k||d||(se(ne),F+=1,we({state:Y?"error":"reconnecting",lastError:ne.message}),on())}},Tr=x=>d?Promise.reject(new Error("relay tunnel closed")):x?.aborted?Promise.reject(Cr()):f?Promise.reject(f):b&&!b.dead?Promise.resolve(b):new Promise(($,D)=>{let M=null;const j={resolve(W){M&&x&&x.removeEventListener("abort",M),$(W)},reject(W){M&&x&&x.removeEventListener("abort",M),D(W)}};x&&(M=()=>{K=K.filter(W=>W!==j),D(Cr())},x.addEventListener("abort",M,{once:!0})),K.push(j)}),yt=async(x,$)=>{const D=await Ed(x,$),M=D.signal;if(M?.aborted)throw Cr();const j=await Tr(M),W=j.nextStreamId();return await new Promise((xe,he)=>{let B=!1,z=!1,te=null,it=null;const de=()=>{j.streams.delete(W),j.assembler.dropStream(W),it&&M&&M.removeEventListener("abort",it)},fe=Q=>{if(!z){if(z=!0,de(),!B){he(Q);return}try{te?.error(Q)}catch{}}},me=Q=>{j.dead||j.send(ze(H.StreamAbort,W,Er({reason:Q})))},ge=Q=>Oc(new Error(Q));it=()=>{me("aborted"),fe(Cr())},j.streams.set(W,{handleFrame(Q,wt){if(Q===H.HttpResponse){if(B||z)return;let q;try{q=Pr(wt,wd)}catch(sn){me("malformed response head"),fe(ge(je(sn).message));return}const Ln=q.status===204||q.status===205||q.status===304;let vr=null;Ln||(vr=new ReadableStream({start(sn){te=sn},cancel(){z||(z=!0,de(),me("response body cancelled"))}})),B=!0,xe(new Response(vr,{status:q.status,headers:q.headers})),Ln&&(z=!0,de());return}if(Q===H.HttpBody){if(!B||z)return;try{te?.enqueue(wt)}catch{}return}if(Q===H.StreamEnd){if(z)return;if(!B){fe(ge("tunnel stream ended before response head"));return}z=!0,de();try{te?.close()}catch{}return}if(Q===H.StreamAbort){let q="stream aborted by host";try{q=Pr(wt,zi).reason}catch{}fe(ge(q))}},fail(Q){fe(ge(Q.message))}}),M&&M.addEventListener("abort",it,{once:!0});const at={method:D.method,path:D.path,query:D.query,headers:D.headers,hasBody:D.body!==null};j.send(ze(H.HttpRequest,W,Er(at))),(async()=>{try{let Q=!1;if(D.body)for await(const wt of D.body){if(z||j.dead)return;for(const q of xc(wt))j.send(ze(H.HttpBody,W,q)),Q=!0}!z&&!j.dead&&(D.body&&!Q&&j.send(ze(H.HttpBody,W,xr)),j.send(ze(H.StreamEnd,W,xr)))}catch(Q){me("request body failed"),fe(ge(je(Q).message))}})()})},Fo=x=>{const $=x.indexOf("?");return $===-1?{path:x,query:""}:{path:x.slice(0,$),query:x.slice($+1)}},Fu=(x,$)=>{let D=Yi,M=null,j=0,W=!1;const xe={get readyState(){return D},onopen:null,onmessage:null,onerror:null,onclose:null,send(B){if(D!==zo||!M||M.dead)throw new Error("relay tunnel socket is not open");if(typeof B=="string"){for(const te of Hi(H.WsText,j,Xd.encode(B)))M.send(te);return}const z=B instanceof ArrayBuffer?new Uint8Array(B.slice(0)):(()=>{const te=new Uint8Array(B.byteLength);return te.set(new Uint8Array(B.buffer,B.byteOffset,B.byteLength)),te})();for(const te of Hi(H.WsBinary,j,z))M.send(te)},close(B=1e3,z=""){D===Xi||D===Qi||(D===zo&&M&&!M.dead&&(D=Qi,M.send(ze(H.WsClose,j,Er({code:B,reason:z})))),he(B,z))}},he=(B,z,te=!1)=>{if(!W){if(W=!0,M&&(M.streams.delete(j),M.assembler.dropStream(j)),D=Xi,te)try{xe.onerror?.()}catch{}try{xe.onclose?.({code:B,reason:z})}catch{}}};return(async()=>{let B;try{B=await Tr()}catch(de){he(1006,je(de).message,!0);return}if(W)return;M=B,j=B.nextStreamId(),B.streams.set(j,{handleFrame(de,fe){if(de===H.WsOpened){if(D===Yi){D=zo;try{xe.onopen?.()}catch{}}return}if(de===H.WsText){try{xe.onmessage?.({data:Zd.decode(fe)})}catch{}return}if(de===H.WsBinary){const me=new ArrayBuffer(fe.byteLength);new Uint8Array(me).set(fe);try{xe.onmessage?.({data:me})}catch{}return}if(de===H.WsClose){let me=1e3,ge="";try{const at=Pr(fe,bd);me=at.code,ge=at.reason}catch{}he(me,ge);return}if(de===H.StreamAbort){let me="stream aborted";try{me=Pr(fe,zi).reason}catch{}he(1006,me,!0)}},fail(de){he(1012,de.message,!0)}});const{path:z,query:te}=Fo(x),it=$&&$.length>0?{path:z,query:te,protocols:$}:{path:z,query:te};B.send(ze(H.WsOpen,j,Er(it)))})(),xe},Uu=()=>{if(d)return;d=!0,k+=1,On(),Qe(),E?.(),E=null;const x=b;b=null;const $=new Error("relay tunnel closed");x&&Pe(x,$),se($);try{w?.close()}catch{}w=null,we({state:"idle"})};return _n(),{fetch:yt,openWebSocket:Fu,getStatus:()=>p,subscribeStatus(x){return g.add(x),()=>{g.delete(x)}},close:Uu}};let De=null,ht=null;const of=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Ao=()=>De,XS=()=>!De||!ht?null:{relayUrl:ht.relayUrl,serverId:ht.serverId,hostEncPubJwk:{...ht.hostEncPubJwk}},ZS=()=>De!==null,sf=e=>(De&&ht&&of(ht,e)||(De?.close(),ht=e,De=ni(e)),De),eT=(e,t)=>{De!==t&&(De?.close(),ht=e,De=t)},af=()=>{De?.close(),De=null,ht=null};let qc=()=>null,Kc="",co={},Xt="",sr=0,Wt=null,Sn="",ir=0,Zt="",qt=null,It="",Kr=0,Vr=0;const ri=1e4,cf=e=>e.toLowerCase()==="authorization",Vc=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const o=n.trim(),s=r.trim();o&&s&&!cf(o)&&(t[o]=s)}return t},lf=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,o])=>t[r]===o)},Io=e=>typeof e!="string"?"":e.trim(),uf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Io(e)},df=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Jc=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():df();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},oi=e=>{try{return new URL(e).origin}catch{return""}},Yc=()=>{Sn="",ir=0,Zt="",qt=null,It="",Kr+=1},hr=()=>{Xt="",sr=0,Yc()},Qc=()=>{Vr+=1,Wt=null,hr(),si()},Xc=e=>{const t=Io(e);Kc=t,Qc(),qc=()=>t?{type:"bearer",token:t}:null},Zc=e=>{const t=Vc(e);lf(co,t)||(co=t,Qc())},xo=()=>{if(Object.keys(co).length>0)return co;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Vc(e):{}},el=()=>Kc||uf(),ff=(e,t)=>{const n=Io(e);if(!n||typeof t!="number"||!Number.isFinite(t)){hr();return}const r=Xt;Xt=n,sr=t,r&&r!==n&&wf()},tl=()=>!Xt||sr<=Date.now()+ri?(hr(),""):Xt,nl=e=>{const t=oi(e);return!t||Zt!==t?"":!Sn||ir<=Date.now()+ri?(Sn="",ir=0,Zt="",""):Sn},pf=()=>{const e=tl();return!e&&(el()||typeof window<"u")&&Co().catch(()=>{}),e},hf=e=>{const t=e?nl(e):"";return!t&&e&&typeof window<"u"&&il(e).catch(()=>{}),t},rl=async()=>{const e=await qc(),t=e?.type==="bearer"?Io(e.token):el();return t?{type:"bearer",token:t}:null},mf=v({token:m(),expiresAt:C()}),ol=async(e,t)=>{const n=await rl(),r=new Headers;for(const[c,l]of Object.entries(xo()))r.set(c,l);n?.type==="bearer"&&r.set("Authorization",`Bearer ${n.token}`);const o=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",s=Ao(),i=s?await s.fetch(o,{method:"POST",headers:r}):await fetch(Jc(e,o),{method:"POST",headers:r,credentials:"include"});if(!i.ok)throw new Error(`Failed to mint runtime URL auth token (${i.status})`);const a=mf.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},tT=async e=>{const t=await ol(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},sl=e=>{if(Wt)return Wt;const t=Vr,r=(async()=>{let o;try{o=await ol(e)}catch(s){throw t===Vr&&hr(),s}if(t!==Vr)throw new Error("Runtime URL auth token response is stale");if(ff(o.token,o.expiresAt),!Xt)throw new Error("Runtime URL auth token response was invalid");return Xt})().finally(()=>{Wt===r&&(Wt=null)});return Wt=r,Wt},gf=e=>{const t=oi(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(qt&&It===t)return qt;const n=Kr,o=(async()=>{const s=await fetch(Jc(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!s.ok)throw n===Kr&&t===It&&(Sn="",ir=0,Zt=""),new Error(`Failed to mint local runtime URL auth token (${s.status})`);const i=await s.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!==Kr||t!==It)throw new Error("Local runtime URL auth token response is stale");return Sn=a,ir=c,Zt=t,a})().finally(()=>{qt===o&&(qt=null,It="")});return qt=o,It=t,qt},Co=async e=>{const t=tl();return t||sl(e)},il=async e=>{const t=oi(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=nl(t);return n||((Zt&&Zt!==t||It&&It!==t)&&Yc(),gf(t))};let gn=0,Jn=null,al=null;const Ss=new Set,yf=5e3,wf=()=>{for(const e of Ss)try{e()}catch{}},cl=()=>{Jn!==null&&(clearTimeout(Jn),Jn=null)},si=()=>{if(cl(),gn<=0||typeof window>"u")return;const e=sr-ri-yf,t=sr>0?Math.max(0,e-Date.now()):0;Jn=setTimeout(()=>{Jn=null,!(gn<=0)&&sl(al).catch(()=>{}).finally(()=>{si()})},t)},nT=e=>{typeof e=="string"&&e.trim()&&(al=e.trim()),gn+=1,si();let t=!1;return()=>{t||(t=!0,gn=Math.max(0,gn-1),gn===0&&cl())}},rT=e=>(Ss.add(e),()=>{Ss.delete(e)}),bf=async e=>{const t=new Headers(e);for(const[r,o]of Object.entries(xo()))t.has(r)||t.set(r,o);if(t.has("Authorization"))return t;const n=await rl();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},lo=gt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Sf=15e3,Tf=5*6e4;let Ts=0,$o=!1;const vf=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),kf=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!vf(t)},ll=async()=>{if(!$o){$o=!0;try{const{runtimeFetch:e}=await Xs(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>Lf);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){lo.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=lo.getState();n==="expired"&&r()}}catch{}finally{$o=!1}}},Ef=(e,t)=>{if(t!==401||lo.getState().state==="expired"||!kf(e))return;const n=Date.now();n-Ts<Sf||(Ts=n,ll())};let ea=!1;const oT=()=>{if(ea)return;ea=!0;let e=Date.now();const t=()=>{if(lo.getState().state!=="ok")return;const n=Date.now();n-e<Tf||(e=n,Ts=n,ll())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},en=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Pf=()=>typeof window>"u"?"":window.location.origin||"",ii=e=>{if(typeof window>"u")return!1;const t=Pf();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}},ai=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Af=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),Pt=(e,t)=>{try{Af(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},ci=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},Jr=e=>{try{const t=Ee().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:en(e.pathname)}catch{return!1}},Go=e=>{if(en(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ii(t)&&en(t.pathname)}catch{return!1}},If=(e,t)=>{try{const n=new URL(e);if(!ii(n))return e;const r=Ot(`${n.pathname}${n.search}`,t);return!ai(r)&&(n.protocol==="http:"||n.protocol==="https:")?(ci(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},Ot=(e,t)=>e==="/health"?Ee().health(t):e.startsWith("/auth/")||e==="/auth"?Ee().auth(e,t):en(e)?Ee().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?If(e,t):e,xf=e=>{const t=e instanceof Request?e.url:e.toString();if(!ai(t))return en(t);try{return Jr(new URL(t))}catch{return!1}},ul=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Cf=(e,t)=>!ul(t),vs=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,o=!1;for(const[s,i]of t)Cf(s,i)?(n.push([s,encodeURIComponent(i)]),r=!0,s.toLowerCase()==="x-opencode-directory"&&(o=!0)):n.push([s,i]);return o&&n.push(["x-opencode-directory-encoding","uri"]),r?n:void 0},ct=async(e,t,n=!0)=>{const r=new Headers(vs(e)??e);return t&&new Headers(vs(t)??t).forEach((o,s)=>r.set(s,o)),n?bf(r):r},Rf=(e,t)=>{if(!t)return e;const n=new URL(e,Zs);return ci(n,t),`${n.pathname}${n.search}`},dl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!ai(n))return en(n)?Rf(n,t):null;try{const r=new URL(n);return!ii(r)||!en(r.pathname)?null:(ci(r,t),`${r.pathname}${r.search}`)}catch{return null}},Df=async(e,t,n)=>{const r=Ao();if(!r)return null;const o=dl(e,n);if(o===null)return null;const s=e instanceof Request?e.headers:void 0,i=await ct(s,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(o,{...t,headers:i})},Of=(e,t)=>{if(typeof e=="string")return Ot(e,t);if(e instanceof URL)return Ot(e.toString(),t);const n=Ot(e.url,t);return n===e.url?e:new Request(n,e)},Mf=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Rr=new Map,_f=(e,t,n)=>n||e!=="GET"||t.includes("/event")||!Mf.test(t)?null:`GET ${t}`,y=async(e,t={})=>{const{query:n,...r}=t,o=Ao(),s=o?dl(e,n):null;let i,a,c;if(o&&s!==null){const g=e instanceof Request?e.headers:void 0,b=await ct(g,r.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...r,headers:b}):()=>o.fetch(s,{...r,headers:b}),a=s,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const g=Of(e,n),b=g instanceof Request?g.headers:void 0,w=await ct(b,r.headers,xf(g)),E=g instanceof Request?g.url:g instanceof URL?g.toString():String(g);Pt(E,w),i=g instanceof Request?()=>fetch(new Request(g,{...r,headers:w})):()=>fetch(g,{...r,headers:w}),a=E,c=String(r.method??(g instanceof Request?g.method:"GET")).toUpperCase()}const l=i;i=()=>l().then(g=>(Ef(a,g.status),g));const u=r.signal!=null||e instanceof Request,d=_f(c,a,u);if(!d)return i();const f=Rr.get(d);if(f)return f.then(g=>g.clone());const p=i();return Rr.set(d,p),p.then(()=>Rr.delete(d),()=>Rr.delete(d)),p.then(g=>g.clone())};let ta=!1;const fl=()=>{if(ta||typeof window>"u")return;ta=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await Df(t,n??{});if(r)return r;if(typeof t=="string"){if(!Go(t)){try{const i=new URL(t);if(Jr(i)){const a=await ct(void 0,n?.headers);return Pt(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const o=await ct(void 0,n?.headers),s=Ot(t);return Pt(s,o),e(s,{...n,headers:o})}if(t instanceof URL){const o=t.toString();if(!Go(o)){if(Jr(t)){const a=await ct(void 0,n?.headers);return Pt(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const s=await ct(void 0,n?.headers),i=Ot(o);return Pt(i,s),e(i,{...n,headers:s})}if(t instanceof Request){if(!Go(t.url)){try{const a=new URL(t.url);if(Jr(a)){const c=await ct(t.headers,n?.headers);return Pt(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const o=await ct(t.headers,n?.headers),s=Ot(t.url);Pt(s,o);const i=s===t.url?t:new Request(s,t);return e(new Request(i,{...n,headers:o}))}return e(t,n)}},Lf=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:Pt,buildRuntimeFetchUrl:Ot,installRuntimeFetchBridge:fl,isLatin1Safe:ul,runtimeFetch:y,sanitizeHeadersForBrowser:vs},Symbol.toStringTag,{value:"Module"})),Tn=16384,uo=globalThis,Ff=e=>{if(uo.Buffer)return uo.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(uo.Buffer)return uo.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 o=0;o<n.length;o+=1)r[o]=n.charCodeAt(o);return new TextDecoder().decode(r)}catch{return null}},Uf=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}},jf=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}},na=e=>typeof e=="string"&&e.length>0,Nf=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!na(t.x)||!na(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Bf=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Hf=e=>{if(!e||typeof e!="object")return null;const t=e,n=Bf(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=Uf(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=jf(t.relayUrl);if(!r)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const s=Nf(t.hostEncPubJwk);if(!s)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:r,serverId:o,hostEncPubJwk:s,...i?{grant:i}:{},...n===void 0?{}:{priority:n}}}return null},li=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 o=Array.isArray(t.candidates)?t.candidates.map(Hf).filter(c=>!!c):[];if(o.length===0)return null;const s=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(s){const c=Date.parse(s);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}:{},...s?{expiresAt:s}:{},candidates:o}},sT=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}),iT=e=>{const t=li(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",Ff(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},zf=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 o=pl(r);return!o||o.length>Tn?null:li(JSON.parse(o))}catch{return null}},aT=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,o=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"&&(o=l)}if(r!=="2"||!o||o.length>Tn)return null;const s=pl(o);if(!s||s.length>Tn)return null;try{return li(JSON.parse(s))}catch{return null}},En=e=>typeof e=="object"&&e!==null,$f=e=>e.trim().toLowerCase()==="authorization",Gf=e=>{if(!En(e))return;const t={};for(const[n,r]of Object.entries(e)){const o=n.trim(),s=typeof r=="string"?r.trim():"";!o||!s||/[\r\n:]/.test(o)||/[\r\n]/.test(s)||$f(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},Wf=e=>`relay://${e}`,qf=e=>{if(!En(e))return null;const t=be(e,"relayUrl")||be(e,"relay_url"),n=be(e,"serverId")||be(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!En(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Kf=()=>{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"},cT=async(e,t)=>{const n=zf(e);if(!n)throw new Error("invalid-connect-link");const r=await Xf().catch(()=>""),o={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:Kf(),...r?{dedupeKey:`desktop:${r}`}:{}})},s=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=ni({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const F=await s(await k.fetch("/api/client-auth/pairing/redeem",o));if(F){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:F};break}}catch{}finally{k.close()}continue}const E=Se(w.url);if(E)try{const k=await s(await fetch(`${E}/api/client-auth/pairing/redeem`,o));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=>Se(w.url)).find(w=>!!w),d=i.directUrl||u,f=d||(l?Wf(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const p=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&Se(w.apiUrl||w.url)===f),g=p?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),b={...p||{},id:g,label:n.label||p?.label||hl(f),url:f,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:g,hosts:p?t.map(w=>w.id===g?b:w):[b,...t]}},Vf=/^(t|.*(?:token|auth|secret|api).*)$/i,Se=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}},lT=e=>{const t=Se(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"}},hl=e=>{const t=Se(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 o of r)Vf.test(o)&&n.searchParams.set(o,"[REDACTED]");return n.toString()}catch{return t}},Dr=(e,t)=>{const n=Se(e),r=Se(t);if(!n||!r)return!1;try{const o=new URL(n),s=new URL(r);if(o.origin!==s.origin||s.search&&o.search!==s.search)return!1;const i=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname,a=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},be=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},ra=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},Jf=e=>{if(!En(e))return null;const t=be(e,"id"),n=be(e,"label"),r=be(e,"url"),o=be(e,"apiUrl")||be(e,"api_url"),s=be(e,"clientToken")||be(e,"client_token"),i=Gf(e.requestHeaders),a=qf(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...o?{apiUrl:o}:{},...s?{clientToken:s}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Yn=e=>Se(e.apiUrl||e.url)||e.apiUrl||e.url,nn=()=>ve()?(e,t)=>oe(e,t):null,ui=async()=>{const e=nn();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!En(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(Jf).filter(a=>!!a):[],o=be(t,"defaultHostId")||be(t,"default_host_id")||be(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=be(t,"localOrigin")||be(t,"local_origin");return{hosts:r,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},Yf=async e=>{const t=nn();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})},Qf=async()=>{const e=nn();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Xf=async()=>{const e=nn();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Zf=8e3,ep=15e3,tp=400,np=async(e,t,n,r)=>{const o=new AbortController,s=window.setTimeout(()=>o.abort(),n);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(s)}},oa=async(e,t,n,r)=>{for(;;){const o=n-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await np(e,t,Math.min(Zf,o),r)}catch(s){if(e.getStatus().state==="error"||Date.now()>=n)throw s;await new Promise(i=>window.setTimeout(i,tp))}}},rp=async(e,t)=>{const n=ni({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),o=r+ep;let s=!1;try{if(!(await oa(n,"/health",o)).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 oa(n,"/auth/session",o,{headers:a});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:l.ok?(s=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...s?{tunnel:n}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{s||n.close()}},di=async(e,t)=>{const n=nn();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(!En(r))return{status:"unreachable",latencyMs:0};const o=r.status,s=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",i=ra(r,"latencyMs")??ra(r,"latency_ms")??0;return{status:s,latencyMs:i}},uT=async(e,t)=>{const n=nn();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},dT=async e=>{const t=nn();t&&await t("desktop_new_window_for_host",{hostId:e})},Dt="local",op=e=>({id:Dt,label:"Local",url:e||ml()}),ml=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,sp=e=>e.id===Dt?"local":`host:${e.id}`,fT=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Dt)?.url||ml(),r=Eo(),o=Se(n)||n,s=Se(t)||t,i=G(),a=e.find(u=>u.relay&&sp(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Dr(r,n))return{id:Dt,label:"Local",url:o};const c=e.find(u=>r?Dr(r,Yn(u)):!1);if(c)return{id:c.id,label:c.label,url:Se(Yn(c))||Yn(c)};if(t&&Dr(t,n))return{id:Dt,label:"Local",url:o};const l=e.find(u=>t?Dr(t,u.url):!1);return l?{id:l.id,label:l.label,url:Se(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:Dt,label:"Local",url:o}:{id:"custom",label:hl(s||"Instance"),url:s}},fo=new Map;let gl=0;const po=new Map;let ks=0,yl={byHostId:{},isProbing:!1};const Es=new Set,ho=()=>{yl={byHostId:Object.fromEntries(fo),isProbing:ks>0};for(const e of Es)try{e()}catch{}},pT=e=>(Es.add(e),()=>{Es.delete(e)}),hT=()=>yl,wl=(e,t)=>{fo.set(e,t),ho()},mT=(e,t)=>{po.set(e,++gl),wl(e,t)},ip=e=>{const t=new Set([Dt,...e]);let n=!1;for(const r of Array.from(fo.keys()))t.has(r)||(fo.delete(r),po.delete(r),n=!0);n&&ho()},ap=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",cp=async()=>tn()?Qf().catch(()=>""):"",lp=async(e,t)=>{const n=e.id===Dt?t:e.clientToken||"",r=async()=>{const i=await rp(e.relay,{clientToken:n,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),a={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(a.via="relay"),a};if(e.relay&&!e.apiUrl)return r();const o=Se(tn()?Yn(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const s=await di(o,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(ap(s.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:s.status,latencyMs:s.latencyMs}},up=async e=>{if(!Je())return;const t=++gl;for(const n of e)po.set(n.id,t);ks+=1,ho();try{const n=await cp();await Promise.all(e.map(async r=>{const o=await lp(r,n);po.get(r.id)===t&&wl(r.id,o)}))}finally{ks-=1,ho()}};let sa=!1;const dp=async()=>{if(sa||!Je())return;sa=!0;const e=await ui().catch(()=>null);e&&(ip(e.hosts.map(t=>t.id)),await up([op(e.localOrigin),...e.hosts]))},fp=5e3,pp=1500;let Wo=!1;const hp=async e=>{if(!tn()||Wo)return;const t=`host:${e}`;if(G()===t){Wo=!0;try{const n=await ui().catch(()=>null),r=n?.hosts.find(d=>d.id===e);if(!n||!r?.relay)return;const o=r.apiUrl?Se(r.apiUrl):null;if(o&&o.startsWith("https://"))return;const s=await y("/api/client-auth/connection/candidates").catch(()=>null);if(!s?.ok)return;const i=await s.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=Se(f.url);p&&!c.includes(p)&&c.push(p)}if(c.length===0)return;const l=o&&c.includes(o)?o:c[0];l!==o&&await Yf({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await di(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(u.status==="unreachable"||u.status==="wrong-service"||u.status==="incompatible"||G()!==t)return;ao({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{Wo=!1}}},mp=e=>{typeof window>"u"||window.setTimeout(()=>{hp(e).catch(()=>{})},fp)},gp=async e=>{if(!tn())return;const t=await ui().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 o=`host:${r.id}`;if(G()===o)return;const s=d=>{ao({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:o})},i=()=>{ao({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:o,relay:r.relay??void 0}),mp(r.id)},a=r.apiUrl?Se(Yn(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=di(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),pp))]);if(u){if(c(u)){s(a);return}i();return}i(),l.then(d=>{c(d)&&G()===o&&s(a)})};class Yt extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const gT=e=>e instanceof Yt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),mo=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},bl=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,ia=/^(?:\/\/\?\/)?[A-Za-z]:$/u,yp=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/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]):/,(o,s)=>s.toUpperCase()+":");return n==="/"?"/":bl.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},wp=e=>{if(e==="/"||bl.test(e)||ia.test(e)||yp.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const n=e.slice(0,t);return ia.test(n)?`${n}/`:n},bp=e=>Ye(e)??"",Sp=Ve(m().min(1),dr("type",[v({type:U("idle")}),v({type:U("busy")}),v({type:U("retry"),attempt:C(),message:m(),next:C()})])),Sl=v({messageID:m(),callID:m()}).optional(),Tp=v({id:m().min(1),sessionID:m().min(1),permission:m(),patterns:N(m()),metadata:Ve(m(),ue()),always:N(m()),tool:Sl}),vp=v({id:m().min(1),sessionID:m().min(1),questions:N(v({question:m(),header:m(),options:N(v({label:m(),description:m()})),multiple:Fe().optional()})),tool:Sl}),kp=v({sessions:Ve(m().min(1),v({status:m(),lastUpdateAt:C()})),pending:Ve(m().min(1),v({permissions:N(Tp),questions:N(vp)})).optional(),serverTime:C()}),aa=500,Tl=()=>{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}},yT=()=>Tl(),$e=(e,t)=>{if(!Tl())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>aa&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-aa)},Ep=()=>{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__=Ep);const wT=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();$e(`${e}:start`,n);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return $e(`${e}:end`,{durationMs:Math.round(s-r)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw $e(`${e}:error`,{durationMs:Math.round(s-r),error:o instanceof Error?o.message:String(o)}),o}},Pp=3,Ap=3e4,Ip=32e3,xp=3600*1e3,Cp=600*1e3,Rp=200,Dp=new Set([429,502,503,504]),ut=new Map,fi=e=>JSON.stringify([G(),e]);function Op(){const e=Date.now();for(const[t,n]of ut){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>xp&&ut.delete(t)}}typeof setInterval<"u"&&setInterval(Op,Cp).unref?.();function Mp(e){const t=fi(e);let n=ut.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Ap},ut.set(t,n);ut.size>Rp;){const r=ut.keys().next().value;if(!r)break;ut.delete(r)}return n}function _p(e){e&&ut.delete(fi(e))}function ca(e,t){if(!e)return;const n=Mp(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Lp(t)&&n.consecutiveErrors>=Pp&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Lp(e){return e!==void 0&&Dp.has(e)}function Fp(e){const t=ut.get(fi(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Ip*4),!1):!0:!1}function Up(e){if(!(!e||!Fp(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const la="/api",jp=1e4,Np=4e3;function yn(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object"&&"message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}const Bp=v({reason:m().optional(),isDirectory:Fe().optional()});function Ne(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${yn(e.error)}`);throw n!==void 0&&(r.status=n),r}if(e.data===void 0||e.data===null)throw new Error(`${t} failed: empty response`);return e.data}function an(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${yn(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}const Hp=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ua="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",zp=14;let da=0,qo=0;const $p=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+=ua[t[r]%ua.length];return n},fa=e=>{const t=Date.now();t!==da&&(da=t,qo=0),qo+=1;const n=BigInt(t)*BigInt(4096)+BigInt(qo),r=new Uint8Array(6);for(let s=0;s<6;s+=1)r[s]=Number(n>>BigInt(40-8*s)&BigInt(255));const o=Array.from(r,s=>s.toString(16).padStart(2,"0")).join("");return`${e}_${o}${$p(zp)}`},pa=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(Hp.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}},ha=()=>{try{return Ee().api("/api")}catch{return null}},vl=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)}},Gp=3e4,Wp=e=>(typeof e=="string"?e:e instanceof URL?e.toString():e.url).includes("/event"),Ko=e=>{const t=e.requestTimeoutMs??Gp;return Hu({...e,fetch:async(n,r)=>{const o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(Wp(n)||o==="POST")return y(n,r);const s=vl(t),i=r?.signal!==void 0?r.signal:n instanceof Request?n.signal:void 0,a=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let c,l=null;if(i&&a)c=AbortSignal.any([i,s.signal]);else if(i){const f=new AbortController,p=()=>f.abort(i.reason),g=()=>f.abort(s.signal.reason);i.aborted?p():s.signal.aborted?g():(i.addEventListener("abort",p,{once:!0}),s.signal.addEventListener("abort",g,{once:!0}),l=()=>{i.removeEventListener("abort",p),s.signal.removeEventListener("abort",g)}),c=f.signal}else c=s.signal;const u=()=>{l?.(),s.cleanup()};let d=!1;try{const f=await y(n,{...r,signal:c});return d=f.body!==null,f}catch(f){throw s.signal.aborted&&!i?.aborted?new Error(`OpenCode request timed out after ${t}ms`):f}finally{!d||c.aborted?u():c.addEventListener("abort",u,{once:!0})}}})},cn=e=>e.replace(/\\/g,"/"),ma=400,ga=()=>{const e=Po();return e&&e.runtime?.isDesktop&&e.files?e.files:null},Or=m().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),qp=v({home:Or,chatsRoot:Or.optional(),canonicalChatsRoot:Or.optional(),canonicalLegacyChatsRoot:Or.optional()});class Kp{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;constructor(t=la){const r=ha()||t;this.baseUrl=pa(r),this.client=Ko({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==G())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=ha(),n=pa(t||la);this.baseUrl=n,this.client=Ko({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear()}getSdkClient(){return this.client}getScopedSdkClient(t){return this.getScopedApiClient(t)}getScopedApiClient(t){const n=this.normalizeCandidatePath(t)??t,r=n||"",o=this.scopedClients.get(r);if(o)return o;const s=Ko({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,s),s}normalizeCandidatePath(t){return Ye(t)}deriveHomeDirectory(t){const n=t.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const s=n[1],a=t.slice(s.length+(t.charAt(s.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${s}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${s}/${a[0]}`,username:a[0]}:{homeDirectory:`${s}/`,username:void 0}}const r=t.startsWith("/"),o=t.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const n=this.normalizeCandidatePath(t)??t;this.currentDirectory!==n&&$e("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 s=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await n()}finally{this.currentDirectory===i&&(this.currentDirectory=s)}},o=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const t=new Set,n=o=>{const s=this.normalizeCandidatePath(o);s&&t.add(s)};try{const s=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;s&&(n(s.directory),n(s.worktree),n(s.state))}catch(o){console.debug("Failed to load path info:",o)}if(!t.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);n(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!t.size)try{(await this.listSessions()).forEach(s=>n(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}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 y("/api/fs/directory-stat",{query:{path:n}}),o=Bp.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&o?.isDirectory===!0)return"available";const s=mo(o?.reason);return s==="not-found"||s==="not-directory"?"missing":"unknown"}catch{return"unknown"}}async listSessions(){const t=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(t.data)?t.data:[]}async createSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.create({...r?{directory:r}:{},parentID:t?.parentID,title:t?.title,metadata:t?.metadata});return Ne(o,"session.create")}async getSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.get({sessionID:t,...r?{directory:r}:{}});return Ne(o,"session.get")}async deleteSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.delete({sessionID:t,...r?{directory:r}:{}});return an(o,"session.delete")===!0}async updateSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s={...n.title!==void 0?{title:n.title}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},...n.time?.archived!==void 0&&n.time.archived!==null?{time:{archived:n.time.archived}}:{}},i=await this.client.session.update({sessionID:t,...o?{directory:o}:{},...s});return Ne(i,"session.update")}async getSessionMessages(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.messages({sessionID:t,...o?{directory:o}:{},...typeof n=="number"?{limit:n}:{}});return Ne(s,"session.messages")}async getSessionTodos(t){try{const n=await this.client.session.todo({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(n.error)return[];const r=n.data;return!r||!Array.isArray(r)?[]:r}catch{return[]}}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 Xs(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 o=t.url.substring(r+1),s=atob(o),i=new Uint8Array(s.length);for(let d=0;d<s.length;d++)i[d]=s.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 o=t.url.substring(5,r),s=t.url.substring(r);n=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toNormalizedFilePartInput(t){const n=await this.normalizeFilePart(t);return{...t.id?{id:t.id}:{},type:"file",mime:n.mime,filename:n.filename,url:n.url}}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??fa("msg"),r=[];if(t.prefaceText&&t.prefaceText.trim()&&r.push({type:"text",text:t.prefaceText,synthetic:t.prefaceTextSynthetic!==!1}),t.text&&t.text.trim()){const l={type:"text",text:t.text};r.push(l)}if(t.files&&t.files.length>0)for(const l of t.files){const u=await this.toNormalizedFilePartInput(l);r.push(u)}if(t.additionalParts&&t.additionalParts.length>0)for(const l of t.additionalParts){if(l.text&&l.text.trim()){const u={type:"text",text:l.text};l.synthetic&&(u.synthetic=!0),l.metadata&&(u.metadata=l.metadata),r.push(u)}if(l.files&&l.files.length>0)for(const u of l.files){const d=await this.toNormalizedFilePartInput(u);r.push(d)}}if(t.agentMentions&&t.agentMentions.length>0)for(const l of t.agentMentions)l?.name&&r.push({type:"agent",name:l.name,...l.source?{source:l.source}:{}});if(r.length===0)throw new Error("Message must have at least one part (text or file)");const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;t.format&&console.info("[git-generation][browser] send structured message",{sessionId:t.id,providerID:t.providerID,modelID:t.modelID,agent:t.agent,variant:t.variant,directory:o,baseUrl:this.baseUrl,formatType:t.format.type}),Up(t.providerID),this.assertRuntimeUnchanged(t.runtimeKey);let s;try{const l=await this.client.session.promptAsync({sessionID:t.id,...o?{directory:o}:{},model:{providerID:t.providerID,modelID:t.modelID},agent:t.agent,variant:t.variant,messageID:n,...t.delivery?{delivery:t.delivery}:{},...t.format?{format:t.format}:{},parts:r});if(l.response instanceof Response)s=l.response;else if(l.error){const u=l.response?.status;if(!u){const d=new Error(`Message send transport failure: ${yn(l.error)}`);throw Pd(l.error)?Oc(d):d}s=new Response(JSON.stringify(l.error),{status:u})}else s=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){throw ca(t.providerID),l}if(s.ok)return _p(t.providerID),n;let i="";try{i=await s.text()}catch{}const a=i&&i.trim().length>0?`: ${i.trim()}`:"",c=new Error(`Failed to send message (${s.status})${a}`);throw c.status=s.status,ca(t.providerID,s.status),c}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??fa("msg"),r=[];if(t.files&&t.files.length>0)for(const i of t.files)r.push(await this.toNormalizedFilePartInput(i));const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;this.assertRuntimeUnchanged(t.runtimeKey);const s=await this.client.session.command({sessionID:t.id,...o?{directory:o}:{},command:t.command,arguments:t.arguments??"",model:`${t.providerID}/${t.modelID}`,agent:t.agent,variant:t.variant,...r.length>0?{parts:r}:{},messageID:n});return an(s,"session.command"),n}async abortSession(t){return!!(await this.client.session.abort({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,r=await this.client.session.shell({sessionID:t.sessionId,...n?{directory:n}:{},messageID:t.messageId,agent:t.agent,model:t.model,command:t.command});return Ne(r,"session.shell")}async revertSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.revert({sessionID:t,...s?{directory:s}:{},messageID:n,partID:r});return Ne(i,"session.revert")}async summarizeSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.summarize({sessionID:t,...s?{directory:s}:{},providerID:n,modelID:r});return an(i,"session.summarize")===!0}async unrevertSession(t){const n=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Ne(n,"session.unrevert")}async forkSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.fork({sessionID:t,...o?{directory:o}:{},messageID:n});return Ne(s,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(t){try{const n=this.normalizeCandidatePath(t),r=await this.client.session.status(n?{directory:n}:void 0);if(r.error)return null;const o=Sp.safeParse(r.data);return o.success?o.data:null}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getHostSessionStatusSnapshot(){try{const t=await y("/api/sessions/status",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=kp.safeParse(await t.json().catch(()=>null));return n.success?n.data:null}catch{return null}}async getWebServerSessionActivity(){try{const t=await y("/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 listToolIds(t){try{const n=typeof t?.directory=="string"?t.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(n?{directory:n}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(t,n,r){const o=this.normalizeCandidatePath(r?.directory??null)??this.currentDirectory,s=await this.client.permission.reply({requestID:t,...o?{directory:o}:{},reply:n,...r?.message?{message:r.message}:{}});return an(s,"permission.reply")===!0}async createPermission(t,n,r,o){try{const s=await this.client.v2.session.permission.create({sessionID:t,action:n,resources:r,...o?.id?{id:o.id}:{},...o?.save?{save:o.save}:{},...o?.metadata?{metadata:o.metadata}:{},...o?.source?{source:o.source}:{},...o?.agent?{agent:o.agent}:{}});if(s.error!==void 0)return null;const i=s.data?.data;return i===void 0?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(t,n,r){try{const s=await(r?this.getScopedSdkClient(r):this.client).v2.session.permission.get({sessionID:t,requestID:n});if(s.error===void 0){const i=s.data?.data;if(i!==void 0)return{state:"ok",permission:i}}return s.response?.status===404?{state:"resolved"}:{state:"unknown"}}catch{return{state:"unknown"}}}async listPendingPermissions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",u=await this.client.permission.list(l?{directory:l}:void 0);if(u.error)throw new Error(`permission.list failed: ${yn(u.error)}`);return u.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const u=l.id;typeof u!="string"||u.length===0||a.has(u)||(a.add(u),i.push(l))}return i}async replyToQuestion(t,n,r){const o=!Array.isArray(n)||n.length===0?[]:Array.isArray(n[0])?n:[n],s=this.normalizeCandidatePath(r)??this.currentDirectory,i=await this.client.question.reply({requestID:t,...s?{directory:s}:{},answers:o});return an(i,"question.reply")===!0}async rejectQuestion(t){const n=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return an(n,"question.reject")===!0}async listPendingQuestions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",u=await this.client.question.list(l?{directory:l}:void 0);if(u.error)throw new Error(`question.list failed: ${yn(u.error)}`);return u.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const u=l.id;typeof u!="string"||u.length===0||a.has(u)||(a.add(u),i.push(l))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configCache.get(r);if(o&&o.expiresAt>Date.now())return $e("opencodeClient.getConfig:cacheHit",{directory:n??null}),o.config;const s=this.configInFlight.get(r);if(s)return $e("opencodeClient.getConfig:deduped",{directory:n??null}),s;const i=this.configCacheGeneration,a=(async()=>{$e("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),u=await(n?this.getScopedApiClient(n):this.client).config.get();if(!u.data)throw new Error("Failed to get config");const d=typeof performance<"u"?performance.now():Date.now();return $e("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(d-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:u.data,expiresAt:Date.now()+jp}),u.data})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async updateConfig(t){const n=await this.client.config.update({config:t}),r=Ne(n,"global.config.update");return this.clearConfigCache(),r}async updateConfigPartial(t){const n=await this.getConfig(),r=t(n);return await this.updateConfig(r)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configProvidersInFlight.get(r);if(o)return o;const s=(async()=>{const i=await this.client.config.providers(n?{directory:n}:void 0);return Ne(i,"config.providers")})();this.configProvidersInFlight.set(r,s);try{return await s}finally{this.configProvidersInFlight.get(r)===s&&this.configProvidersInFlight.delete(r)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.listAgentsInFlight.get(r);if(o)return o;const s=(async()=>{const i=n?{directory:n}:void 0,a=await this.client.app.agents(i);if(!a.error&&Array.isArray(a.data)&&a.data.length>0)return a.data;const c=await y("/api/agent",{...n?{query:{directory:n}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${yn(a.error)}`):new Error(`agent.list failed (${c.status})`);const l=await c.json().catch(()=>null);if(!Array.isArray(l))throw new Error("agent.list failed: invalid response");return l})();this.listAgentsInFlight.set(r,s);try{return await s}finally{this.listAgentsInFlight.get(r)===s&&this.listAgentsInFlight.delete(r)}}async listCommandsWithDetails(t,n){const r=this.normalizeCandidatePath(t??null)??this.currentDirectory,o=await this.client.command.list(r?{directory:r}:void 0,{signal:n});return(Ne(o,"command.list")||[]).map(i=>({name:i.name,description:i.description,agent:i.agent,model:i.model,source:i.source,template:i.template}))}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,n=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;$e("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});const r=vl(Np),o=await y(n,{signal:r.signal}).finally(r.cleanup);if($e("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return $e("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,n){const r=ga();if(r?.createDirectory)try{return await r.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}if(n?.asProject){const a=await y(`${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 o={path:t,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await y(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const a=await s.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await s.json()}async cloneRepository(t){const n=await y(`${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 o=`${typeof t=="string"?cn(t.trim()):""}|${n?.respectGitignore?"1":"0"}`,s=Date.now(),i=this.listDirectoryCache.get(o);if(i&&i.expiresAt>s)return i.entries;const a=this.listDirectoryInFlight.get(o);if(a)return a;const l=(async()=>{const u=ga();try{if(u){const w=await u.listDirectory(t||"",n);if(!w||!Array.isArray(w.entries))throw new Yt("Directory listing returned an invalid response",{reason:"invalid-response"});const E=w.entries.map(k=>({name:k.name,path:cn(k.path),isDirectory:!!k.isDirectory,isFile:!k.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:E,expiresAt:Date.now()+ma}),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 y(`${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 Yt(E,{reason:mo(w.reason),status:p.status})}const g=await p.json();if(!g||!Array.isArray(g.entries))throw new Yt("Directory listing returned an invalid response",{reason:"invalid-response"});const b=g.entries;return this.listDirectoryCache.set(o,{entries:b,expiresAt:Date.now()+ma}),b}catch(d){throw console.error("Failed to list directory contents:",d),d}})().finally(()=>{this.listDirectoryInFlight.get(o)===l&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,l),l}async searchFiles(t,n){const r=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():this.currentDirectory,o=r?cn(r):null,s=r?this.getScopedApiClient(r):this.client;try{const i=await s.find.files({query:t,limit:typeof n?.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0,dirs:n?.dirs===!1||n?.type==="file"?"false":"true",type:n?.type});return(Array.isArray(i?.data)?i.data:[]).map(c=>{const l=cn(c),u=l.split("/").filter(Boolean).pop()||l,d=cn(o?`${o}/${l}`:l);return{name:u,path:d,relativePath:l,extension:u.includes(".")?u.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const t=G();if(!t||t==="local"){const n=await Gc();if(n)return n}try{const n=await y(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const o=await n.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}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 y(`${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 qp.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`;console.log("[OpencodeClient] POST",n,"with path:",t);try{const r=await y(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),o=await r.json().catch(()=>null);if(!r.ok){const s=o??{},i=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:t}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const rt=new Kp;let Vo=null,Jo=null,Yo=null;const ya=new Set;let wa=!1;const kl=e=>{if(ya.add(e),wa||typeof window>"u")return;wa=!0;const t=()=>{for(const n of ya)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{}},Vp=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,o=new Set;let s;const i=()=>{if(s=void 0,r.size===0&&o.size===0)return;const c=Array.from(r.entries()),l=Array.from(o);r.clear(),o.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)&&!o.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)||o.add(u)}},a=()=>{s===void 0&&(s=setTimeout(i,0))};return kl(i),{getItem:c=>{if(r.has(c))return r.get(c)??null;if(o.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),o.delete(c),a()},removeItem:c=>{r.delete(c),o.add(c),a()}}},pi=e=>Vp(()=>Al(),e),Jp=e=>{const t=new Map,n=new Set;let r;const o=()=>{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)}},s=()=>{r===void 0&&(r=setTimeout(o,0))};return kl(o),{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),s()},removeItem:i=>{t.delete(i),n.add(i),s()},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}}},El=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},hi=()=>{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}}},Pl=e=>{const t=hi(),n=new Set,r=new Set,o=l=>{if(r.has(l))return null;if(n.has(l))return t.getItem(l);try{return e.getItem(l)}catch{return null}},s=(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:o,setItem:s,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},Yp=()=>{const e=El("localStorage");return e?Pl(e):hi()},Al=()=>(Vo||(Vo=Yp()),Vo),mr=()=>(Yo||(Yo=Jp(Al())),Yo),Qp=()=>{const e=El("sessionStorage");return e?Pl(e):hi()},Xp=()=>(Jo||(Jo=Qp()),Jo),Zp={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.84375rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},bT={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function ba(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Mr={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)"}}},Qo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Mr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Mr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Mr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Mr.tool.inline})},eh=[{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'}],th=[{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'}],Il=e=>Object.fromEntries(e.map(t=>[t.id,t])),nh=Il(eh),rh=Il(th),oh="system",sh="system-mono",ih=e=>typeof e=="string"&&e in nh,ah=e=>typeof e=="string"&&e in rh,Ps="openchamber.mobileKeyboardMode",ch='meta[name="viewport"]',Sa="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",ST=()=>!0;function Ro(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const lh=e=>Ro(e)==="resize-content"?`${Sa}, interactive-widget=resizes-content`:Sa,uh=()=>{if(typeof window>"u")return"resize-content";try{return Ro(localStorage.getItem(Ps))}catch{return"resize-content"}},xl=e=>{const t=Ro(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Ps):localStorage.setItem(Ps,t)}catch{}return t},TT=e=>{const t=xl(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(ch);if(n instanceof HTMLMetaElement){const r=lh(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},Xo=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),dh=new Set(["starting","running","stopping"]),fh=e=>!!e?.tabs.some(t=>wn(t.purpose)&&t.lifecycle!=="exited"),As=512*1024,ph=new TextEncoder,hh=new TextDecoder,Zo=e=>{const t=ph.encode(e);if(t.byteLength<=As)return{text:e,byteLength:t.byteLength};let n=t.byteLength-As;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:hh.decode(r),byteLength:r.byteLength}},Xe=(e,t)=>`${e}\0${t}`,ln=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},mh="terminal-store";let Ta=!1,va=0;const gh=v({type:U("project-action"),actionId:m()}),zn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(va+=1,`tab-${Date.now().toString(36)}-${va.toString(36)}`),es=e=>typeof e=="object"&&e!==null,wn=e=>e.type==="project-action",_r=(e,t)=>wn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,yh=()=>zn().replace(/^tab-/,"exec-"),ka=e=>e==="running"?"running":"exited",wh=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),bh=e=>{const t=new Map,n=[];for(const r of e){if(r.purpose?.type!=="project-action"){n.push(r);continue}const o=t.get(r.purpose.actionId);(!o||r.status==="running"&&o.status!=="running"||r.status===o.status&&((r.createdAt??0)>(o.createdAt??0)||r.createdAt===o.createdAt&&r.sessionId>o.sessionId))&&t.set(r.purpose.actionId,r)}return[...n,...t.values()]},ts={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},Sh=e=>e.trim()||"Action",Th=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},X=bp,go=(e,t)=>`${e}\0${t}`,jn=(e,t,n,r)=>{e.set(go(t,n),r)},Ea=(e,t,n,r)=>{if(!r)return!1;const o=go(t,n),s=e.actionMutationRevisions.get(o)??0,i=r.get(o)??0;return s>i},vh=/^Terminal(?: (\d+))?$/,Pa=e=>{let t=0;for(const n of e){const r=vh.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},vT=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&dh.has(e.lifecycle),kh=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),Lr=(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}),ns=e=>({tabs:[e],activeTabId:e.id}),Ae=(e,t)=>e.tabs.findIndex(n=>n.id===t);let rs=null,os=null;const Eh=e=>{if(os&&rs?.sessions===e.sessions&&rs.nextTabId===e.nextTabId)return os;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt,purpose:o.purpose.type==="project-action"?{type:"project-action",actionId:o.purpose.actionId}:{type:"terminal"}}))}]),nextTabId:e.nextTabId};return rs={sessions:e.sessions,nextTabId:e.nextTabId},os=t,t},Ph=()=>{const e=Bu(()=>Xp());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))}},Yr=gt()(xn(fr((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=X(n);r&&e(o=>{if(o.sessions.has(r))return o;const s=new Map(o.sessions),i=zn(),a=Lr(i,"Terminal");return s.set(r,ns(a)),{sessions:s,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=X(n);return t().sessions.get(r)},getActiveTab:n=>{const r=X(n),o=t().sessions.get(r);if(!o)return;const s=o.activeTabId;return s?o.tabs.find(i=>i.id===s)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(Xe(X(n),r))??Xo,matchesActionExecution:(n,r,o)=>{const s=t().sessions.get(X(n))?.tabs.find(i=>i.id===r);return!!(s&&wn(s.purpose)&&s.purpose.executionId===o)},captureStartedActionMutationRevisions:n=>{const r=X(n),o=go(r,""),s=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(o)&&s.set(i,a);return s},createTab:n=>{const r=X(n);if(!r)return"tab-invalid";const o=zn();return e(s=>{const i=new Map(s.sessions),a=i.get(r),c=s.nextTabId+1,l=Pa(a?.tabs??[]),u=Lr(o,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,ns(u)),{sessions:i,nextTabId:c}}),o},reconcileServerSessions:(n,r,o)=>{const s=X(n);s&&e(i=>{const a=i.sessions.get(s);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,g=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(Xe(s,c[0].id))?c[0]:null;g&&r.length>0&&(c.length=0);for(const R of bh(r)){let we=c.findIndex(L=>L.terminalSessionId===R.sessionId||L.id===R.sessionId);const se=R.purpose,Lo=se?.type==="project-action"&&Ea(i,s,se.actionId,o?.startedActionMutationRevisions);if(se?.type==="project-action"){f.add(se.actionId);const L=c.findIndex(Qe=>wn(Qe.purpose)&&Qe.purpose.actionId===se.actionId);if(Lo){L>=0&&p.add(c[L].id);continue}we<0&&(we=L)}const Pe=se?.type==="project-action"?wh(se,R.status):{type:"terminal"};if(we>=0){const L=c[we];let Qe=L.purpose.type==="project-action"||se?.type==="project-action"?ka(R.status):R.status;L.lifecycle==="stopping"&&R.status==="running"&&L.purpose.type==="project-action"&&Pe.type==="project-action"&&L.purpose.executionId===Pe.executionId&&(Qe="stopping");const on=R.createdAt??L.createdAt,Sr=se?.type==="project-action"&&(L.terminalSessionId!==R.sessionId||Pe.type==="project-action"&&Pe.executionId!==null&&(L.purpose.type!=="project-action"||L.purpose.executionId!==Pe.executionId));if(Sr){const yt=Xe(s,L.id);l=ln(l,Fo=>Fo===yt)??l}const _n=se?.type==="project-action"&&R.status==="running"&&(L.terminalSessionId!==R.sessionId||L.lifecycle!=="running"),Tr=L.purpose.type!==Pe.type||L.purpose.type==="project-action"&&Pe.type==="project-action"&&(L.purpose.actionId!==Pe.actionId||L.purpose.executionId!==Pe.executionId);if((L.terminalSessionId!==R.sessionId||L.lifecycle!==Qe||L.isConnecting!==!1||L.createdAt!==on||Tr)&&(c[we]={...L,terminalSessionId:R.sessionId,lifecycle:Qe,purpose:Pe,isConnecting:!1,createdAt:on},Sr&&Object.assign(c[we],ts),u=!0),_n){const yt={tabId:L.id,createdAt:on,index:we};(!d||yt.createdAt>d.createdAt||yt.createdAt===d.createdAt&&yt.index>d.index)&&(d=yt)}p.add(L.id);continue}const On=se?.type==="project-action"?Sh(se.actionId):g&&c.length===0?g.label:Pa(c),Mn=se?.type==="project-action"?"play":null,Lt={...Lr(R.sessionId,On),terminalSessionId:R.sessionId,lifecycle:se?.type==="project-action"?ka(R.status):R.status,purpose:Pe,iconKey:Mn,createdAt:R.createdAt??Date.now()};if(c.push(Lt),u=!0,se?.type==="project-action"&&R.status==="running"){const L={tabId:Lt.id,createdAt:Lt.createdAt,index:c.length-1};(!d||L.createdAt>d.createdAt||L.createdAt===d.createdAt&&L.index>d.index)&&(d=L)}p.add(Lt.id)}let b=u||!!(g&&r.length>0);const w=c.map(R=>!wn(R.purpose)||f.has(R.purpose.actionId)||p.has(R.id)||R.lifecycle==="starting"||Ea(i,s,R.purpose.actionId,o?.startedActionMutationRevisions)||R.lifecycle==="exited"&&!R.isConnecting?R:(b=!0,{...R,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:R.purpose.actionId,executionId:null}})),E=a?.activeTabId??null,k=E&&w.some(R=>R.id===E)?E:w[0]?.id??null,F=k?w.find(R=>R.id===k):w[0],O=d&&!kh(F)?d.tabId:k;if(!b&&a&&O===a.activeTabId&&w.length===a.tabs.length&&w.every((R,we)=>R===a.tabs[we]))return i;const K=new Map(i.sessions);return K.set(s,{tabs:w,activeTabId:O}),{sessions:K,buffers:l}})},setActiveTab:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);return!a||a.activeTabId===r||Ae(a,r)<0?s:(i.set(o,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,o)=>{const s=X(n),i=o.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(s);if(!l)return a;const u=Ae(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(s,{...l,tabs:d}),{sessions:c}})},setTabIconKey:(n,r,o)=>{const s=X(n);e(i=>{const a=new Map(i.sessions),c=a.get(s);if(!c)return i;const l=Ae(c,r);if(l<0)return i;const u=o?.trim()||null;if(c.tabs[l]?.iconKey===u)return i;const d=[...c.tabs];return d[l]={...d[l],iconKey:u},a.set(s,{...c,tabs:d}),{sessions:a}})},closeTab:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=Ae(a,r);if(c<0)return s;const l=a.tabs[c].purpose;let u=s.actionMutationRevisions,d=s.nextActionMutationRevision;l.type==="project-action"&&(u=new Map(u),jn(u,o,l.actionId,d),d+=1);const f={actionMutationRevisions:u,nextActionMutationRevision:d},p=a.tabs.filter(k=>k.id!==r),g=Xe(o,r),b=s.buffers.has(g)?ln(s.buffers,k=>k===g):null;if(p.length===0){const k=zn(),F=Lr(k,"Terminal");i.set(o,ns(F));const O={sessions:i,nextTabId:s.nextTabId+1};return b&&(O.buffers=b),{...O,...f}}let w=a.activeTabId;a.activeTabId===r&&(w=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),i.set(o,{...a,tabs:p,activeTabId:w});const E={sessions:i};return b&&(E.buffers=b),{...E,...f}})},setTabPurpose:(n,r,o)=>{const s=X(n);e(i=>{const a=i.sessions.get(s);if(!a)return i;const c=Ae(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(o))return i;const u=[...a.tabs],d=o.type==="project-action"&&o.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==o.executionId);u[c]={...l,purpose:o},d&&Object.assign(u[c],ts);const f=Xe(s,r),p=d?ln(i.buffers,w=>w===f)??i.buffers:i.buffers,g=new Map(i.sessions);if(g.set(s,{...a,tabs:u}),o.type!=="project-action")return{sessions:g};const b=new Map(i.actionMutationRevisions);return jn(b,s,o.actionId,i.nextActionMutationRevision),{sessions:g,buffers:p,actionMutationRevisions:b,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,o)=>{const s=X(n),i=t().sessions.get(s);if(!i||Ae(i,r)<0)return null;const a=yh();return e(c=>{const l=c.sessions.get(s);if(!l)return c;const u=Ae(l,r);if(u<0)return c;const d=[...l.tabs];d[u]={...d[u],purpose:{type:"project-action",actionId:o,executionId:a},lifecycle:"starting",terminalSessionId:null,...ts,isConnecting:!1};const f=new Map(c.sessions);f.set(s,{...l,tabs:d});const p=new Map(c.actionMutationRevisions);jn(p,s,o,c.nextActionMutationRevision);const g=Xe(s,r),b=ln(c.buffers,w=>w===g)??c.buffers;return{sessions:f,buffers:b,actionMutationRevisions:p,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0)return a;const d=l.tabs[u];if(!_r(d,s?.expectedExecutionId))return a;const f=o!==null&&d.terminalSessionId!==o,p=o?"running":d.terminalSessionId?"exited":d.lifecycle,g={...d,terminalSessionId:o,lifecycle:p,isConnecting:!1},b=Xe(i,r),w=f&&a.buffers.has(b)?ln(a.buffers,F=>F===b):null,E=[...l.tabs];E[u]=g,c.set(i,{...l,tabs:E});const k={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(wn(d.purpose)){const F=new Map(a.actionMutationRevisions);jn(F,i,d.purpose.actionId,a.nextActionMutationRevision),k.actionMutationRevisions=F,k.nextActionMutationRevision=a.nextActionMutationRevision+1}return w&&(k.buffers=w),k})},setTabLifecycle:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0||!_r(l.tabs[u],s?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===o&&!d.isConnecting)return a;const f=[...l.tabs];if(f[u]={...d,lifecycle:o,isConnecting:!1},c.set(i,{...l,tabs:f}),d.purpose.type!=="project-action"||d.lifecycle===o)return{sessions:c};const p=new Map(a.actionMutationRevisions);return jn(p,i,d.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:p,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0||!_r(l.tabs[u],s?.expectedExecutionId))return a;const d=[...l.tabs];return d[u]={...d[u],isConnecting:o},c.set(i,{...l,tabs:d}),{sessions:c}})},replaceBuffer:(n,r,o,s,i)=>{const a=X(n);e(c=>{const l=c.sessions.get(a);if(!l||Ae(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??Xo;if(d.lastSequence>s)return c;const f=Zo(o),p=d.chunks[0]?.size;if(d.lastSequence===s&&d.byteLength===f.byteLength&&d.chunks.map(w=>w.data).join("")===f.text&&p?.cols===i?.cols&&p?.rows===i?.rows)return c;const g=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:f.text?[{id:g,data:f.text,byteLength:f.byteLength,...i?{size:i}:{}}]:[],byteLength:f.byteLength,lastSequence:s}),{buffers:b,nextChunkId:f.text?g+1:g}})},appendToBuffer:(n,r,o,s,i)=>{if(!o)return;const a=X(n);e(c=>{const l=c.sessions.get(a);if(!l||Ae(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??Xo;if(s!==void 0&&s<=d.lastSequence)return c;const f=c.nextChunkId,p=Zo(o),g=i!==void 0&&i!==o?Zo(i).text:void 0,b={id:f,data:p.text,...g!==void 0?{replayData:g}:{},byteLength:p.byteLength},w=[...d.chunks,b];let E=d.byteLength+b.byteLength;for(;E>As&&w.length>1;){const F=w.shift();if(!F)break;E-=F.byteLength}const k=new Map(c.buffers);return k.set(u,{chunks:w,byteLength:E,lastSequence:s??d.lastSequence}),{buffers:k,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,s={})=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0)return a;const d=l.tabs[u];if(!_r(d,s.expectedExecutionId))return a;const f=s.autoOpened??d.previewAutoOpened,p=s.locked??d.previewUrlLocked;if(d.previewUrl===o&&d.previewAutoOpened===f&&d.previewUrlLocked===p)return a;const g=[...l.tabs];return g[u]={...d,previewUrl:o,previewAutoOpened:f,previewUrlLocked:p},c.set(i,{...l,tabs:g}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=Ae(a,r);if(c<0)return s;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return s;const u=[...a.tabs];return u[c]={...l,previewAutoOpened:!0},i.set(o,{...a,tabs:u}),{sessions:i}})},removeDirectory:n=>{const r=X(n);e(o=>{const s=new Map(o.sessions);s.delete(r);const i=Xe(r,""),a=ln(o.buffers,d=>d.startsWith(i)),c=go(r,"");let l;for(const d of o.actionMutationRevisions.keys())d.startsWith(c)&&(l??=new Map(o.actionMutationRevisions),l.delete(d));const u={sessions:s};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:mh,storage:Ph(),partialize:Eh,merge:(e,t)=>{if(!es(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const a of n){if(!Array.isArray(a)||a.length!==2)continue;const[c,l]=a;if(typeof c!="string"||!es(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],f=new Map;for(const w of u){if(!es(w))continue;const E=typeof w.id=="string"?w.id:null;if(!E)continue;const k=Th(E);k!==null&&(o=Math.max(o,k));const F=k===null?E:zn();f.set(E,F);const O=gh.safeParse(w.purpose).data,K=O?{type:"project-action",actionId:O.actionId,executionId:null}:{type:"terminal"};d.push({id:F,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:K,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,g=p?f.get(p)??p:null,b=g?d.some(w=>w.id===g):!1;r.set(c,{tabs:d,activeTabId:b?g:d[0].id})}const s=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,i=Math.max(t.nextTabId,s,o+1);return{...t,sessions:r,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:i,hasHydrated:!0}}})));if(typeof window<"u"&&!Ta){Ta=!0;const e=Yr.persist,t=()=>{Yr.getState().hasHydrated||Yr.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Ze=20,Ah=8,Aa=4096,Ih=2160*60*6e4,J=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",s=/^[A-Za-z]:\/$/.test(r);return!o&&!s&&(r=r.replace(/\/+$/,"")),r},At=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,xt=(e,t)=>{const n=J(t),r=J(e);if(!n||!r)return!1;const o=At(n),s=At(r);return s===o||s.startsWith(`${o}/`)},Nn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=J(r);if(!s||!o||typeof o!="object")continue;const i=o,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(p=>typeof p=="string").map(p=>J(p)).filter(p=>p.length<=Aa&&xt(p,s)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(p=>typeof p=="string").map(p=>J(p)).filter(p=>p.length<=Aa&&xt(p,s)))).slice(-500):[],l=typeof i.selectedPath=="string"?J(i.selectedPath):null,u=l&&xt(l,s)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>Ih)continue;const f=n[s];if(f){const p=Array.from(new Set([...f.openPaths,...a])),g=Array.from(new Set([...f.expandedPaths,...c])),b=f.selectedPath??u??p[0]??null;n[s]={openPaths:p,selectedPath:b,expandedPaths:g,touchedAt:Math.max(f.touchedAt,d)};continue}n[s]={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((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},un=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},xh=gt()(xn(fr((e,t)=>({byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const o={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Nn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:o,byRoot:Nn(o[n]?.byRoot)}})},addOpenPath:(n,r,o)=>{const s=J((n||"").trim()),i=J((r||"").trim());!s||!i||!o?.allowOutsideRoot&&!xt(i,s)||e(a=>{const c=a.byRoot[s],l=un(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&u&&c.selectedPath===f)return a;const p={...a.byRoot,[s]:{...l,openPaths:d,selectedPath:f}};return{byRoot:et(p,Ze)}})},removeOpenPath:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=At(s),l=g=>At(g)===c,u=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!u)return i;const d=a.openPaths.filter(g=>!l(g)),f=u?d[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeOpenPathsByPrefix:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=At(s),l=c.endsWith("/")?c:`${c}/`,u=g=>{const b=At(g);return b===c||b.startsWith(l)},d=a.openPaths.filter(g=>!u(g));if(d.length===a.openPaths.length)return i;const f=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeExpandedPathsByPrefix:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=At(s),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(f=>{const p=At(f);return p!==c&&!p.startsWith(l)});if(u.length===a.expandedPaths.length)return i;const d={...i.byRoot,[o]:{...a,expandedPaths:u,touchedAt:Date.now()}};return{byRoot:et(d,Ze)}})},setSelectedPath:(n,r,o)=>{const s=J((n||"").trim()),i=r?J(r.trim()):null;!s||i&&!o?.allowOutsideRoot&&!xt(i,s)||e(a=>{const c=a.byRoot[s],l=un(c),u=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&u===c.openPaths)return a;const d={...a.byRoot,[s]:{...l,openPaths:u,selectedPath:i}};return{byRoot:et(d,Ze)}})},ensureSelectedPath:n=>{const r=J((n||"").trim());if(!r)return;const o=t().byRoot[r];if(!o||o.selectedPath)return;const s=o.openPaths[0]??null;s&&t().setSelectedPath(r,s)},toggleExpandedPath:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||!xt(s,o)||e(i=>{const a=i.byRoot[o],c=un(a),u=c.expandedPaths.includes(s)?c.expandedPaths.filter(f=>f!==s):[...c.expandedPaths,s];if(a&&a.expandedPaths===u&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:u}};return{byRoot:et(d,Ze)}})},collapseAllExpandedPaths:n=>{const r=J((n||"").trim());r&&e(o=>{const s=o.byRoot[r];if(!s||s.expandedPaths.length===0)return o;const i={...o.byRoot,[r]:{...un(s),expandedPaths:[]}};return{byRoot:et(i,Ze)}})},expandPath:(n,r)=>{const o=J((n||"").trim()),s=J((r||"").trim());!o||!s||!xt(s,o)||e(i=>{const a=i.byRoot[o],c=un(a);if(c.expandedPaths.includes(s)&&a)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,s]}};return{byRoot:et(u,Ze)}})},expandPaths:(n,r)=>{const o=J((n||"").trim());if(!o||!r||r.length===0)return;const s=r.map(i=>J((i||"").trim())).filter(i=>i&&xt(i,o));s.length!==0&&e(i=>{const a=i.byRoot[o],c=un(a),l=new Set(c.expandedPaths),u=s.filter(f=>!l.has(f));if(u.length===0)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:et(d,Ze)}})}}),{name:"files-view-tabs-store",version:3,storage:pi(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:G(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Nn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,o])=>o.updatedAt-r.updatedAt).slice(0,Ah).map(([r,o])=>[r,{byRoot:Nn(o.byRoot),updatedAt:o.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:{},o=G();return{...t,activeRuntimeKey:o,runtimeSnapshots:r,byRoot:Nn(r[o]?.byRoot)}}}),{name:"files-view-tabs-store"})),Ch=["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"],Rh=/^plugin:[a-z][a-z0-9-]*$/,Dh=new Set(Ch),Oh=e=>Rh.test(e),Mh=e=>Dh.has(e)||Oh(e),kT=e=>e.slice(7),ET=e=>`plugin:${e}`,mi=["session","repository","usage","telemetry","subagents","tasks","mcp","pinned","contextSources"],PT={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",tasks:"chat.workStatus.section.tasks",mcp:"chat.workStatus.section.mcp",pinned:"chat.workStatus.section.pinned",contextSources:"chat.workStatus.section.contextBreakdown"},_h=new Set(mi),Cl=e=>typeof e=="string"&&_h.has(e),Is=e=>{const t=new Set;if(Array.isArray(e))for(const n of e)Cl(n)&&t.add(n);for(const n of mi)t.add(n);return[...t]},AT=(e,t)=>!e?.includes(t),IT=e=>e!=null&&mi.every(t=>e.includes(t)),xT=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),Rl=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e)Cl(r)&&n.add(r);return t||n.delete("telemetry"),[...n]},Lh=e=>Math.min(480,Math.max(200,Math.round(e))),Fh=Te(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),Uh=v({widthByMode:Ve(m(),C().finite().optional().catch(void 0)).catch({}),widthFractionByMode:Ve(m(),C().positive().max(1).optional().catch(void 0)).catch({})}),Dl="ask",Ia=e=>e==="attach"||e==="inline"||e==="ask"?e:Dl;function xa(e){return e==="vim"?"vim":"default"}const dt="all";function Ca(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function Ra(e){return e==="me"||e==="any"?e:"any"}function Ol(e){return typeof e!="string"?dt:e.trim()||dt}function Da(e,t){const n=G();if(Uc(n))return e;const r={...e};return t===dt?delete r[n]:r[n]=t,r}function jh(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 o=Ol(r);o!==dt&&(t[n]=o)}return t}function Oa(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const Fr={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}"}},St={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Ur=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,Nh=e=>{if(!e||typeof e!="object")return!1;const t=e;return Ur(t.completion,Fr.completion)&&Ur(t.error,Fr.error)&&Ur(t.question,Fr.question)&&Ur(t.subtask,Fr.subtask)},Bh=380,Hh=320,zh=1e4,Ml=12,Ma=120,$h=280;let _a=0;const Gh=e=>pe(e),pe=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},_l=e=>Number.isFinite(e)?Math.min(zh,Math.max(Hh,Math.round(e))):Bh,ar=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},yo=e=>{const t=ar(e);return t&&Gh(t)||null},wo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>Ma?t.slice(0,Ma):t:null},gi=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,Ll=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},Wh=(e,t)=>(e==="file"||e==="browser")&&t||e,Fl=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return Wh(e,t)},Ul=(e,t)=>t===e?e:`${e}:${t}`,yi=e=>{const t=ar(e.targetPath),n=e.mode==="terminal"?yo(e.targetDirectory):null,r=Fl(e.mode,t,e.dedupeKey);return{id:Ul(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Ll(e.projectPlanRef),dedupeKey:r,label:wo(e.label),sessionTitleFallback:wo(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:gi(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 o=[...r.entries()].filter(([,i])=>i>t);if(o.length===0)return e;const s=new Set;for(const[i,a]of o){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))s.add(u.id)}return s.size===0?e:e.filter(i=>!s.has(i.id))},Nl=e=>{if(!Array.isArray(e))return[];const t=Me(),n=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o;if(typeof s.mode!="string"||!Mh(s.mode)||t&&s.mode==="browser")continue;const i=ar(typeof s.targetPath=="string"?s.targetPath:null),a=s.mode==="terminal"?yo(s.targetDirectory):null,c=typeof s.projectPlanId=="string"&&s.projectPlanId.trim()?s.projectPlanId.trim():null,l=Ll(s.projectPlanRef);if(s.mode==="plan"&&c!==null!=(l!==null))continue;const u=Fl(s.mode,i,typeof s.dedupeKey=="string"?s.dedupeKey:null),d=Ul(s.mode,u);!d||r.has(d)||(r.add(d),n.push({id:d,mode:s.mode,targetPath:i,targetDirectory:a,projectPlanId:c,projectPlanRef:l,dedupeKey:u,label:wo(typeof s.label=="string"?s.label:null),sessionTitleFallback:wo(typeof s.sessionTitleFallback=="string"?s.sessionTitleFallback:null),readOnly:s.readOnly===!0,stagedDiff:s.stagedDiff===!0,diffScope:gi(s.diffScope)??(s.stagedDiff===!0?"staged":"working"),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}))}return n},Pn=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,Nt=e=>{if(e){const t=Nl(e.tabs),n=Pn(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()}},qh=(e,t,n)=>{const r=n?.reveal!==!1,o=yi(t),s=o.mode==="file"&&o.targetPath?e.tabs.filter(u=>!(u.mode==="file"&&!u.targetPath)):e.tabs,i=s.findIndex(u=>u.id===o.id),a=i===-1?[...s,o]:s.map((u,d)=>d===i?{...u,mode:o.mode,targetPath:o.targetPath||u.targetPath,targetDirectory:o.targetDirectory,projectPlanId:o.projectPlanId??u.projectPlanId,projectPlanRef:o.projectPlanRef??u.projectPlanRef,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||u.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:u),c=r?o.id:e.activeTabId??o.id,l=jl(a,Ml,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:Pn(l,c),touchedAt:Date.now()}},Kh=(e,t)=>{const n=new Set(t),r=e.tabs.filter(l=>n.has(l.id)),o=e.tabs.filter(l=>!n.has(l.id));if(o.length===e.tabs.length)return e;if(!(e.activeTabId?n.has(e.activeTabId):!1))return{...e,tabs:o,activeTabId:Pn(o,e.activeTabId),isOpen:o.length>0?e.isOpen:!1,touchedAt:Date.now()};const i=r.find(l=>l.id===e.activeTabId)?.mode??null,a=i?o.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=yi({mode:"file"});return{...e,tabs:[...o,l],activeTabId:l.id,isOpen:e.isOpen,touchedAt:Date.now()}}return{...e,tabs:o,activeTabId:c?.id??Pn(o,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},Vh=(e,t,n)=>{if(t===n)return e;const r=e.tabs.findIndex(a=>a.id===t),o=e.tabs.findIndex(a=>a.id===n);if(r===-1||o===-1)return e;const s=[...e.tabs],[i]=s.splice(r,1);return i?(s.splice(o,0,i),{...e,tabs:s,touchedAt:Date.now()}):e},Jh=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),ss=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=pe(r);if(!s||!o||typeof o!="object")continue;const i=o;let a=Nl(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=[yi({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=Pn(a,c),u=jl(a,Ml,l),d={},f={},p=Uh.parse(o);for(const g of Fh.options){const b=p.widthByMode[g],w=p.widthFractionByMode[g];b!==void 0&&(d[g]=_l(b)),w!==void 0&&(f[g]=w)}n[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:Pn(u,l),widthByMode:d,widthFractionByMode:f,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},Bt=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},T=gt()(xn(fr((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:$h,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:Is([]),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,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,showOpenCodeRestartConfirm:!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:oh,monoFont:sh,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:uh(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",toolJsonViewMode:"summary",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:dt,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:{...St.completion},error:{...St.error},question:{...St.question},subtask:{...St.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!Yd(),agentControlToolEnabled:!0,agentWebToolEnabled:!0,agentMemoryToolEnabled:!1,agentMemoryFeatureAvailable:!1,routingFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:Dl,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((o,s)=>typeof o=="string"&&o.trim()!==""&&n.indexOf(o)===s):[];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:Lh(n)})},openContextSurface:(n,r)=>{const o=pe((n||"").trim());if(!o)return;const s=t(),i=s.contextPanelByDirectory[o],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=Yr.getState().getDirectoryState(f);if(fh(p))return}s.openContextPanelTab(o,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),s.closeContextPanel(o);return}r==="file"&&!s.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);s.setActiveContextPanelTab(o,d.id);return}r!=="chat"&&s.openContextPanelTab(o,{mode:r})},openContextPanelTab:(n,r,o)=>{const s=pe((n||"").trim());if(!s)return;const i=r.mode==="terminal"?{...r,targetDirectory:yo(r.targetDirectory)===s?null:yo(r.targetDirectory)}:r,a=i.mode==="file"&&!!i.targetPath&&o?.reveal!==!1;e(c=>{const l=c.contextPanelByDirectory[s],u=Nt(l),d={...c.contextPanelByDirectory,[s]:qh(u,i,o)};return{contextPanelByDirectory:Bt(d,20),contextEditorVisible:a||c.contextEditorVisible}})},openContextDiff:(n,r,o=!1,s=null)=>{const i=pe((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=gi(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const o=pe((n||"").trim()),s=ar(r);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,s)=>{const i=pe((n||"").trim()),a=ar(r),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,l=Number.isFinite(s)?Math.max(1,Math.trunc(s)):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=pe((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const o=pe((n||"").trim()),s=(r||"").trim();!o||!s||Me()||t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:s,label:null})},openNewContextBrowserTab:n=>{const r=pe((n||"").trim());!r||Me()||(_a+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${_a}`,label:null}))},openContextBrowser:(n,r="",o)=>{const s=pe((n||"").trim());if(!s||Me())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(s,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},o)},setContextPanelTabTargetPath:(n,r,o)=>{const s=pe((n||"").trim()),i=(r||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:Jh(c,i,o)}}:a})},setActiveContextPanelTab:(n,r)=>{const o=pe((n||"").trim()),s=(r||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Nt(a),l=c.tabs.find(f=>f.id===s);if(!l)return i;const u=l.mode==="file"&&!!l.targetPath;if(c.activeTabId===s&&c.isOpen)return u?{contextEditorVisible:!0}:i;const d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:s,touchedAt:Date.now(),tabs:c.tabs.map(f=>f.id===s?{...f,touchedAt:Date.now()}:f)}};return{contextPanelByDirectory:Bt(d,20),contextEditorVisible:u||i.contextEditorVisible}})},reorderContextPanelTabs:(n,r,o)=>{const s=pe((n||"").trim()),i=(r||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],u=Nt(l);if(!u.tabs.some(p=>p.id===i)||!u.tabs.some(p=>p.id===a))return c;const d=Vh(u,i,a);if(d.tabs===u.tabs)return c;const f={...c.contextPanelByDirectory,[s]:d};return{contextPanelByDirectory:Bt(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const o=pe((n||"").trim()),s=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!o||s.length===0)return;const i=s.map(a=>t().contextPanelByDirectory[o]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[o],l=Nt(c);if(!l.tabs.some(g=>s.includes(g.id)))return a;const u=Kh(l,s),d=u.tabs.find(g=>g.id===u.activeTabId),f=u.isOpen&&d?.mode==="file"&&!d.targetPath,p={...a.contextPanelByDirectory,[o]:u};return{contextPanelByDirectory:Bt(p,20),contextEditorTreeVisible:f||a.contextEditorTreeVisible}});for(const a of i)a.mode==="file"&&a.targetPath&&xh.getState().removeOpenPath(o,a.targetPath)},closeContextPanel:n=>{const r=pe((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...Nt(s),isOpen:!1}};return{contextPanelByDirectory:Bt(i,20)}})},toggleContextPanelExpanded:n=>{const r=pe((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r],i=Nt(s),a={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Bt(a,20)}})},setContextPanelWidth:(n,r,o,s)=>{const i=pe((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=Nt(c),u=_l(o),d={...l.widthFractionByMode};s!==void 0&&Number.isFinite(s)&&s>0?d[r]=Math.min(1,u/s):delete d[r];const f={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:Bt(f,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(o=>o.workStatusExpandedSections[n]===r?o:{workStatusExpandedSections:{...o.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(o=>{const s=o.workStatusHiddenSections,i=s.includes(n);return r===!i?o:{workStatusHiddenSectionsExplicit:!0,workStatusHiddenSections:r?s.filter(a=>a!==n):[...s,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)],workStatusHiddenSectionsExplicit:!0})},setWorkStatusSectionOrder:n=>{e({workStatusSectionOrder:Is(n)})},setContextRailSurfaceVisible:(n,r)=>{e(o=>{const s=o.contextRailHiddenSurfaces,i=s.includes(n);return r===!i?o:{contextRailHiddenSurfaces:r?s.filter(a=>a!==n):[...s,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,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?o:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:o})},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,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isArchivePageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{worktreesPageProjectId:null})},setOpenGuestPage:n=>{e(n?{openGuestPageId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{openGuestPageId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.worktreesPageProjectId&&!n.isMultiRunLauncherOpen&&!n.openGuestPageId||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!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})},setShowOpenCodeRestartConfirm:n=>{e({showOpenCodeRestartConfirm: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),o=Math.max(9,Math.min(52,r));e({terminalFontSize:o})},setTerminalShell:n=>{e({terminalShell:n})},setTerminalLoginShells:n=>{e({terminalLoginShells:[...new Set(n)]})},setEditorFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(32,r));e({editorFontSize:o})},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,o=n/100,s=Object.entries(Zp);if(o===1){r.style.removeProperty("font-size");for(const[i]of s)r.style.removeProperty(ba(i));return}r.style.fontSize=`${o*100}%`;for(const[i]of s)r.style.removeProperty(ba(i))},applyPadding:()=>{const{padding:n}=t(),r=document.documentElement,o=n/100;if(o===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 s=Math.sqrt(o);r.style.setProperty("--padding-scale",s.toString());const i=1+(o-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(o=>({diffFileLayout:{...o.diffFileLayout,[n]:r}}))},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:Ca(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:Ra(n)})},setLinearIssueListTeamId:n=>{const r=Ol(n);e(o=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:Da(o.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=G();e(r=>({linearIssueListTeamId:Uc(n)?dt:r.linearIssueListTeamIdByRuntime[n]??dt}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:Oa(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:dt,linearIssueListTeamIdByRuntime:Da(n.linearIssueListTeamIdByRuntime,dt),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(o=>o.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...o.favoriteModels]})},reorderFavoriteModel:(n,r,o,s)=>{e(i=>{const a=i.favoriteModels.findIndex(d=>d.providerID===n&&d.modelID===r),c=i.favoriteModels.findIndex(d=>d.providerID===o&&d.modelID===s);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 o=n.filter(i=>typeof i=="string"&&i.length>0),s=r.providerOrder;return s.length===o.length&&s.every((i,a)=>i===o[a])?r:{providerOrder:o}})},toggleHiddenModel:(n,r)=>{e(o=>o.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...o.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},hideAllModels:(n,r)=>{e(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...s]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(o=>o.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>o.collapsedModelProviders.includes(r)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...o.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const o=Array.from(new Set(n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean)));o.length!==0&&e(s=>{const i=new Set(o),a=s.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...o]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},addRecentModel:(n,r)=>{e(o=>{const s=o.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...s].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>{if(o.recentAgents.includes(r))return o;const s=o.recentAgents;return{recentAgents:[r,...s].slice(0,5)}})},addRecentEffort:(n,r,o)=>{const s=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!s||!i)return;const a=`${s}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.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 o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{e(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:"",...n?{isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,openGuestPageId:null}:{}}))},openMultiRunLauncher:()=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},openMultiRunLauncherWithPrompt:n=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!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})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setAgentMemoryFeatureAvailable:n=>{e({agentMemoryFeatureAvailable:n})},setRoutingFeatureAvailable:n=>{e({routingFeatureAvailable:n})},setProjectContextSidebarWidth:n=>{e({projectContextSidebarWidth:n})},markAgentMemoryViewed:(n,r)=>{e(o=>({agentMemoryViewedAt:r>(o.agentMemoryViewedAt[n]??0)?{...o.agentMemoryViewedAt,[n]:r}:o.agentMemoryViewedAt}))},setProjectContextTab:n=>{e({projectContextTab:n})},setInputSpellcheckEnabled:n=>{e({inputSpellcheckEnabled:n})},setLargeTextPasteBehavior:n=>{e({largeTextPasteBehavior:Ia(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(o=>({shortcutOverrides:{...o.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{e(r=>{const o={...r.shortcutOverrides};return delete o[n],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:n=>{e({fileEditorKeymap:xa(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:pi(),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 o of Object.values(r)){if(!o||typeof o!="object")continue;const s=o,i=s.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(s.tabs))continue;const a=new Set,c=[];for(const l of s.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(s.tabs=c,typeof s.activeTabId=="string"&&s.activeTabId.startsWith("preview")){const l=c.find(u=>typeof u.id=="string");s.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 o=localStorage.getItem("openchamber:files:auto-save-enabled");o!==null&&(r=o!=="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&&Nh(n.notificationTemplates)&&(n.notificationTemplates={completion:{...St.completion},error:{...St.error},question:{...St.question},subtask:{...St.subtask}}),t<3){const r=new Set([90,120,180,220]),o=n.memoryLimitHistorical,s=n.memoryLimitActiveSession;typeof o=="number"&&!r.has(o)?n.messageLimit=o:typeof s=="number"&&!r.has(s)&&(n.messageLimit=s),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if(delete n.isRightSidebarOpen,delete n.rightSidebarWidth,delete n.rightSidebarTab,n.contextPanelByDirectory=ss(n.contextPanelByDirectory),t<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,o={};for(const[s,i]of Object.entries(r))typeof s=="string"&&typeof i=="string"&&(o[s]=i);n.shortcutOverrides=o}return t<6&&(n.contextPanelByDirectory=ss(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=ss(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Ca(n.linearIssueListStatus),n.linearIssueListAssignee=Ra(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=jh(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=Oa(n.linearIssueListPriority),n.fileEditorKeymap=xa(n.fileEditorKeymap),n.largeTextPasteBehavior=Ia(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,showOpenCodeRestartConfirm:e.showOpenCodeRestartConfirm,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,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,agentMemoryToolEnabled:e.agentMemoryToolEnabled,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"})),Yh=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},Qh=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Xh=e=>{const t=T.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Zh=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=Qh(t);return Yh(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},em=(e,t)=>{const n=e??{};return t<2&&(n.projectSortOrder="manual"),t<3&&n.projectSortOrder==="recent"&&(n.projectSortOrder="manual"),t<4&&delete n.displayMode,n},xs=gt()(fr(e=>({projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sessionGroupingMode:"by-worktree",setSessionGroupingMode:t=>e({sessionGroupingMode:t}),stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,projectSortOrder:"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})}),{name:"session-display-mode",version:5,migrate:em})),Bl="directoryTreeShowHidden",Cs="directory-show-hidden-change",Rs=()=>{if(typeof window>"u")return!0;try{const e=mr().getItem(Bl);return e===null?!0:e==="true"}catch{return!0}},tm=()=>{typeof window>"u"||window.dispatchEvent(new Event(Cs))},nm=()=>Rs(),rm=(e,t={})=>{if(!(typeof window>"u")){try{mr().setItem(Bl,e?"true":"false"),tm()}catch{}t.persist!==!1&&ft({directoryShowHidden:e})}},CT=()=>{const e=bc.c(2),[t,n]=no.useState(Rs);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(Rs())};return window.addEventListener("storage",s),window.addEventListener(Cs,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Cs,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),no.useEffect(r,o),t},Hl=[{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"}],om=new Map(Hl.map(e=>[e.name,e])),RT=e=>om.get(e),DT=Hl.map(e=>({type:"command",name:e.name})),OT="terminal-box",MT="book-open",_T=e=>`${e.type}:${e.name}`,LT=(e,t)=>e.type===t.type&&e.name===t.name,FT=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},sm=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=o.type==="command"||o.type==="skill"?o.type:null,i=typeof o.name=="string"?o.name.trim():"";if(!s||!i)continue;const a=`${s}:${i}`;n.has(a)||(n.add(a),t.push({type:s,name:i}))}return t},zl="filesViewShowGitignored",Ds="files-view-show-gitignored-change",Os=()=>{if(typeof window>"u")return!1;try{return mr().getItem(zl)==="true"}catch{return!1}},im=()=>{typeof window>"u"||window.dispatchEvent(new Event(Ds))},am=()=>Os(),cm=(e,t={})=>{if(!(typeof window>"u")){try{mr().setItem(zl,e?"true":"false"),im()}catch{}t.persist!==!1&&ft({filesViewShowGitignored:e})}},UT=()=>{const e=bc.c(2),[t,n]=no.useState(Os);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(Os())};return window.addEventListener("storage",s),window.addEventListener(Ds,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Ds,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),no.useEffect(r,o),t},$l="session",Gl=40,lm=1,um=100,Wl=e=>e==="global"||e==="session",wi=e=>e!=null&&Number.isInteger(e)&&e>=lm&&e<=um,dm=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],bi=e=>e==="auto"||typeof e=="string"&&dm.includes(e),bn="openchamber-input-history.v1",fm=8,pm=50,hm=[40,25,10,5,1],is=Object.freeze([]);let lt=null,La=0;const Qn=(e=$l,t=Gl)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),ql=()=>(La+=1,Date.now()*1e3+La),Kl=e=>JSON.stringify([e]),Ms=(e,t,n)=>JSON.stringify([e,t,n]),Si=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},mm=()=>{const e=Si(),t=Ge?JSON.stringify(Xr(Ge.base)):lt;if(!e)return t;try{return e.getItem(bn)??(Ge?null:lt)}catch{return t}},Fa=Ve(m(),ue()),gm=v({key:m().min(1),source:Qt([U("file-url"),U("vscode-file")]),filename:m().min(1),mimeType:m().min(1),size:C().finite().nonnegative(),reference:m().min(1)}),ym=v({text:m(),attachmentKeys:N(m()),restorableAttachments:N(gm),submittedAt:C().finite().nonnegative()}),wm=v({touchedAt:C().finite().nonnegative(),entries:N(ue())}),bm=(e,t)=>{try{const n=JSON.parse(e),o=(t===1?ji([m().trim().min(1)]):ji([m().trim().min(1),m().trim().min(1),m().trim().min(1)])).safeParse(n);if(!o.success)return null;if(t===3){const s=Ye(o.data[1]);if(!s||s!==o.data[1])return null}return o.data}catch{return null}},Ua=(e,t)=>{const n=[];for(const[r,o]of Object.entries(e)){if(!bm(r,t))continue;const s=wm.safeParse(o);if(!s.success)continue;const i=s.data.entries.map(a=>ym.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:s.data.touchedAt,entries:i}])}return Object.fromEntries(n)},Sm=()=>{const e=mm();if(e===null)return Qn();try{const t=JSON.parse(e),n=v({version:U(1),entryLimit:C().int().optional(),scope:Qt([U("global"),U("session")]).optional(),global:Fa.default({}),session:Fa.default({})}).safeParse(t);return n.success?{entryLimit:wi(n.data.entryLimit)?n.data.entryLimit:Gl,scope:n.data.scope??$l,globalBuckets:Ua(n.data.global,1),sessionBuckets:Ua(n.data.session,3)}:Qn()}catch{const t=Si();if(t)try{t.removeItem(bn)}catch{}return lt=null,Qn()}};let Ge=null,Qr=Qn();const ja=(e,t,n)=>{const r={...e};for(const o of new Set([...Object.keys(t),...Object.keys(n)])){if(JSON.stringify(t[o])===JSON.stringify(n[o]))continue;const s=n[o];if(!s){delete r[o];continue}const i=new Set((t[o]?.entries??[]).map(u=>JSON.stringify(u))),a=new Set(s.entries.map(u=>JSON.stringify(u))),c=(e[o]?.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 s.entries){const d=JSON.stringify(u);!i.has(d)&&!l.has(d)&&c.push(u)}c.sort((u,d)=>u.submittedAt-d.submittedAt),r[o]={touchedAt:Math.max(s.touchedAt,e[o]?.touchedAt??0),entries:c}}return r},$n=()=>{const e=Sm();if(Qr=e,!Ge)return e;const{base:t,value:n}=Ge;return _s({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)})},Vl=(e,t)=>e.slice(Math.max(0,e.length-t)),Na=(e,t,n)=>{const r=Object.entries(e).map(([o,s])=>[o,{touchedAt:s.touchedAt,entries:Vl(s.entries,n)}]).sort((o,s)=>s[1].touchedAt-o[1].touchedAt).slice(0,t);return Object.fromEntries(r)},_s=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Na(e.globalBuckets,fm,t),sessionBuckets:Na(e.sessionBuckets,pm,t)}),Xr=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Ba=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Gn=e=>{const t=_s(e),n=JSON.stringify(Xr(t));Ge={base:Qr,value:t};const r=Si();if(!r)return lt=n,t;try{return r.setItem(bn,n),Ge=null,lt=n,t}catch(i){if(!(i instanceof Error)||!Ba(i))return lt=n,t}try{r.removeItem(bn)}catch{}for(const i of hm){const a=_s(t,i),c=JSON.stringify(Xr(a));try{return r.setItem(bn,c),Ge=null,lt=c,a}catch(l){if(!(l instanceof Error)||!Ba(l))return Ge={base:Qr,value:a},lt=c,a}}const o=Qn(t.scope,t.entryLimit),s=JSON.stringify(Xr(o));try{r.setItem(bn,s),Ge=null}catch{Ge={base:Qr,value:o}}return lt=s,o},Tm=(e,t,n)=>{const r=e.trim(),o=Ye(t),s=n.trim();return!r||!o||!s?null:{runtimeKey:r,directory:o,sessionId:s}},Jl=e=>e.source==="vscode"&&e.vscodeSource==="file"?Ye(e.vscodePath??null):e.dataUrl.trim()||null,vm=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Ls=e=>{const t=Jl(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("|")},km=e=>{const t=Jl(e);return!t||!vm(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Ls(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Ls(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},Em=(e,t)=>({text:e,attachmentKeys:t.map(Ls),restorableAttachments:t.map(km).filter(n=>n!==null)}),Pm=(e,t)=>e.length===t.length&&e.every((n,r)=>{const o=t[r];return o!==void 0&&n.key===o.key&&n.source===o.source&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.size===o.size&&n.reference===o.reference}),Am=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&Pm(e.restorableAttachments,t.restorableAttachments),Ha=(e,t,n,r)=>{const o=e?[...e.entries]:[];for(const s of t){const i=o.at(-1);Am(i,s)||o.push({text:s.text,attachmentKeys:[...s.attachmentKeys],restorableAttachments:s.restorableAttachments.map(a=>({...a})),submittedAt:ql()})}return{touchedAt:n,entries:Vl(o,r)}},Im=Gn($n()),Wn=gt(e=>({...Im,applyEntryLimit:t=>{wi(t)&&e(n=>{const r=$n();if(r.entryLimit===t)return{...n,...r};const o=Gn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},applyScope:t=>{Wl(t)&&e(n=>{const r=$n();if(r.scope===t)return{...n,...r};const o=Gn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const o=$n(),s=ql(),i=Kl(t.runtimeKey),a=Ms(t.runtimeKey,t.directory,t.sessionId),c=Gn({entryLimit:o.entryLimit,scope:o.scope,globalBuckets:{...o.globalBuckets,[i]:Ha(o.globalBuckets[i],n,s,o.entryLimit)},sessionBuckets:{...o.sessionBuckets,[a]:Ha(o.sessionBuckets[a],n,s,o.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=$n(),o=Ms(t.runtimeKey,t.directory,t.sessionId);if(!(o in r.sessionBuckets))return{...n,...r};const s={...r.sessionBuckets};delete s[o];const i=Gn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:s});return{...n,...i}})}})),jT=(e,t)=>t?e.scope==="session"?e.sessionBuckets[Ms(t.runtimeKey,t.directory,t.sessionId)]?.entries??is:e.globalBuckets[Kl(t.runtimeKey)]?.entries??is:is,xm=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Cm=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
3
3
  `).replace(/^\n+|\n+$/g,"");if(!t||!n||!r)return null;const o=Math.max(1,Math.floor(e.startLine));return{terminalId:t,terminalLabel:n,startLine:o,endLine:Math.max(o,Math.floor(e.endLine)),text:r}},Rm=(e,t)=>{const n=t.map(Cm).filter(s=>s!==null);if(n.length===0)return e;const o=["<terminal_context>",...n.flatMap((s,i)=>[`- ${s.terminalLabel} lines ${s.startLine}-${s.endLine}:`,...s.text.split(`
4
4
  `).map((a,c)=>` ${s.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
5
5
  `);return e.trim()?`${e.trim()}