@pi-chamber/web 1.0.5-rc.3 → 1.0.5-rc.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 (52) hide show
  1. package/dist/assets/{DiagramView-DxLAcmg-.js → DiagramView-CiAfS52a.js} +1 -1
  2. package/dist/assets/{DiffView-BzVBoNCp.js → DiffView-CEAAlJ4b.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-2KqGdUdB.js → FileSaveConflictDialog-yvhJRLj7.js} +1 -1
  4. package/dist/assets/{FilesView-3spQTRpf.js → FilesView-DAEtByHZ.js} +1 -1
  5. package/dist/assets/{GitHubDetailScaffold-C2d4WqKe.js → GitHubDetailScaffold-CtFeWl_3.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-BDwZtk0x.js → GitHubLinkPicker-BEB6WkNO.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-Dor_K85Y.js → GitHubListPrimitives-BilsEUSt.js} +1 -1
  8. package/dist/assets/{GitView-CSAJagWK.js → GitView-C19-aC7A.js} +3 -3
  9. package/dist/assets/{IssuesSurface-euZzv2L9.js → IssuesSurface-zvICpciG.js} +2 -2
  10. package/dist/assets/{JsonTreeView-Drmn7tIN.js → JsonTreeView-D99tzKTq.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-Bq0p5v9N.js → MarkdownRendererImpl-CRfobHRu.js} +1 -1
  12. package/dist/assets/{PatchDiff-BegAimf3.js → PatchDiff-Fbf3Mt_o.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-DgU2Zcmr.js → PierreDiffViewer-C2nEOax_.js} +1 -1
  14. package/dist/assets/{PullRequestsSurface-CnGgmkuf.js → PullRequestsSurface-DMWgrwmP.js} +2 -2
  15. package/dist/assets/{SessionSwitcherContent-Cq5LIBuG.js → SessionSwitcherContent-DByH7H41.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-Dpob2_y5.js → SessionSwitcherDropdown-D-kE5IJ_.js} +2 -2
  17. package/dist/assets/{SessionUnreadDot-BPKnpGAh.js → SessionUnreadDot-DNbvtMOd.js} +1 -1
  18. package/dist/assets/{SettingsView-DcOJRyym.js → SettingsView-BhXkRsZT.js} +4 -4
  19. package/dist/assets/{SettingsWindow-C2RB0AjV.js → SettingsWindow-B1_mMQyb.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-DmzNX2QX.js → ToolOutputDialog-BO3d88qF.js} +1 -1
  21. package/dist/assets/{ToolPartDiffPreview-CO5Gg17_.js → ToolPartDiffPreview-BgbLfmmd.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-CJ1m8JE-.js → VirtualizedFileDiff-D7kxYBDG.js} +1 -1
  23. package/dist/assets/{collapsible-BOcd0lzY.js → collapsible-9MJx4VhA.js} +1 -1
  24. package/dist/assets/{computeVirtualFileMetrics-8mC_o5zA.js → computeVirtualFileMetrics-8pZIB8G2.js} +1 -1
  25. package/dist/assets/{contextFileOpenGuard-CRboGmXF.js → contextFileOpenGuard-BNtzRA7B.js} +1 -1
  26. package/dist/assets/{gitStatusPredicates-BqV-kOGY.js → gitStatusPredicates-B7adeDSu.js} +1 -1
  27. package/dist/assets/{githubLink-DSgdECMr.js → githubLink-DVRaj2ms.js} +1 -1
  28. package/dist/assets/{index-B3qmI8VW.js → index-B7HgGIB0.js} +1 -1
  29. package/dist/assets/{index-DsQIBAWK.css → index-BwoW_-vk.css} +1 -1
  30. package/dist/assets/{index-DWSrsQWl.js → index-D4n3TVp2.js} +2 -2
  31. package/dist/assets/{main-HPNu-7DG.js → main-BWWBkkNK.js} +4 -4
  32. package/dist/assets/{main-Bn93XwxQ.js → main-C-nlfc4f.js} +2 -2
  33. package/dist/assets/{markdownCore-Csm6UEBe.js → markdownCore-B6YzRefV.js} +1 -1
  34. package/dist/assets/{miniChat-C3W5IvM4.js → miniChat-b8DbqBHL.js} +2 -2
  35. package/dist/assets/{mobile-COEEitAQ.js → mobile-BDDUPrDt.js} +2 -2
  36. package/dist/assets/{nativeFileSave-CFuugNKV.js → nativeFileSave-BJsGPh58.js} +1 -1
  37. package/dist/assets/{pi-session-focus-preference-DQjF7Nh1.js → pi-session-focus-preference-gLalTsQo.js} +1 -1
  38. package/dist/assets/{renderDiffWithHighlighter-BBwvKSDe.js → renderDiffWithHighlighter-BamhejwM.js} +1 -1
  39. package/dist/assets/{renderElectronMiniChatApp-7vIiCPiK.js → renderElectronMiniChatApp-CiWui-Wg.js} +2 -2
  40. package/dist/assets/{renderFileWithHighlighter-VOwWxIE1.js → renderFileWithHighlighter-CFlqKZg7.js} +1 -1
  41. package/dist/assets/{renderMobileApp-BQDG02OP.js → renderMobileApp-C27Xb0G7.js} +3 -3
  42. package/dist/assets/{runtimeEndpointReset-CzwDZ_EP.js → runtimeEndpointReset-O-OHpVl7.js} +6 -6
  43. package/dist/assets/{runtimeSurface-Der4qUnI.js → runtimeSurface-k1Eit61v.js} +1 -1
  44. package/dist/assets/{useAppFontEffects-BQ1JUauS.js → useAppFontEffects-B6Bro-YP.js} +77 -77
  45. package/dist/assets/{useFilesViewSearch-BYG2TZWz.js → useFilesViewSearch-jAAdikwo.js} +1 -1
  46. package/dist/assets/{useGitHubRemoteSearch-Bo1LF-x_.js → useGitHubRemoteSearch-BoCzq4zs.js} +1 -1
  47. package/dist/assets/{useSwitcherItems-q0ZavMJb.js → useSwitcherItems-C8IKoSTL.js} +1 -1
  48. package/dist/assets/{web-components-CJ0xIy7r.js → web-components-DTteDmIQ.js} +1 -1
  49. package/dist/index.html +4 -4
  50. package/dist/mini-chat.html +3 -3
  51. package/dist/mobile.html +3 -3
  52. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nativeFileSave-CFuugNKV.js","assets/vendor-boot-EC6IyLt1.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js"])))=>i.map(i=>d[i]);
2
- import{c as Br,d as Cr,p as qn}from"./vendor-zustand-CUi8eEds.js";import{_ as yc}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as bc}from"./vendor-clsx-B-dksMZM.js";import{t as Ac}from"./vendor-tailwind-merge-CPcsbTWB.js";import{F as _s}from"./vendor-fuse.js-Dw8P0qyA.js";import{R as Ia}from"./vendor-react-DASdDPIk.js";const fr=1,Ec="pichamber-relay-v1",xs=1,Os=12,mr=1+Os,Fr=64*1024,yr=5,ao=128,Ns=0,Ls=1,zt=4,wc=1+zt,tn=Fr-yr-wc,_={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Bc=new Set(Object.values(_)),Cc=e=>Bc.has(e),At={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},$e=globalThis.crypto.subtle,Us={name:"ECDH",namedCurve:"P-256"},Hs=16,Po=32,vc=16,rn=4,js=8;class tt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const kc=()=>$e.generateKey(Us,!0,["deriveBits"]),Dc=async e=>{const t=await $e.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Sc=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new tt("invalid ECDH public key JWK");try{return await $e.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Us,!0,[])}catch{throw new tt("invalid ECDH public key JWK")}},Mc=()=>{const e=new Uint8Array(Hs);return globalThis.crypto.getRandomValues(e),e},Tc=async(e,t,r)=>{if(r.length!==Hs)throw new tt("invalid handshake nonce length");const o=await $e.deriveBits({name:"ECDH",public:t},e,256),n=await $e.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=new Uint8Array(await $e.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(Ec)},n,Po*2*8)),s=(i,c)=>$e.importKey("raw",i,{name:"AES-GCM"},!1,c);return{clientToHost:await s(a.slice(0,Po),["encrypt","decrypt"]),hostToClient:await s(a.slice(Po),["encrypt","decrypt"])}},Rc=(e,t,r)=>{for(let o=js-1;o>=0;o-=1)e[t+o]=Number(r&0xffn),r>>=8n},Pc=(e,t)=>{let r=0n;for(let o=0;o<js;o+=1)r=r<<8n|BigInt(e[t+o]);return r},Ic=e=>{const t=new Uint8Array(rn);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(o){if(o.length>Fr)throw new tt("plaintext frame exceeds maximum size");r+=1n;const n=new Uint8Array(Os);n.set(t,0),Rc(n,rn,r);const a=new Uint8Array(await $e.encrypt({name:"AES-GCM",iv:n},e,o)),s=new Uint8Array(mr+a.length);return s[0]=xs,s.set(n,1),s.set(a,mr),s}}},_c=e=>{let t=0n;return{async decrypt(r){if(r.length<mr+vc)throw new tt("encrypted frame too short");if(r[0]!==xs)throw new tt("unsupported encrypted frame version");const o=r.slice(1,mr),n=Pc(o,rn);if(n<=t)throw new tt("frame counter regression");let a;try{a=await $e.decrypt({name:"AES-GCM",iv:o},e,r.slice(mr))}catch{throw new tt("frame decryption failed")}return t=n,new Uint8Array(a)}}},Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",xc=e=>{let t="";for(let r=0;r<e.length;r+=3){const o=e[r],n=r+1<e.length?e[r+1]:void 0,a=r+2<e.length?e[r+2]:void 0;t+=Nr[o>>2],t+=Nr[(o&3)<<4|(n??0)>>4],n!==void 0&&(t+=Nr[(n&15)<<2|(a??0)>>6]),a!==void 0&&(t+=Nr[a&63])}return t},_a=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const r=t;if(r.v!==fr)return null;const o=r.batch===!0;return r.t==="ready"?{t:"ready",v:fr,batch:o}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:fr,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:o}:null},Oc=e=>({type:"fail",closeCode:At.ChannelFailure,reason:e}),Nc=async(e,t={})=>{const r=t.batch!==!1,o=await Sc(e),n=await kc(),a=Mc(),s={t:"hello",v:fr,clientPubJwk:await Dc(n.publicKey),nonce:xc(a),...r?{batch:!0}:{}};let i=!1;return{helloText:JSON.stringify(s),get established(){return i},async handleText(c){if(i)return _a(c)?.t==="ready"?{type:"ignore"}:Oc("plaintext frame on established channel");const d=_a(c);if(d?.t!=="ready")return{type:"ignore"};const l=await Tc(n.privateKey,o,a);return i=!0,{type:"established",batch:r&&d.batch===!0,channel:{encryptor:Ic(l.clientToHost),decryptor:_c(l.hostToClient)}}}}},$s=4294967295;class re extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Te=(e,t,r,o=!1)=>{if(!Number.isInteger(t)||t<0||t>$s)throw new re("invalid stream id");if(r.length>tn)throw new re("tunnel payload exceeds maximum size");const n=new Uint8Array(yr+r.length);return n[0]=o?e|ao:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(r,yr),n},Lc=e=>{if(e.length<yr)throw new re("tunnel frame too short");const t=e[0],r=(t&ao)!==0,o=t&~ao;if(!Cc(o))throw new re(`unknown tunnel frame type ${o}`);const n=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:o,streamId:n,payload:e.slice(yr),hasMoreFragments:r}},Uc=new TextEncoder,Hc=new TextDecoder,so=e=>Uc.encode(JSON.stringify(e)),io=(e,t)=>{let r;try{r=JSON.parse(Hc.decode(e))}catch{throw new re("malformed JSON tunnel payload")}if(!t(r))throw new re("unexpected JSON tunnel payload shape");return r},Ks=(e,t=tn)=>{if(t<=0||t>tn)throw new re("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r},xa=(e,t,r)=>{const o=Ks(r);return o.map((n,a)=>Te(e,t,n,a<o.length-1))},jc=(e=16*1024*1024)=>{const t=new Map;return{push(r){const o=`${r.streamId}:${r.frameType}`,n=t.get(o);if(!r.hasMoreFragments&&!n)return r.payload;const a=n?.chunks??[],s=(n?.totalBytes??0)+r.payload.length;if(s>e)throw t.delete(o),new re("fragmented message exceeds maximum size");if(a.push(r.payload),r.hasMoreFragments)return t.set(o,{chunks:a,totalBytes:s}),null;t.delete(o);const i=new Uint8Array(s);let c=0;for(const d of a)i.set(d,c),c+=d.length;return i},dropStream(r){for(const o of t.keys())o.startsWith(`${r}:`)&&t.delete(o)}}},$c=e=>{if(e.length===0)throw new re("cannot encode an empty frame batch");if(e.length===1){const n=e[0],a=new Uint8Array(1+n.length);if(a[0]=Ns,a.set(n,1),a.length>Fr)throw new re("frame batch exceeds maximum plaintext size");return a}let t=1;for(const n of e)t+=zt+n.length;if(t>Fr)throw new re("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=Ls;let o=1;for(const n of e)r[o]=n.length>>>24&255,r[o+1]=n.length>>>16&255,r[o+2]=n.length>>>8&255,r[o+3]=n.length&255,o+=zt,r.set(n,o),o+=n.length;return r},Kc=e=>{if(e.length<1)throw new re("empty batch plaintext");const t=e[0];if(t===Ns)return[e.slice(1)];if(t!==Ls)throw new re(`unknown batch container tag ${t}`);const r=[];let o=1;for(;o<e.length;){if(o+zt>e.length)throw new re("truncated batch frame length");const n=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;if(o+=zt,o+n>e.length)throw new re("truncated batch frame body");r.push(e.slice(o,o+n)),o+=n}if(r.length===0)throw new re("empty frame batch");return r},zc=new Set([_.HttpBody,_.WsText,_.WsBinary]),zs=150,qc=24*1024,Gc=32,Wc=e=>{const t=e.windowMs??zs,r=e.maxBatchBytes??qc,o=e.maxBatchFrames??Gc,n=e.now??(()=>Date.now()),a=e.setTimer??((g,A)=>setTimeout(g,A)),s=e.clearTimer??(g=>clearTimeout(g));let i=[],c=0,d=null,l=0,u=!1;const f=()=>{d!==null&&(s(d),d=null)},m=()=>{if(f(),i.length===0)return;const g=i;i=[],c=0,l=n(),e.sendBatch($c(g))};return{enqueue:g=>{if(u)return;const A=g[0]&~ao;if(!zc.has(A)){i.push(g),m();return}const y=n();if(i.length===0&&y-l>=t){i.push(g),m();return}const b=zt+g.length;if(i.length>0&&1+c+b>Fr&&m(),i.push(g),c+=b,c>=r||i.length>=o){m();return}d===null&&(d=a(m,t))},flush:m,dispose(){u=!0,f(),i=[],c=0}}},Vc=()=>{let e=1;return{next(){if(e>$s)throw new re("stream id space exhausted");const t=e;return e+=2,t}}},Jc=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(r){e.send(r)},close(r,o){e.close(r,o)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>t.onmessage?.({data:r.data}),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),e.onerror=()=>t.onerror?.(),t},Yc=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(r){r&&(e.binaryType=r)},onopen:null,onmessage:null,onerror:null,onclose:null,send(r){e.send(r)},close(r,o){e.close(r,o)}};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>{const o=r.data;(typeof o=="string"||o instanceof ArrayBuffer)&&t.onmessage?.({data:o})},e.onerror=()=>t.onerror?.(),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),t},Oa=0,Io=1,Na=2,La=3,Qc=new Set([At.AuthFailed,At.DuplicateClient,At.LimitExceeded]),Xc={[At.AuthFailed]:"relay authentication failed",[At.DuplicateClient]:"relay connection replaced by another client",[At.LimitExceeded]:"relay connection limit reached"},Bo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zc=e=>Bo(e)&&Object.values(e).every(t=>typeof t=="string"),ed=e=>Bo(e)&&typeof e.status=="number"&&Zc(e.headers),qs=e=>Bo(e)&&typeof e.reason=="string",td=e=>Bo(e)&&typeof e.code=="number"&&typeof e.reason=="string",Gs=/^[a-z][a-z\d+.-]*:\/\//i,Gn="http://tunnel.invalid",rd=e=>{try{const t=Gs.test(e)?new URL(e):new URL(e,Gn);return`${t.pathname}${t.search}`}catch{return e}},Lr=e=>({async*[Symbol.asyncIterator](){yield e}}),od=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:r,value:o}=await t.read();if(r)return;o&&(yield o)}}finally{t.releaseLock()}}}),nd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},ad=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:od(e)};if(typeof e=="string")return{body:Lr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Lr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Lr(nd(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,o=new Uint8Array(await t.arrayBuffer());return{body:Lr(o),contentType:r}},sd=async(e,t)=>{let r;const o=new Headers;let n="GET",a=null,s;e instanceof Request?(r=e.url,n=e.method,e.headers.forEach((u,f)=>o.set(f,u)),s=e.signal,a=e.body):r=e.toString(),t&&(t.method&&(n=t.method),t.headers&&new Headers(t.headers).forEach((u,f)=>o.set(f,u)),t.body!==void 0&&(a=t.body),t.signal&&(s=t.signal));const i=Gs.test(r)?new URL(r):new URL(r,Gn),{body:c,contentType:d}=await ad(a);d&&!o.has("content-type")&&o.set("content-type",d);const l={};return o.forEach((u,f)=>{l[f]=u}),{method:n.toUpperCase(),path:i.pathname,query:i.search.startsWith("?")?i.search.slice(1):i.search,headers:l,body:c,signal:s}},id="__pichamberAmbiguousTransport",cd=e=>(Object.defineProperty(e,id,{value:!0,enumerable:!1,configurable:!0}),e),dd=new Uint8Array(0),ld=new TextEncoder,ud=new TextDecoder,on=e=>e instanceof Error?e:new Error(String(e)),Ua=()=>new DOMException("The operation was aborted.","AbortError"),fd=async(e,t,r)=>{const o=await sd(t,r),n=o.signal;if(n?.aborted)throw Ua();const a=await e(n),s=a.nextStreamId();return await new Promise((i,c)=>{let d=!1,l=!1,u=null,f=null;const m=()=>{a.streams.delete(s),a.assembler.dropStream(s),f&&n&&n.removeEventListener("abort",f)},p=b=>{if(!l){if(l=!0,m(),!d){c(b);return}try{u?.error(b)}catch{}}},g=b=>{a.dead||a.send(Te(_.StreamAbort,s,so({reason:b})))},A=b=>cd(new Error(b));f=()=>{g("aborted"),p(Ua())},a.streams.set(s,{handleFrame(b,D){if(b===_.HttpResponse){if(d||l)return;let h;try{h=io(D,ed)}catch(W){g("malformed response head"),p(A(on(W).message));return}const v=h.status===204||h.status===205||h.status===304;let O=null;v||(O=new ReadableStream({start(W){u=W},cancel(){l||(l=!0,m(),g("response body cancelled"))}})),d=!0,i(new Response(O,{status:h.status,headers:h.headers})),v&&(l=!0,m());return}if(b===_.HttpBody){if(!d||l)return;try{u?.enqueue(D)}catch{}return}if(b===_.StreamEnd){if(l)return;if(!d){p(A("tunnel stream ended before response head"));return}l=!0,m();try{u?.close()}catch{}return}if(b===_.StreamAbort){let h="stream aborted by host";try{h=io(D,qs).reason}catch{}p(A(h))}},fail(b){p(A(b.message))}}),n&&n.addEventListener("abort",f,{once:!0});const y={method:o.method,path:o.path,query:o.query,headers:o.headers};a.send(Te(_.HttpRequest,s,so(y))),(async()=>{try{if(o.body)for await(const b of o.body){if(l||a.dead)return;for(const D of Ks(b))a.send(Te(_.HttpBody,s,D))}!l&&!a.dead&&a.send(Te(_.StreamEnd,s,dd))}catch(b){g("request body failed"),p(A(on(b).message))}})()})},md=e=>{const t=e.indexOf("?");return t===-1?{path:e,query:""}:{path:e.slice(0,t),query:e.slice(t+1)}},gd=(e,t,r)=>{let o=Oa,n=null,a=0,s=!1;const i={get readyState(){return o},onopen:null,onmessage:null,onerror:null,onclose:null,send(d){if(o!==Io||!n||n.dead)throw new Error("relay tunnel socket is not open");if(typeof d=="string"){for(const u of xa(_.WsText,a,ld.encode(d)))n.send(u);return}const l=d instanceof ArrayBuffer?new Uint8Array(d.slice(0)):(()=>{const u=new Uint8Array(d.byteLength);return u.set(new Uint8Array(d.buffer,d.byteOffset,d.byteLength)),u})();for(const u of xa(_.WsBinary,a,l))n.send(u)},close(d=1e3,l=""){o===La||o===Na||(o===Io&&n&&!n.dead&&(o=Na,n.send(Te(_.WsClose,a,so({code:d,reason:l})))),c(d,l))}},c=(d,l,u=!1)=>{if(!s){if(s=!0,n&&(n.streams.delete(a),n.assembler.dropStream(a)),o=La,u)try{i.onerror?.()}catch{}try{i.onclose?.({code:d,reason:l})}catch{}}};return(async()=>{let d;try{d=await e()}catch(m){c(1006,on(m).message,!0);return}if(s)return;n=d,a=d.nextStreamId(),d.streams.set(a,{handleFrame(m,p){if(m===_.WsOpened){if(o===Oa){o=Io;try{i.onopen?.()}catch{}}return}if(m===_.WsText){try{i.onmessage?.({data:ud.decode(p)})}catch{}return}if(m===_.WsBinary){const g=new ArrayBuffer(p.byteLength);new Uint8Array(g).set(p);try{i.onmessage?.({data:g})}catch{}return}if(m===_.WsClose){let g=1e3,A="";try{const y=io(p,td);g=y.code,A=y.reason}catch{}c(g,A);return}if(m===_.StreamAbort){let g="stream aborted";try{g=io(p,qs).reason}catch{}c(1006,g,!0)}},fail(m){c(1012,m.message,!0)}});const{path:l,query:u}=md(t),f=r&&r.length>0?{path:l,query:u,protocols:r}:{path:l,query:u};d.send(Te(_.WsOpen,a,so(f)))})(),i},_o=new Uint8Array(0),Le=e=>e instanceof Error?e:new Error(String(e)),Ha=()=>new DOMException("The operation was aborted.","AbortError"),ja=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Wn=e=>{const t=e.helloRetryMs??1e3,r=e.helloTimeoutMs??3e4,o=e.pingIntervalMs??3e4,n=e.pingTimeoutMs??15e3,a=e.resumeProbeTimeoutMs??5e3,s=e.batchWindowMs??zs,i=e.batch!==!1,c=e.reconnectBaseDelayMs??1e3,d=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(B=>Jc(new WebSocket(B)));let f=!1,m={state:"idle"};const p=new Set;let g=null,A=null,y=null,b=null,D=0,h=0,v=null,O=[];const W=B=>{if(!(m.state===B.state&&m.lastError===B.lastError)){m=B;for(const N of p)try{N(m)}catch{}}},oe=B=>{const N=O;O=[];for(const L of N)L.reject(B)},ve=B=>{const N=O;O=[];for(const L of N)L.resolve(B)},_e=(B,N)=>{B.dead=!0;const L=Array.from(B.streams.values());B.streams.clear();for(const x of L)try{x.fail(N)}catch{}},ae=()=>{v!==null&&(clearTimeout(v),v=null)},ye=()=>{if(!(f||ja())){if(v!==null){ae(),St();return}m.state==="connecting"||m.state==="reconnecting"||g&&!g.dead&&b?.()}},er=()=>{typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",ye),window.addEventListener("pichamber:system-resume",ye))},Ir=()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",ye),window.removeEventListener("pichamber:system-resume",ye))},tr=()=>{if(f||v!==null)return;const B=c*Math.pow(1.5,Math.min(h,8)),N=Math.random()*.3*B,L=Math.min(d,Math.round(B+N)),x=ja()?Math.max(L,l):L;v=setTimeout(()=>{v=null,St()},x)},dt=()=>{const B=new URL(e.relayUrl);return B.searchParams.set("v",String(fr)),B.searchParams.set("role","client"),B.searchParams.set("serverId",e.serverId),e.grant&&B.searchParams.set("grant",e.grant),B.toString()},St=async()=>{if(f)return;const B=++D;ae(),y?.(),y=null,W({state:h===0?"connecting":"reconnecting"});let N;try{N=await Nc(e.hostEncPubJwk,{batch:i})}catch(H){Oe(B,Le(H),!0);return}if(f||B!==D)return;let L;try{L=u(dt())}catch(H){Oe(B,Le(H));return}A=L;let x=null,se=null,me=null,ee=null,lt=!1,Mt=null,de=!1,le=null,Tt=null,xe=Date.now(),E=!1,R=Promise.resolve();const U=()=>{b===ue&&(b=null),lt=!1,x!==null&&(clearInterval(x),x=null),se!==null&&(clearTimeout(se),se=null),me!==null&&(clearInterval(me),me=null),ee!==null&&(clearTimeout(ee),ee=null),Mt?.dispose(),Mt=null};y=U;const T=(H,V={})=>{const{terminal:G=!1,asErrorState:z=!1}=V;if(!(de||B!==D)){de=!0,U(),y===U&&(y=null),le&&_e(le,H),g===le&&(g=null);try{L.close()}catch{}if(A===L&&(A=null),G){f=!0,oe(H),W({state:"error",lastError:H.message});return}Oe(B,H,z)}},ue=()=>{de||B!==D||!le||le.dead||lt||(lt=!0,xe=Date.now(),ee!==null&&(clearTimeout(ee),ee=null),le.send(Te(_.Ping,0,_o)),ee=setTimeout(()=>{ee=null,T(new Error("relay resume probe timeout"))},a))},be=()=>{if(L.readyState===1)try{L.send(N.helloText)}catch(H){T(Le(H))}},xr=(H,V)=>{Tt=H,E=V,x!==null&&(clearInterval(x),x=null),se!==null&&(clearTimeout(se),se=null),h=0;const G=new Map,z=Vc(),ut=jc();let ge=Promise.resolve();const Ne=nr=>{ge=ge.then(async()=>{if(or.dead)return;const Fc=await H.encryptor.encrypt(nr);L.send(Fc)}).catch(()=>{})},ft=V?Wc({windowMs:s,sendBatch:Ne}):null;Mt=ft;const or={streams:G,assembler:ut,nextStreamId:()=>z.next(),send:nr=>{if(xe=Date.now(),ft){ft.enqueue(nr);return}Ne(nr)},dead:!1};le=or,g=or,b=ue,W({state:"connected"}),ve(or),me=setInterval(()=>{Date.now()-xe<o||(or.send(Te(_.Ping,0,_o)),ee===null&&(ee=setTimeout(()=>{ee=null,T(new Error("relay keepalive timeout"))},n)))},o)},Or=(H,V)=>{let G;try{G=Lc(V)}catch(ge){T(Le(ge));return}if(ee!==null&&(clearTimeout(ee),ee=null),lt=!1,G.frameType===_.Ping){H.send(Te(_.Pong,G.streamId,_o));return}if(G.frameType===_.Pong)return;xe=Date.now();let z=G.payload;if(G.frameType===_.WsText||G.frameType===_.WsBinary){let ge;try{ge=H.assembler.push(G)}catch(Ne){T(Le(Ne));return}if(ge===null)return;z=ge}else if(G.hasMoreFragments){T(new Error("unexpected fragmented tunnel frame"));return}const ut=H.streams.get(G.streamId);ut&&ut.handleFrame(G.frameType,z)};L.onopen=()=>{de||B!==D||(be(),x=setInterval(be,t))},L.onmessage=H=>{if(de||B!==D)return;const V=H.data;if(typeof V=="string"){R=R.then(async()=>{if(de||B!==D)return;const z=await N.handleText(V);if(z.type==="established"){if(Tt)return;xr(z.channel,z.batch)}else z.type==="fail"&&T(new Error(`relay handshake failed: ${z.reason}`))}).catch(z=>{T(Le(z))});return}const G=V instanceof ArrayBuffer?new Uint8Array(V):V instanceof Uint8Array?V:null;G&&(R=R.then(async()=>{if(de||B!==D)return;const z=le,ut=Tt;if(!z||!ut){T(new Error("encrypted frame before handshake completed"));return}let ge;try{ge=await ut.decryptor.decrypt(G)}catch(Ne){T(Le(Ne));return}if(E){let Ne;try{Ne=Kc(ge)}catch(ft){T(Le(ft));return}for(const ft of Ne){if(de||B!==D||z.dead)return;Or(z,ft)}return}Or(z,ge)}).catch(z=>{T(Le(z))}))},L.onclose=H=>{const V=Qc.has(H.code);T(new Error(Xc[H.code]??`relay socket closed (code ${H.code})`),{terminal:V,asErrorState:V})},L.onerror=()=>{},se=setTimeout(()=>{se=null,T(new Error("relay handshake timeout"),{asErrorState:!0})},r);function Oe(H,V,G=!1){H!==D||f||(oe(V),h+=1,W({state:G?"error":"reconnecting",lastError:V.message}),tr())}},_r=B=>f?Promise.reject(new Error("relay tunnel closed")):B?.aborted?Promise.reject(Ha()):g&&!g.dead?Promise.resolve(g):new Promise((N,L)=>{let x=null;const se={resolve(me){x&&B&&B.removeEventListener("abort",x),N(me)},reject(me){x&&B&&B.removeEventListener("abort",x),L(me)}};B&&(x=()=>{O=O.filter(me=>me!==se),L(Ha())},B.addEventListener("abort",x,{once:!0})),O.push(se)}),rr=()=>{if(f)return;f=!0,D+=1,ae(),Ir(),y?.(),y=null;const B=g;g=null;const N=new Error("relay tunnel closed");B&&_e(B,N),oe(N);try{A?.close()}catch{}A=null,W({state:"idle"})};return er(),St(),{fetch:(B,N)=>fd(_r,B,N),openWebSocket:(B,N)=>gd(()=>_r(),B,N),getStatus:()=>m,subscribeStatus(B){return p.add(B),()=>{p.delete(B)}},close:rr}};let he=null,gr=null;const pd=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),vr=()=>he,Jt=()=>he!==null,nn=new Set,q0=e=>(nn.add(e),()=>{nn.delete(e)}),Vn=e=>{if(e!==Jt())for(const t of[...nn])t()},hd=e=>{if(he&&gr&&pd(gr,e))return he;const t=Jt();return he?.close(),gr=e,he=Wn(e),Vn(t),he},G0=(e,t)=>{if(he===t)return;const r=Jt();he?.close(),gr=e,he=t,Vn(r)},Fd=()=>{const e=Jt();he?.close(),he=null,gr=null,Vn(e)};let Ws=()=>null,Vs="",co={},at="",br=0,ht=null,Ut="",Ar=0,wt="",Ft=null,Qe="",Jr=0,Yr=0;const Jn=1e4,yd=e=>e.toLowerCase()==="authorization",Js=e=>{const t={};for(const[r,o]of Object.entries(e||{})){const n=r.trim(),a=o.trim();n&&a&&!yd(n)&&(t[n]=a)}return t},bd=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([o,n])=>t[o]===n)},kr=e=>typeof e!="string"?"":e.trim(),Ad=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_CLIENT_TOKEN__;return kr(e)},Ed=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Ys=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():Ed();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},Yn=e=>{try{return new URL(e).origin}catch{return""}},Qs=()=>{Ut="",Ar=0,wt="",Ft=null,Qe="",Jr+=1},Dr=e=>{e!==void 0&&kr(e)!==at||(at="",br=0,Qs())},Xs=()=>{Yr+=1,ht=null,Dr(),Xn()},Zs=e=>{const t=kr(e);Vs=t,Xs(),Ws=()=>t?{type:"bearer",token:t}:null},ei=e=>{const t=Js(e);bd(co,t)||(co=t,Xs())},Qn=()=>{if(Object.keys(co).length>0)return co;if(typeof window>"u")return{};const e=window.__PICHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Js(e):{}},Co=()=>Vs||Ad(),wd=(e,t)=>{const r=kr(e);if(!r||typeof t!="number"||!Number.isFinite(t)){Dr();return}const o=at;at=r,br=t,o&&o!==r&&Sd()},ti=()=>!at||br<=Date.now()+Jn?(Dr(),""):at,Bd=e=>{const t=Yn(e);return!t||wt!==t?"":!Ut||Ar<=Date.now()+Jn?(Ut="",Ar=0,wt="",""):Ut},Cd=()=>{const e=ti();return!e&&(Co()||typeof window<"u")&&Sr().catch(()=>{}),e},ri=async()=>{const e=await Ws(),t=e?.type==="bearer"?kr(e.token):Co();return t?{type:"bearer",token:t}:null},oi=e=>{if(ht)return ht;const t=Yr,o=(async()=>{const n=await ri(),a=new Headers;for(const[u,f]of Object.entries(Qn()))a.set(u,f);n?.type==="bearer"&&a.set("Authorization",`Bearer ${n.token}`);const s=vr(),i=s?await s.fetch("/auth/url-token",{method:"POST",headers:a}):await fetch(Ys(e,"/auth/url-token"),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw t===Yr&&Dr(),new Error(`Failed to mint runtime URL auth token (${i.status})`);const c=await i.json().catch(()=>null),d=typeof c?.token=="string"?c.token.trim():"",l=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==Yr)throw new Error("Runtime URL auth token response is stale");if(wd(d,l),!at)throw new Error("Runtime URL auth token response was invalid");return at})().finally(()=>{ht===o&&(ht=null)});return ht=o,ht},vd=e=>{const t=Yn(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Ft&&Qe===t)return Ft;const r=Jr,n=(async()=>{const a=await fetch(Ys(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!a.ok)throw r===Jr&&t===Qe&&(Ut="",Ar=0,wt=""),new Error(`Failed to mint local runtime URL auth token (${a.status})`);const s=await a.json().catch(()=>null),i=typeof s?.token=="string"?s.token.trim():"",c=typeof s?.expiresAt=="number"?s.expiresAt:0;if(!i||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(r!==Jr||t!==Qe)throw new Error("Local runtime URL auth token response is stale");return Ut=i,Ar=c,wt=t,i})().finally(()=>{Ft===n&&(Ft=null,Qe="")});return Ft=n,Qe=t,Ft},Sr=async e=>{const t=ti();return t||oi(e)},kd=async e=>{const t=Yn(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const r=Bd(t);return r||((wt&&wt!==t||Qe&&Qe!==t)&&Qs(),vd(t))};let _t=0,pr=null,ni=null;const an=new Set,Dd=5e3,Sd=()=>{for(const e of an)try{e()}catch{}},ai=()=>{pr!==null&&(clearTimeout(pr),pr=null)},Xn=()=>{if(ai(),_t<=0||typeof window>"u")return;const e=br-Jn-Dd,t=br>0?Math.max(0,e-Date.now()):0;pr=setTimeout(()=>{pr=null,!(_t<=0)&&oi(ni).catch(()=>{}).finally(()=>{Xn()})},t)},W0=e=>{typeof e=="string"&&e.trim()&&(ni=e.trim()),_t+=1,Xn();let t=!1;return()=>{t||(t=!0,_t=Math.max(0,_t-1),_t===0&&ai())}},V0=e=>(an.add(e),()=>{an.delete(e)}),Md=async e=>{const t=new Headers(e);for(const[o,n]of Object.entries(Qn()))t.has(o)||t.set(o,n);if(t.has("Authorization"))return t;const r=await ri();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},sn="pichamber:auth-expired",J0=()=>{typeof window>"u"||window.dispatchEvent(new Event(sn))},Y0=e=>typeof window>"u"?()=>{}:(window.addEventListener(sn,e),()=>{window.removeEventListener(sn,e)}),Q0=async(e,t,r)=>{if(e.length===0)return[];const o=Math.max(1,Math.min(t,e.length)),n=new Array(e.length);let a=0;const s=async()=>{for(;;){const i=a;if(a+=1,i>=e.length)return;n[i]=await r(e[i])}};return await Promise.all(Array.from({length:o},()=>s())),n},$a=e=>{if(e instanceof Error)return e;if(typeof DOMException<"u")return new DOMException(typeof e=="string"?e:"The operation was aborted.","AbortError");const t=new Error(typeof e=="string"?e:"The operation was aborted.");return t.name="AbortError",t},si=(e,t)=>t?t.aborted?Promise.reject($a(t.reason)):new Promise((r,o)=>{let n=!1;const a=()=>{n||(n=!0,o($a(t.reason)))};t.addEventListener("abort",a,{once:!0}),e().then(s=>{n||(n=!0,t.removeEventListener("abort",a),r(s))},s=>{n||(n=!0,t.removeEventListener("abort",a),o(s))})}):e(),Td=["local","remote",null],Rd=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function ii(e){if(!e||typeof e!="object")return{valid:!1};const t=e,r=t.localAvailable===!1?{localAvailable:!1}:{},o=t.target,n=t.status;if(o!==null&&(typeof o!="string"||!Td.includes(o)))return{valid:!1};if(typeof n!="string"||!Rd.includes(n))return{valid:!1};if(o==="remote"||o==="local"){if(n==="ok"&&o==="local")return{valid:!0,outcome:{target:"local",status:"ok",...r}};if(n==="ok"&&o==="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,...r}};if(n==="unreachable")return o==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...r}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...r}};if(n==="incompatible"||n==="wrong-service")return o!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url,...r}};if(n==="missing")return o!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...r}}}if(o===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...r}};if(n==="missing")return{valid:!1}}return{valid:!1}}function Pd(){if(Id()!=="valid")return null;const t=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__,r=ii(t);return r.valid?r.outcome:null}function Id(){if(typeof window>"u")return"not-injected";const e=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":ii(e).valid?"valid":"malformed"}const lo=/^[a-z][a-z\d+.-]*:\/\//i,_d=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},cn=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),xd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return cn(e)},Od=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},dn=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[o,n]of r)n!=null&&e.searchParams.set(o,String(n))},Nd=(e,t)=>{if(!t)return e;const r=new URLSearchParams;dn({searchParams:r},t);const o=r.toString();return o?e.includes("?")?`${e}&${o}`:`${e}?${o}`:e},Ka=(e,t,r)=>{if(lo.test(t)){const a=new URL(t);return dn(a,r),a.toString()}const o=_d(t);if(!e)return Nd(o,r);const n=new URL(o,`${e}/`);return dn(n,r),n.toString()},xo=(e,t)=>{const r=t===void 0?Cd():t;if(!r)return e;const o=lo.test(e)?new URL(e):new URL(e,"http://pichamber.local");return o.searchParams.set("oc_url_token",r),lo.test(e)?o.toString():`${o.pathname}${o.search}${o.hash}`},Ld=(e,t)=>{const r=lo.test(e)?new URL(e):new URL(e,Od(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},Zn=(e={})=>{const t=cn(e.apiBaseUrl),r=cn(e.realtimeBaseUrl),o=()=>t||xd(),n=()=>r||o(),a=(i,c)=>Ka(o(),i,c),s=(i,c)=>Ka(n(),i,c);return{api:a,authenticatedAsset:(i,c)=>xo(a(i,c)),auth:a,health:i=>a("/health",i),rawFile:(i,c)=>a("/api/fs/raw",{path:i,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(i,c)=>xo(s(i,c)),websocket:(i,c,d)=>Ld(xo(s(i,c),d),e)}};let uo=Zn();const Re=()=>uo,Ud=e=>{uo=e},ea=e=>(uo=Zn(e),uo);let Oo=null,No=null,Lo=null;const za=new Set;let qa=!1;const ci=e=>{if(za.add(e),qa||typeof window>"u")return;qa=!0;const t=()=>{for(const r of za)r()};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{}},Hd=(e,t)=>{let r;try{r=e()}catch{return}const o=new Map,n=new Set;let a;const s=()=>{if(a=void 0,o.size===0&&n.size===0)return;const c=Array.from(o.entries()),d=Array.from(n);o.clear(),n.clear();for(const[l,u]of c)try{r.setItem(l,JSON.stringify(u,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!o.has(l)&&!n.has(l)&&o.set(l,u)}for(const l of d)try{r.removeItem(l)}catch(u){console.error("Failed to remove deferred storage value",u),o.has(l)||n.add(l)}},i=()=>{a===void 0&&(a=setTimeout(s,0))};return ci(s),{getItem:c=>{if(o.has(c))return o.get(c)??null;if(n.has(c))return null;const d=u=>{if(u===null)return null;try{return JSON.parse(u,t?.reviver)}catch{try{r.removeItem(c)}catch{}return null}},l=r.getItem(c);return l instanceof Promise?l.then(d):d(l)},setItem:(c,d)=>{o.set(c,d),n.delete(c),i()},removeItem:c=>{o.delete(c),n.add(c),i()}}},ta=e=>Hd(()=>ui(),e),jd=e=>{const t=new Map,r=new Set;let o;const n=()=>{if(o=void 0,t.size===0&&r.size===0)return;const s=Array.from(t.entries()),i=Array.from(r);t.clear(),r.clear();for(const[c,d]of s)try{e.setItem(c,d)}catch(l){console.error("Failed to persist deferred storage value",l),!t.has(c)&&!r.has(c)&&t.set(c,d)}for(const c of i)try{e.removeItem(c)}catch(d){console.error("Failed to remove deferred storage value",d),t.has(c)||r.add(c)}},a=()=>{o===void 0&&(o=setTimeout(n,0))};return ci(n),{getItem:s=>t.has(s)?t.get(s)??null:r.has(s)?null:e.getItem(s),setItem:(s,i)=>{t.set(s,i),r.delete(s),a()},removeItem:s=>{t.delete(s),r.add(s),a()},clear:()=>{t.clear(),r.clear(),o!==void 0&&(clearTimeout(o),o=void 0),e.clear()},key:s=>e.key(s),get length(){return e.length}}},di=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},ra=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,r)=>{e.set(t,r)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},li=e=>{const t=ra(),r=new Set,o=new Set,n=d=>{if(o.has(d))return null;if(r.has(d))return t.getItem(d);try{return e.getItem(d)}catch{return null}},a=(d,l)=>{try{e.setItem(d,l),t.removeItem(d),r.delete(d),o.delete(d);return}catch{try{e.removeItem(d)}catch{}}t.setItem(d,l),r.add(d),o.delete(d)},s=d=>{try{e.removeItem(d),o.delete(d)}catch{o.add(d)}t.removeItem(d),r.delete(d)},i=()=>{const d=[];try{for(let l=0;l<e.length;l+=1){const u=e.key(l);u&&d.push(u)}}catch{}try{e.clear(),o.clear()}catch{for(const l of d)o.add(l)}t.clear(),r.clear()},c=()=>{const d=new Set;try{for(let l=0;l<e.length;l+=1){const u=e.key(l);u&&!o.has(u)&&!r.has(u)&&d.add(u)}}catch{}for(const l of r)d.add(l);return[...d]};return{getItem:n,setItem:a,removeItem:s,clear:i,key:d=>c()[d]??null,get length(){return c().length}}},$d=()=>{const e=di("localStorage");return e?li(e):ra()},ui=()=>(Oo||(Oo=$d()),Oo),Mr=()=>(Lo||(Lo=jd(ui())),Lo),Kd=()=>{const e=di("sessionStorage");return e?li(e):ra()},X0=()=>(No||(No=Kd()),No),ln="pichamber:runtime-endpoint-changed",un="pichamber:runtime-endpoint-will-change";let st="",Bt="",fi=0;const Z0=()=>(vo(),fi),fn="pichamber:lastRuntimeEndpoint.v1",zd=()=>{try{const e=Mr().getItem(fn);if(!e)return null;const t=JSON.parse(e),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl.trim():"",o=typeof t.runtimeKey=="string"?t.runtimeKey.trim():"";return!r||!o||o==="mobile-disconnected"?null:{apiBaseUrl:r,runtimeKey:o}}catch{return null}},qd=(e,t)=>{try{const r=Mr();if(t==="mobile-disconnected"||!e){r.removeItem(fn);return}r.setItem(fn,JSON.stringify({apiBaseUrl:e,runtimeKey:t}))}catch{}},vo=()=>{if(st||Bt||typeof window>"u")return;const e=zd();if(e){st=e.apiBaseUrl,Bt=e.runtimeKey;try{window.__PICHAMBER_API_BASE_URL__=e.apiBaseUrl}catch{}ea({apiBaseUrl:e.apiBaseUrl,realtimeBaseUrl:e.apiBaseUrl})}},Uo=(e,t,r)=>{try{e[t]=r}catch{}},oa=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"}`}},mi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},gi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},pi=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},qe=()=>(vo(),st||mi());let Ho="",Ga=null,Wa,Va;const Ja=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},C=()=>{if(vo(),Bt)return Bt;const e=Ja("__PICHAMBER_API_BASE_URL__"),t=Ja("__PICHAMBER_LOCAL_ORIGIN__");if(Ga===st&&Wa===e&&Va===t)return Ho;const r=qe();return Ho=pi(r,gi())?"local":oa(r),Ga=st,Wa=e,Va=t,Ho},Gd=(e={})=>{if(vo(),st||Bt)return;const t=e.apiBaseUrl?.trim()||mi();t&&(st=t,Bt=e.runtimeKey?.trim()||(pi(t,gi())?"local":oa(t)))},Ht=e=>{const t=e.apiBaseUrl.trim(),r=qe(),o=C(),n=e.runtimeKey?.trim()||oa(t);fi+=1,qd(t,n);const a={apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(un,{detail:a})),st=t,Bt=n,typeof window<"u"){const s=window;Uo(s,"__PICHAMBER_API_BASE_URL__",t),Uo(s,"__PICHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Uo(s,"__PICHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}ea({apiBaseUrl:t,realtimeBaseUrl:t}),ei(e.requestHeaders||null),Zs(e.clientToken||null),e.relay?hd(e.relay):Fd(),Sr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ln,{detail:a}))},Wd=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(un,t),()=>window.removeEventListener(un,t)},hi=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(ln,t),()=>window.removeEventListener(ln,t)};let mn=null;const Vd=e=>{mn=e},na=()=>mn||(typeof window>"u"?null:window.__PICHAMBER_RUNTIME_APIS__??null),ey=Object.freeze(Object.defineProperty({__proto__:null,getRegisteredRuntimeAPIs:na,registerRuntimeAPIs:Vd},Symbol.toStringTag,{value:"Module"})),Jd=()=>typeof window>"u"?null:window.__PICHAMBER_ELECTRON__??null,Yt=()=>typeof window>"u"?null:window.__PICHAMBER_DESKTOP__??null,ko=()=>Jd()?.runtime==="electron",ty=()=>{if(typeof window>"u")return null;const e=window.__PICHAMBER_PLATFORM__;return typeof e=="string"?e:null},Z=()=>typeof Yt()?.invoke=="function",Ie=()=>ko()&&Z(),$=async(e,t)=>{const r=Yt();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},Ya=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},jo=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}}},Yd=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),ar=e=>{const t=Yd(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ce=()=>typeof window>"u"?!1:ko(),ce=()=>{if(typeof window>"u"||!Ce())return!1;if(C()==="local")return!0;const e=typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",t=jo(e),r=jo(qe());if(!r&&t&&Pd()?.target==="local")return!0;if(t&&r){if(t.origin===r.origin)return!0;const s=t.port||(t.protocol==="https:"?"443":"80"),i=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&s===i&&ar(t.hostname)&&ar(r.hostname)}const o=jo(window.location.origin);if(t&&o){if(t.origin===o.origin)return!0;const s=t.port||(t.protocol==="https:"?"443":"80"),i=o.port||(o.protocol==="https:"?"443":"80");return t.protocol===o.protocol&&s===i&&ar(t.hostname)&&ar(o.hostname)}const n=Ya(e),a=Ya(window.location.origin)||window.location.origin;return n&&a&&n===a?!0:!!(o&&ar(o.hostname))},ry=()=>{const t=na()?.runtime?.platform;return t==="web"?!0:t!=="desktop"},oy=(e,t=Ce())=>e==="web"&&!t,ny=async()=>{if(!Ie())return null;try{const e=await $("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}},ay=async e=>{if(!Ie())return null;try{const t=await $("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}},sy=async()=>{if(!Ie())return null;try{const e=await $("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}},iy=async e=>{if(!Ie())return null;try{const t=await $("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}},cy=async()=>{if(!Ie())return null;try{const e=await $("desktop_get_close_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get close to tray status",e),null}},dy=async e=>{if(!Ie())return null;try{const t=await $("desktop_set_close_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set close to tray status",t),null}},ly=async()=>{if(!Ie())return null;try{const e=await $("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}},uy=async e=>{if(!Ie())return null;try{const t=await $("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}},fy=async()=>{if(!Ie())return null;try{const e=await $("desktop_get_process_performance_recording");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get process performance recording status",e),null}},my=async e=>{if(!Ie())return null;try{const t=await $("desktop_set_process_performance_recording",{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 process performance recording status",t),null}},Qd=()=>Ce()&&Z()&&ce(),Xd=async()=>{if(typeof window<"u"){const e=window.__PICHAMBER_HOME__;if(e&&e.length>0)return e}return null},gy=async e=>{if(Qd())try{const t=await Yt()?.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"}},Fi=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),py=async e=>{if(Z()&&ce())try{const t=await Yt()?.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(!Fi(t))return{success:!1,error:"File selection cancelled"};const r=typeof t.path=="string"?t.path:"";return r?{success:!0,path:r,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"}},hy=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!Z()||!ce())return{success:!1,error:"Native file access not available"};try{const r=await Yt()?.grantFileAccess?.(t);if(!Fi(r))return{success:!1,error:"File access was not granted"};const o=typeof r.path=="string"?r.path:"",n=typeof r.outsideFileGrant=="string"?r.outsideFileGrant:"";return!o||!n?{success:!1,error:"File access was not granted"}:{success:!0,path:o,outsideFileGrant:n}}catch(r){return console.warn("Failed to request existing file access",r),{success:!1,error:r instanceof Error?r.message:String(r)}}},Fy=async e=>({success:!0}),yy=async e=>({success:!0}),by=async()=>Z()&&await $("desktop_get_update_channel")==="rc"?"rc":"stable",Ay=async e=>{if(!Z())throw new Error("Desktop update settings are unavailable.");const t=await $("desktop_set_update_channel",{channel:e});if(t!=="stable"&&t!=="rc")throw new Error("Unable to save the desktop update channel.");return t},Ey=async()=>Z()?await $("desktop_check_for_updates"):null,wy=async e=>{if(!Z())return!1;const t=Yt();let r=null,o=0,n;try{return typeof e=="function"&&t?.listen&&(r=await t.listen("pichamber:update-progress",a=>{const s=a?.payload;if(!s||typeof s!="object")return;const i=s,c=typeof i.event=="string"?i.event:null,d=i.data&&typeof i.data=="object"?i.data:null;if(c==="Started"){o=0,n=typeof d?.contentLength=="number"?d.contentLength:void 0,e({downloaded:o,total:n});return}if(c==="Progress"){const l=d?.downloaded,u=d?.total;typeof l=="number"&&(o=l),typeof u=="number"&&(n=u),e({downloaded:o,total:n});return}c==="Finished"&&e({downloaded:o,total:n})})),await $("desktop_download_and_install_update"),!0}catch(a){throw a instanceof Error?a:new Error(String(a))}finally{if(r)try{const a=r();a instanceof Promise&&await a}catch{}}},Zd=async()=>{if(!Z())return!1;try{return await $("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},By=async()=>Z()?Zd():!1,Cy=async()=>{if(!Z()||!ce())return null;try{const e=await $("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}},el=async(e,t)=>{if(!Z()||!ce())return!1;const r=e?.trim();if(!r)return!1;try{return await $("desktop_open_path",{path:r,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(o){return console.warn("Failed to open path",o),!1}},vy=async e=>{if(!Z()||!ce())return!1;const t=e?.trim();if(!t)return!1;try{return await $("desktop_reveal_path",{path:t}),!0}catch{return el(t)}},ky=async(e,t)=>{if(!Z()||!ce())return null;const r=e?.trim();if(!r)return null;try{const o=await $("desktop_save_markdown_file",{defaultFileName:r,content:t});return typeof o=="string"&&o.trim().length>0?o:null}catch(o){return console.warn("Failed to save markdown file",o),null}},Dy=async(e,t,r)=>{if(!Z()||!ce())return!1;const o=e?.trim(),n=t?.trim(),a=r?.trim();if(!o||!n||!a)return!1;try{return await $("desktop_open_in_app",{projectPath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},Sy=async(e,t,r)=>{if(!Z()||!ce())return!1;const o=e?.trim(),n=t?.trim(),a=r?.trim();if(!o||!n||!a)return!1;try{return await $("desktop_open_file_in_app",{filePath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open file in app",s),!1}},My=async(e,t)=>{if(!Z()||!ce())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const r=Array.isArray(e)?e.filter(o=>typeof o=="string"):[];if(r.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await $("desktop_get_installed_apps",{apps:r,force:t===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=o;return n.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(n.apps)?{apps:n.apps.filter(s=>s&&typeof s=="object").map(s=>{const i=s;return{name:typeof i.name=="string"?i.name:"",iconDataUrl:typeof i.iconDataUrl=="string"?i.iconDataUrl:null}}).filter(s=>s.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(o){return console.warn("Failed to fetch installed apps",o),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Qt=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location?.protocol==="capacitor:",Ty=()=>{if(typeof window>"u"||!Qt()||tl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},tl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ce()?"desktop":"web"},Ry=()=>{if(typeof navigator>"u")return!1;const e=navigator.platform||"",t=navigator.userAgent||"";return/Win/i.test(e)&&/ARM|aarch64/i.test(t)},Ct=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",rl=()=>typeof window>"u"?"":window.location.origin||"",aa=e=>{if(typeof window>"u")return!1;const t=rl();if(t&&e.origin===t)return!0;try{const r=new URL(window.location.href||t);return e.protocol===r.protocol&&e.host===r.host}catch{return!1}},sa=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),ia=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[o,n]of r)n!=null&&e.searchParams.set(o,String(n))},Qr=e=>{try{const t=Re().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const r=new URL(t);return e.origin!==r.origin?!1:Ct(e.pathname)}catch{return!1}},$o=e=>{if(Ct(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return aa(t)&&Ct(t.pathname)}catch{return!1}},ol=(e,t)=>{try{const r=new URL(e);if(!aa(r))return e;const o=Et(`${r.pathname}${r.search}`,t);return!sa(o)&&(r.protocol==="http:"||r.protocol==="https:")?(ia(r,t),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return e}},Et=(e,t)=>e==="/health"?Re().health(t):e.startsWith("/auth/")||e==="/auth"?Re().auth(e,t):Ct(e)?Re().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?ol(e,t):e,nl=e=>{const t=e instanceof Request?e.url:e.toString();if(!sa(t))return Ct(t);try{return Qr(new URL(t))}catch{return!1}},al=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},sl=(e,t)=>!al(t),Qa=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 r=[];let o=!1;for(const[n,a]of t)sl(n,a)?(r.push([n,encodeURIComponent(a)]),o=!0):r.push([n,a]);return o?r:void 0},Ue=async(e,t,r=!0)=>{const o=new Headers(Qa(e)??e);return t&&new Headers(Qa(t)??t).forEach((n,a)=>o.set(a,n)),r?Md(o):o},il=(e,t)=>{if(!t)return e;const r=new URL(e,Gn);return ia(r,t),`${r.pathname}${r.search}`},yi=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!sa(r))return Ct(r)?il(r,t):null;try{const o=new URL(r);return!aa(o)||!Ct(o.pathname)?null:(ia(o,t),`${o.pathname}${o.search}`)}catch{return null}},cl=async(e,t,r)=>{const o=vr();if(!o)return null;const n=yi(e,r);if(n===null)return null;const a=e instanceof Request?e.headers:void 0,s=await Ue(a,t.headers,!0);return e instanceof Request?o.fetch(e,{...t,headers:s}):o.fetch(n,{...t,headers:s})},dl=(e,t)=>{if(typeof e=="string")return Et(e,t);if(e instanceof URL)return Et(e.toString(),t);const r=Et(e.url,t);return r===e.url?e:new Request(r,e)},ll=/\/api\/pi\/(health|projects|sessions|providers|resources|runtime|settings)(\b|\/|\?|$)/,Ur=new Map,ul=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!ll.test(t)?null:`GET ${t}`,F=async(e,t={})=>{const{query:r,...o}=t,n=vr(),a=n?yi(e,r):null,s=o.signal??(e instanceof Request?e.signal:void 0);let i,c,d;if(n&&a!==null){const p=e instanceof Request?e.headers:void 0,g=await Ue(p,o.headers,!0);i=e instanceof Request?()=>n.fetch(e,{...o,headers:g}):()=>n.fetch(a,{...o,headers:g}),c=a,d=String(o.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const p=dl(e,r),g=p instanceof Request?p.headers:void 0,A=await Ue(g,o.headers,nl(p));let y=p instanceof Request?()=>fetch(new Request(p,{...o,headers:A})):()=>fetch(p,{...o,headers:A});if(Qt()&&s){const b=y;y=()=>si(b,s)}i=y,c=p instanceof Request?p.url:p instanceof URL?p.toString():String(p),d=String(o.method??(p instanceof Request?p.method:"GET")).toUpperCase()}const l=o.signal!=null||e instanceof Request,u=ul(d,c,l);if(!u)return i();const f=Ur.get(u);if(f)return f.then(p=>p.clone());const m=i();return Ur.set(u,m),m.then(()=>Ur.delete(u),()=>Ur.delete(u)),m.then(p=>p.clone())};let Xa=!1;const fl=()=>{if(Xa||typeof window>"u")return;Xa=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const o=await cl(t,r??{});if(o)return o;if(typeof t=="string"){if(!$o(t)){try{const a=new URL(t);if(Qr(a)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}}catch{}return e(t,r)}const n=await Ue(void 0,r?.headers);return e(Et(t),{...r,headers:n})}if(t instanceof URL){const n=t.toString();if(!$o(n)){if(Qr(t)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}return e(t,r)}const a=await Ue(void 0,r?.headers);return e(Et(n),{...r,headers:a})}if(t instanceof Request){if(!$o(t.url)){try{const i=new URL(t.url);if(Qr(i)){const c=await Ue(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const n=await Ue(t.headers,r?.headers),a=Et(t.url),s=a===t.url?t:new Request(a,t);return e(new Request(s,{...r,headers:n}))}return e(t,r)}},jt=16384,fo=globalThis,ml=e=>{if(fo.Buffer)return fo.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let r="";for(let o=0;o<t.length;o+=32768)r+=String.fromCharCode(...t.slice(o,o+32768));return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},bi=e=>{try{if(fo.Buffer)return fo.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n+=1)o[n]=r.charCodeAt(n);return new TextDecoder().decode(o)}catch{return null}},gl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:(r.hash="",r.toString().replace(/\/+$/g,""))}catch{return null}},pl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="ws:"&&r.protocol!=="wss:"?null:(r.hash="",r.toString())}catch{return null}},Za=e=>typeof e=="string"&&e.length>0,hl=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Za(t.x)||!Za(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Fl=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,yl=e=>{if(!e||typeof e!="object")return null;const t=e,r=Fl(t.priority);if(t.type==="lan"||t.type==="tunnel"||t.type==="tailscale"){const o=gl(t.url);if(!o)return null;const n=t.type==="tailscale"&&(t.mode==="private"||t.mode==="public")?t.mode:void 0;return{type:t.type,url:o,...n?{mode:n}:{},...r===void 0?{}:{priority:r}}}if(t.type==="relay"){const o=pl(t.relayUrl);if(!o)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const a=hl(t.hostEncPubJwk);if(!a)return null;const s=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:o,serverId:n,hostEncPubJwk:a,...s?{grant:s}:{},...r===void 0?{}:{priority:r}}}return null},ca=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const r=typeof t.pairingId=="string"?t.pairingId.trim():"",o=typeof t.secret=="string"?t.secret.trim():"";if(!r||!o)return null;const n=Array.isArray(t.candidates)?t.candidates.map(yl).filter(c=>!!c):[];if(n.length===0)return null;const a=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(a){const c=Date.parse(a);if(!Number.isFinite(c)||c<=Date.now())return null}const s=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,i=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:r,secret:o,...s?{label:s}:{},...i?{fingerprint:i}:{},...a?{expiresAt:a}:{},candidates:n}},Py=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}),Iy=e=>{const t=ca(e);if(!t)throw new Error("Invalid pairing connection payload");const r=new URLSearchParams;return r.set("v","2"),r.set("p",ml(JSON.stringify(t))),`pichamber://connect?${r.toString()}`},bl=e=>{const t=e.trim();if(!t||t.length>jt)return null;try{const r=new URL(t);if(r.protocol!=="pichamber:"||r.hostname!=="connect"||r.searchParams.get("v")!=="2")return null;const o=r.searchParams.get("p")||"";if(!o||o.length>jt)return null;const n=bi(o);return!n||n.length>jt?null:ca(JSON.parse(n))}catch{return null}},_y=e=>{const t=e.trim();if(!t||t.length>jt)return null;const r=t.indexOf("?");if(r===-1||!/^pichamber:\/\/connect\/?$/i.test(t.slice(0,r)))return null;let o=null,n=null;for(const s of t.slice(r+1).split("&")){const i=s.indexOf("=");if(i===-1)continue;const c=s.slice(0,i),d=s.slice(i+1);c==="v"?o=d:c==="p"&&(n=d)}if(o!=="2"||!n||n.length>jt)return null;const a=bi(n);if(!a||a.length>jt)return null;try{return ca(JSON.parse(a))}catch{return null}},qt=e=>typeof e=="object"&&e!==null,Al=e=>e.trim().toLowerCase()==="authorization",El=e=>{if(!qt(e))return;const t={};for(const[r,o]of Object.entries(e)){const n=r.trim(),a=typeof o=="string"?o.trim():"";!n||!a||/[\r\n:]/.test(n)||/[\r\n]/.test(a)||Al(n)||(t[n]=a)}return Object.keys(t).length>0?t:void 0},Ai=e=>`relay://${e}`,wl=e=>{if(!qt(e))return null;const t=Y(e,"relayUrl")||Y(e,"relay_url"),r=Y(e,"serverId")||Y(e,"server_id"),o=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!r||!qt(o)?null:{relayUrl:t,serverId:r,hostEncPubJwk:o}},Bl=()=>{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"},Ei=5e3,Cl=async(e,t,r)=>{const o=bl(e);if(!o)throw new Error("invalid-connect-link");const n=await Ci().catch(()=>""),a={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:o.pairingId,secret:o.secret,clientLabel:o.label||"PiChamber Desktop",clientKind:"desktop",deviceName:"PiChamber Desktop",devicePlatform:Bl(),...n?{dedupeKey:`desktop:${n}`}:{}})},s=async h=>{if(!h.ok)return null;const v=await h.json().catch(()=>null);return(typeof v?.clientToken=="string"?v.clientToken.trim():"")||null};let i=null;const c=[...o.candidates].sort((h,v)=>(h.type==="relay"?1:0)-(v.type==="relay"?1:0));for(const h of c){if(h.type==="relay"){const O=Wn({relayUrl:h.relayUrl,serverId:h.serverId,hostEncPubJwk:h.hostEncPubJwk,...h.grant?{grant:h.grant}:{}});try{const W=await s(await O.fetch("/api/client-auth/pairing/redeem",a));if(W){i={relay:{relayUrl:h.relayUrl,serverId:h.serverId,hostEncPubJwk:h.hostEncPubJwk},token:W};break}}catch{}finally{O.close()}continue}const v=Q(h.url);if(v)try{const O=await s(await fetch(`${v}/api/client-auth/pairing/redeem`,a));if(O){i={directUrl:v,token:O};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const d=o.candidates.find(h=>h.type==="relay"),l=i.relay||(d?{relayUrl:d.relayUrl,serverId:d.serverId,hostEncPubJwk:d.hostEncPubJwk}:void 0),u=o.candidates.filter(h=>h.type!=="relay").map(h=>Q(h.url)).find(h=>!!h),f=i.directUrl||u,m=f||(l?Ai(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");let p=null;if(i.directUrl){const h=r?.healthTimeoutMs??Ei,v=new AbortController,O=setTimeout(()=>v.abort(),h);try{const W=await fetch(`${i.directUrl}/health`,{headers:{Accept:"application/json"},signal:v.signal,credentials:"omit"});if(W.ok){const oe=await W.json().catch(()=>null),ve=typeof oe?.serverId=="string"?oe.serverId.trim():"";ve&&(p=ve)}}catch{}finally{clearTimeout(O)}}const g=new Set;l?.serverId&&g.add(l.serverId),p&&g.add(p);const A=h=>{for(const v of g)if(h.serverId===v||h.relay?.serverId===v)return!0;return!1},y=t.find(h=>{if(l){if(h.relay?.serverId===l.serverId)return!0}else if(!h.relay&&Q(h.apiUrl||h.url)===m)return!(h.serverId&&p&&h.serverId!==p);return A(h)}),b=y?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),D={...y||{},id:b,label:o.label||y?.label||da(m),url:m,apiUrl:f,clientToken:i.token,...l?{relay:l}:{}};return y?.serverId?D.serverId=y.serverId:p&&(D.serverId=p),{hostId:b,hosts:y?t.map(h=>h.id===b?D:h):[D,...t]}},vl=/^(t|.*(?:token|auth|secret|api).*)$/i,Q=e=>{const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},kl=e=>{const t=Q(e);if(!t)return null;try{const r=new URL(t);if((r.pathname.replace(/\/+$/,"")||"/")==="/connect"&&r.searchParams.has("t"))return{persistedUrl:r.origin,redeemUrl:r.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},da=e=>{const t=Q(e);if(!t)return e;try{const r=new URL(t);(r.username||r.password)&&(r.username="",r.password="");const o=Array.from(new Set(Array.from(r.searchParams.keys())));for(const n of o)vl.test(n)&&r.searchParams.set(n,"[REDACTED]");return r.toString()}catch{return t}},rt=(e,t)=>{const r=Q(e),o=Q(t);if(!r||!o)return!1;try{const n=new URL(r),a=new URL(o);if(n.origin!==a.origin||a.search&&n.search!==a.search)return!1;const s=a.pathname.length>1?a.pathname.replace(/\/+$/,""):a.pathname,i=n.pathname.length>1?n.pathname.replace(/\/+$/,""):n.pathname;return s==="/"?!0:i===s||i.startsWith(`${s}/`)}catch{return!1}},Y=(e,t)=>{const r=e[t];return typeof r=="string"?r:null},es=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},Dl=e=>{if(!qt(e))return null;const t=Y(e,"id"),r=Y(e,"label"),o=Y(e,"url"),n=Y(e,"apiUrl")||Y(e,"api_url"),a=Y(e,"clientToken")||Y(e,"client_token"),s=El(e.requestHeaders),i=wl(e.relay),c=Y(e,"serverId")||Y(e,"server_id");return!t||!r||!o?null:{id:t,label:r,url:o,...n?{apiUrl:n}:{},...a?{clientToken:a}:{},...s?{requestHeaders:s}:{},...i?{relay:i}:{},...c?.trim()?{serverId:c.trim()}:{}}},Pe=e=>Q(e.apiUrl||e.url)||e.apiUrl||e.url,Sl=(e,t)=>{const r={...e,url:t,apiUrl:t};return Q(Pe(e))!==Q(t)&&delete r.serverId,r},kt=()=>Z()?(e,t)=>$(e,t):null,la=async()=>{const e=kt();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!qt(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const r=t.hosts,o=Array.isArray(r)?r.map(Dl).filter(i=>!!i):[],n=Y(t,"defaultHostId")||Y(t,"default_host_id")||Y(t,"defaultHostID"),a=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,s=Y(t,"localOrigin")||Y(t,"local_origin");return{hosts:o,defaultHostId:n,initialHostChoiceCompleted:a,localOrigin:s}},wi=async e=>{const t=kt();if(!t)return;const r={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(r.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:r})},Bi=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Ci=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Ml=8e3,ts=async(e,t,r)=>{const o=new AbortController,n=window.setTimeout(()=>o.abort(),Ml);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(n)}},Tl=async(e,t)=>{const r=Wn({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),o=Date.now();let n=!1;try{if(!(await ts(r,"/health")).ok)return{status:"unreachable",latencyMs:0};const s=new Headers({Accept:"application/json"});for(const[d,l]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&s.set(d,l);const i=t?.clientToken?.trim();i&&s.set("Authorization",`Bearer ${i}`);const c=await ts(r,"/auth/session",{headers:s});return c.status===401||c.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-o)}:c.ok?(n=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-o),...n?{tunnel:r}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{n||r.close()}},ua=async(e,t)=>{const r=kt();if(!r)return{status:"unreachable",latencyMs:0};const o=await r("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!qt(o))return{status:"unreachable",latencyMs:0};const n=o.status,a=n==="ok"||n==="auth"||n==="update-recommended"||n==="incompatible"||n==="wrong-service"||n==="unreachable"?n:"unreachable",s=es(o,"latencyMs")??es(o,"latency_ms")??0,i=Y(o,"reportedServerId");return{status:a,latencyMs:s,...i?.trim()?{reportedServerId:i.trim()}:{}}},Rl=async(e,t)=>{const r=kt();r&&await r("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Pl=async e=>{const t=kt();t&&await t("desktop_new_window_for_host",{hostId:e})},xy=Object.freeze(Object.defineProperty({__proto__:null,DESKTOP_HOST_HEALTH_PIN_TIMEOUT_MS:Ei,desktopHostProbe:ua,desktopHostsGet:la,desktopHostsSet:wi,desktopInstallIdGet:Ci,desktopLocalClientTokenGet:Bi,desktopOpenNewWindowAtUrl:Rl,desktopOpenNewWindowForHost:Pl,getDesktopHostApiUrl:Pe,importDesktopHostPairing:Cl,locationMatchesHost:rt,normalizeHostUrl:Q,probeRelayDesktopHost:Tl,redactSensitiveUrl:da,relayHostDisplayUrl:Ai,resolveDesktopHostUrl:kl,withEditedDesktopHostUrl:Sl},Symbol.toStringTag,{value:"Module"})),ot="local",Il=e=>({id:ot,label:"Local",url:e||fa()}),fa=()=>typeof window>"u"?"":window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,ma=e=>e.id===ot?"local":`host:${e.id}`,rs="host:",vi=e=>{const t=e.runtimeKey.trim();if(t===ot)return{kind:"local"};if(t.startsWith(rs)){const o=t.slice(rs.length),n=e.hosts.find(a=>a.id===o);if(n)return{kind:"host",host:n}}const r=e.hosts.find(o=>e.apiBaseUrl?rt(e.apiBaseUrl,Pe(o)):!1);return r?{kind:"host",host:r}:e.localOrigin&&e.apiBaseUrl&&rt(e.apiBaseUrl,e.localOrigin)?{kind:"local"}:null},_l=e=>{const t=typeof window>"u"?"":window.location.href,r=e.find(l=>l.id===ot)?.url||fa(),o=qe(),n=Q(r)||r,a=Q(t)||t,s=C(),i=e.find(l=>l.relay&&ma(l)===s);if(i)return{id:i.id,label:i.label,url:i.url};if(o&&rt(o,r))return{id:ot,label:"Local",url:n};const c=e.find(l=>o?rt(o,Pe(l)):!1);if(c)return{id:c.id,label:c.label,url:Q(Pe(c))||Pe(c)};if(t&&rt(t,r))return{id:ot,label:"Local",url:n};const d=e.find(l=>t?rt(t,l.url):!1);return d?{id:d.id,label:d.label,url:Q(d.url)||d.url}:t.startsWith("pichamber-ui://")?{id:ot,label:"Local",url:n}:{id:"custom",label:da(a||"Instance"),url:a}},Oy=Object.freeze(Object.defineProperty({__proto__:null,LOCAL_HOST_ID:ot,buildLocalDesktopHost:Il,getLocalDesktopOrigin:fa,resolveCurrentDesktopHost:_l,resolveDesktopHostIdentity:vi,runtimeKeyForDesktopHost:ma},Symbol.toStringTag,{value:"Module"})),xl=5e3,Ol=1500;let Ko=!1;const Nl=async e=>{if(!ko()||Ko)return;const t=`host:${e}`;if(C()===t){Ko=!0;try{const r=await la().catch(()=>null),o=r?.hosts.find(m=>m.id===e);if(!r||!o?.relay)return;const n=o.apiUrl?Q(o.apiUrl):null;if(n&&n.startsWith("https://"))return;const a=await F("/api/client-auth/connection/candidates").catch(()=>null);if(!a?.ok)return;const s=await a.json().catch(()=>null);if(!s||s.serverId!==o.relay.serverId)return;const i=Array.isArray(s.candidates)?s.candidates:[],c=[],d=[];for(const m of i){if(!m||typeof m!="object")continue;const p=m;if(p.type!=="lan"&&p.type!=="tailscale"||typeof p.url!="string")continue;const g=Q(p.url),A=p.type==="tailscale"?d:c;g&&!A.includes(g)&&A.push(g)}const l=c.length>0?c:d;if(l.length===0)return;const u=n&&l.includes(n)?n:l[0];u!==n&&await wi({hosts:r.hosts.map(m=>m.id===e?{...m,apiUrl:u}:m),defaultHostId:r.defaultHostId,initialHostChoiceCompleted:r.initialHostChoiceCompleted}).catch(()=>{});const f=await ua(u,{clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,expectedServerId:o.serverId??o.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(f.status==="unreachable"||f.status==="wrong-service"||f.status==="incompatible"||C()!==t)return;Ht({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:t})}finally{Ko=!1}}},Ll=e=>{typeof window>"u"||window.setTimeout(()=>{Nl(e).catch(()=>{})},xl)},Ul=(e,t)=>{if(t){const o=e.hosts.find(n=>n.id===t);return o?{kind:"host",host:o}:null}const r=vi({runtimeKey:C(),apiBaseUrl:qe(),hosts:e.hosts,localOrigin:e.localOrigin});if(r)return r;if(e.defaultHostId&&e.defaultHostId!=="local"){const o=e.hosts.find(n=>n.id===e.defaultHostId);if(o)return{kind:"host",host:o}}return{kind:"local"}},Hl=(e,t)=>{const r=e.clientToken||"";!r||Co()===r||Ht({apiBaseUrl:qe()||Pe(e),clientToken:r,requestHeaders:e.requestHeaders||null,runtimeKey:t,relay:Jt()?e.relay:void 0})},jl=async e=>{if(!ko())return;const t=await la().catch(()=>null);if(!t)return;const r=Ul(t,e);if(!r)return;if(r.kind==="local"){const u=await Bi();if(!u)return;const f=t.localOrigin||qe();if(!f||C()==="local"&&Co()===u)return;Ht({apiBaseUrl:f,clientToken:u,runtimeKey:"local"});return}const o=r.host,n=ma(o),a=u=>{Ht({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:n})},s=()=>{Ht({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:o.clientToken||null,runtimeKey:n,relay:o.relay??void 0}),Ll(o.id)};if(C()===n){const u=o.apiUrl?Q(Pe(o)):"";if(!!(u&&rt(qe(),u))||!o.relay){Hl(o,n);return}s();return}if(!o.relay){const u=Pe(o);if(!u)return;a(u);return}const i=o.apiUrl?Q(Pe(o)):null;if(!i){s();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",d=ua(i,{clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,expectedServerId:o.serverId??o.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),l=await Promise.race([d,new Promise(u=>setTimeout(()=>u(null),Ol))]);if(l){if(c(l)){a(i);return}s();return}s(),d.then(u=>{c(u)&&C()===n&&a(i)})},$l=64*1024,Kl=(e,t,r)=>{let o=0;return new ReadableStream({async pull(n){if(t?.aborted){n.error(new DOMException("The operation was aborted.","AbortError"));return}if(o>=e.size){n.close();return}const a=Math.min(o+$l,e.size),s=new Uint8Array(await e.slice(o,a).arrayBuffer());o=a,n.enqueue(s),r?.({loaded:o,total:e.size})}})},zl=(e,t)=>!Qt()||e instanceof File?e:new File([e],t.filename,{type:t.mime||e.type}),ql=async(e,t,r)=>{const o=!!vr();o||r.onProgress?.({loaded:0,total:t.size});const n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/octet-stream","X-PiChamber-Filename":encodeURIComponent(r.filename),"X-PiChamber-Mime":r.mime},body:o?Kl(t,r.signal,r.onProgress):zl(t,r),signal:r.signal,...o?{duplex:"half"}:{}},a=await F(e,n);return!o&&a.ok&&r.onProgress?.({loaded:t.size,total:t.size}),a},Pt=1,Gl="events.streamEpoch",Wl=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return Number.isSafeInteger(t.count)&&t.count>=1&&t.count<=99&&(t.kind==="input"||t.kind==="approval")&&typeof t.since=="number"&&Number.isFinite(t.since)&&t.since>0},Vl=["session.snapshot","session.lifecycle","session.deleted","session.updated","session.tree.updated","session.input","assistant.message.start","assistant.message.delta","assistant.message.end","assistant.thinking.delta","session.tool.start","session.tool.update","session.tool.end","session.queue","session.model","session.thinking","session.compaction","session.error","session.interrupted","extension.entry","extension.message","extension.notify","extension.catalog","extension.editor","extension.title","extension.status","extension.widget","extension.dialog","extension.dialog.dismiss","extension.ui","extension.app","extension.working","extension.editor.track","extension.error"],gn=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.protocolVersion===Pt&&t.kind==="event"&&typeof t.name=="string"&&Number.isSafeInteger(t.sequence)&&t.sequence>=0&&typeof t.sessionId=="string"&&t.sessionId.length>0&&typeof t.directory=="string"&&t.directory.length>0&&!!(t.payload&&typeof t.payload=="object"&&!Array.isArray(t.payload))&&Vl.includes(t.name)},ki=(e,t)=>{const r=vr();return r?r.openWebSocket(rd(e),t):Yc(new WebSocket(e))},Di="pichamber.mobile.diagnostics.v1",ga=300,Jl=240,Yl=1e3;let Gt=[],os=!1,$t=null,zo=!1;const xt=e=>e==null?void 0:String(e).replace(/(?:authorization|proxy-authorization)\s*:\s*bearer\s+[^\s,;]+/gi,"authorization=[redacted]").replace(/\b(bearer|token|password|secret|api[-_]?key)\b(?:\s*[:=]\s*|\s+)[^\s,;]+/gi,"$1=[redacted]").replace(/(?:https?|wss?):\/\/[^\s"'`]+/gi,"[url]").replace(/(?:[A-Za-z]:[\\/]|\/(?:home|Users|data|storage|private|var)\/)[^\s"'`]+/g,"[path]").replace(/\s+/g," ").trim().slice(0,Jl)||void 0,Ql=e=>{if(!e||typeof e!="object")return{detail:xt(e)};const t=e;return{...typeof t.code=="string"?{code:xt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.message!==void 0?{detail:xt(t.message)}:typeof t.name=="string"?{detail:xt(t.name)}:{}}},Si=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},Do=()=>{if(os)return;os=!0;const e=Si();if(e)try{const t=e.getItem(Di);if(!t)return;const r=JSON.parse(t);if(!Array.isArray(r))return;const o=[];for(const n of r){if(!n||typeof n!="object")continue;const a=n,s=typeof a.at=="string"?a.at:null,i=typeof a.category=="string"?a.category:null;if(!s||!i)continue;const c={at:s,category:i,...typeof a.code=="string"?{code:a.code}:{},...typeof a.status=="number"&&Number.isFinite(a.status)?{status:a.status}:{},...typeof a.detail=="string"?{detail:a.detail}:{}};o.push(c)}Gt=[...o,...Gt].slice(-ga)}catch{}},Xl=()=>{$t!==null&&(clearTimeout($t),$t=null)},Zl=()=>{$t===null&&($t=setTimeout(()=>{$t=null,Xr()},Yl))},Xr=()=>{Xl();const e=Si();if(e)try{Do(),e.setItem(Di,JSON.stringify(Gt.slice(-ga)))}catch{}},q=(e,t={})=>{if(!Qt())return;Do();const r={at:new Date().toISOString(),category:e.trim().slice(0,80)||"unknown",...t.code?{code:xt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.detail!==void 0?{detail:xt(t.detail)}:{}};Gt=[...Gt,r].slice(-ga),Zl()},eu=(e,t)=>{q(e,Ql(t))},tu=()=>(Do(),JSON.stringify({format:"pichamber-mobile-diagnostics-v1",generatedAt:new Date().toISOString(),platform:typeof navigator>"u"?"unknown":navigator.userAgent,entries:Gt},null,2)),Ny=async()=>{const e=tu(),{isShareCancelledError:t,saveOrShareFile:r}=await yc(async()=>{const{isShareCancelledError:n,saveOrShareFile:a}=await import("./nativeFileSave-CFuugNKV.js");return{isShareCancelledError:n,saveOrShareFile:a}},__vite__mapDeps([0,1,2,3,4,5,6,7]));if(typeof navigator<"u"&&typeof navigator.share=="function")try{return await navigator.share({title:"PiChamber mobile diagnostics",text:e}),"shared"}catch(n){if(t(n))throw new Error("Diagnostics export was cancelled")}if(window.Capacitor?.getPlatform?.()==="android")try{return await r({filename:"pichamber-mobile-diagnostics.json",mimeType:"application/json",data:e}),"shared"}catch{}if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),"copied";if(typeof document<"u"){const n=new Blob([e],{type:"application/json"}),a=URL.createObjectURL(n),s=document.createElement("a");return s.href=a,s.download="pichamber-mobile-diagnostics.json",document.body.appendChild(s),s.click(),s.remove(),window.setTimeout(()=>URL.revokeObjectURL(a),0),"downloaded"}throw new Error("No mobile export method is available")},Ly=()=>{if(!Qt()||typeof window>"u"||zo)return()=>{};zo=!0,Do(),q("app-launch",{code:"start"});const e=n=>{q("window-error",{code:n.error?.name,detail:n.message})},t=n=>{eu("unhandled-rejection",n.reason)},r=()=>{Xr()},o=()=>{document.visibilityState==="hidden"&&Xr()};return window.addEventListener("error",e),window.addEventListener("unhandledrejection",t),window.addEventListener("pagehide",r),document.addEventListener("visibilitychange",o),()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",t),window.removeEventListener("pagehide",r),document.removeEventListener("visibilitychange",o),Xr(),zo=!1}},ru=3e4,ou=250,nu=5e3,au=6e4,su=8,iu=2e3,cu=1e4,du=5e3,lu=3e4,uu=5e3,It=new Map,fu=8,mu=(e,t)=>{if(!(!e||!t||t.length>128))for(It.delete(e),It.set(e,t);It.size>fu;){const r=It.keys().next();if(r.done)break;It.delete(r.value)}},Xe=(e=C())=>It.get(e),Mi=e=>{const t={};return typeof e.fromSequence=="number"&&Number.isFinite(e.fromSequence)&&(t.fromSequence=String(Math.max(0,Math.floor(e.fromSequence)))),typeof e.sessionId=="string"&&e.sessionId.length>0&&(t.sessionId=e.sessionId),typeof e.streamEpoch=="string"&&e.streamEpoch.length>0&&(t.streamEpoch=e.streamEpoch),t.capabilities=Gl,t},ns=(e,t,r)=>{const o=Re(),n=Mi(t);return e==="ws"?o.websocket("/api/pi/events",n,r):o.sse("/api/pi/events",n)},gu=()=>"/api/pi/runtime",Zr=()=>Qt()&&!Jt()&&typeof EventSource<"u",pu=3e3;let pn=null,lr=null;const Uy=()=>{pn=null,lr=null},hu=1e4,Hr=e=>({...e,capabilities:[...e.capabilities]}),mo=async(e,t,r)=>{const o=t??C();if(!r?.fresh){const s=pn;if(s&&s.runtimeKey===o&&s.runtimeKey===C()&&Date.now()<s.expiresAt)return Hr(s.result)}const n=!r?.fresh&&!e;if(n){const s=lr;if(s&&s.runtimeKey===o&&s.runtimeKey===C())return s.promise.then(Hr)}const a=async()=>{const s=r?.timeoutMs??hu,i=new AbortController,c=()=>i.abort(),d=setTimeout(()=>i.abort(),s);e&&(e.aborted?i.abort():e.addEventListener("abort",c,{once:!0}));try{const l=await F(gu(),{signal:i.signal});if(o!==C())return{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:"DAEMON_UNAVAILABLE",message:"Runtime changed during request"}};if(!l.ok)return q("runtime-health",{status:l.status,code:l.status===401||l.status===403?"auth":"http-error"}),{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:l.status===401||l.status===403?"DAEMON_AUTH_FAILED":"DAEMON_UNAVAILABLE"}};const f=await si(()=>l.json(),i.signal).catch(A=>{if((A instanceof DOMException||A instanceof Error)&&A.name==="AbortError")throw A;return null});if(!f||typeof f!="object")return{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:"DAEMON_PROTOCOL_MISMATCH"}};const m=typeof f.error?.code=="string"?f.error.code:void 0,p=typeof f.streamEpoch=="string"&&f.streamEpoch.length>0&&f.streamEpoch.length<=128?f.streamEpoch:void 0;f.state==="ready"&&p&&mu(o,p);const g={state:f.state==="ready"?"ready":"unavailable",protocolVersion:typeof f.protocolVersion=="number"?f.protocolVersion:Pt,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter(A=>typeof A=="string"):[],...p?{streamEpoch:p}:{},...m?{error:{code:m,...typeof f.error?.message=="string"?{message:f.error.message}:{}}}:{}};return!r?.fresh&&g.state==="ready"&&o===C()&&(pn={runtimeKey:o,result:Hr(g),expiresAt:Date.now()+pu}),g}catch(l){const u=(l instanceof DOMException||l instanceof Error)&&l.name==="AbortError";return q("runtime-health",{code:u?"timeout":"unreachable"}),{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:u?"DAEMON_TIMEOUT":"DAEMON_UNAVAILABLE"}}}finally{clearTimeout(d),e&&e.removeEventListener("abort",c)}};if(n){const s=a().finally(()=>{lr?.promise===s&&(lr=null)});return lr={runtimeKey:o,promise:s},s.then(Hr)}return a()},Fu=async(e,t,r)=>{const o=new AbortController,n=()=>o.abort(),a=setTimeout(n,t);r.aborted?o.abort():r.addEventListener("abort",n,{once:!0});try{const s=await mo(o.signal,e,{fresh:!0});return s.state==="unavailable"&&s.error?.code==="DAEMON_AUTH_FAILED"?"auth":"transient"}catch{return"transient"}finally{clearTimeout(a),r.removeEventListener("abort",n)}},yu=(e,t,r,o,n,a,s)=>{if(Zr()){const f=new EventSource(Re().sse("/api/pi/events",e)),m=new AbortController;let p=!1,g=!1,A=setTimeout(()=>{A=null,!(g||p)&&(q("stream-connect",{code:"setup-timeout"}),D(),a("sse-setup-timeout"))},s.setupTimeoutMs);const y=()=>{A&&clearTimeout(A),A=null},b=()=>{p||o()},D=()=>{y(),m.abort(),!p&&(p=!0,f.removeEventListener("heartbeat",b),f.close(),t.removeEventListener("abort",D))},h=v=>{try{const O=JSON.parse(v);gn(O)&&n(O)}catch{q("stream-frame",{code:"bad-sse-frame"})}};return f.onopen=()=>{p||(g=!0,y(),r())},f.onmessage=v=>{p||(o(),typeof v.data=="string"&&v.data.trim()&&h(v.data))},f.onerror=()=>{if(p)return;y(),f.removeEventListener("heartbeat",b),f.close(),t.removeEventListener("abort",D),p=!0,q("stream-disconnect",{code:"sse-error"});const v=s.classifySourceError;if(!v){a("sse-error");return}v(m.signal).then(O=>{m.signal.aborted||a(O==="auth"?"sse-auth-probe":"sse-error")})},f.addEventListener("heartbeat",b),t.aborted?D():t.addEventListener("abort",D,{once:!0}),D}const i=new AbortController,c=()=>i.abort();t.aborted?i.abort():t.addEventListener("abort",c,{once:!0});let d=!1,l=setTimeout(()=>{l=null,!(d||i.signal.aborted)&&(q("stream-connect",{code:"setup-timeout"}),a("sse-setup-timeout"),c())},s.setupTimeoutMs);const u=()=>{l&&clearTimeout(l),l=null};return F("/api/pi/events",{headers:{Accept:"text/event-stream"},query:e,signal:i.signal}).then(async f=>{if(!f.ok||!f.body){if(q("stream-connect",{status:f.status,code:f.body?"http-error":"missing-stream-body"}),f.status===401||f.status===403){u(),a(`sse-auth-${f.status}`);return}a(`sse-status-${f.status}`);return}d=!0,u(),r();const m=f.body.getReader(),p=new TextDecoder;let g="",A=[];const y=()=>{if(A.length===0)return;const b=A.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nativeFileSave-BJsGPh58.js","assets/vendor-boot-EC6IyLt1.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js"])))=>i.map(i=>d[i]);
2
+ import{c as Br,d as Cr,p as qn}from"./vendor-zustand-CUi8eEds.js";import{_ as yc}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as bc}from"./vendor-clsx-B-dksMZM.js";import{t as Ac}from"./vendor-tailwind-merge-CPcsbTWB.js";import{F as _s}from"./vendor-fuse.js-Dw8P0qyA.js";import{R as Ia}from"./vendor-react-DASdDPIk.js";const fr=1,Ec="pichamber-relay-v1",xs=1,Os=12,mr=1+Os,Fr=64*1024,yr=5,ao=128,Ns=0,Ls=1,zt=4,wc=1+zt,tn=Fr-yr-wc,_={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Bc=new Set(Object.values(_)),Cc=e=>Bc.has(e),At={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},$e=globalThis.crypto.subtle,Us={name:"ECDH",namedCurve:"P-256"},Hs=16,Po=32,vc=16,rn=4,js=8;class tt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const kc=()=>$e.generateKey(Us,!0,["deriveBits"]),Dc=async e=>{const t=await $e.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Sc=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new tt("invalid ECDH public key JWK");try{return await $e.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Us,!0,[])}catch{throw new tt("invalid ECDH public key JWK")}},Mc=()=>{const e=new Uint8Array(Hs);return globalThis.crypto.getRandomValues(e),e},Tc=async(e,t,r)=>{if(r.length!==Hs)throw new tt("invalid handshake nonce length");const o=await $e.deriveBits({name:"ECDH",public:t},e,256),n=await $e.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=new Uint8Array(await $e.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(Ec)},n,Po*2*8)),s=(i,c)=>$e.importKey("raw",i,{name:"AES-GCM"},!1,c);return{clientToHost:await s(a.slice(0,Po),["encrypt","decrypt"]),hostToClient:await s(a.slice(Po),["encrypt","decrypt"])}},Rc=(e,t,r)=>{for(let o=js-1;o>=0;o-=1)e[t+o]=Number(r&0xffn),r>>=8n},Pc=(e,t)=>{let r=0n;for(let o=0;o<js;o+=1)r=r<<8n|BigInt(e[t+o]);return r},Ic=e=>{const t=new Uint8Array(rn);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(o){if(o.length>Fr)throw new tt("plaintext frame exceeds maximum size");r+=1n;const n=new Uint8Array(Os);n.set(t,0),Rc(n,rn,r);const a=new Uint8Array(await $e.encrypt({name:"AES-GCM",iv:n},e,o)),s=new Uint8Array(mr+a.length);return s[0]=xs,s.set(n,1),s.set(a,mr),s}}},_c=e=>{let t=0n;return{async decrypt(r){if(r.length<mr+vc)throw new tt("encrypted frame too short");if(r[0]!==xs)throw new tt("unsupported encrypted frame version");const o=r.slice(1,mr),n=Pc(o,rn);if(n<=t)throw new tt("frame counter regression");let a;try{a=await $e.decrypt({name:"AES-GCM",iv:o},e,r.slice(mr))}catch{throw new tt("frame decryption failed")}return t=n,new Uint8Array(a)}}},Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",xc=e=>{let t="";for(let r=0;r<e.length;r+=3){const o=e[r],n=r+1<e.length?e[r+1]:void 0,a=r+2<e.length?e[r+2]:void 0;t+=Nr[o>>2],t+=Nr[(o&3)<<4|(n??0)>>4],n!==void 0&&(t+=Nr[(n&15)<<2|(a??0)>>6]),a!==void 0&&(t+=Nr[a&63])}return t},_a=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const r=t;if(r.v!==fr)return null;const o=r.batch===!0;return r.t==="ready"?{t:"ready",v:fr,batch:o}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:fr,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:o}:null},Oc=e=>({type:"fail",closeCode:At.ChannelFailure,reason:e}),Nc=async(e,t={})=>{const r=t.batch!==!1,o=await Sc(e),n=await kc(),a=Mc(),s={t:"hello",v:fr,clientPubJwk:await Dc(n.publicKey),nonce:xc(a),...r?{batch:!0}:{}};let i=!1;return{helloText:JSON.stringify(s),get established(){return i},async handleText(c){if(i)return _a(c)?.t==="ready"?{type:"ignore"}:Oc("plaintext frame on established channel");const d=_a(c);if(d?.t!=="ready")return{type:"ignore"};const l=await Tc(n.privateKey,o,a);return i=!0,{type:"established",batch:r&&d.batch===!0,channel:{encryptor:Ic(l.clientToHost),decryptor:_c(l.hostToClient)}}}}},$s=4294967295;class re extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Te=(e,t,r,o=!1)=>{if(!Number.isInteger(t)||t<0||t>$s)throw new re("invalid stream id");if(r.length>tn)throw new re("tunnel payload exceeds maximum size");const n=new Uint8Array(yr+r.length);return n[0]=o?e|ao:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(r,yr),n},Lc=e=>{if(e.length<yr)throw new re("tunnel frame too short");const t=e[0],r=(t&ao)!==0,o=t&~ao;if(!Cc(o))throw new re(`unknown tunnel frame type ${o}`);const n=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:o,streamId:n,payload:e.slice(yr),hasMoreFragments:r}},Uc=new TextEncoder,Hc=new TextDecoder,so=e=>Uc.encode(JSON.stringify(e)),io=(e,t)=>{let r;try{r=JSON.parse(Hc.decode(e))}catch{throw new re("malformed JSON tunnel payload")}if(!t(r))throw new re("unexpected JSON tunnel payload shape");return r},Ks=(e,t=tn)=>{if(t<=0||t>tn)throw new re("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r},xa=(e,t,r)=>{const o=Ks(r);return o.map((n,a)=>Te(e,t,n,a<o.length-1))},jc=(e=16*1024*1024)=>{const t=new Map;return{push(r){const o=`${r.streamId}:${r.frameType}`,n=t.get(o);if(!r.hasMoreFragments&&!n)return r.payload;const a=n?.chunks??[],s=(n?.totalBytes??0)+r.payload.length;if(s>e)throw t.delete(o),new re("fragmented message exceeds maximum size");if(a.push(r.payload),r.hasMoreFragments)return t.set(o,{chunks:a,totalBytes:s}),null;t.delete(o);const i=new Uint8Array(s);let c=0;for(const d of a)i.set(d,c),c+=d.length;return i},dropStream(r){for(const o of t.keys())o.startsWith(`${r}:`)&&t.delete(o)}}},$c=e=>{if(e.length===0)throw new re("cannot encode an empty frame batch");if(e.length===1){const n=e[0],a=new Uint8Array(1+n.length);if(a[0]=Ns,a.set(n,1),a.length>Fr)throw new re("frame batch exceeds maximum plaintext size");return a}let t=1;for(const n of e)t+=zt+n.length;if(t>Fr)throw new re("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=Ls;let o=1;for(const n of e)r[o]=n.length>>>24&255,r[o+1]=n.length>>>16&255,r[o+2]=n.length>>>8&255,r[o+3]=n.length&255,o+=zt,r.set(n,o),o+=n.length;return r},Kc=e=>{if(e.length<1)throw new re("empty batch plaintext");const t=e[0];if(t===Ns)return[e.slice(1)];if(t!==Ls)throw new re(`unknown batch container tag ${t}`);const r=[];let o=1;for(;o<e.length;){if(o+zt>e.length)throw new re("truncated batch frame length");const n=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;if(o+=zt,o+n>e.length)throw new re("truncated batch frame body");r.push(e.slice(o,o+n)),o+=n}if(r.length===0)throw new re("empty frame batch");return r},zc=new Set([_.HttpBody,_.WsText,_.WsBinary]),zs=150,qc=24*1024,Gc=32,Wc=e=>{const t=e.windowMs??zs,r=e.maxBatchBytes??qc,o=e.maxBatchFrames??Gc,n=e.now??(()=>Date.now()),a=e.setTimer??((g,A)=>setTimeout(g,A)),s=e.clearTimer??(g=>clearTimeout(g));let i=[],c=0,d=null,l=0,u=!1;const f=()=>{d!==null&&(s(d),d=null)},m=()=>{if(f(),i.length===0)return;const g=i;i=[],c=0,l=n(),e.sendBatch($c(g))};return{enqueue:g=>{if(u)return;const A=g[0]&~ao;if(!zc.has(A)){i.push(g),m();return}const y=n();if(i.length===0&&y-l>=t){i.push(g),m();return}const b=zt+g.length;if(i.length>0&&1+c+b>Fr&&m(),i.push(g),c+=b,c>=r||i.length>=o){m();return}d===null&&(d=a(m,t))},flush:m,dispose(){u=!0,f(),i=[],c=0}}},Vc=()=>{let e=1;return{next(){if(e>$s)throw new re("stream id space exhausted");const t=e;return e+=2,t}}},Jc=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(r){e.send(r)},close(r,o){e.close(r,o)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>t.onmessage?.({data:r.data}),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),e.onerror=()=>t.onerror?.(),t},Yc=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(r){r&&(e.binaryType=r)},onopen:null,onmessage:null,onerror:null,onclose:null,send(r){e.send(r)},close(r,o){e.close(r,o)}};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>{const o=r.data;(typeof o=="string"||o instanceof ArrayBuffer)&&t.onmessage?.({data:o})},e.onerror=()=>t.onerror?.(),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),t},Oa=0,Io=1,Na=2,La=3,Qc=new Set([At.AuthFailed,At.DuplicateClient,At.LimitExceeded]),Xc={[At.AuthFailed]:"relay authentication failed",[At.DuplicateClient]:"relay connection replaced by another client",[At.LimitExceeded]:"relay connection limit reached"},Bo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zc=e=>Bo(e)&&Object.values(e).every(t=>typeof t=="string"),ed=e=>Bo(e)&&typeof e.status=="number"&&Zc(e.headers),qs=e=>Bo(e)&&typeof e.reason=="string",td=e=>Bo(e)&&typeof e.code=="number"&&typeof e.reason=="string",Gs=/^[a-z][a-z\d+.-]*:\/\//i,Gn="http://tunnel.invalid",rd=e=>{try{const t=Gs.test(e)?new URL(e):new URL(e,Gn);return`${t.pathname}${t.search}`}catch{return e}},Lr=e=>({async*[Symbol.asyncIterator](){yield e}}),od=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:r,value:o}=await t.read();if(r)return;o&&(yield o)}}finally{t.releaseLock()}}}),nd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},ad=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:od(e)};if(typeof e=="string")return{body:Lr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Lr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Lr(nd(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,o=new Uint8Array(await t.arrayBuffer());return{body:Lr(o),contentType:r}},sd=async(e,t)=>{let r;const o=new Headers;let n="GET",a=null,s;e instanceof Request?(r=e.url,n=e.method,e.headers.forEach((u,f)=>o.set(f,u)),s=e.signal,a=e.body):r=e.toString(),t&&(t.method&&(n=t.method),t.headers&&new Headers(t.headers).forEach((u,f)=>o.set(f,u)),t.body!==void 0&&(a=t.body),t.signal&&(s=t.signal));const i=Gs.test(r)?new URL(r):new URL(r,Gn),{body:c,contentType:d}=await ad(a);d&&!o.has("content-type")&&o.set("content-type",d);const l={};return o.forEach((u,f)=>{l[f]=u}),{method:n.toUpperCase(),path:i.pathname,query:i.search.startsWith("?")?i.search.slice(1):i.search,headers:l,body:c,signal:s}},id="__pichamberAmbiguousTransport",cd=e=>(Object.defineProperty(e,id,{value:!0,enumerable:!1,configurable:!0}),e),dd=new Uint8Array(0),ld=new TextEncoder,ud=new TextDecoder,on=e=>e instanceof Error?e:new Error(String(e)),Ua=()=>new DOMException("The operation was aborted.","AbortError"),fd=async(e,t,r)=>{const o=await sd(t,r),n=o.signal;if(n?.aborted)throw Ua();const a=await e(n),s=a.nextStreamId();return await new Promise((i,c)=>{let d=!1,l=!1,u=null,f=null;const m=()=>{a.streams.delete(s),a.assembler.dropStream(s),f&&n&&n.removeEventListener("abort",f)},p=b=>{if(!l){if(l=!0,m(),!d){c(b);return}try{u?.error(b)}catch{}}},g=b=>{a.dead||a.send(Te(_.StreamAbort,s,so({reason:b})))},A=b=>cd(new Error(b));f=()=>{g("aborted"),p(Ua())},a.streams.set(s,{handleFrame(b,D){if(b===_.HttpResponse){if(d||l)return;let h;try{h=io(D,ed)}catch(W){g("malformed response head"),p(A(on(W).message));return}const v=h.status===204||h.status===205||h.status===304;let O=null;v||(O=new ReadableStream({start(W){u=W},cancel(){l||(l=!0,m(),g("response body cancelled"))}})),d=!0,i(new Response(O,{status:h.status,headers:h.headers})),v&&(l=!0,m());return}if(b===_.HttpBody){if(!d||l)return;try{u?.enqueue(D)}catch{}return}if(b===_.StreamEnd){if(l)return;if(!d){p(A("tunnel stream ended before response head"));return}l=!0,m();try{u?.close()}catch{}return}if(b===_.StreamAbort){let h="stream aborted by host";try{h=io(D,qs).reason}catch{}p(A(h))}},fail(b){p(A(b.message))}}),n&&n.addEventListener("abort",f,{once:!0});const y={method:o.method,path:o.path,query:o.query,headers:o.headers};a.send(Te(_.HttpRequest,s,so(y))),(async()=>{try{if(o.body)for await(const b of o.body){if(l||a.dead)return;for(const D of Ks(b))a.send(Te(_.HttpBody,s,D))}!l&&!a.dead&&a.send(Te(_.StreamEnd,s,dd))}catch(b){g("request body failed"),p(A(on(b).message))}})()})},md=e=>{const t=e.indexOf("?");return t===-1?{path:e,query:""}:{path:e.slice(0,t),query:e.slice(t+1)}},gd=(e,t,r)=>{let o=Oa,n=null,a=0,s=!1;const i={get readyState(){return o},onopen:null,onmessage:null,onerror:null,onclose:null,send(d){if(o!==Io||!n||n.dead)throw new Error("relay tunnel socket is not open");if(typeof d=="string"){for(const u of xa(_.WsText,a,ld.encode(d)))n.send(u);return}const l=d instanceof ArrayBuffer?new Uint8Array(d.slice(0)):(()=>{const u=new Uint8Array(d.byteLength);return u.set(new Uint8Array(d.buffer,d.byteOffset,d.byteLength)),u})();for(const u of xa(_.WsBinary,a,l))n.send(u)},close(d=1e3,l=""){o===La||o===Na||(o===Io&&n&&!n.dead&&(o=Na,n.send(Te(_.WsClose,a,so({code:d,reason:l})))),c(d,l))}},c=(d,l,u=!1)=>{if(!s){if(s=!0,n&&(n.streams.delete(a),n.assembler.dropStream(a)),o=La,u)try{i.onerror?.()}catch{}try{i.onclose?.({code:d,reason:l})}catch{}}};return(async()=>{let d;try{d=await e()}catch(m){c(1006,on(m).message,!0);return}if(s)return;n=d,a=d.nextStreamId(),d.streams.set(a,{handleFrame(m,p){if(m===_.WsOpened){if(o===Oa){o=Io;try{i.onopen?.()}catch{}}return}if(m===_.WsText){try{i.onmessage?.({data:ud.decode(p)})}catch{}return}if(m===_.WsBinary){const g=new ArrayBuffer(p.byteLength);new Uint8Array(g).set(p);try{i.onmessage?.({data:g})}catch{}return}if(m===_.WsClose){let g=1e3,A="";try{const y=io(p,td);g=y.code,A=y.reason}catch{}c(g,A);return}if(m===_.StreamAbort){let g="stream aborted";try{g=io(p,qs).reason}catch{}c(1006,g,!0)}},fail(m){c(1012,m.message,!0)}});const{path:l,query:u}=md(t),f=r&&r.length>0?{path:l,query:u,protocols:r}:{path:l,query:u};d.send(Te(_.WsOpen,a,so(f)))})(),i},_o=new Uint8Array(0),Le=e=>e instanceof Error?e:new Error(String(e)),Ha=()=>new DOMException("The operation was aborted.","AbortError"),ja=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Wn=e=>{const t=e.helloRetryMs??1e3,r=e.helloTimeoutMs??3e4,o=e.pingIntervalMs??3e4,n=e.pingTimeoutMs??15e3,a=e.resumeProbeTimeoutMs??5e3,s=e.batchWindowMs??zs,i=e.batch!==!1,c=e.reconnectBaseDelayMs??1e3,d=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(B=>Jc(new WebSocket(B)));let f=!1,m={state:"idle"};const p=new Set;let g=null,A=null,y=null,b=null,D=0,h=0,v=null,O=[];const W=B=>{if(!(m.state===B.state&&m.lastError===B.lastError)){m=B;for(const N of p)try{N(m)}catch{}}},oe=B=>{const N=O;O=[];for(const L of N)L.reject(B)},ve=B=>{const N=O;O=[];for(const L of N)L.resolve(B)},_e=(B,N)=>{B.dead=!0;const L=Array.from(B.streams.values());B.streams.clear();for(const x of L)try{x.fail(N)}catch{}},ae=()=>{v!==null&&(clearTimeout(v),v=null)},ye=()=>{if(!(f||ja())){if(v!==null){ae(),St();return}m.state==="connecting"||m.state==="reconnecting"||g&&!g.dead&&b?.()}},er=()=>{typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",ye),window.addEventListener("pichamber:system-resume",ye))},Ir=()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",ye),window.removeEventListener("pichamber:system-resume",ye))},tr=()=>{if(f||v!==null)return;const B=c*Math.pow(1.5,Math.min(h,8)),N=Math.random()*.3*B,L=Math.min(d,Math.round(B+N)),x=ja()?Math.max(L,l):L;v=setTimeout(()=>{v=null,St()},x)},dt=()=>{const B=new URL(e.relayUrl);return B.searchParams.set("v",String(fr)),B.searchParams.set("role","client"),B.searchParams.set("serverId",e.serverId),e.grant&&B.searchParams.set("grant",e.grant),B.toString()},St=async()=>{if(f)return;const B=++D;ae(),y?.(),y=null,W({state:h===0?"connecting":"reconnecting"});let N;try{N=await Nc(e.hostEncPubJwk,{batch:i})}catch(H){Oe(B,Le(H),!0);return}if(f||B!==D)return;let L;try{L=u(dt())}catch(H){Oe(B,Le(H));return}A=L;let x=null,se=null,me=null,ee=null,lt=!1,Mt=null,de=!1,le=null,Tt=null,xe=Date.now(),E=!1,R=Promise.resolve();const U=()=>{b===ue&&(b=null),lt=!1,x!==null&&(clearInterval(x),x=null),se!==null&&(clearTimeout(se),se=null),me!==null&&(clearInterval(me),me=null),ee!==null&&(clearTimeout(ee),ee=null),Mt?.dispose(),Mt=null};y=U;const T=(H,V={})=>{const{terminal:G=!1,asErrorState:z=!1}=V;if(!(de||B!==D)){de=!0,U(),y===U&&(y=null),le&&_e(le,H),g===le&&(g=null);try{L.close()}catch{}if(A===L&&(A=null),G){f=!0,oe(H),W({state:"error",lastError:H.message});return}Oe(B,H,z)}},ue=()=>{de||B!==D||!le||le.dead||lt||(lt=!0,xe=Date.now(),ee!==null&&(clearTimeout(ee),ee=null),le.send(Te(_.Ping,0,_o)),ee=setTimeout(()=>{ee=null,T(new Error("relay resume probe timeout"))},a))},be=()=>{if(L.readyState===1)try{L.send(N.helloText)}catch(H){T(Le(H))}},xr=(H,V)=>{Tt=H,E=V,x!==null&&(clearInterval(x),x=null),se!==null&&(clearTimeout(se),se=null),h=0;const G=new Map,z=Vc(),ut=jc();let ge=Promise.resolve();const Ne=nr=>{ge=ge.then(async()=>{if(or.dead)return;const Fc=await H.encryptor.encrypt(nr);L.send(Fc)}).catch(()=>{})},ft=V?Wc({windowMs:s,sendBatch:Ne}):null;Mt=ft;const or={streams:G,assembler:ut,nextStreamId:()=>z.next(),send:nr=>{if(xe=Date.now(),ft){ft.enqueue(nr);return}Ne(nr)},dead:!1};le=or,g=or,b=ue,W({state:"connected"}),ve(or),me=setInterval(()=>{Date.now()-xe<o||(or.send(Te(_.Ping,0,_o)),ee===null&&(ee=setTimeout(()=>{ee=null,T(new Error("relay keepalive timeout"))},n)))},o)},Or=(H,V)=>{let G;try{G=Lc(V)}catch(ge){T(Le(ge));return}if(ee!==null&&(clearTimeout(ee),ee=null),lt=!1,G.frameType===_.Ping){H.send(Te(_.Pong,G.streamId,_o));return}if(G.frameType===_.Pong)return;xe=Date.now();let z=G.payload;if(G.frameType===_.WsText||G.frameType===_.WsBinary){let ge;try{ge=H.assembler.push(G)}catch(Ne){T(Le(Ne));return}if(ge===null)return;z=ge}else if(G.hasMoreFragments){T(new Error("unexpected fragmented tunnel frame"));return}const ut=H.streams.get(G.streamId);ut&&ut.handleFrame(G.frameType,z)};L.onopen=()=>{de||B!==D||(be(),x=setInterval(be,t))},L.onmessage=H=>{if(de||B!==D)return;const V=H.data;if(typeof V=="string"){R=R.then(async()=>{if(de||B!==D)return;const z=await N.handleText(V);if(z.type==="established"){if(Tt)return;xr(z.channel,z.batch)}else z.type==="fail"&&T(new Error(`relay handshake failed: ${z.reason}`))}).catch(z=>{T(Le(z))});return}const G=V instanceof ArrayBuffer?new Uint8Array(V):V instanceof Uint8Array?V:null;G&&(R=R.then(async()=>{if(de||B!==D)return;const z=le,ut=Tt;if(!z||!ut){T(new Error("encrypted frame before handshake completed"));return}let ge;try{ge=await ut.decryptor.decrypt(G)}catch(Ne){T(Le(Ne));return}if(E){let Ne;try{Ne=Kc(ge)}catch(ft){T(Le(ft));return}for(const ft of Ne){if(de||B!==D||z.dead)return;Or(z,ft)}return}Or(z,ge)}).catch(z=>{T(Le(z))}))},L.onclose=H=>{const V=Qc.has(H.code);T(new Error(Xc[H.code]??`relay socket closed (code ${H.code})`),{terminal:V,asErrorState:V})},L.onerror=()=>{},se=setTimeout(()=>{se=null,T(new Error("relay handshake timeout"),{asErrorState:!0})},r);function Oe(H,V,G=!1){H!==D||f||(oe(V),h+=1,W({state:G?"error":"reconnecting",lastError:V.message}),tr())}},_r=B=>f?Promise.reject(new Error("relay tunnel closed")):B?.aborted?Promise.reject(Ha()):g&&!g.dead?Promise.resolve(g):new Promise((N,L)=>{let x=null;const se={resolve(me){x&&B&&B.removeEventListener("abort",x),N(me)},reject(me){x&&B&&B.removeEventListener("abort",x),L(me)}};B&&(x=()=>{O=O.filter(me=>me!==se),L(Ha())},B.addEventListener("abort",x,{once:!0})),O.push(se)}),rr=()=>{if(f)return;f=!0,D+=1,ae(),Ir(),y?.(),y=null;const B=g;g=null;const N=new Error("relay tunnel closed");B&&_e(B,N),oe(N);try{A?.close()}catch{}A=null,W({state:"idle"})};return er(),St(),{fetch:(B,N)=>fd(_r,B,N),openWebSocket:(B,N)=>gd(()=>_r(),B,N),getStatus:()=>m,subscribeStatus(B){return p.add(B),()=>{p.delete(B)}},close:rr}};let he=null,gr=null;const pd=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),vr=()=>he,Jt=()=>he!==null,nn=new Set,q0=e=>(nn.add(e),()=>{nn.delete(e)}),Vn=e=>{if(e!==Jt())for(const t of[...nn])t()},hd=e=>{if(he&&gr&&pd(gr,e))return he;const t=Jt();return he?.close(),gr=e,he=Wn(e),Vn(t),he},G0=(e,t)=>{if(he===t)return;const r=Jt();he?.close(),gr=e,he=t,Vn(r)},Fd=()=>{const e=Jt();he?.close(),he=null,gr=null,Vn(e)};let Ws=()=>null,Vs="",co={},at="",br=0,ht=null,Ut="",Ar=0,wt="",Ft=null,Qe="",Jr=0,Yr=0;const Jn=1e4,yd=e=>e.toLowerCase()==="authorization",Js=e=>{const t={};for(const[r,o]of Object.entries(e||{})){const n=r.trim(),a=o.trim();n&&a&&!yd(n)&&(t[n]=a)}return t},bd=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([o,n])=>t[o]===n)},kr=e=>typeof e!="string"?"":e.trim(),Ad=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_CLIENT_TOKEN__;return kr(e)},Ed=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Ys=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():Ed();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},Yn=e=>{try{return new URL(e).origin}catch{return""}},Qs=()=>{Ut="",Ar=0,wt="",Ft=null,Qe="",Jr+=1},Dr=e=>{e!==void 0&&kr(e)!==at||(at="",br=0,Qs())},Xs=()=>{Yr+=1,ht=null,Dr(),Xn()},Zs=e=>{const t=kr(e);Vs=t,Xs(),Ws=()=>t?{type:"bearer",token:t}:null},ei=e=>{const t=Js(e);bd(co,t)||(co=t,Xs())},Qn=()=>{if(Object.keys(co).length>0)return co;if(typeof window>"u")return{};const e=window.__PICHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Js(e):{}},Co=()=>Vs||Ad(),wd=(e,t)=>{const r=kr(e);if(!r||typeof t!="number"||!Number.isFinite(t)){Dr();return}const o=at;at=r,br=t,o&&o!==r&&Sd()},ti=()=>!at||br<=Date.now()+Jn?(Dr(),""):at,Bd=e=>{const t=Yn(e);return!t||wt!==t?"":!Ut||Ar<=Date.now()+Jn?(Ut="",Ar=0,wt="",""):Ut},Cd=()=>{const e=ti();return!e&&(Co()||typeof window<"u")&&Sr().catch(()=>{}),e},ri=async()=>{const e=await Ws(),t=e?.type==="bearer"?kr(e.token):Co();return t?{type:"bearer",token:t}:null},oi=e=>{if(ht)return ht;const t=Yr,o=(async()=>{const n=await ri(),a=new Headers;for(const[u,f]of Object.entries(Qn()))a.set(u,f);n?.type==="bearer"&&a.set("Authorization",`Bearer ${n.token}`);const s=vr(),i=s?await s.fetch("/auth/url-token",{method:"POST",headers:a}):await fetch(Ys(e,"/auth/url-token"),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw t===Yr&&Dr(),new Error(`Failed to mint runtime URL auth token (${i.status})`);const c=await i.json().catch(()=>null),d=typeof c?.token=="string"?c.token.trim():"",l=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==Yr)throw new Error("Runtime URL auth token response is stale");if(wd(d,l),!at)throw new Error("Runtime URL auth token response was invalid");return at})().finally(()=>{ht===o&&(ht=null)});return ht=o,ht},vd=e=>{const t=Yn(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Ft&&Qe===t)return Ft;const r=Jr,n=(async()=>{const a=await fetch(Ys(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!a.ok)throw r===Jr&&t===Qe&&(Ut="",Ar=0,wt=""),new Error(`Failed to mint local runtime URL auth token (${a.status})`);const s=await a.json().catch(()=>null),i=typeof s?.token=="string"?s.token.trim():"",c=typeof s?.expiresAt=="number"?s.expiresAt:0;if(!i||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(r!==Jr||t!==Qe)throw new Error("Local runtime URL auth token response is stale");return Ut=i,Ar=c,wt=t,i})().finally(()=>{Ft===n&&(Ft=null,Qe="")});return Ft=n,Qe=t,Ft},Sr=async e=>{const t=ti();return t||oi(e)},kd=async e=>{const t=Yn(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const r=Bd(t);return r||((wt&&wt!==t||Qe&&Qe!==t)&&Qs(),vd(t))};let _t=0,pr=null,ni=null;const an=new Set,Dd=5e3,Sd=()=>{for(const e of an)try{e()}catch{}},ai=()=>{pr!==null&&(clearTimeout(pr),pr=null)},Xn=()=>{if(ai(),_t<=0||typeof window>"u")return;const e=br-Jn-Dd,t=br>0?Math.max(0,e-Date.now()):0;pr=setTimeout(()=>{pr=null,!(_t<=0)&&oi(ni).catch(()=>{}).finally(()=>{Xn()})},t)},W0=e=>{typeof e=="string"&&e.trim()&&(ni=e.trim()),_t+=1,Xn();let t=!1;return()=>{t||(t=!0,_t=Math.max(0,_t-1),_t===0&&ai())}},V0=e=>(an.add(e),()=>{an.delete(e)}),Md=async e=>{const t=new Headers(e);for(const[o,n]of Object.entries(Qn()))t.has(o)||t.set(o,n);if(t.has("Authorization"))return t;const r=await ri();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},sn="pichamber:auth-expired",J0=()=>{typeof window>"u"||window.dispatchEvent(new Event(sn))},Y0=e=>typeof window>"u"?()=>{}:(window.addEventListener(sn,e),()=>{window.removeEventListener(sn,e)}),Q0=async(e,t,r)=>{if(e.length===0)return[];const o=Math.max(1,Math.min(t,e.length)),n=new Array(e.length);let a=0;const s=async()=>{for(;;){const i=a;if(a+=1,i>=e.length)return;n[i]=await r(e[i])}};return await Promise.all(Array.from({length:o},()=>s())),n},$a=e=>{if(e instanceof Error)return e;if(typeof DOMException<"u")return new DOMException(typeof e=="string"?e:"The operation was aborted.","AbortError");const t=new Error(typeof e=="string"?e:"The operation was aborted.");return t.name="AbortError",t},si=(e,t)=>t?t.aborted?Promise.reject($a(t.reason)):new Promise((r,o)=>{let n=!1;const a=()=>{n||(n=!0,o($a(t.reason)))};t.addEventListener("abort",a,{once:!0}),e().then(s=>{n||(n=!0,t.removeEventListener("abort",a),r(s))},s=>{n||(n=!0,t.removeEventListener("abort",a),o(s))})}):e(),Td=["local","remote",null],Rd=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function ii(e){if(!e||typeof e!="object")return{valid:!1};const t=e,r=t.localAvailable===!1?{localAvailable:!1}:{},o=t.target,n=t.status;if(o!==null&&(typeof o!="string"||!Td.includes(o)))return{valid:!1};if(typeof n!="string"||!Rd.includes(n))return{valid:!1};if(o==="remote"||o==="local"){if(n==="ok"&&o==="local")return{valid:!0,outcome:{target:"local",status:"ok",...r}};if(n==="ok"&&o==="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,...r}};if(n==="unreachable")return o==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...r}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...r}};if(n==="incompatible"||n==="wrong-service")return o!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url,...r}};if(n==="missing")return o!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...r}}}if(o===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...r}};if(n==="missing")return{valid:!1}}return{valid:!1}}function Pd(){if(Id()!=="valid")return null;const t=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__,r=ii(t);return r.valid?r.outcome:null}function Id(){if(typeof window>"u")return"not-injected";const e=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":ii(e).valid?"valid":"malformed"}const lo=/^[a-z][a-z\d+.-]*:\/\//i,_d=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},cn=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),xd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return cn(e)},Od=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},dn=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[o,n]of r)n!=null&&e.searchParams.set(o,String(n))},Nd=(e,t)=>{if(!t)return e;const r=new URLSearchParams;dn({searchParams:r},t);const o=r.toString();return o?e.includes("?")?`${e}&${o}`:`${e}?${o}`:e},Ka=(e,t,r)=>{if(lo.test(t)){const a=new URL(t);return dn(a,r),a.toString()}const o=_d(t);if(!e)return Nd(o,r);const n=new URL(o,`${e}/`);return dn(n,r),n.toString()},xo=(e,t)=>{const r=t===void 0?Cd():t;if(!r)return e;const o=lo.test(e)?new URL(e):new URL(e,"http://pichamber.local");return o.searchParams.set("oc_url_token",r),lo.test(e)?o.toString():`${o.pathname}${o.search}${o.hash}`},Ld=(e,t)=>{const r=lo.test(e)?new URL(e):new URL(e,Od(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},Zn=(e={})=>{const t=cn(e.apiBaseUrl),r=cn(e.realtimeBaseUrl),o=()=>t||xd(),n=()=>r||o(),a=(i,c)=>Ka(o(),i,c),s=(i,c)=>Ka(n(),i,c);return{api:a,authenticatedAsset:(i,c)=>xo(a(i,c)),auth:a,health:i=>a("/health",i),rawFile:(i,c)=>a("/api/fs/raw",{path:i,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(i,c)=>xo(s(i,c)),websocket:(i,c,d)=>Ld(xo(s(i,c),d),e)}};let uo=Zn();const Re=()=>uo,Ud=e=>{uo=e},ea=e=>(uo=Zn(e),uo);let Oo=null,No=null,Lo=null;const za=new Set;let qa=!1;const ci=e=>{if(za.add(e),qa||typeof window>"u")return;qa=!0;const t=()=>{for(const r of za)r()};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{}},Hd=(e,t)=>{let r;try{r=e()}catch{return}const o=new Map,n=new Set;let a;const s=()=>{if(a=void 0,o.size===0&&n.size===0)return;const c=Array.from(o.entries()),d=Array.from(n);o.clear(),n.clear();for(const[l,u]of c)try{r.setItem(l,JSON.stringify(u,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!o.has(l)&&!n.has(l)&&o.set(l,u)}for(const l of d)try{r.removeItem(l)}catch(u){console.error("Failed to remove deferred storage value",u),o.has(l)||n.add(l)}},i=()=>{a===void 0&&(a=setTimeout(s,0))};return ci(s),{getItem:c=>{if(o.has(c))return o.get(c)??null;if(n.has(c))return null;const d=u=>{if(u===null)return null;try{return JSON.parse(u,t?.reviver)}catch{try{r.removeItem(c)}catch{}return null}},l=r.getItem(c);return l instanceof Promise?l.then(d):d(l)},setItem:(c,d)=>{o.set(c,d),n.delete(c),i()},removeItem:c=>{o.delete(c),n.add(c),i()}}},ta=e=>Hd(()=>ui(),e),jd=e=>{const t=new Map,r=new Set;let o;const n=()=>{if(o=void 0,t.size===0&&r.size===0)return;const s=Array.from(t.entries()),i=Array.from(r);t.clear(),r.clear();for(const[c,d]of s)try{e.setItem(c,d)}catch(l){console.error("Failed to persist deferred storage value",l),!t.has(c)&&!r.has(c)&&t.set(c,d)}for(const c of i)try{e.removeItem(c)}catch(d){console.error("Failed to remove deferred storage value",d),t.has(c)||r.add(c)}},a=()=>{o===void 0&&(o=setTimeout(n,0))};return ci(n),{getItem:s=>t.has(s)?t.get(s)??null:r.has(s)?null:e.getItem(s),setItem:(s,i)=>{t.set(s,i),r.delete(s),a()},removeItem:s=>{t.delete(s),r.add(s),a()},clear:()=>{t.clear(),r.clear(),o!==void 0&&(clearTimeout(o),o=void 0),e.clear()},key:s=>e.key(s),get length(){return e.length}}},di=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},ra=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,r)=>{e.set(t,r)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},li=e=>{const t=ra(),r=new Set,o=new Set,n=d=>{if(o.has(d))return null;if(r.has(d))return t.getItem(d);try{return e.getItem(d)}catch{return null}},a=(d,l)=>{try{e.setItem(d,l),t.removeItem(d),r.delete(d),o.delete(d);return}catch{try{e.removeItem(d)}catch{}}t.setItem(d,l),r.add(d),o.delete(d)},s=d=>{try{e.removeItem(d),o.delete(d)}catch{o.add(d)}t.removeItem(d),r.delete(d)},i=()=>{const d=[];try{for(let l=0;l<e.length;l+=1){const u=e.key(l);u&&d.push(u)}}catch{}try{e.clear(),o.clear()}catch{for(const l of d)o.add(l)}t.clear(),r.clear()},c=()=>{const d=new Set;try{for(let l=0;l<e.length;l+=1){const u=e.key(l);u&&!o.has(u)&&!r.has(u)&&d.add(u)}}catch{}for(const l of r)d.add(l);return[...d]};return{getItem:n,setItem:a,removeItem:s,clear:i,key:d=>c()[d]??null,get length(){return c().length}}},$d=()=>{const e=di("localStorage");return e?li(e):ra()},ui=()=>(Oo||(Oo=$d()),Oo),Mr=()=>(Lo||(Lo=jd(ui())),Lo),Kd=()=>{const e=di("sessionStorage");return e?li(e):ra()},X0=()=>(No||(No=Kd()),No),ln="pichamber:runtime-endpoint-changed",un="pichamber:runtime-endpoint-will-change";let st="",Bt="",fi=0;const Z0=()=>(vo(),fi),fn="pichamber:lastRuntimeEndpoint.v1",zd=()=>{try{const e=Mr().getItem(fn);if(!e)return null;const t=JSON.parse(e),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl.trim():"",o=typeof t.runtimeKey=="string"?t.runtimeKey.trim():"";return!r||!o||o==="mobile-disconnected"?null:{apiBaseUrl:r,runtimeKey:o}}catch{return null}},qd=(e,t)=>{try{const r=Mr();if(t==="mobile-disconnected"||!e){r.removeItem(fn);return}r.setItem(fn,JSON.stringify({apiBaseUrl:e,runtimeKey:t}))}catch{}},vo=()=>{if(st||Bt||typeof window>"u")return;const e=zd();if(e){st=e.apiBaseUrl,Bt=e.runtimeKey;try{window.__PICHAMBER_API_BASE_URL__=e.apiBaseUrl}catch{}ea({apiBaseUrl:e.apiBaseUrl,realtimeBaseUrl:e.apiBaseUrl})}},Uo=(e,t,r)=>{try{e[t]=r}catch{}},oa=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"}`}},mi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},gi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},pi=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},qe=()=>(vo(),st||mi());let Ho="",Ga=null,Wa,Va;const Ja=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},C=()=>{if(vo(),Bt)return Bt;const e=Ja("__PICHAMBER_API_BASE_URL__"),t=Ja("__PICHAMBER_LOCAL_ORIGIN__");if(Ga===st&&Wa===e&&Va===t)return Ho;const r=qe();return Ho=pi(r,gi())?"local":oa(r),Ga=st,Wa=e,Va=t,Ho},Gd=(e={})=>{if(vo(),st||Bt)return;const t=e.apiBaseUrl?.trim()||mi();t&&(st=t,Bt=e.runtimeKey?.trim()||(pi(t,gi())?"local":oa(t)))},Ht=e=>{const t=e.apiBaseUrl.trim(),r=qe(),o=C(),n=e.runtimeKey?.trim()||oa(t);fi+=1,qd(t,n);const a={apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(un,{detail:a})),st=t,Bt=n,typeof window<"u"){const s=window;Uo(s,"__PICHAMBER_API_BASE_URL__",t),Uo(s,"__PICHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Uo(s,"__PICHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}ea({apiBaseUrl:t,realtimeBaseUrl:t}),ei(e.requestHeaders||null),Zs(e.clientToken||null),e.relay?hd(e.relay):Fd(),Sr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ln,{detail:a}))},Wd=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(un,t),()=>window.removeEventListener(un,t)},hi=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(ln,t),()=>window.removeEventListener(ln,t)};let mn=null;const Vd=e=>{mn=e},na=()=>mn||(typeof window>"u"?null:window.__PICHAMBER_RUNTIME_APIS__??null),ey=Object.freeze(Object.defineProperty({__proto__:null,getRegisteredRuntimeAPIs:na,registerRuntimeAPIs:Vd},Symbol.toStringTag,{value:"Module"})),Jd=()=>typeof window>"u"?null:window.__PICHAMBER_ELECTRON__??null,Yt=()=>typeof window>"u"?null:window.__PICHAMBER_DESKTOP__??null,ko=()=>Jd()?.runtime==="electron",ty=()=>{if(typeof window>"u")return null;const e=window.__PICHAMBER_PLATFORM__;return typeof e=="string"?e:null},Z=()=>typeof Yt()?.invoke=="function",Ie=()=>ko()&&Z(),$=async(e,t)=>{const r=Yt();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},Ya=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},jo=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}}},Yd=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),ar=e=>{const t=Yd(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ce=()=>typeof window>"u"?!1:ko(),ce=()=>{if(typeof window>"u"||!Ce())return!1;if(C()==="local")return!0;const e=typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",t=jo(e),r=jo(qe());if(!r&&t&&Pd()?.target==="local")return!0;if(t&&r){if(t.origin===r.origin)return!0;const s=t.port||(t.protocol==="https:"?"443":"80"),i=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&s===i&&ar(t.hostname)&&ar(r.hostname)}const o=jo(window.location.origin);if(t&&o){if(t.origin===o.origin)return!0;const s=t.port||(t.protocol==="https:"?"443":"80"),i=o.port||(o.protocol==="https:"?"443":"80");return t.protocol===o.protocol&&s===i&&ar(t.hostname)&&ar(o.hostname)}const n=Ya(e),a=Ya(window.location.origin)||window.location.origin;return n&&a&&n===a?!0:!!(o&&ar(o.hostname))},ry=()=>{const t=na()?.runtime?.platform;return t==="web"?!0:t!=="desktop"},oy=(e,t=Ce())=>e==="web"&&!t,ny=async()=>{if(!Ie())return null;try{const e=await $("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}},ay=async e=>{if(!Ie())return null;try{const t=await $("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}},sy=async()=>{if(!Ie())return null;try{const e=await $("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}},iy=async e=>{if(!Ie())return null;try{const t=await $("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}},cy=async()=>{if(!Ie())return null;try{const e=await $("desktop_get_close_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get close to tray status",e),null}},dy=async e=>{if(!Ie())return null;try{const t=await $("desktop_set_close_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set close to tray status",t),null}},ly=async()=>{if(!Ie())return null;try{const e=await $("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}},uy=async e=>{if(!Ie())return null;try{const t=await $("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}},fy=async()=>{if(!Ie())return null;try{const e=await $("desktop_get_process_performance_recording");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get process performance recording status",e),null}},my=async e=>{if(!Ie())return null;try{const t=await $("desktop_set_process_performance_recording",{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 process performance recording status",t),null}},Qd=()=>Ce()&&Z()&&ce(),Xd=async()=>{if(typeof window<"u"){const e=window.__PICHAMBER_HOME__;if(e&&e.length>0)return e}return null},gy=async e=>{if(Qd())try{const t=await Yt()?.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"}},Fi=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),py=async e=>{if(Z()&&ce())try{const t=await Yt()?.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(!Fi(t))return{success:!1,error:"File selection cancelled"};const r=typeof t.path=="string"?t.path:"";return r?{success:!0,path:r,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"}},hy=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!Z()||!ce())return{success:!1,error:"Native file access not available"};try{const r=await Yt()?.grantFileAccess?.(t);if(!Fi(r))return{success:!1,error:"File access was not granted"};const o=typeof r.path=="string"?r.path:"",n=typeof r.outsideFileGrant=="string"?r.outsideFileGrant:"";return!o||!n?{success:!1,error:"File access was not granted"}:{success:!0,path:o,outsideFileGrant:n}}catch(r){return console.warn("Failed to request existing file access",r),{success:!1,error:r instanceof Error?r.message:String(r)}}},Fy=async e=>({success:!0}),yy=async e=>({success:!0}),by=async()=>Z()&&await $("desktop_get_update_channel")==="rc"?"rc":"stable",Ay=async e=>{if(!Z())throw new Error("Desktop update settings are unavailable.");const t=await $("desktop_set_update_channel",{channel:e});if(t!=="stable"&&t!=="rc")throw new Error("Unable to save the desktop update channel.");return t},Ey=async()=>Z()?await $("desktop_check_for_updates"):null,wy=async e=>{if(!Z())return!1;const t=Yt();let r=null,o=0,n;try{return typeof e=="function"&&t?.listen&&(r=await t.listen("pichamber:update-progress",a=>{const s=a?.payload;if(!s||typeof s!="object")return;const i=s,c=typeof i.event=="string"?i.event:null,d=i.data&&typeof i.data=="object"?i.data:null;if(c==="Started"){o=0,n=typeof d?.contentLength=="number"?d.contentLength:void 0,e({downloaded:o,total:n});return}if(c==="Progress"){const l=d?.downloaded,u=d?.total;typeof l=="number"&&(o=l),typeof u=="number"&&(n=u),e({downloaded:o,total:n});return}c==="Finished"&&e({downloaded:o,total:n})})),await $("desktop_download_and_install_update"),!0}catch(a){throw a instanceof Error?a:new Error(String(a))}finally{if(r)try{const a=r();a instanceof Promise&&await a}catch{}}},Zd=async()=>{if(!Z())return!1;try{return await $("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},By=async()=>Z()?Zd():!1,Cy=async()=>{if(!Z()||!ce())return null;try{const e=await $("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}},el=async(e,t)=>{if(!Z()||!ce())return!1;const r=e?.trim();if(!r)return!1;try{return await $("desktop_open_path",{path:r,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(o){return console.warn("Failed to open path",o),!1}},vy=async e=>{if(!Z()||!ce())return!1;const t=e?.trim();if(!t)return!1;try{return await $("desktop_reveal_path",{path:t}),!0}catch{return el(t)}},ky=async(e,t)=>{if(!Z()||!ce())return null;const r=e?.trim();if(!r)return null;try{const o=await $("desktop_save_markdown_file",{defaultFileName:r,content:t});return typeof o=="string"&&o.trim().length>0?o:null}catch(o){return console.warn("Failed to save markdown file",o),null}},Dy=async(e,t,r)=>{if(!Z()||!ce())return!1;const o=e?.trim(),n=t?.trim(),a=r?.trim();if(!o||!n||!a)return!1;try{return await $("desktop_open_in_app",{projectPath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},Sy=async(e,t,r)=>{if(!Z()||!ce())return!1;const o=e?.trim(),n=t?.trim(),a=r?.trim();if(!o||!n||!a)return!1;try{return await $("desktop_open_file_in_app",{filePath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open file in app",s),!1}},My=async(e,t)=>{if(!Z()||!ce())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const r=Array.isArray(e)?e.filter(o=>typeof o=="string"):[];if(r.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await $("desktop_get_installed_apps",{apps:r,force:t===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=o;return n.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(n.apps)?{apps:n.apps.filter(s=>s&&typeof s=="object").map(s=>{const i=s;return{name:typeof i.name=="string"?i.name:"",iconDataUrl:typeof i.iconDataUrl=="string"?i.iconDataUrl:null}}).filter(s=>s.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(o){return console.warn("Failed to fetch installed apps",o),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Qt=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location?.protocol==="capacitor:",Ty=()=>{if(typeof window>"u"||!Qt()||tl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},tl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ce()?"desktop":"web"},Ry=()=>{if(typeof navigator>"u")return!1;const e=navigator.platform||"",t=navigator.userAgent||"";return/Win/i.test(e)&&/ARM|aarch64/i.test(t)},Ct=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",rl=()=>typeof window>"u"?"":window.location.origin||"",aa=e=>{if(typeof window>"u")return!1;const t=rl();if(t&&e.origin===t)return!0;try{const r=new URL(window.location.href||t);return e.protocol===r.protocol&&e.host===r.host}catch{return!1}},sa=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),ia=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[o,n]of r)n!=null&&e.searchParams.set(o,String(n))},Qr=e=>{try{const t=Re().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const r=new URL(t);return e.origin!==r.origin?!1:Ct(e.pathname)}catch{return!1}},$o=e=>{if(Ct(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return aa(t)&&Ct(t.pathname)}catch{return!1}},ol=(e,t)=>{try{const r=new URL(e);if(!aa(r))return e;const o=Et(`${r.pathname}${r.search}`,t);return!sa(o)&&(r.protocol==="http:"||r.protocol==="https:")?(ia(r,t),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return e}},Et=(e,t)=>e==="/health"?Re().health(t):e.startsWith("/auth/")||e==="/auth"?Re().auth(e,t):Ct(e)?Re().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?ol(e,t):e,nl=e=>{const t=e instanceof Request?e.url:e.toString();if(!sa(t))return Ct(t);try{return Qr(new URL(t))}catch{return!1}},al=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},sl=(e,t)=>!al(t),Qa=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 r=[];let o=!1;for(const[n,a]of t)sl(n,a)?(r.push([n,encodeURIComponent(a)]),o=!0):r.push([n,a]);return o?r:void 0},Ue=async(e,t,r=!0)=>{const o=new Headers(Qa(e)??e);return t&&new Headers(Qa(t)??t).forEach((n,a)=>o.set(a,n)),r?Md(o):o},il=(e,t)=>{if(!t)return e;const r=new URL(e,Gn);return ia(r,t),`${r.pathname}${r.search}`},yi=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!sa(r))return Ct(r)?il(r,t):null;try{const o=new URL(r);return!aa(o)||!Ct(o.pathname)?null:(ia(o,t),`${o.pathname}${o.search}`)}catch{return null}},cl=async(e,t,r)=>{const o=vr();if(!o)return null;const n=yi(e,r);if(n===null)return null;const a=e instanceof Request?e.headers:void 0,s=await Ue(a,t.headers,!0);return e instanceof Request?o.fetch(e,{...t,headers:s}):o.fetch(n,{...t,headers:s})},dl=(e,t)=>{if(typeof e=="string")return Et(e,t);if(e instanceof URL)return Et(e.toString(),t);const r=Et(e.url,t);return r===e.url?e:new Request(r,e)},ll=/\/api\/pi\/(health|projects|sessions|providers|resources|runtime|settings)(\b|\/|\?|$)/,Ur=new Map,ul=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!ll.test(t)?null:`GET ${t}`,F=async(e,t={})=>{const{query:r,...o}=t,n=vr(),a=n?yi(e,r):null,s=o.signal??(e instanceof Request?e.signal:void 0);let i,c,d;if(n&&a!==null){const p=e instanceof Request?e.headers:void 0,g=await Ue(p,o.headers,!0);i=e instanceof Request?()=>n.fetch(e,{...o,headers:g}):()=>n.fetch(a,{...o,headers:g}),c=a,d=String(o.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const p=dl(e,r),g=p instanceof Request?p.headers:void 0,A=await Ue(g,o.headers,nl(p));let y=p instanceof Request?()=>fetch(new Request(p,{...o,headers:A})):()=>fetch(p,{...o,headers:A});if(Qt()&&s){const b=y;y=()=>si(b,s)}i=y,c=p instanceof Request?p.url:p instanceof URL?p.toString():String(p),d=String(o.method??(p instanceof Request?p.method:"GET")).toUpperCase()}const l=o.signal!=null||e instanceof Request,u=ul(d,c,l);if(!u)return i();const f=Ur.get(u);if(f)return f.then(p=>p.clone());const m=i();return Ur.set(u,m),m.then(()=>Ur.delete(u),()=>Ur.delete(u)),m.then(p=>p.clone())};let Xa=!1;const fl=()=>{if(Xa||typeof window>"u")return;Xa=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const o=await cl(t,r??{});if(o)return o;if(typeof t=="string"){if(!$o(t)){try{const a=new URL(t);if(Qr(a)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}}catch{}return e(t,r)}const n=await Ue(void 0,r?.headers);return e(Et(t),{...r,headers:n})}if(t instanceof URL){const n=t.toString();if(!$o(n)){if(Qr(t)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}return e(t,r)}const a=await Ue(void 0,r?.headers);return e(Et(n),{...r,headers:a})}if(t instanceof Request){if(!$o(t.url)){try{const i=new URL(t.url);if(Qr(i)){const c=await Ue(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const n=await Ue(t.headers,r?.headers),a=Et(t.url),s=a===t.url?t:new Request(a,t);return e(new Request(s,{...r,headers:n}))}return e(t,r)}},jt=16384,fo=globalThis,ml=e=>{if(fo.Buffer)return fo.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let r="";for(let o=0;o<t.length;o+=32768)r+=String.fromCharCode(...t.slice(o,o+32768));return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},bi=e=>{try{if(fo.Buffer)return fo.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n+=1)o[n]=r.charCodeAt(n);return new TextDecoder().decode(o)}catch{return null}},gl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:(r.hash="",r.toString().replace(/\/+$/g,""))}catch{return null}},pl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="ws:"&&r.protocol!=="wss:"?null:(r.hash="",r.toString())}catch{return null}},Za=e=>typeof e=="string"&&e.length>0,hl=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Za(t.x)||!Za(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Fl=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,yl=e=>{if(!e||typeof e!="object")return null;const t=e,r=Fl(t.priority);if(t.type==="lan"||t.type==="tunnel"||t.type==="tailscale"){const o=gl(t.url);if(!o)return null;const n=t.type==="tailscale"&&(t.mode==="private"||t.mode==="public")?t.mode:void 0;return{type:t.type,url:o,...n?{mode:n}:{},...r===void 0?{}:{priority:r}}}if(t.type==="relay"){const o=pl(t.relayUrl);if(!o)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const a=hl(t.hostEncPubJwk);if(!a)return null;const s=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:o,serverId:n,hostEncPubJwk:a,...s?{grant:s}:{},...r===void 0?{}:{priority:r}}}return null},ca=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const r=typeof t.pairingId=="string"?t.pairingId.trim():"",o=typeof t.secret=="string"?t.secret.trim():"";if(!r||!o)return null;const n=Array.isArray(t.candidates)?t.candidates.map(yl).filter(c=>!!c):[];if(n.length===0)return null;const a=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(a){const c=Date.parse(a);if(!Number.isFinite(c)||c<=Date.now())return null}const s=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,i=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:r,secret:o,...s?{label:s}:{},...i?{fingerprint:i}:{},...a?{expiresAt:a}:{},candidates:n}},Py=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}),Iy=e=>{const t=ca(e);if(!t)throw new Error("Invalid pairing connection payload");const r=new URLSearchParams;return r.set("v","2"),r.set("p",ml(JSON.stringify(t))),`pichamber://connect?${r.toString()}`},bl=e=>{const t=e.trim();if(!t||t.length>jt)return null;try{const r=new URL(t);if(r.protocol!=="pichamber:"||r.hostname!=="connect"||r.searchParams.get("v")!=="2")return null;const o=r.searchParams.get("p")||"";if(!o||o.length>jt)return null;const n=bi(o);return!n||n.length>jt?null:ca(JSON.parse(n))}catch{return null}},_y=e=>{const t=e.trim();if(!t||t.length>jt)return null;const r=t.indexOf("?");if(r===-1||!/^pichamber:\/\/connect\/?$/i.test(t.slice(0,r)))return null;let o=null,n=null;for(const s of t.slice(r+1).split("&")){const i=s.indexOf("=");if(i===-1)continue;const c=s.slice(0,i),d=s.slice(i+1);c==="v"?o=d:c==="p"&&(n=d)}if(o!=="2"||!n||n.length>jt)return null;const a=bi(n);if(!a||a.length>jt)return null;try{return ca(JSON.parse(a))}catch{return null}},qt=e=>typeof e=="object"&&e!==null,Al=e=>e.trim().toLowerCase()==="authorization",El=e=>{if(!qt(e))return;const t={};for(const[r,o]of Object.entries(e)){const n=r.trim(),a=typeof o=="string"?o.trim():"";!n||!a||/[\r\n:]/.test(n)||/[\r\n]/.test(a)||Al(n)||(t[n]=a)}return Object.keys(t).length>0?t:void 0},Ai=e=>`relay://${e}`,wl=e=>{if(!qt(e))return null;const t=Y(e,"relayUrl")||Y(e,"relay_url"),r=Y(e,"serverId")||Y(e,"server_id"),o=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!r||!qt(o)?null:{relayUrl:t,serverId:r,hostEncPubJwk:o}},Bl=()=>{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"},Ei=5e3,Cl=async(e,t,r)=>{const o=bl(e);if(!o)throw new Error("invalid-connect-link");const n=await Ci().catch(()=>""),a={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:o.pairingId,secret:o.secret,clientLabel:o.label||"PiChamber Desktop",clientKind:"desktop",deviceName:"PiChamber Desktop",devicePlatform:Bl(),...n?{dedupeKey:`desktop:${n}`}:{}})},s=async h=>{if(!h.ok)return null;const v=await h.json().catch(()=>null);return(typeof v?.clientToken=="string"?v.clientToken.trim():"")||null};let i=null;const c=[...o.candidates].sort((h,v)=>(h.type==="relay"?1:0)-(v.type==="relay"?1:0));for(const h of c){if(h.type==="relay"){const O=Wn({relayUrl:h.relayUrl,serverId:h.serverId,hostEncPubJwk:h.hostEncPubJwk,...h.grant?{grant:h.grant}:{}});try{const W=await s(await O.fetch("/api/client-auth/pairing/redeem",a));if(W){i={relay:{relayUrl:h.relayUrl,serverId:h.serverId,hostEncPubJwk:h.hostEncPubJwk},token:W};break}}catch{}finally{O.close()}continue}const v=Q(h.url);if(v)try{const O=await s(await fetch(`${v}/api/client-auth/pairing/redeem`,a));if(O){i={directUrl:v,token:O};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const d=o.candidates.find(h=>h.type==="relay"),l=i.relay||(d?{relayUrl:d.relayUrl,serverId:d.serverId,hostEncPubJwk:d.hostEncPubJwk}:void 0),u=o.candidates.filter(h=>h.type!=="relay").map(h=>Q(h.url)).find(h=>!!h),f=i.directUrl||u,m=f||(l?Ai(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");let p=null;if(i.directUrl){const h=r?.healthTimeoutMs??Ei,v=new AbortController,O=setTimeout(()=>v.abort(),h);try{const W=await fetch(`${i.directUrl}/health`,{headers:{Accept:"application/json"},signal:v.signal,credentials:"omit"});if(W.ok){const oe=await W.json().catch(()=>null),ve=typeof oe?.serverId=="string"?oe.serverId.trim():"";ve&&(p=ve)}}catch{}finally{clearTimeout(O)}}const g=new Set;l?.serverId&&g.add(l.serverId),p&&g.add(p);const A=h=>{for(const v of g)if(h.serverId===v||h.relay?.serverId===v)return!0;return!1},y=t.find(h=>{if(l){if(h.relay?.serverId===l.serverId)return!0}else if(!h.relay&&Q(h.apiUrl||h.url)===m)return!(h.serverId&&p&&h.serverId!==p);return A(h)}),b=y?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),D={...y||{},id:b,label:o.label||y?.label||da(m),url:m,apiUrl:f,clientToken:i.token,...l?{relay:l}:{}};return y?.serverId?D.serverId=y.serverId:p&&(D.serverId=p),{hostId:b,hosts:y?t.map(h=>h.id===b?D:h):[D,...t]}},vl=/^(t|.*(?:token|auth|secret|api).*)$/i,Q=e=>{const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},kl=e=>{const t=Q(e);if(!t)return null;try{const r=new URL(t);if((r.pathname.replace(/\/+$/,"")||"/")==="/connect"&&r.searchParams.has("t"))return{persistedUrl:r.origin,redeemUrl:r.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},da=e=>{const t=Q(e);if(!t)return e;try{const r=new URL(t);(r.username||r.password)&&(r.username="",r.password="");const o=Array.from(new Set(Array.from(r.searchParams.keys())));for(const n of o)vl.test(n)&&r.searchParams.set(n,"[REDACTED]");return r.toString()}catch{return t}},rt=(e,t)=>{const r=Q(e),o=Q(t);if(!r||!o)return!1;try{const n=new URL(r),a=new URL(o);if(n.origin!==a.origin||a.search&&n.search!==a.search)return!1;const s=a.pathname.length>1?a.pathname.replace(/\/+$/,""):a.pathname,i=n.pathname.length>1?n.pathname.replace(/\/+$/,""):n.pathname;return s==="/"?!0:i===s||i.startsWith(`${s}/`)}catch{return!1}},Y=(e,t)=>{const r=e[t];return typeof r=="string"?r:null},es=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},Dl=e=>{if(!qt(e))return null;const t=Y(e,"id"),r=Y(e,"label"),o=Y(e,"url"),n=Y(e,"apiUrl")||Y(e,"api_url"),a=Y(e,"clientToken")||Y(e,"client_token"),s=El(e.requestHeaders),i=wl(e.relay),c=Y(e,"serverId")||Y(e,"server_id");return!t||!r||!o?null:{id:t,label:r,url:o,...n?{apiUrl:n}:{},...a?{clientToken:a}:{},...s?{requestHeaders:s}:{},...i?{relay:i}:{},...c?.trim()?{serverId:c.trim()}:{}}},Pe=e=>Q(e.apiUrl||e.url)||e.apiUrl||e.url,Sl=(e,t)=>{const r={...e,url:t,apiUrl:t};return Q(Pe(e))!==Q(t)&&delete r.serverId,r},kt=()=>Z()?(e,t)=>$(e,t):null,la=async()=>{const e=kt();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!qt(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const r=t.hosts,o=Array.isArray(r)?r.map(Dl).filter(i=>!!i):[],n=Y(t,"defaultHostId")||Y(t,"default_host_id")||Y(t,"defaultHostID"),a=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,s=Y(t,"localOrigin")||Y(t,"local_origin");return{hosts:o,defaultHostId:n,initialHostChoiceCompleted:a,localOrigin:s}},wi=async e=>{const t=kt();if(!t)return;const r={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(r.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:r})},Bi=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Ci=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Ml=8e3,ts=async(e,t,r)=>{const o=new AbortController,n=window.setTimeout(()=>o.abort(),Ml);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(n)}},Tl=async(e,t)=>{const r=Wn({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),o=Date.now();let n=!1;try{if(!(await ts(r,"/health")).ok)return{status:"unreachable",latencyMs:0};const s=new Headers({Accept:"application/json"});for(const[d,l]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&s.set(d,l);const i=t?.clientToken?.trim();i&&s.set("Authorization",`Bearer ${i}`);const c=await ts(r,"/auth/session",{headers:s});return c.status===401||c.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-o)}:c.ok?(n=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-o),...n?{tunnel:r}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{n||r.close()}},ua=async(e,t)=>{const r=kt();if(!r)return{status:"unreachable",latencyMs:0};const o=await r("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!qt(o))return{status:"unreachable",latencyMs:0};const n=o.status,a=n==="ok"||n==="auth"||n==="update-recommended"||n==="incompatible"||n==="wrong-service"||n==="unreachable"?n:"unreachable",s=es(o,"latencyMs")??es(o,"latency_ms")??0,i=Y(o,"reportedServerId");return{status:a,latencyMs:s,...i?.trim()?{reportedServerId:i.trim()}:{}}},Rl=async(e,t)=>{const r=kt();r&&await r("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Pl=async e=>{const t=kt();t&&await t("desktop_new_window_for_host",{hostId:e})},xy=Object.freeze(Object.defineProperty({__proto__:null,DESKTOP_HOST_HEALTH_PIN_TIMEOUT_MS:Ei,desktopHostProbe:ua,desktopHostsGet:la,desktopHostsSet:wi,desktopInstallIdGet:Ci,desktopLocalClientTokenGet:Bi,desktopOpenNewWindowAtUrl:Rl,desktopOpenNewWindowForHost:Pl,getDesktopHostApiUrl:Pe,importDesktopHostPairing:Cl,locationMatchesHost:rt,normalizeHostUrl:Q,probeRelayDesktopHost:Tl,redactSensitiveUrl:da,relayHostDisplayUrl:Ai,resolveDesktopHostUrl:kl,withEditedDesktopHostUrl:Sl},Symbol.toStringTag,{value:"Module"})),ot="local",Il=e=>({id:ot,label:"Local",url:e||fa()}),fa=()=>typeof window>"u"?"":window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,ma=e=>e.id===ot?"local":`host:${e.id}`,rs="host:",vi=e=>{const t=e.runtimeKey.trim();if(t===ot)return{kind:"local"};if(t.startsWith(rs)){const o=t.slice(rs.length),n=e.hosts.find(a=>a.id===o);if(n)return{kind:"host",host:n}}const r=e.hosts.find(o=>e.apiBaseUrl?rt(e.apiBaseUrl,Pe(o)):!1);return r?{kind:"host",host:r}:e.localOrigin&&e.apiBaseUrl&&rt(e.apiBaseUrl,e.localOrigin)?{kind:"local"}:null},_l=e=>{const t=typeof window>"u"?"":window.location.href,r=e.find(l=>l.id===ot)?.url||fa(),o=qe(),n=Q(r)||r,a=Q(t)||t,s=C(),i=e.find(l=>l.relay&&ma(l)===s);if(i)return{id:i.id,label:i.label,url:i.url};if(o&&rt(o,r))return{id:ot,label:"Local",url:n};const c=e.find(l=>o?rt(o,Pe(l)):!1);if(c)return{id:c.id,label:c.label,url:Q(Pe(c))||Pe(c)};if(t&&rt(t,r))return{id:ot,label:"Local",url:n};const d=e.find(l=>t?rt(t,l.url):!1);return d?{id:d.id,label:d.label,url:Q(d.url)||d.url}:t.startsWith("pichamber-ui://")?{id:ot,label:"Local",url:n}:{id:"custom",label:da(a||"Instance"),url:a}},Oy=Object.freeze(Object.defineProperty({__proto__:null,LOCAL_HOST_ID:ot,buildLocalDesktopHost:Il,getLocalDesktopOrigin:fa,resolveCurrentDesktopHost:_l,resolveDesktopHostIdentity:vi,runtimeKeyForDesktopHost:ma},Symbol.toStringTag,{value:"Module"})),xl=5e3,Ol=1500;let Ko=!1;const Nl=async e=>{if(!ko()||Ko)return;const t=`host:${e}`;if(C()===t){Ko=!0;try{const r=await la().catch(()=>null),o=r?.hosts.find(m=>m.id===e);if(!r||!o?.relay)return;const n=o.apiUrl?Q(o.apiUrl):null;if(n&&n.startsWith("https://"))return;const a=await F("/api/client-auth/connection/candidates").catch(()=>null);if(!a?.ok)return;const s=await a.json().catch(()=>null);if(!s||s.serverId!==o.relay.serverId)return;const i=Array.isArray(s.candidates)?s.candidates:[],c=[],d=[];for(const m of i){if(!m||typeof m!="object")continue;const p=m;if(p.type!=="lan"&&p.type!=="tailscale"||typeof p.url!="string")continue;const g=Q(p.url),A=p.type==="tailscale"?d:c;g&&!A.includes(g)&&A.push(g)}const l=c.length>0?c:d;if(l.length===0)return;const u=n&&l.includes(n)?n:l[0];u!==n&&await wi({hosts:r.hosts.map(m=>m.id===e?{...m,apiUrl:u}:m),defaultHostId:r.defaultHostId,initialHostChoiceCompleted:r.initialHostChoiceCompleted}).catch(()=>{});const f=await ua(u,{clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,expectedServerId:o.serverId??o.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(f.status==="unreachable"||f.status==="wrong-service"||f.status==="incompatible"||C()!==t)return;Ht({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:t})}finally{Ko=!1}}},Ll=e=>{typeof window>"u"||window.setTimeout(()=>{Nl(e).catch(()=>{})},xl)},Ul=(e,t)=>{if(t){const o=e.hosts.find(n=>n.id===t);return o?{kind:"host",host:o}:null}const r=vi({runtimeKey:C(),apiBaseUrl:qe(),hosts:e.hosts,localOrigin:e.localOrigin});if(r)return r;if(e.defaultHostId&&e.defaultHostId!=="local"){const o=e.hosts.find(n=>n.id===e.defaultHostId);if(o)return{kind:"host",host:o}}return{kind:"local"}},Hl=(e,t)=>{const r=e.clientToken||"";!r||Co()===r||Ht({apiBaseUrl:qe()||Pe(e),clientToken:r,requestHeaders:e.requestHeaders||null,runtimeKey:t,relay:Jt()?e.relay:void 0})},jl=async e=>{if(!ko())return;const t=await la().catch(()=>null);if(!t)return;const r=Ul(t,e);if(!r)return;if(r.kind==="local"){const u=await Bi();if(!u)return;const f=t.localOrigin||qe();if(!f||C()==="local"&&Co()===u)return;Ht({apiBaseUrl:f,clientToken:u,runtimeKey:"local"});return}const o=r.host,n=ma(o),a=u=>{Ht({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:n})},s=()=>{Ht({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:o.clientToken||null,runtimeKey:n,relay:o.relay??void 0}),Ll(o.id)};if(C()===n){const u=o.apiUrl?Q(Pe(o)):"";if(!!(u&&rt(qe(),u))||!o.relay){Hl(o,n);return}s();return}if(!o.relay){const u=Pe(o);if(!u)return;a(u);return}const i=o.apiUrl?Q(Pe(o)):null;if(!i){s();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",d=ua(i,{clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,expectedServerId:o.serverId??o.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),l=await Promise.race([d,new Promise(u=>setTimeout(()=>u(null),Ol))]);if(l){if(c(l)){a(i);return}s();return}s(),d.then(u=>{c(u)&&C()===n&&a(i)})},$l=64*1024,Kl=(e,t,r)=>{let o=0;return new ReadableStream({async pull(n){if(t?.aborted){n.error(new DOMException("The operation was aborted.","AbortError"));return}if(o>=e.size){n.close();return}const a=Math.min(o+$l,e.size),s=new Uint8Array(await e.slice(o,a).arrayBuffer());o=a,n.enqueue(s),r?.({loaded:o,total:e.size})}})},zl=(e,t)=>!Qt()||e instanceof File?e:new File([e],t.filename,{type:t.mime||e.type}),ql=async(e,t,r)=>{const o=!!vr();o||r.onProgress?.({loaded:0,total:t.size});const n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/octet-stream","X-PiChamber-Filename":encodeURIComponent(r.filename),"X-PiChamber-Mime":r.mime},body:o?Kl(t,r.signal,r.onProgress):zl(t,r),signal:r.signal,...o?{duplex:"half"}:{}},a=await F(e,n);return!o&&a.ok&&r.onProgress?.({loaded:t.size,total:t.size}),a},Pt=1,Gl="events.streamEpoch",Wl=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return Number.isSafeInteger(t.count)&&t.count>=1&&t.count<=99&&(t.kind==="input"||t.kind==="approval")&&typeof t.since=="number"&&Number.isFinite(t.since)&&t.since>0},Vl=["session.snapshot","session.lifecycle","session.deleted","session.updated","session.tree.updated","session.input","assistant.message.start","assistant.message.delta","assistant.message.end","assistant.thinking.delta","session.tool.start","session.tool.update","session.tool.end","session.queue","session.model","session.thinking","session.compaction","session.error","session.interrupted","extension.entry","extension.message","extension.notify","extension.catalog","extension.editor","extension.title","extension.status","extension.widget","extension.dialog","extension.dialog.dismiss","extension.ui","extension.app","extension.working","extension.editor.track","extension.error"],gn=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.protocolVersion===Pt&&t.kind==="event"&&typeof t.name=="string"&&Number.isSafeInteger(t.sequence)&&t.sequence>=0&&typeof t.sessionId=="string"&&t.sessionId.length>0&&typeof t.directory=="string"&&t.directory.length>0&&!!(t.payload&&typeof t.payload=="object"&&!Array.isArray(t.payload))&&Vl.includes(t.name)},ki=(e,t)=>{const r=vr();return r?r.openWebSocket(rd(e),t):Yc(new WebSocket(e))},Di="pichamber.mobile.diagnostics.v1",ga=300,Jl=240,Yl=1e3;let Gt=[],os=!1,$t=null,zo=!1;const xt=e=>e==null?void 0:String(e).replace(/(?:authorization|proxy-authorization)\s*:\s*bearer\s+[^\s,;]+/gi,"authorization=[redacted]").replace(/\b(bearer|token|password|secret|api[-_]?key)\b(?:\s*[:=]\s*|\s+)[^\s,;]+/gi,"$1=[redacted]").replace(/(?:https?|wss?):\/\/[^\s"'`]+/gi,"[url]").replace(/(?:[A-Za-z]:[\\/]|\/(?:home|Users|data|storage|private|var)\/)[^\s"'`]+/g,"[path]").replace(/\s+/g," ").trim().slice(0,Jl)||void 0,Ql=e=>{if(!e||typeof e!="object")return{detail:xt(e)};const t=e;return{...typeof t.code=="string"?{code:xt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.message!==void 0?{detail:xt(t.message)}:typeof t.name=="string"?{detail:xt(t.name)}:{}}},Si=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},Do=()=>{if(os)return;os=!0;const e=Si();if(e)try{const t=e.getItem(Di);if(!t)return;const r=JSON.parse(t);if(!Array.isArray(r))return;const o=[];for(const n of r){if(!n||typeof n!="object")continue;const a=n,s=typeof a.at=="string"?a.at:null,i=typeof a.category=="string"?a.category:null;if(!s||!i)continue;const c={at:s,category:i,...typeof a.code=="string"?{code:a.code}:{},...typeof a.status=="number"&&Number.isFinite(a.status)?{status:a.status}:{},...typeof a.detail=="string"?{detail:a.detail}:{}};o.push(c)}Gt=[...o,...Gt].slice(-ga)}catch{}},Xl=()=>{$t!==null&&(clearTimeout($t),$t=null)},Zl=()=>{$t===null&&($t=setTimeout(()=>{$t=null,Xr()},Yl))},Xr=()=>{Xl();const e=Si();if(e)try{Do(),e.setItem(Di,JSON.stringify(Gt.slice(-ga)))}catch{}},q=(e,t={})=>{if(!Qt())return;Do();const r={at:new Date().toISOString(),category:e.trim().slice(0,80)||"unknown",...t.code?{code:xt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.detail!==void 0?{detail:xt(t.detail)}:{}};Gt=[...Gt,r].slice(-ga),Zl()},eu=(e,t)=>{q(e,Ql(t))},tu=()=>(Do(),JSON.stringify({format:"pichamber-mobile-diagnostics-v1",generatedAt:new Date().toISOString(),platform:typeof navigator>"u"?"unknown":navigator.userAgent,entries:Gt},null,2)),Ny=async()=>{const e=tu(),{isShareCancelledError:t,saveOrShareFile:r}=await yc(async()=>{const{isShareCancelledError:n,saveOrShareFile:a}=await import("./nativeFileSave-BJsGPh58.js");return{isShareCancelledError:n,saveOrShareFile:a}},__vite__mapDeps([0,1,2,3,4,5,6,7]));if(typeof navigator<"u"&&typeof navigator.share=="function")try{return await navigator.share({title:"PiChamber mobile diagnostics",text:e}),"shared"}catch(n){if(t(n))throw new Error("Diagnostics export was cancelled")}if(window.Capacitor?.getPlatform?.()==="android")try{return await r({filename:"pichamber-mobile-diagnostics.json",mimeType:"application/json",data:e}),"shared"}catch{}if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),"copied";if(typeof document<"u"){const n=new Blob([e],{type:"application/json"}),a=URL.createObjectURL(n),s=document.createElement("a");return s.href=a,s.download="pichamber-mobile-diagnostics.json",document.body.appendChild(s),s.click(),s.remove(),window.setTimeout(()=>URL.revokeObjectURL(a),0),"downloaded"}throw new Error("No mobile export method is available")},Ly=()=>{if(!Qt()||typeof window>"u"||zo)return()=>{};zo=!0,Do(),q("app-launch",{code:"start"});const e=n=>{q("window-error",{code:n.error?.name,detail:n.message})},t=n=>{eu("unhandled-rejection",n.reason)},r=()=>{Xr()},o=()=>{document.visibilityState==="hidden"&&Xr()};return window.addEventListener("error",e),window.addEventListener("unhandledrejection",t),window.addEventListener("pagehide",r),document.addEventListener("visibilitychange",o),()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",t),window.removeEventListener("pagehide",r),document.removeEventListener("visibilitychange",o),Xr(),zo=!1}},ru=3e4,ou=250,nu=5e3,au=6e4,su=8,iu=2e3,cu=1e4,du=5e3,lu=3e4,uu=5e3,It=new Map,fu=8,mu=(e,t)=>{if(!(!e||!t||t.length>128))for(It.delete(e),It.set(e,t);It.size>fu;){const r=It.keys().next();if(r.done)break;It.delete(r.value)}},Xe=(e=C())=>It.get(e),Mi=e=>{const t={};return typeof e.fromSequence=="number"&&Number.isFinite(e.fromSequence)&&(t.fromSequence=String(Math.max(0,Math.floor(e.fromSequence)))),typeof e.sessionId=="string"&&e.sessionId.length>0&&(t.sessionId=e.sessionId),typeof e.streamEpoch=="string"&&e.streamEpoch.length>0&&(t.streamEpoch=e.streamEpoch),t.capabilities=Gl,t},ns=(e,t,r)=>{const o=Re(),n=Mi(t);return e==="ws"?o.websocket("/api/pi/events",n,r):o.sse("/api/pi/events",n)},gu=()=>"/api/pi/runtime",Zr=()=>Qt()&&!Jt()&&typeof EventSource<"u",pu=3e3;let pn=null,lr=null;const Uy=()=>{pn=null,lr=null},hu=1e4,Hr=e=>({...e,capabilities:[...e.capabilities]}),mo=async(e,t,r)=>{const o=t??C();if(!r?.fresh){const s=pn;if(s&&s.runtimeKey===o&&s.runtimeKey===C()&&Date.now()<s.expiresAt)return Hr(s.result)}const n=!r?.fresh&&!e;if(n){const s=lr;if(s&&s.runtimeKey===o&&s.runtimeKey===C())return s.promise.then(Hr)}const a=async()=>{const s=r?.timeoutMs??hu,i=new AbortController,c=()=>i.abort(),d=setTimeout(()=>i.abort(),s);e&&(e.aborted?i.abort():e.addEventListener("abort",c,{once:!0}));try{const l=await F(gu(),{signal:i.signal});if(o!==C())return{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:"DAEMON_UNAVAILABLE",message:"Runtime changed during request"}};if(!l.ok)return q("runtime-health",{status:l.status,code:l.status===401||l.status===403?"auth":"http-error"}),{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:l.status===401||l.status===403?"DAEMON_AUTH_FAILED":"DAEMON_UNAVAILABLE"}};const f=await si(()=>l.json(),i.signal).catch(A=>{if((A instanceof DOMException||A instanceof Error)&&A.name==="AbortError")throw A;return null});if(!f||typeof f!="object")return{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:"DAEMON_PROTOCOL_MISMATCH"}};const m=typeof f.error?.code=="string"?f.error.code:void 0,p=typeof f.streamEpoch=="string"&&f.streamEpoch.length>0&&f.streamEpoch.length<=128?f.streamEpoch:void 0;f.state==="ready"&&p&&mu(o,p);const g={state:f.state==="ready"?"ready":"unavailable",protocolVersion:typeof f.protocolVersion=="number"?f.protocolVersion:Pt,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter(A=>typeof A=="string"):[],...p?{streamEpoch:p}:{},...m?{error:{code:m,...typeof f.error?.message=="string"?{message:f.error.message}:{}}}:{}};return!r?.fresh&&g.state==="ready"&&o===C()&&(pn={runtimeKey:o,result:Hr(g),expiresAt:Date.now()+pu}),g}catch(l){const u=(l instanceof DOMException||l instanceof Error)&&l.name==="AbortError";return q("runtime-health",{code:u?"timeout":"unreachable"}),{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:u?"DAEMON_TIMEOUT":"DAEMON_UNAVAILABLE"}}}finally{clearTimeout(d),e&&e.removeEventListener("abort",c)}};if(n){const s=a().finally(()=>{lr?.promise===s&&(lr=null)});return lr={runtimeKey:o,promise:s},s.then(Hr)}return a()},Fu=async(e,t,r)=>{const o=new AbortController,n=()=>o.abort(),a=setTimeout(n,t);r.aborted?o.abort():r.addEventListener("abort",n,{once:!0});try{const s=await mo(o.signal,e,{fresh:!0});return s.state==="unavailable"&&s.error?.code==="DAEMON_AUTH_FAILED"?"auth":"transient"}catch{return"transient"}finally{clearTimeout(a),r.removeEventListener("abort",n)}},yu=(e,t,r,o,n,a,s)=>{if(Zr()){const f=new EventSource(Re().sse("/api/pi/events",e)),m=new AbortController;let p=!1,g=!1,A=setTimeout(()=>{A=null,!(g||p)&&(q("stream-connect",{code:"setup-timeout"}),D(),a("sse-setup-timeout"))},s.setupTimeoutMs);const y=()=>{A&&clearTimeout(A),A=null},b=()=>{p||o()},D=()=>{y(),m.abort(),!p&&(p=!0,f.removeEventListener("heartbeat",b),f.close(),t.removeEventListener("abort",D))},h=v=>{try{const O=JSON.parse(v);gn(O)&&n(O)}catch{q("stream-frame",{code:"bad-sse-frame"})}};return f.onopen=()=>{p||(g=!0,y(),r())},f.onmessage=v=>{p||(o(),typeof v.data=="string"&&v.data.trim()&&h(v.data))},f.onerror=()=>{if(p)return;y(),f.removeEventListener("heartbeat",b),f.close(),t.removeEventListener("abort",D),p=!0,q("stream-disconnect",{code:"sse-error"});const v=s.classifySourceError;if(!v){a("sse-error");return}v(m.signal).then(O=>{m.signal.aborted||a(O==="auth"?"sse-auth-probe":"sse-error")})},f.addEventListener("heartbeat",b),t.aborted?D():t.addEventListener("abort",D,{once:!0}),D}const i=new AbortController,c=()=>i.abort();t.aborted?i.abort():t.addEventListener("abort",c,{once:!0});let d=!1,l=setTimeout(()=>{l=null,!(d||i.signal.aborted)&&(q("stream-connect",{code:"setup-timeout"}),a("sse-setup-timeout"),c())},s.setupTimeoutMs);const u=()=>{l&&clearTimeout(l),l=null};return F("/api/pi/events",{headers:{Accept:"text/event-stream"},query:e,signal:i.signal}).then(async f=>{if(!f.ok||!f.body){if(q("stream-connect",{status:f.status,code:f.body?"http-error":"missing-stream-body"}),f.status===401||f.status===403){u(),a(`sse-auth-${f.status}`);return}a(`sse-status-${f.status}`);return}d=!0,u(),r();const m=f.body.getReader(),p=new TextDecoder;let g="",A=[];const y=()=>{if(A.length===0)return;const b=A.join(`
3
3
  `).trim();if(A=[],!!b)try{const D=JSON.parse(b);gn(D)&&n(D)}catch{}};for(;;){const{value:b,done:D}=await m.read();if(D){y(),u(),a("sse-eof");return}o(),g+=p.decode(b,{stream:!0});let h=g.indexOf(`
4
4
  `);for(;h!==-1;){const v=g.slice(0,h).replace(/\r$/,"");g=g.slice(h+1),v.length===0?y():v.startsWith("data:")&&A.push(v.slice(5).replace(/^ /,"")),h=g.indexOf(`
5
5
  `)}}}).catch(f=>{if(i.signal.aborted)return;const m=f instanceof Error?f.message.slice(0,80):"fetch-failed";q("stream-connect",{code:"fetch-failed",detail:m}),a(`sse-error:${m}`)}).finally(()=>{u(),t.removeEventListener("abort",c)}),c},bu=(e,t,r,o,n,a)=>{const s=ki(e);let i=!1,c=!1,d=null;const l=()=>{if(!i){i=!0,d&&clearTimeout(d),d=null;try{s.close()}catch{}}};d=setTimeout(()=>{c||i||(n("ws-ready-timeout"),l())},a);const u=()=>l();return t.aborted?l():t.addEventListener("abort",u,{once:!0}),s.onopen=()=>{c=!0,d&&clearTimeout(d),d=null,r()},s.onmessage=f=>{const m=typeof f.data=="string"?f.data:void 0;if(m)try{const p=JSON.parse(m);gn(p)&&o(p)}catch{}},s.onerror=()=>{i||n("ws-error")},s.onclose=f=>{t.removeEventListener("abort",u),i||n(`ws-close-${f?.code??0}`)},l},as=()=>typeof document>"u"||document.visibilityState==="visible",ss=()=>typeof navigator>"u"||navigator.onLine!==!1,Hy=(e,t={})=>{const r=new AbortController,o=t.signal,n=()=>r.abort();o&&(o.aborted?r.abort():o.addEventListener("abort",n,{once:!0}));const a=r.signal,s=t.runtimeKey,i=()=>!s||s===C();let c=!1,d=0;const l=typeof t.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:null;let u=typeof t.fromSequence=="number"&&Number.isFinite(t.fromSequence)?Math.max(0,Math.floor(t.fromSequence)):l?0:void 0,f=t.transport==="ws"?"ws":"sse",m=null,p=null,g=null,A=null,y=0,b=!1,D=!1;const h=t.setupTimeoutMs??cu,v=t.authTokenTimeoutMs??du,O=t.healthResetMs??lu,W=t.epochProbeTimeoutMs??uu;let oe=null;const ve=new Set;let _e=!1,ae=null,ye=null,er=null,Ir=!1;const tr=()=>{m&&clearTimeout(m),p&&clearTimeout(p),g&&clearTimeout(g),m=null,p=null,g=null},dt=()=>{y+=1,A?.(),A=null,p&&clearTimeout(p),p=null,g&&clearTimeout(g),g=null},St=E=>{p&&clearTimeout(p),p=setTimeout(()=>{E===y&&x("heartbeat-timeout",E)},t.heartbeatTimeoutMs??ru)},_r=E=>{c||a.aborted||E!==y||(St(E),Ir&&ee(E),Ir=!0)},rr=E=>{if(c||a.aborted||E!==y)return;const R=!b;b=!0,D=!1,R&&(g&&clearTimeout(g),g=setTimeout(()=>{g=null,E===y&&b&&(d=0)},O),q("stream-ready",{code:f}),e.onReconnect?.()),St(E)},B=()=>{const E=as()&&ss()?nu:au,R=Math.min(su,d),U=Math.min(E,ou*2**R);return d===0&&t.reconnectDelayMs!==void 0?Math.max(0,t.reconnectDelayMs):U+Math.floor(Math.random()*100)},N=(E,R=!0)=>{c||a.aborted||m||(q("stream-reconnect",{code:E}),R&&e.onDisconnect?.(E),m=setTimeout(()=>{m=null,d+=1,de()},B()))},L=()=>{c||a.aborted||!m||(clearTimeout(m),m=null,d+=1,de())},x=(E,R)=>{if(!(c||a.aborted||R!==y)){if(dt(),!b&&f==="ws"&&t.transport!=="ws"&&(f="sse",e.onTransportSwitch?.()),b=!1,E==="runtime-change"){e.onDisconnect?.(E);return}if(E==="sse-auth-401"||E==="sse-auth-403"||E==="sse-auth-probe"){q("stream-auth",{code:E}),e.onDisconnect?.(E),e.onAuthRequired?.();return}N(E)}},se=(E,R)=>{if(c||a.aborted||R!==y)return;if(!i()){x("runtime-change",R);return}const U=typeof E.streamEpoch=="string"&&E.streamEpoch.length>0?E.streamEpoch:null;if(U&&U!==oe){if(ve.has(U)){q("stream-epoch",{code:"retired-frame"});return}const T=oe??l;if(T!==null&&T!==U){if(_e){ye??={event:E,epoch:U,connectionId:R};return}me(E,U,T,R);return}oe=U,u=Math.max(u??0,E.sequence),T===null&&e.onEpochChange?.(U)}(u===void 0||E.sequence>u)&&(u=E.sequence),rr(R),e.onEvent(E)},me=async(E,R,U,T)=>{_e=!0,ae=new AbortController;const ue=setTimeout(()=>ae?.abort(),W);try{const be=await mo(ae.signal,s,{fresh:!0});if(c||a.aborted||T!==y)return;if(be.state==="ready"&&be.streamEpoch===R){ve.add(U),oe=R,u=E.sequence,q("stream-epoch",{code:"verified"}),e.onEpochChange?.(R),rr(T),e.onEvent(E);return}if(be.state==="unavailable"&&be.error?.code==="DAEMON_AUTH_FAILED"){x("sse-auth-probe",T);return}if(be.state==="ready"){ve.add(R),q("stream-epoch",{code:"rejected"});return}q("stream-epoch",{code:"unverified"}),x("epoch-unverified",T)}finally{clearTimeout(ue),_e=!1,ae=null,ye=null,lt()}},ee=async E=>{const R=oe??l;if(!R)return;if(_e){er=E;return}_e=!0,ae=new AbortController;const U=setTimeout(()=>ae?.abort(),W);try{const T=await mo(ae.signal,s,{fresh:!0});if(c||a.aborted||E!==y)return;const ue=T.state==="ready"?T.streamEpoch:void 0;if(!ue||ue===R||ve.has(ue)||(oe??l)!==R)return;ve.add(R),oe=ue,u=void 0,q("stream-epoch",{code:"verified-on-resubscribe"}),e.onEpochChange?.(ue)}catch{}finally{clearTimeout(U),_e=!1,ae=null;const T=ye;ye=null,T&&se(T.event,T.connectionId),lt()}},lt=()=>{const E=er;er=null,!(E===null||c||a.aborted||E!==y)&&ee(E)},Mt=async()=>{let E=null;try{return await Promise.race([Sr(),new Promise((R,U)=>{E=setTimeout(()=>U(new Error("url-token-timeout")),v)})])}finally{E&&clearTimeout(E)}},de=async()=>{if(c||a.aborted)return;if(!i()){e.onDisconnect?.("runtime-change");return}const E=y+1;y=E;let R;if(f==="ws")try{R=await Mt()}catch{if(E!==y||c||a.aborted)return;if(t.transport!=="ws"){f="sse",e.onTransportSwitch?.(),dt(),de();return}q("stream-auth",{code:"url-token-unavailable"}),x("ws-auth-token-unavailable",E);return}if(E!==y||c||a.aborted)return;if(!i()){x("runtime-change",E);return}if(f==="sse"&&Zr()){try{await Mt()}catch{if(E!==y||c||a.aborted)return;q("stream-auth",{code:"url-token-unavailable"}),x("sse-auth-token-unavailable",E);return}if(E!==y||c||a.aborted||!i())return}const U=oe??l??void 0,T=ns(f,{...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...U?{streamEpoch:U}:{}},R),ue=()=>_r(E),be=Oe=>se(Oe,E),xr=Oe=>x(Oe,E),Or=Mi({...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...U?{streamEpoch:U}:{}});A=f==="ws"?bu(T,a,ue,be,xr,iu):yu(Or,a,ue,()=>rr(E),be,xr,{setupTimeoutMs:h,...Zr()?{classifySourceError:Oe=>Fu(s,W,Oe)}:{}})},le=()=>{!as()||!ss()||L()},Tt=()=>{if(!(!Zr()||c||a.aborted)){if(D){L();return}D=!0,tr(),dt(),b=!1,N("system-resume",!1)}};typeof window<"u"&&(window.addEventListener("pichamber:system-resume",Tt),window.addEventListener("online",le)),typeof document<"u"&&document.addEventListener("visibilitychange",le);const xe=()=>{c||(c=!0,typeof window<"u"&&(window.removeEventListener("pichamber:system-resume",Tt),window.removeEventListener("online",le)),typeof document<"u"&&document.removeEventListener("visibilitychange",le),o?.removeEventListener("abort",n),a.removeEventListener("abort",xe),tr(),dt(),ae?.abort(),ae=null,a.aborted||r.abort())};return a.aborted?xe():a.addEventListener("abort",xe,{once:!0}),de(),{dispose:xe,reconnect:(E="manual")=>{c||a.aborted||(tr(),dt(),N(E))},get eventsUrl(){const E=oe??l??void 0;return ns(f,{...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...E?{streamEpoch:E}:{}})}}},Au=3e4,Eu=1,wu=300,Bu=e=>new Promise(t=>setTimeout(t,e)),k=async(e,t)=>{const r=t.runtimeKey;if(r&&r!==C())throw new K("DAEMON_UNAVAILABLE","Runtime changed during request");const o=t.query?`?${new URLSearchParams(Object.entries(t.query).map(([c,d])=>[c,String(d)])).toString()}`:"",n={Accept:"application/json"};t.body!==void 0&&(n["Content-Type"]="application/json");const s=t.retry!==!1?Eu:0;let i;for(let c=0;c<=s;c+=1){if(c>0){if(t.signal?.aborted)break;if(r&&r!==C())throw new K("DAEMON_UNAVAILABLE","Runtime changed during request");if(await Bu(wu),t.signal?.aborted)break;if(r&&r!==C())throw new K("DAEMON_UNAVAILABLE","Runtime changed during request")}const d=new AbortController,l=setTimeout(()=>d.abort(),Au),u=t.signal,f=()=>d.abort();u&&(u.aborted?d.abort():u.addEventListener("abort",f,{once:!0}));try{const m=await F(e+o,{method:t.method,headers:n,body:t.body===void 0?void 0:JSON.stringify(t.body),signal:d.signal});if(!m.ok){const A=(await m.json().catch(()=>null))?.error??{code:"DAEMON_REQUEST_FAILED"};if(m.status===503&&(A.code==="DAEMON_UNAVAILABLE"||A.code==="DAEMON_TIMEOUT")&&c<s&&!u?.aborted){i=new K(A.code,A.message,m.status);continue}throw new K(A.code,A.message,m.status)}if(m.status===204){if(r&&r!==C())throw new K("DAEMON_UNAVAILABLE","Runtime changed during request");return}const p=await m.json();if(r&&r!==C())throw new K("DAEMON_UNAVAILABLE","Runtime changed during request");return p}catch(m){if(i=m,m instanceof K||u?.aborted||m instanceof DOMException&&m.name==="AbortError")throw m;if(c<s&&!u?.aborted)continue;throw m}finally{clearTimeout(l),u&&u.removeEventListener("abort",f)}}throw i};class K extends Error{code;status;constructor(t,r,o){super(r??`Pi request failed: ${t}`),this.name="PiRequestError",this.code=t,o!==void 0&&(this.status=o)}}class sr extends Error{code;status;constructor(t,r,o){super(r??`Pi send outcome unknown: ${t}`,o?.cause!==void 0?{cause:o.cause}:void 0),this.name="PiSendUnconfirmedError",this.code=t,o?.status!==void 0&&(this.status=o.status),o?.cause!==void 0&&this.cause===void 0&&(this.cause=o.cause)}}const Cu=e=>{if(!e||typeof e!="object")return!1;const t=e;if(!Array.isArray(t.sessions)||!Number.isSafeInteger(t.sequence)||t.sequence<0)return!1;for(const r of t.sessions){if(!r||typeof r!="object")return!1;const o=r;if(typeof o.sessionId!="string"||o.sessionId.length===0||typeof o.directory!="string"||o.directory.length===0||!Wl(o.pending))return!1}return!0},qo=e=>{if(!e||typeof e!="object")return!1;const t=e;return!(t.accepted!==!0||typeof t.messageId!="string"||t.messageId.length===0||t.deduplicated!==void 0&&t.deduplicated!==!0)},vu=e=>{if(!(e instanceof K))return!1;const t=e.status;return!(typeof t!="number"||!Number.isInteger(t)||t<400||t>499||t===408||e.code==="OPERATION_EXPIRED"||e.code==="STALE_STREAM_EPOCH")},Go=e=>e instanceof sr?e:e instanceof K?new sr(e.code,e.message,{status:e.status,cause:e}):e instanceof DOMException&&e.name==="AbortError"?new sr("DAEMON_TIMEOUT",e.message||"Send timed out",{cause:e}):e instanceof Error?new sr("DAEMON_REQUEST_FAILED",e.message,{cause:e}):new sr("DAEMON_REQUEST_FAILED",void 0,{cause:e}),w=e=>{if(e?.runtimeKey&&e.runtimeKey!==C())throw new K("DAEMON_UNAVAILABLE","Runtime changed during request")},jr=(e,t)=>{const r=Xe(e);if(!t||!r||t!==r)throw new K("STALE_STREAM_EPOCH","The Pi runtime restarted before this send could be verified.",409);return t},Ti=5e3,is=32,Ee=new Map,$r=new Map,Ri=new Map,ku=(e,t)=>`${e}