@pi-chamber/web 1.0.6 → 1.0.7-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramView-DsCdfDOP.js → DiagramView-DyF8zzYx.js} +1 -1
- package/dist/assets/{DiffView-BWo7yT-P.js → DiffView-C3rA5DfE.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-IFbuQCcP.js → FileSaveConflictDialog-CC4F--8H.js} +1 -1
- package/dist/assets/{FilesView-DLIQkVep.js → FilesView-Dsg-QTJu.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-CxGg6x7R.js → GitHubDetailScaffold-C9WuBMGr.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-BmqbTUpE.js → GitHubLinkPicker-BkVdYxZT.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-a1DxU6Zp.js → GitHubListPrimitives-CcVlv_rJ.js} +1 -1
- package/dist/assets/{GitView-DbqM8Qi1.js → GitView-OpFCss_4.js} +3 -3
- package/dist/assets/{IssuesSurface-B2EfICtZ.js → IssuesSurface-DD6Gz5Ox.js} +2 -2
- package/dist/assets/{JsonTreeView-DzVqgwz-.js → JsonTreeView-Dj75jgH6.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-7yTzCIEI.js → MarkdownRendererImpl-CnIzmT1p.js} +1 -1
- package/dist/assets/{PatchDiff-Dvfm6eOV.js → PatchDiff-DND5RBnF.js} +1 -1
- package/dist/assets/{PierreDiffViewer-ByYaUifK.js → PierreDiffViewer-Cq5CIrmH.js} +1 -1
- package/dist/assets/{PullRequestsSurface-1IP_dDn8.js → PullRequestsSurface-g8HAvbFg.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-DVxWhG4x.js → SessionSwitcherContent-CUz6Cc1-.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DiBGmmtD.js → SessionSwitcherDropdown-COZ50Y5a.js} +2 -2
- package/dist/assets/{SessionUnreadDot-qw67HcBO.js → SessionUnreadDot-DOUcgBw6.js} +1 -1
- package/dist/assets/{SettingsView-CMTIIpWD.js → SettingsView-AFymxZYC.js} +3 -3
- package/dist/assets/{SettingsWindow-DZUSs5Is.js → SettingsWindow-J6YOvGcV.js} +1 -1
- package/dist/assets/{ToolOutputDialog-pgTNzNPN.js → ToolOutputDialog-5Tc7HM4z.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-Cvnr4JkU.js → ToolPartDiffPreview-7GiFbVl7.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-D8dSHI_H.js → VirtualizedFileDiff-Dq8pyTGy.js} +1 -1
- package/dist/assets/{collapsible-ZT74WYMA.js → collapsible-D6qdoq7-.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-g1aOl5nF.js → computeVirtualFileMetrics-uXZ9uhI_.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-IWdho_6z.js → contextFileOpenGuard-CckKFYjI.js} +1 -1
- package/dist/assets/{fileTreeStatus-trDHgX4B.js → fileTreeStatus-C_7jbeGv.js} +1 -1
- package/dist/assets/{gitStatusPredicates-CfBh9Rne.js → gitStatusPredicates-CNLvdt2V.js} +1 -1
- package/dist/assets/{githubLink-CuQ2WFBa.js → githubLink-0EoMGZKd.js} +1 -1
- package/dist/assets/{index-CK9t5Znh.js → index-DD0xW5WE.js} +1 -1
- package/dist/assets/{index-fmzQmSSv.js → index-I2QYqABE.js} +3 -3
- package/dist/assets/{main-DOlk_lfi.js → main-BnWf2tm9.js} +2 -2
- package/dist/assets/{main-UnRe9F68.js → main-yQe-k30g.js} +4 -4
- package/dist/assets/{markdownCore-DuZmdypZ.js → markdownCore-C-Ulh4n9.js} +1 -1
- package/dist/assets/{miniChat-Dy9h0B6G.js → miniChat-DKK1hotU.js} +2 -2
- package/dist/assets/{mobile-CWrtn0Si.js → mobile-BuAWpKj9.js} +2 -2
- package/dist/assets/{nativeFileSave-B4Rg6n8u.js → nativeFileSave-Cp9i5QGd.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-q-s-Bhf0.js → pi-session-focus-preference-DaWQ2rEE.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-HRnE6vfE.js → renderDiffWithHighlighter-DD-iWWus.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-OZ2fG5eY.js → renderElectronMiniChatApp-CKuFQBRo.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-tJRUQWjE.js → renderFileWithHighlighter-B0pofdV1.js} +1 -1
- package/dist/assets/{renderMobileApp-D1nkBJLP.js → renderMobileApp-B3P_bita.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-Bby2E_Je.js → runtimeEndpointReset-DutinXZK.js} +6 -6
- package/dist/assets/{runtimeSurface-X62LLBLv.js → runtimeSurface-CFwnvks_.js} +1 -1
- package/dist/assets/{useAppFontEffects-BFgKpDYT.js → useAppFontEffects-DQlUEhzN.js} +85 -87
- package/dist/assets/{useGitHubRemoteSearch-MxC4J-VO.js → useGitHubRemoteSearch-BoZvJAk3.js} +1 -1
- package/dist/assets/{useSwitcherItems-D5TsQEbM.js → useSwitcherItems-Dy2yumiU.js} +1 -1
- package/dist/assets/{web-components-B_NMC-2c.js → web-components-DB-GDG7P.js} +1 -1
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +2 -2
- package/dist/mobile.html +2 -2
- package/package.json +1 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +2 -2
- package/server/lib/pi/session-daemon/extension-custom-host.js +37 -4
- package/server/lib/pi/session-daemon/extension-custom-host.test.js +231 -2
- package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +55 -0
- package/server/lib/pi/session-daemon/session-daemon.js +18 -2
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nativeFileSave-
|
|
2
|
-
import{c as Mr,d as Tr,p as Qn}from"./vendor-zustand-CXhN0IMY.js";import{_ as Pc}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ic}from"./vendor-clsx-B-dksMZM.js";import{t as _c}from"./vendor-tailwind-merge-BKkUfl9q.js";import{e as qs}from"./vendor-fuse.js-t_7AcMTv.js";import{R as Ka}from"./vendor-react-Bz1tRBxM.js";const pr=1,xc="pichamber-relay-v1",Gs=1,Ws=12,hr=1+Ws,Er=64*1024,wr=5,uo=128,Vs=0,Js=1,zt=4,Oc=1+zt,cn=Er-wr-Oc,x={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Nc=new Set(Object.values(x)),Lc=e=>Nc.has(e),At={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},ze=globalThis.crypto.subtle,Ys={name:"ECDH",namedCurve:"P-256"},Xs=16,Lo=32,Uc=16,dn=4,Qs=8;class tt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Hc=()=>ze.generateKey(Ys,!0,["deriveBits"]),jc=async e=>{const t=await ze.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},$c=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 ze.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Ys,!0,[])}catch{throw new tt("invalid ECDH public key JWK")}},Kc=()=>{const e=new Uint8Array(Xs);return globalThis.crypto.getRandomValues(e),e},zc=async(e,t,r)=>{if(r.length!==Xs)throw new tt("invalid handshake nonce length");const o=await ze.deriveBits({name:"ECDH",public:t},e,256),n=await ze.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=new Uint8Array(await ze.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(xc)},n,Lo*2*8)),s=(i,c)=>ze.importKey("raw",i,{name:"AES-GCM"},!1,c);return{clientToHost:await s(a.slice(0,Lo),["encrypt","decrypt"]),hostToClient:await s(a.slice(Lo),["encrypt","decrypt"])}},qc=(e,t,r)=>{for(let o=Qs-1;o>=0;o-=1)e[t+o]=Number(r&0xffn),r>>=8n},Gc=(e,t)=>{let r=0n;for(let o=0;o<Qs;o+=1)r=r<<8n|BigInt(e[t+o]);return r},Wc=e=>{const t=new Uint8Array(dn);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(o){if(o.length>Er)throw new tt("plaintext frame exceeds maximum size");r+=1n;const n=new Uint8Array(Ws);n.set(t,0),qc(n,dn,r);const a=new Uint8Array(await ze.encrypt({name:"AES-GCM",iv:n},e,o)),s=new Uint8Array(hr+a.length);return s[0]=Gs,s.set(n,1),s.set(a,hr),s}}},Vc=e=>{let t=0n;return{async decrypt(r){if(r.length<hr+Uc)throw new tt("encrypted frame too short");if(r[0]!==Gs)throw new tt("unsupported encrypted frame version");const o=r.slice(1,hr),n=Gc(o,dn);if(n<=t)throw new tt("frame counter regression");let a;try{a=await ze.decrypt({name:"AES-GCM",iv:o},e,r.slice(hr))}catch{throw new tt("frame decryption failed")}return t=n,new Uint8Array(a)}}},Kr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Jc=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+=Kr[o>>2],t+=Kr[(o&3)<<4|(n??0)>>4],n!==void 0&&(t+=Kr[(n&15)<<2|(a??0)>>6]),a!==void 0&&(t+=Kr[a&63])}return t},za=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!==pr)return null;const o=r.batch===!0;return r.t==="ready"?{t:"ready",v:pr,batch:o}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:pr,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:o}:null},Yc=e=>({type:"fail",closeCode:At.ChannelFailure,reason:e}),Xc=async(e,t={})=>{const r=t.batch!==!1,o=await $c(e),n=await Hc(),a=Kc(),s={t:"hello",v:pr,clientPubJwk:await jc(n.publicKey),nonce:Jc(a),...r?{batch:!0}:{}};let i=!1;return{helloText:JSON.stringify(s),get established(){return i},async handleText(c){if(i)return za(c)?.t==="ready"?{type:"ignore"}:Yc("plaintext frame on established channel");const d=za(c);if(d?.t!=="ready")return{type:"ignore"};const l=await zc(n.privateKey,o,a);return i=!0,{type:"established",batch:r&&d.batch===!0,channel:{encryptor:Wc(l.clientToHost),decryptor:Vc(l.hostToClient)}}}}},Zs=4294967295;class re extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Re=(e,t,r,o=!1)=>{if(!Number.isInteger(t)||t<0||t>Zs)throw new re("invalid stream id");if(r.length>cn)throw new re("tunnel payload exceeds maximum size");const n=new Uint8Array(wr+r.length);return n[0]=o?e|uo:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(r,wr),n},Qc=e=>{if(e.length<wr)throw new re("tunnel frame too short");const t=e[0],r=(t&uo)!==0,o=t&~uo;if(!Lc(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(wr),hasMoreFragments:r}},Zc=new TextEncoder,ed=new TextDecoder,fo=e=>Zc.encode(JSON.stringify(e)),mo=(e,t)=>{let r;try{r=JSON.parse(ed.decode(e))}catch{throw new re("malformed JSON tunnel payload")}if(!t(r))throw new re("unexpected JSON tunnel payload shape");return r},ei=(e,t=cn)=>{if(t<=0||t>cn)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},qa=(e,t,r)=>{const o=ei(r);return o.map((n,a)=>Re(e,t,n,a<o.length-1))},td=(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)}}},rd=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]=Vs,a.set(n,1),a.length>Er)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>Er)throw new re("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=Js;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},od=e=>{if(e.length<1)throw new re("empty batch plaintext");const t=e[0];if(t===Vs)return[e.slice(1)];if(t!==Js)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},nd=new Set([x.HttpBody,x.WsText,x.WsBinary]),ti=150,ad=24*1024,sd=32,id=e=>{const t=e.windowMs??ti,r=e.maxBatchBytes??ad,o=e.maxBatchFrames??sd,n=e.now??(()=>Date.now()),a=e.setTimer??((p,h)=>setTimeout(p,h)),s=e.clearTimer??(p=>clearTimeout(p));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 p=i;i=[],c=0,l=n(),e.sendBatch(rd(p))};return{enqueue:p=>{if(u)return;const h=p[0]&~uo;if(!nd.has(h)){i.push(p),m();return}const E=n();if(i.length===0&&E-l>=t){i.push(p),m();return}const A=zt+p.length;if(i.length>0&&1+c+A>Er&&m(),i.push(p),c+=A,c>=r||i.length>=o){m();return}d===null&&(d=a(m,t))},flush:m,dispose(){u=!0,f(),i=[],c=0}}},cd=()=>{let e=1;return{next(){if(e>Zs)throw new re("stream id space exhausted");const t=e;return e+=2,t}}},dd=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},ld=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},Ga=0,Uo=1,Wa=2,Va=3,ud=new Set([At.AuthFailed,At.DuplicateClient,At.LimitExceeded]),fd={[At.AuthFailed]:"relay authentication failed",[At.DuplicateClient]:"relay connection replaced by another client",[At.LimitExceeded]:"relay connection limit reached"},So=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),md=e=>So(e)&&Object.values(e).every(t=>typeof t=="string"),gd=e=>So(e)&&typeof e.status=="number"&&md(e.headers),ri=e=>So(e)&&typeof e.reason=="string",pd=e=>So(e)&&typeof e.code=="number"&&typeof e.reason=="string",oi=/^[a-z][a-z\d+.-]*:\/\//i,Zn="http://tunnel.invalid",hd=e=>{try{const t=oi.test(e)?new URL(e):new URL(e,Zn);return`${t.pathname}${t.search}`}catch{return e}},zr=e=>({async*[Symbol.asyncIterator](){yield e}}),Fd=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()}}}),yd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},bd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Fd(e)};if(typeof e=="string")return{body:zr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:zr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:zr(yd(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,o=new Uint8Array(await t.arrayBuffer());return{body:zr(o),contentType:r}},Ad=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=oi.test(r)?new URL(r):new URL(r,Zn),{body:c,contentType:d}=await bd(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}},Ed="__pichamberAmbiguousTransport",wd=e=>(Object.defineProperty(e,Ed,{value:!0,enumerable:!1,configurable:!0}),e),Bd=new Uint8Array(0),Cd=new TextEncoder,vd=new TextDecoder,ln=e=>e instanceof Error?e:new Error(String(e)),Ja=()=>new DOMException("The operation was aborted.","AbortError"),kd=async(e,t,r)=>{const o=await Ad(t,r),n=o.signal;if(n?.aborted)throw Ja();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)},g=A=>{if(!l){if(l=!0,m(),!d){c(A);return}try{u?.error(A)}catch{}}},p=A=>{a.dead||a.send(Re(x.StreamAbort,s,fo({reason:A})))},h=A=>wd(new Error(A));f=()=>{p("aborted"),g(Ja())},a.streams.set(s,{handleFrame(A,C){if(A===x.HttpResponse){if(d||l)return;let y;try{y=mo(C,gd)}catch(V){p("malformed response head"),g(h(ln(V).message));return}const w=y.status===204||y.status===205||y.status===304;let R=null;w||(R=new ReadableStream({start(V){u=V},cancel(){l||(l=!0,m(),p("response body cancelled"))}})),d=!0,i(new Response(R,{status:y.status,headers:y.headers})),w&&(l=!0,m());return}if(A===x.HttpBody){if(!d||l)return;try{u?.enqueue(C)}catch{}return}if(A===x.StreamEnd){if(l)return;if(!d){g(h("tunnel stream ended before response head"));return}l=!0,m();try{u?.close()}catch{}return}if(A===x.StreamAbort){let y="stream aborted by host";try{y=mo(C,ri).reason}catch{}g(h(y))}},fail(A){g(h(A.message))}}),n&&n.addEventListener("abort",f,{once:!0});const E={method:o.method,path:o.path,query:o.query,headers:o.headers};a.send(Re(x.HttpRequest,s,fo(E))),(async()=>{try{if(o.body)for await(const A of o.body){if(l||a.dead)return;for(const C of ei(A))a.send(Re(x.HttpBody,s,C))}!l&&!a.dead&&a.send(Re(x.StreamEnd,s,Bd))}catch(A){p("request body failed"),g(h(ln(A).message))}})()})},Dd=e=>{const t=e.indexOf("?");return t===-1?{path:e,query:""}:{path:e.slice(0,t),query:e.slice(t+1)}},Sd=(e,t,r)=>{let o=Ga,n=null,a=0,s=!1;const i={get readyState(){return o},onopen:null,onmessage:null,onerror:null,onclose:null,send(d){if(o!==Uo||!n||n.dead)throw new Error("relay tunnel socket is not open");if(typeof d=="string"){for(const u of qa(x.WsText,a,Cd.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 qa(x.WsBinary,a,l))n.send(u)},close(d=1e3,l=""){o===Va||o===Wa||(o===Uo&&n&&!n.dead&&(o=Wa,n.send(Re(x.WsClose,a,fo({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=Va,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,ln(m).message,!0);return}if(s)return;n=d,a=d.nextStreamId(),d.streams.set(a,{handleFrame(m,g){if(m===x.WsOpened){if(o===Ga){o=Uo;try{i.onopen?.()}catch{}}return}if(m===x.WsText){try{i.onmessage?.({data:vd.decode(g)})}catch{}return}if(m===x.WsBinary){const p=new ArrayBuffer(g.byteLength);new Uint8Array(p).set(g);try{i.onmessage?.({data:p})}catch{}return}if(m===x.WsClose){let p=1e3,h="";try{const E=mo(g,pd);p=E.code,h=E.reason}catch{}c(p,h);return}if(m===x.StreamAbort){let p="stream aborted";try{p=mo(g,ri).reason}catch{}c(1006,p,!0)}},fail(m){c(1012,m.message,!0)}});const{path:l,query:u}=Dd(t),f=r&&r.length>0?{path:l,query:u,protocols:r}:{path:l,query:u};d.send(Re(x.WsOpen,a,fo(f)))})(),i},Ho=new Uint8Array(0),He=e=>e instanceof Error?e:new Error(String(e)),Ya=()=>new DOMException("The operation was aborted.","AbortError"),Xa=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ea=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??ti,i=e.batch!==!1,c=e.reconnectBaseDelayMs??1e3,d=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(v=>dd(new WebSocket(v)));let f=!1,m={state:"idle"};const g=new Set;let p=null,h=null,E=null,A=null,C=0,y=0,w=null,R=[];const V=v=>{if(!(m.state===v.state&&m.lastError===v.lastError)){m=v;for(const N of g)try{N(m)}catch{}}},oe=v=>{const N=R;R=[];for(const L of N)L.reject(v)},ve=v=>{const N=R;R=[];for(const L of N)L.resolve(v)},Oe=(v,N)=>{v.dead=!0;const L=Array.from(v.streams.values());v.streams.clear();for(const O of L)try{O.fail(N)}catch{}},ae=()=>{w!==null&&(clearTimeout(w),w=null)},ye=()=>{if(!(f||Xa())){if(w!==null){ae(),St();return}m.state==="connecting"||m.state==="reconnecting"||p&&!p.dead&&A?.()}},tr=()=>{typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",ye),window.addEventListener("pichamber:system-resume",ye))},Ur=()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",ye),window.removeEventListener("pichamber:system-resume",ye))},rr=()=>{if(f||w!==null)return;const v=c*Math.pow(1.5,Math.min(y,8)),N=Math.random()*.3*v,L=Math.min(d,Math.round(v+N)),O=Xa()?Math.max(L,l):L;w=setTimeout(()=>{w=null,St()},O)},dt=()=>{const v=new URL(e.relayUrl);return v.searchParams.set("v",String(pr)),v.searchParams.set("role","client"),v.searchParams.set("serverId",e.serverId),e.grant&&v.searchParams.set("grant",e.grant),v.toString()},St=async()=>{if(f)return;const v=++C;ae(),E?.(),E=null,V({state:y===0?"connecting":"reconnecting"});let N;try{N=await Xc(e.hostEncPubJwk,{batch:i})}catch(H){Le(v,He(H),!0);return}if(f||v!==C)return;let L;try{L=u(dt())}catch(H){Le(v,He(H));return}h=L;let O=null,se=null,me=null,ee=null,lt=!1,Mt=null,de=!1,le=null,Tt=null,Ne=Date.now(),b=!1,P=Promise.resolve();const U=()=>{A===ue&&(A=null),lt=!1,O!==null&&(clearInterval(O),O=null),se!==null&&(clearTimeout(se),se=null),me!==null&&(clearInterval(me),me=null),ee!==null&&(clearTimeout(ee),ee=null),Mt?.dispose(),Mt=null};E=U;const T=(H,J={})=>{const{terminal:W=!1,asErrorState:q=!1}=J;if(!(de||v!==C)){de=!0,U(),E===U&&(E=null),le&&Oe(le,H),p===le&&(p=null);try{L.close()}catch{}if(h===L&&(h=null),W){f=!0,oe(H),V({state:"error",lastError:H.message});return}Le(v,H,q)}},ue=()=>{de||v!==C||!le||le.dead||lt||(lt=!0,Ne=Date.now(),ee!==null&&(clearTimeout(ee),ee=null),le.send(Re(x.Ping,0,Ho)),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(He(H))}},jr=(H,J)=>{Tt=H,b=J,O!==null&&(clearInterval(O),O=null),se!==null&&(clearTimeout(se),se=null),y=0;const W=new Map,q=cd(),ut=td();let ge=Promise.resolve();const Ue=ar=>{ge=ge.then(async()=>{if(nr.dead)return;const Rc=await H.encryptor.encrypt(ar);L.send(Rc)}).catch(()=>{})},ft=J?id({windowMs:s,sendBatch:Ue}):null;Mt=ft;const nr={streams:W,assembler:ut,nextStreamId:()=>q.next(),send:ar=>{if(Ne=Date.now(),ft){ft.enqueue(ar);return}Ue(ar)},dead:!1};le=nr,p=nr,A=ue,V({state:"connected"}),ve(nr),me=setInterval(()=>{Date.now()-Ne<o||(nr.send(Re(x.Ping,0,Ho)),ee===null&&(ee=setTimeout(()=>{ee=null,T(new Error("relay keepalive timeout"))},n)))},o)},$r=(H,J)=>{let W;try{W=Qc(J)}catch(ge){T(He(ge));return}if(ee!==null&&(clearTimeout(ee),ee=null),lt=!1,W.frameType===x.Ping){H.send(Re(x.Pong,W.streamId,Ho));return}if(W.frameType===x.Pong)return;Ne=Date.now();let q=W.payload;if(W.frameType===x.WsText||W.frameType===x.WsBinary){let ge;try{ge=H.assembler.push(W)}catch(Ue){T(He(Ue));return}if(ge===null)return;q=ge}else if(W.hasMoreFragments){T(new Error("unexpected fragmented tunnel frame"));return}const ut=H.streams.get(W.streamId);ut&&ut.handleFrame(W.frameType,q)};L.onopen=()=>{de||v!==C||(be(),O=setInterval(be,t))},L.onmessage=H=>{if(de||v!==C)return;const J=H.data;if(typeof J=="string"){P=P.then(async()=>{if(de||v!==C)return;const q=await N.handleText(J);if(q.type==="established"){if(Tt)return;jr(q.channel,q.batch)}else q.type==="fail"&&T(new Error(`relay handshake failed: ${q.reason}`))}).catch(q=>{T(He(q))});return}const W=J instanceof ArrayBuffer?new Uint8Array(J):J instanceof Uint8Array?J:null;W&&(P=P.then(async()=>{if(de||v!==C)return;const q=le,ut=Tt;if(!q||!ut){T(new Error("encrypted frame before handshake completed"));return}let ge;try{ge=await ut.decryptor.decrypt(W)}catch(Ue){T(He(Ue));return}if(b){let Ue;try{Ue=od(ge)}catch(ft){T(He(ft));return}for(const ft of Ue){if(de||v!==C||q.dead)return;$r(q,ft)}return}$r(q,ge)}).catch(q=>{T(He(q))}))},L.onclose=H=>{const J=ud.has(H.code);T(new Error(fd[H.code]??`relay socket closed (code ${H.code})`),{terminal:J,asErrorState:J})},L.onerror=()=>{},se=setTimeout(()=>{se=null,T(new Error("relay handshake timeout"),{asErrorState:!0})},r);function Le(H,J,W=!1){H!==C||f||(oe(J),y+=1,V({state:W?"error":"reconnecting",lastError:J.message}),rr())}},Hr=v=>f?Promise.reject(new Error("relay tunnel closed")):v?.aborted?Promise.reject(Ya()):p&&!p.dead?Promise.resolve(p):new Promise((N,L)=>{let O=null;const se={resolve(me){O&&v&&v.removeEventListener("abort",O),N(me)},reject(me){O&&v&&v.removeEventListener("abort",O),L(me)}};v&&(O=()=>{R=R.filter(me=>me!==se),L(Ya())},v.addEventListener("abort",O,{once:!0})),R.push(se)}),or=()=>{if(f)return;f=!0,C+=1,ae(),Ur(),E?.(),E=null;const v=p;p=null;const N=new Error("relay tunnel closed");v&&Oe(v,N),oe(N);try{h?.close()}catch{}h=null,V({state:"idle"})};return tr(),St(),{fetch:(v,N)=>kd(Hr,v,N),openWebSocket:(v,N)=>Sd(()=>Hr(),v,N),getStatus:()=>m,subscribeStatus(v){return g.add(v),()=>{g.delete(v)}},close:or}};let he=null,Fr=null;const Md=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Rr=()=>he,Yt=()=>he!==null,un=new Set,by=e=>(un.add(e),()=>{un.delete(e)}),ta=e=>{if(e!==Yt())for(const t of[...un])t()},Td=e=>{if(he&&Fr&&Md(Fr,e))return he;const t=Yt();return he?.close(),Fr=e,he=ea(e),ta(t),he},Ay=(e,t)=>{if(he===t)return;const r=Yt();he?.close(),Fr=e,he=t,ta(r)},Rd=()=>{const e=Yt();he?.close(),he=null,Fr=null,ta(e)};let ni=()=>null,ai="",go={},at="",Br=0,ht=null,Ut="",Cr=0,wt="",Ft=null,Qe="",to=0,ro=0;const ra=1e4,Pd=e=>e.toLowerCase()==="authorization",si=e=>{const t={};for(const[r,o]of Object.entries(e||{})){const n=r.trim(),a=o.trim();n&&a&&!Pd(n)&&(t[n]=a)}return t},Id=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([o,n])=>t[o]===n)},Pr=e=>typeof e!="string"?"":e.trim(),_d=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_CLIENT_TOKEN__;return Pr(e)},xd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},ii=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():xd();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},oa=e=>{try{return new URL(e).origin}catch{return""}},ci=()=>{Ut="",Cr=0,wt="",Ft=null,Qe="",to+=1},Ir=e=>{e!==void 0&&Pr(e)!==at||(at="",Br=0,ci())},di=()=>{ro+=1,ht=null,Ir(),aa()},li=e=>{const t=Pr(e);ai=t,di(),ni=()=>t?{type:"bearer",token:t}:null},ui=e=>{const t=si(e);Id(go,t)||(go=t,di())},na=()=>{if(Object.keys(go).length>0)return go;if(typeof window>"u")return{};const e=window.__PICHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?si(e):{}},Mo=()=>ai||_d(),Od=(e,t)=>{const r=Pr(e);if(!r||typeof t!="number"||!Number.isFinite(t)){Ir();return}const o=at;at=r,Br=t,o&&o!==r&&$d()},fi=()=>!at||Br<=Date.now()+ra?(Ir(),""):at,Nd=e=>{const t=oa(e);return!t||wt!==t?"":!Ut||Cr<=Date.now()+ra?(Ut="",Cr=0,wt="",""):Ut},Ld=()=>{const e=fi();return!e&&(Mo()||typeof window<"u")&&_r().catch(()=>{}),e},mi=async()=>{const e=await ni(),t=e?.type==="bearer"?Pr(e.token):Mo();return t?{type:"bearer",token:t}:null},gi=e=>{if(ht)return ht;const t=ro,o=(async()=>{const n=await mi(),a=new Headers;for(const[u,f]of Object.entries(na()))a.set(u,f);n?.type==="bearer"&&a.set("Authorization",`Bearer ${n.token}`);const s=Rr(),i=s?await s.fetch("/auth/url-token",{method:"POST",headers:a}):await fetch(ii(e,"/auth/url-token"),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw t===ro&&Ir(),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!==ro)throw new Error("Runtime URL auth token response is stale");if(Od(d,l),!at)throw new Error("Runtime URL auth token response was invalid");return at})().finally(()=>{ht===o&&(ht=null)});return ht=o,ht},Ud=e=>{const t=oa(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Ft&&Qe===t)return Ft;const r=to,n=(async()=>{const a=await fetch(ii(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!a.ok)throw r===to&&t===Qe&&(Ut="",Cr=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!==to||t!==Qe)throw new Error("Local runtime URL auth token response is stale");return Ut=i,Cr=c,wt=t,i})().finally(()=>{Ft===n&&(Ft=null,Qe="")});return Ft=n,Qe=t,Ft},_r=async e=>{const t=fi();return t||gi(e)},Hd=async e=>{const t=oa(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const r=Nd(t);return r||((wt&&wt!==t||Qe&&Qe!==t)&&ci(),Ud(t))};let _t=0,yr=null,pi=null;const fn=new Set,jd=5e3,$d=()=>{for(const e of fn)try{e()}catch{}},hi=()=>{yr!==null&&(clearTimeout(yr),yr=null)},aa=()=>{if(hi(),_t<=0||typeof window>"u")return;const e=Br-ra-jd,t=Br>0?Math.max(0,e-Date.now()):0;yr=setTimeout(()=>{yr=null,!(_t<=0)&&gi(pi).catch(()=>{}).finally(()=>{aa()})},t)},Ey=e=>{typeof e=="string"&&e.trim()&&(pi=e.trim()),_t+=1,aa();let t=!1;return()=>{t||(t=!0,_t=Math.max(0,_t-1),_t===0&&hi())}},wy=e=>(fn.add(e),()=>{fn.delete(e)}),Kd=async e=>{const t=new Headers(e);for(const[o,n]of Object.entries(na()))t.has(o)||t.set(o,n);if(t.has("Authorization"))return t;const r=await mi();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},mn="pichamber:auth-expired",By=()=>{typeof window>"u"||window.dispatchEvent(new Event(mn))},Cy=e=>typeof window>"u"?()=>{}:(window.addEventListener(mn,e),()=>{window.removeEventListener(mn,e)}),vy=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},Qa=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},Fi=(e,t)=>t?t.aborted?Promise.reject(Qa(t.reason)):new Promise((r,o)=>{let n=!1;const a=()=>{n||(n=!0,o(Qa(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(),zd=["local","remote",null],qd=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function yi(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"||!zd.includes(o)))return{valid:!1};if(typeof n!="string"||!qd.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 Gd(){if(Wd()!=="valid")return null;const t=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__,r=yi(t);return r.valid?r.outcome:null}function Wd(){if(typeof window>"u")return"not-injected";const e=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":yi(e).valid?"valid":"malformed"}const po=/^[a-z][a-z\d+.-]*:\/\//i,Vd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},gn=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Jd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return gn(e)},Yd=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},pn=(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))},Xd=(e,t)=>{if(!t)return e;const r=new URLSearchParams;pn({searchParams:r},t);const o=r.toString();return o?e.includes("?")?`${e}&${o}`:`${e}?${o}`:e},Za=(e,t,r)=>{if(po.test(t)){const a=new URL(t);return pn(a,r),a.toString()}const o=Vd(t);if(!e)return Xd(o,r);const n=new URL(o,`${e}/`);return pn(n,r),n.toString()},jo=(e,t)=>{const r=t===void 0?Ld():t;if(!r)return e;const o=po.test(e)?new URL(e):new URL(e,"http://pichamber.local");return o.searchParams.set("oc_url_token",r),po.test(e)?o.toString():`${o.pathname}${o.search}${o.hash}`},Qd=(e,t)=>{const r=po.test(e)?new URL(e):new URL(e,Yd(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},sa=(e={})=>{const t=gn(e.apiBaseUrl),r=gn(e.realtimeBaseUrl),o=()=>t||Jd(),n=()=>r||o(),a=(i,c)=>Za(o(),i,c),s=(i,c)=>Za(n(),i,c);return{api:a,authenticatedAsset:(i,c)=>jo(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)=>jo(s(i,c)),websocket:(i,c,d)=>Qd(jo(s(i,c),d),e)}};let ho=sa();const Ie=()=>ho,Zd=e=>{ho=e},ia=e=>(ho=sa(e),ho);let $o=null,Ko=null,zo=null;const es=new Set;let ts=!1;const bi=e=>{if(es.add(e),ts||typeof window>"u")return;ts=!0;const t=()=>{for(const r of es)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{}},el=(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 bi(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()}}},ca=e=>el(()=>wi(),e),tl=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 bi(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}}},Ai=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},da=()=>{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}}},Ei=e=>{const t=da(),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}}},rl=()=>{const e=Ai("localStorage");return e?Ei(e):da()},wi=()=>($o||($o=rl()),$o),xr=()=>(zo||(zo=tl(wi())),zo),ol=()=>{const e=Ai("sessionStorage");return e?Ei(e):da()},ky=()=>(Ko||(Ko=ol()),Ko),hn="pichamber:runtime-endpoint-changed",Fn="pichamber:runtime-endpoint-will-change";let st="",Bt="",Bi=0;const Dy=()=>(To(),Bi),yn="pichamber:lastRuntimeEndpoint.v1",nl=()=>{try{const e=xr().getItem(yn);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}},al=(e,t)=>{try{const r=xr();if(t==="mobile-disconnected"||!e){r.removeItem(yn);return}r.setItem(yn,JSON.stringify({apiBaseUrl:e,runtimeKey:t}))}catch{}},To=()=>{if(st||Bt||typeof window>"u")return;const e=nl();if(e){st=e.apiBaseUrl,Bt=e.runtimeKey;try{window.__PICHAMBER_API_BASE_URL__=e.apiBaseUrl}catch{}ia({apiBaseUrl:e.apiBaseUrl,realtimeBaseUrl:e.apiBaseUrl})}},qo=(e,t,r)=>{try{e[t]=r}catch{}},la=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"}`}},Ci=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},vi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},ki=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ge=()=>(To(),st||Ci());let Go="",rs=null,os,ns;const as=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(To(),Bt)return Bt;const e=as("__PICHAMBER_API_BASE_URL__"),t=as("__PICHAMBER_LOCAL_ORIGIN__");if(rs===st&&os===e&&ns===t)return Go;const r=Ge();return Go=ki(r,vi())?"local":la(r),rs=st,os=e,ns=t,Go},sl=(e={})=>{if(To(),st||Bt)return;const t=e.apiBaseUrl?.trim()||Ci();t&&(st=t,Bt=e.runtimeKey?.trim()||(ki(t,vi())?"local":la(t)))},Ht=e=>{const t=e.apiBaseUrl.trim(),r=Ge(),o=D(),n=e.runtimeKey?.trim()||la(t);Bi+=1,al(t,n);const a={apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fn,{detail:a})),st=t,Bt=n,typeof window<"u"){const s=window;qo(s,"__PICHAMBER_API_BASE_URL__",t),qo(s,"__PICHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),qo(s,"__PICHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}ia({apiBaseUrl:t,realtimeBaseUrl:t}),ui(e.requestHeaders||null),li(e.clientToken||null),e.relay?Td(e.relay):Rd(),_r(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(hn,{detail:a}))},il=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(Fn,t),()=>window.removeEventListener(Fn,t)},Di=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(hn,t),()=>window.removeEventListener(hn,t)};let bn=null;const cl=e=>{bn=e},ua=()=>bn||(typeof window>"u"?null:window.__PICHAMBER_RUNTIME_APIS__??null),Sy=Object.freeze(Object.defineProperty({__proto__:null,getRegisteredRuntimeAPIs:ua,registerRuntimeAPIs:cl},Symbol.toStringTag,{value:"Module"})),dl=()=>typeof window>"u"?null:window.__PICHAMBER_ELECTRON__??null,Xt=()=>typeof window>"u"?null:window.__PICHAMBER_DESKTOP__??null,Ro=()=>dl()?.runtime==="electron",My=()=>{if(typeof window>"u")return null;const e=window.__PICHAMBER_PLATFORM__;return typeof e=="string"?e:null},Z=()=>typeof Xt()?.invoke=="function",xe=()=>Ro()&&Z(),z=async(e,t)=>{const r=Xt();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},ss=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}}},Wo=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}}},ll=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),sr=e=>{const t=ll(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ce=()=>typeof window>"u"?!1:Ro(),ce=()=>{if(typeof window>"u"||!Ce())return!1;if(D()==="local")return!0;const e=typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",t=Wo(e),r=Wo(Ge());if(!r&&t&&Gd()?.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&&sr(t.hostname)&&sr(r.hostname)}const o=Wo(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&&sr(t.hostname)&&sr(o.hostname)}const n=ss(e),a=ss(window.location.origin)||window.location.origin;return n&&a&&n===a?!0:!!(o&&sr(o.hostname))},Ty=()=>{const t=ua()?.runtime?.platform;return t==="web"?!0:t!=="desktop"},Ry=(e,t=Ce())=>e==="web"&&!t,Py=async()=>{if(!xe())return null;try{const e=await z("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}},Iy=async e=>{if(!xe())return null;try{const t=await z("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}},_y=async()=>{if(!xe())return null;try{const e=await z("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}},xy=async e=>{if(!xe())return null;try{const t=await z("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}},Oy=async()=>{if(!xe())return null;try{const e=await z("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}},Ny=async e=>{if(!xe())return null;try{const t=await z("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(!xe())return null;try{const e=await z("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(!xe())return null;try{const t=await z("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}},Hy=async()=>{if(!xe())return null;try{const e=await z("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}},jy=async e=>{if(!xe())return null;try{const t=await z("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}},ul=()=>Ce()&&Z()&&ce(),fl=async()=>{if(typeof window<"u"){const e=window.__PICHAMBER_HOME__;if(e&&e.length>0)return e}return null},$y=async e=>{if(ul())try{const t=await Xt()?.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"}},Si=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ky=async e=>{if(Z()&&ce())try{const t=await Xt()?.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(!Si(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"}},zy=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 Xt()?.grantFileAccess?.(t);if(!Si(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)}}},qy=async e=>({success:!0}),Gy=async e=>({success:!0}),Wy=async()=>Z()&&await z("desktop_get_update_channel")==="rc"?"rc":"stable",Vy=async e=>{if(!Z())throw new Error("Desktop update settings are unavailable.");const t=await z("desktop_set_update_channel",{channel:e});if(t!=="stable"&&t!=="rc")throw new Error("Unable to save the desktop update channel.");return t},Jy=async()=>Z()?await z("desktop_check_for_updates"):null,Yy=async e=>{if(!Z())return!1;const t=Xt();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 z("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{}}},ml=async()=>{if(!Z())return!1;try{return await z("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},Xy=async()=>Z()?ml():!1,Qy=async()=>{if(!Z()||!ce())return null;try{const e=await z("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}},gl=async(e,t)=>{if(!Z()||!ce())return!1;const r=e?.trim();if(!r)return!1;try{return await z("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}},Zy=async e=>{if(!Z()||!ce())return!1;const t=e?.trim();if(!t)return!1;try{return await z("desktop_reveal_path",{path:t}),!0}catch{return gl(t)}},eb=async(e,t)=>{if(!Z()||!ce())return null;const r=e?.trim();if(!r)return null;try{const o=await z("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}},tb=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 z("desktop_open_in_app",{projectPath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},rb=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 z("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}},ob=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 z("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:",nb=()=>{if(typeof window>"u"||!Qt()||pl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},pl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ce()?"desktop":"web"},ab=()=>{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",hl=()=>typeof window>"u"?"":window.location.origin||"",fa=e=>{if(typeof window>"u")return!1;const t=hl();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}},ma=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),ga=(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))},oo=e=>{try{const t=Ie().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}},Vo=e=>{if(Ct(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return fa(t)&&Ct(t.pathname)}catch{return!1}},Fl=(e,t)=>{try{const r=new URL(e);if(!fa(r))return e;const o=Et(`${r.pathname}${r.search}`,t);return!ma(o)&&(r.protocol==="http:"||r.protocol==="https:")?(ga(r,t),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return e}},Et=(e,t)=>e==="/health"?Ie().health(t):e.startsWith("/auth/")||e==="/auth"?Ie().auth(e,t):Ct(e)?Ie().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Fl(e,t):e,yl=e=>{const t=e instanceof Request?e.url:e.toString();if(!ma(t))return Ct(t);try{return oo(new URL(t))}catch{return!1}},bl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Al=(e,t)=>!bl(t),is=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)Al(n,a)?(r.push([n,encodeURIComponent(a)]),o=!0):r.push([n,a]);return o?r:void 0},je=async(e,t,r=!0)=>{const o=new Headers(is(e)??e);return t&&new Headers(is(t)??t).forEach((n,a)=>o.set(a,n)),r?Kd(o):o},El=(e,t)=>{if(!t)return e;const r=new URL(e,Zn);return ga(r,t),`${r.pathname}${r.search}`},Mi=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!ma(r))return Ct(r)?El(r,t):null;try{const o=new URL(r);return!fa(o)||!Ct(o.pathname)?null:(ga(o,t),`${o.pathname}${o.search}`)}catch{return null}},wl=async(e,t,r)=>{const o=Rr();if(!o)return null;const n=Mi(e,r);if(n===null)return null;const a=e instanceof Request?e.headers:void 0,s=await je(a,t.headers,!0);return e instanceof Request?o.fetch(e,{...t,headers:s}):o.fetch(n,{...t,headers:s})},Bl=(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)},Cl=/\/api\/pi\/(health|projects|sessions|providers|resources|runtime|settings)(\b|\/|\?|$)/,qr=new Map,vl=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!Cl.test(t)?null:`GET ${t}`,F=async(e,t={})=>{const{query:r,...o}=t,n=Rr(),a=n?Mi(e,r):null,s=o.signal??(e instanceof Request?e.signal:void 0);let i,c,d;if(n&&a!==null){const g=e instanceof Request?e.headers:void 0,p=await je(g,o.headers,!0);i=e instanceof Request?()=>n.fetch(e,{...o,headers:p}):()=>n.fetch(a,{...o,headers:p}),c=a,d=String(o.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const g=Bl(e,r),p=g instanceof Request?g.headers:void 0,h=await je(p,o.headers,yl(g));let E=g instanceof Request?()=>fetch(new Request(g,{...o,headers:h})):()=>fetch(g,{...o,headers:h});if(Qt()&&s){const A=E;E=()=>Fi(A,s)}i=E,c=g instanceof Request?g.url:g instanceof URL?g.toString():String(g),d=String(o.method??(g instanceof Request?g.method:"GET")).toUpperCase()}const l=o.signal!=null||e instanceof Request,u=vl(d,c,l);if(!u)return i();const f=qr.get(u);if(f)return f.then(g=>g.clone());const m=i();return qr.set(u,m),m.then(()=>qr.delete(u),()=>qr.delete(u)),m.then(g=>g.clone())};let cs=!1;const kl=()=>{if(cs||typeof window>"u")return;cs=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const o=await wl(t,r??{});if(o)return o;if(typeof t=="string"){if(!Vo(t)){try{const a=new URL(t);if(oo(a)){const s=await je(void 0,r?.headers);return e(t,{...r,headers:s})}}catch{}return e(t,r)}const n=await je(void 0,r?.headers);return e(Et(t),{...r,headers:n})}if(t instanceof URL){const n=t.toString();if(!Vo(n)){if(oo(t)){const s=await je(void 0,r?.headers);return e(t,{...r,headers:s})}return e(t,r)}const a=await je(void 0,r?.headers);return e(Et(n),{...r,headers:a})}if(t instanceof Request){if(!Vo(t.url)){try{const i=new URL(t.url);if(oo(i)){const c=await je(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const n=await je(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,Dl=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,"")},Ti=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}},Sl=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}},Ml=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}},ds=e=>typeof e=="string"&&e.length>0,Tl=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ds(t.x)||!ds(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Rl=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pl=e=>{if(!e||typeof e!="object")return null;const t=e,r=Rl(t.priority);if(t.type==="lan"||t.type==="tunnel"||t.type==="tailscale"){const o=Sl(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=Ml(t.relayUrl);if(!o)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const a=Tl(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},pa=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(Pl).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}},sb=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}),ib=e=>{const t=pa(e);if(!t)throw new Error("Invalid pairing connection payload");const r=new URLSearchParams;return r.set("v","2"),r.set("p",Dl(JSON.stringify(t))),`pichamber://connect?${r.toString()}`},Il=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=Ti(o);return!n||n.length>jt?null:pa(JSON.parse(n))}catch{return null}},cb=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=Ti(n);if(!a||a.length>jt)return null;try{return pa(JSON.parse(a))}catch{return null}},qt=e=>typeof e=="object"&&e!==null,_l=e=>e.trim().toLowerCase()==="authorization",xl=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)||_l(n)||(t[n]=a)}return Object.keys(t).length>0?t:void 0},Ri=e=>`relay://${e}`,Ol=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}},Nl=()=>{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"},Pi=5e3,Ll=async(e,t,r)=>{const o=Il(e);if(!o)throw new Error("invalid-connect-link");const n=await xi().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:Nl(),...n?{dedupeKey:`desktop:${n}`}:{}})},s=async y=>{if(!y.ok)return null;const w=await y.json().catch(()=>null);return(typeof w?.clientToken=="string"?w.clientToken.trim():"")||null};let i=null;const c=[...o.candidates].sort((y,w)=>(y.type==="relay"?1:0)-(w.type==="relay"?1:0));for(const y of c){if(y.type==="relay"){const R=ea({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const V=await s(await R.fetch("/api/client-auth/pairing/redeem",a));if(V){i={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:V};break}}catch{}finally{R.close()}continue}const w=X(y.url);if(w)try{const R=await s(await fetch(`${w}/api/client-auth/pairing/redeem`,a));if(R){i={directUrl:w,token:R};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const d=o.candidates.find(y=>y.type==="relay"),l=i.relay||(d?{relayUrl:d.relayUrl,serverId:d.serverId,hostEncPubJwk:d.hostEncPubJwk}:void 0),u=o.candidates.filter(y=>y.type!=="relay").map(y=>X(y.url)).find(y=>!!y),f=i.directUrl||u,m=f||(l?Ri(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");let g=null;if(i.directUrl){const y=r?.healthTimeoutMs??Pi,w=new AbortController,R=setTimeout(()=>w.abort(),y);try{const V=await fetch(`${i.directUrl}/health`,{headers:{Accept:"application/json"},signal:w.signal,credentials:"omit"});if(V.ok){const oe=await V.json().catch(()=>null),ve=typeof oe?.serverId=="string"?oe.serverId.trim():"";ve&&(g=ve)}}catch{}finally{clearTimeout(R)}}const p=new Set;l?.serverId&&p.add(l.serverId),g&&p.add(g);const h=y=>{for(const w of p)if(y.serverId===w||y.relay?.serverId===w)return!0;return!1},E=t.find(y=>{if(l){if(y.relay?.serverId===l.serverId)return!0}else if(!y.relay&&X(y.apiUrl||y.url)===m)return!(y.serverId&&g&&y.serverId!==g);return h(y)}),A=E?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),C={...E||{},id:A,label:o.label||E?.label||ha(m),url:m,apiUrl:f,clientToken:i.token,...l?{relay:l}:{}};return E?.serverId?C.serverId=E.serverId:g&&(C.serverId=g),{hostId:A,hosts:E?t.map(y=>y.id===A?C:y):[C,...t]}},Ul=/^(t|.*(?:token|auth|secret|api).*)$/i,X=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}},Hl=e=>{const t=X(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"}},ha=e=>{const t=X(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)Ul.test(n)&&r.searchParams.set(n,"[REDACTED]");return r.toString()}catch{return t}},rt=(e,t)=>{const r=X(e),o=X(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},ls=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},jl=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=xl(e.requestHeaders),i=Ol(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()}:{}}},_e=e=>X(e.apiUrl||e.url)||e.apiUrl||e.url,$l=(e,t)=>{const r={...e,url:t,apiUrl:t};return X(_e(e))!==X(t)&&delete r.serverId,r},kt=()=>Z()?(e,t)=>z(e,t):null,Fa=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(jl).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}},Ii=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})},_i=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},xi=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Kl=8e3,us=async(e,t,r)=>{const o=new AbortController,n=window.setTimeout(()=>o.abort(),Kl);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(n)}},zl=async(e,t)=>{const r=ea({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),o=Date.now();let n=!1;try{if(!(await us(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 us(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()}},ya=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=ls(o,"latencyMs")??ls(o,"latency_ms")??0,i=Y(o,"reportedServerId");return{status:a,latencyMs:s,...i?.trim()?{reportedServerId:i.trim()}:{}}},ql=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})},Gl=async e=>{const t=kt();t&&await t("desktop_new_window_for_host",{hostId:e})},db=Object.freeze(Object.defineProperty({__proto__:null,DESKTOP_HOST_HEALTH_PIN_TIMEOUT_MS:Pi,desktopHostProbe:ya,desktopHostsGet:Fa,desktopHostsSet:Ii,desktopInstallIdGet:xi,desktopLocalClientTokenGet:_i,desktopOpenNewWindowAtUrl:ql,desktopOpenNewWindowForHost:Gl,getDesktopHostApiUrl:_e,importDesktopHostPairing:Ll,locationMatchesHost:rt,normalizeHostUrl:X,probeRelayDesktopHost:zl,redactSensitiveUrl:ha,relayHostDisplayUrl:Ri,resolveDesktopHostUrl:Hl,withEditedDesktopHostUrl:$l},Symbol.toStringTag,{value:"Module"})),ot="local",Wl=e=>({id:ot,label:"Local",url:e||ba()}),ba=()=>typeof window>"u"?"":window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,Aa=e=>e.id===ot?"local":`host:${e.id}`,fs="host:",Oi=e=>{const t=e.runtimeKey.trim();if(t===ot)return{kind:"local"};if(t.startsWith(fs)){const o=t.slice(fs.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,_e(o)):!1);return r?{kind:"host",host:r}:e.localOrigin&&e.apiBaseUrl&&rt(e.apiBaseUrl,e.localOrigin)?{kind:"local"}:null},Vl=e=>{const t=typeof window>"u"?"":window.location.href,r=e.find(l=>l.id===ot)?.url||ba(),o=Ge(),n=X(r)||r,a=X(t)||t,s=D(),i=e.find(l=>l.relay&&Aa(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,_e(l)):!1);if(c)return{id:c.id,label:c.label,url:X(_e(c))||_e(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:X(d.url)||d.url}:t.startsWith("pichamber-ui://")?{id:ot,label:"Local",url:n}:{id:"custom",label:ha(a||"Instance"),url:a}},lb=Object.freeze(Object.defineProperty({__proto__:null,LOCAL_HOST_ID:ot,buildLocalDesktopHost:Wl,getLocalDesktopOrigin:ba,resolveCurrentDesktopHost:Vl,resolveDesktopHostIdentity:Oi,runtimeKeyForDesktopHost:Aa},Symbol.toStringTag,{value:"Module"})),Jl=5e3,Yl=1500;let Jo=!1;const Xl=async e=>{if(!Ro()||Jo)return;const t=`host:${e}`;if(D()===t){Jo=!0;try{const r=await Fa().catch(()=>null),o=r?.hosts.find(m=>m.id===e);if(!r||!o?.relay)return;const n=o.apiUrl?X(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 g=m;if(g.type!=="lan"&&g.type!=="tailscale"||typeof g.url!="string")continue;const p=X(g.url),h=g.type==="tailscale"?d:c;p&&!h.includes(p)&&h.push(p)}const l=c.length>0?c:d;if(l.length===0)return;const u=n&&l.includes(n)?n:l[0];u!==n&&await Ii({hosts:r.hosts.map(m=>m.id===e?{...m,apiUrl:u}:m),defaultHostId:r.defaultHostId,initialHostChoiceCompleted:r.initialHostChoiceCompleted}).catch(()=>{});const f=await ya(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"||D()!==t)return;Ht({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:t})}finally{Jo=!1}}},Ql=e=>{typeof window>"u"||window.setTimeout(()=>{Xl(e).catch(()=>{})},Jl)},Zl=(e,t)=>{if(t){const o=e.hosts.find(n=>n.id===t);return o?{kind:"host",host:o}:null}const r=Oi({runtimeKey:D(),apiBaseUrl:Ge(),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"}},eu=(e,t)=>{const r=e.clientToken||"";!r||Mo()===r||Ht({apiBaseUrl:Ge()||_e(e),clientToken:r,requestHeaders:e.requestHeaders||null,runtimeKey:t,relay:Yt()?e.relay:void 0})},tu=async e=>{if(!Ro())return;const t=await Fa().catch(()=>null);if(!t)return;const r=Zl(t,e);if(!r)return;if(r.kind==="local"){const u=await _i();if(!u)return;const f=t.localOrigin||Ge();if(!f||D()==="local"&&Mo()===u)return;Ht({apiBaseUrl:f,clientToken:u,runtimeKey:"local"});return}const o=r.host,n=Aa(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}),Ql(o.id)};if(D()===n){const u=o.apiUrl?X(_e(o)):"";if(!!(u&&rt(Ge(),u))||!o.relay){eu(o,n);return}s();return}if(!o.relay){const u=_e(o);if(!u)return;a(u);return}const i=o.apiUrl?X(_e(o)):null;if(!i){s();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",d=ya(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),Yl))]);if(l){if(c(l)){a(i);return}s();return}s(),d.then(u=>{c(u)&&D()===n&&a(i)})},ru=64*1024,ou=(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+ru,e.size),s=new Uint8Array(await e.slice(o,a).arrayBuffer());o=a,n.enqueue(s),r?.({loaded:o,total:e.size})}})},nu=(e,t)=>!Qt()||e instanceof File?e:new File([e],t.filename,{type:t.mime||e.type}),au=async(e,t,r)=>{const o=!!Rr();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?ou(t,r.signal,r.onProgress):nu(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,su="events.streamEpoch",iu=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},ub="pichamber.bash",fb=64*1024,ms=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0,Ni=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return!(t.snoozedUntil!==void 0&&(!ms(t.snoozedUntil)||!ms(t.snoozedAt)))},cu=e=>{if(!e||typeof e!="object")return!1;const t=e.sessions;return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(Ni)},du=["session.snapshot","session.lifecycle","session.deleted","session.updated","session.tree.updated","session.input","session.bash","session.bash.output","session.bash.recorded","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","session.openUrl","session.archive","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.custom","extension.custom.frame","extension.custom.dismiss","extension.error"],An=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))&&du.includes(t.name)},Li=(e,t)=>{const r=Rr();return r?r.openWebSocket(hd(e),t):ld(new WebSocket(e))},Ui="pichamber.mobile.diagnostics.v1",Ea=300,lu=240,uu=1e3;let Gt=[],gs=!1,$t=null,Yo=!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,lu)||void 0,fu=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)}:{}}},Hi=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},Po=()=>{if(gs)return;gs=!0;const e=Hi();if(e)try{const t=e.getItem(Ui);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(-Ea)}catch{}},mu=()=>{$t!==null&&(clearTimeout($t),$t=null)},gu=()=>{$t===null&&($t=setTimeout(()=>{$t=null,no()},uu))},no=()=>{mu();const e=Hi();if(e)try{Po(),e.setItem(Ui,JSON.stringify(Gt.slice(-Ea)))}catch{}},G=(e,t={})=>{if(!Qt())return;Po();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(-Ea),gu()},pu=(e,t)=>{G(e,fu(t))},hu=()=>(Po(),JSON.stringify({format:"pichamber-mobile-diagnostics-v1",generatedAt:new Date().toISOString(),platform:typeof navigator>"u"?"unknown":navigator.userAgent,entries:Gt},null,2)),mb=async()=>{const e=hu(),{isShareCancelledError:t,saveOrShareFile:r}=await Pc(async()=>{const{isShareCancelledError:n,saveOrShareFile:a}=await import("./nativeFileSave-B4Rg6n8u.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")},gb=()=>{if(!Qt()||typeof window>"u"||Yo)return()=>{};Yo=!0,Po(),G("app-launch",{code:"start"});const e=n=>{G("window-error",{code:n.error?.name,detail:n.message})},t=n=>{pu("unhandled-rejection",n.reason)},r=()=>{no()},o=()=>{document.visibilityState==="hidden"&&no()};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),no(),Yo=!1}},Fu=3e4,yu=250,bu=5e3,Au=6e4,Eu=8,wu=2e3,Bu=1e4,Cu=5e3,vu=3e4,ku=5e3,It=new Map,Du=8,Su=(e,t)=>{if(!(!e||!t||t.length>128))for(It.delete(e),It.set(e,t);It.size>Du;){const r=It.keys().next();if(r.done)break;It.delete(r.value)}},Ze=(e=D())=>It.get(e),ji=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=su,t},ps=(e,t,r)=>{const o=Ie(),n=ji(t);return e==="ws"?o.websocket("/api/pi/events",n,r):o.sse("/api/pi/events",n)},Mu=()=>"/api/pi/runtime",ao=()=>Qt()&&!Yt()&&typeof EventSource<"u",Tu=3e3;let En=null,mr=null;const pb=()=>{En=null,mr=null},Ru=1e4,Gr=e=>({...e,capabilities:[...e.capabilities]}),yo=async(e,t,r)=>{const o=t??D();if(!r?.fresh){const s=En;if(s&&s.runtimeKey===o&&s.runtimeKey===D()&&Date.now()<s.expiresAt)return Gr(s.result)}const n=!r?.fresh&&!e;if(n){const s=mr;if(s&&s.runtimeKey===o&&s.runtimeKey===D())return s.promise.then(Gr)}const a=async()=>{const s=r?.timeoutMs??Ru,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(Mu(),{signal:i.signal});if(o!==D())return{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:"DAEMON_UNAVAILABLE",message:"Runtime changed during request"}};if(!l.ok)return G("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 Fi(()=>l.json(),i.signal).catch(h=>{if((h instanceof DOMException||h instanceof Error)&&h.name==="AbortError")throw h;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,g=typeof f.streamEpoch=="string"&&f.streamEpoch.length>0&&f.streamEpoch.length<=128?f.streamEpoch:void 0;f.state==="ready"&&g&&Su(o,g);const p={state:f.state==="ready"?"ready":"unavailable",protocolVersion:typeof f.protocolVersion=="number"?f.protocolVersion:Pt,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter(h=>typeof h=="string"):[],...g?{streamEpoch:g}:{},...m?{error:{code:m,...typeof f.error?.message=="string"?{message:f.error.message}:{}}}:{}};return!r?.fresh&&p.state==="ready"&&o===D()&&(En={runtimeKey:o,result:Gr(p),expiresAt:Date.now()+Tu}),p}catch(l){const u=(l instanceof DOMException||l instanceof Error)&&l.name==="AbortError";return G("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(()=>{mr?.promise===s&&(mr=null)});return mr={runtimeKey:o,promise:s},s.then(Gr)}return a()},Pu=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 yo(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)}},Iu=(e,t,r,o,n,a,s)=>{if(ao()){const f=new EventSource(Ie().sse("/api/pi/events",e)),m=new AbortController;let g=!1,p=!1,h=setTimeout(()=>{h=null,!(p||g)&&(G("stream-connect",{code:"setup-timeout"}),C(),a("sse-setup-timeout"))},s.setupTimeoutMs);const E=()=>{h&&clearTimeout(h),h=null},A=()=>{g||o()},C=()=>{E(),m.abort(),!g&&(g=!0,f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C))},y=w=>{try{const R=JSON.parse(w);An(R)&&n(R)}catch{G("stream-frame",{code:"bad-sse-frame"})}};return f.onopen=()=>{g||(p=!0,E(),r())},f.onmessage=w=>{g||(o(),typeof w.data=="string"&&w.data.trim()&&y(w.data))},f.onerror=()=>{if(g)return;E(),f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C),g=!0,G("stream-disconnect",{code:"sse-error"});const w=s.classifySourceError;if(!w){a("sse-error");return}w(m.signal).then(R=>{m.signal.aborted||a(R==="auth"?"sse-auth-probe":"sse-error")})},f.addEventListener("heartbeat",A),t.aborted?C():t.addEventListener("abort",C,{once:!0}),C}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)&&(G("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(G("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(),g=new TextDecoder;let p="",h=[];const E=()=>{if(h.length===0)return;const A=h.join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nativeFileSave-Cp9i5QGd.js","assets/vendor-boot-3SaHYVb1.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as Mr,d as Tr,p as Qn}from"./vendor-zustand-CXhN0IMY.js";import{_ as Pc}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ic}from"./vendor-clsx-B-dksMZM.js";import{t as _c}from"./vendor-tailwind-merge-BKkUfl9q.js";import{e as qs}from"./vendor-fuse.js-t_7AcMTv.js";import{R as Ka}from"./vendor-react-Bz1tRBxM.js";const pr=1,xc="pichamber-relay-v1",Gs=1,Ws=12,hr=1+Ws,Er=64*1024,wr=5,uo=128,Vs=0,Js=1,zt=4,Oc=1+zt,cn=Er-wr-Oc,x={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Nc=new Set(Object.values(x)),Lc=e=>Nc.has(e),At={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},ze=globalThis.crypto.subtle,Ys={name:"ECDH",namedCurve:"P-256"},Xs=16,Lo=32,Uc=16,dn=4,Qs=8;class tt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Hc=()=>ze.generateKey(Ys,!0,["deriveBits"]),jc=async e=>{const t=await ze.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},$c=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 ze.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Ys,!0,[])}catch{throw new tt("invalid ECDH public key JWK")}},Kc=()=>{const e=new Uint8Array(Xs);return globalThis.crypto.getRandomValues(e),e},zc=async(e,t,r)=>{if(r.length!==Xs)throw new tt("invalid handshake nonce length");const o=await ze.deriveBits({name:"ECDH",public:t},e,256),n=await ze.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=new Uint8Array(await ze.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(xc)},n,Lo*2*8)),s=(i,c)=>ze.importKey("raw",i,{name:"AES-GCM"},!1,c);return{clientToHost:await s(a.slice(0,Lo),["encrypt","decrypt"]),hostToClient:await s(a.slice(Lo),["encrypt","decrypt"])}},qc=(e,t,r)=>{for(let o=Qs-1;o>=0;o-=1)e[t+o]=Number(r&0xffn),r>>=8n},Gc=(e,t)=>{let r=0n;for(let o=0;o<Qs;o+=1)r=r<<8n|BigInt(e[t+o]);return r},Wc=e=>{const t=new Uint8Array(dn);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(o){if(o.length>Er)throw new tt("plaintext frame exceeds maximum size");r+=1n;const n=new Uint8Array(Ws);n.set(t,0),qc(n,dn,r);const a=new Uint8Array(await ze.encrypt({name:"AES-GCM",iv:n},e,o)),s=new Uint8Array(hr+a.length);return s[0]=Gs,s.set(n,1),s.set(a,hr),s}}},Vc=e=>{let t=0n;return{async decrypt(r){if(r.length<hr+Uc)throw new tt("encrypted frame too short");if(r[0]!==Gs)throw new tt("unsupported encrypted frame version");const o=r.slice(1,hr),n=Gc(o,dn);if(n<=t)throw new tt("frame counter regression");let a;try{a=await ze.decrypt({name:"AES-GCM",iv:o},e,r.slice(hr))}catch{throw new tt("frame decryption failed")}return t=n,new Uint8Array(a)}}},Kr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Jc=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+=Kr[o>>2],t+=Kr[(o&3)<<4|(n??0)>>4],n!==void 0&&(t+=Kr[(n&15)<<2|(a??0)>>6]),a!==void 0&&(t+=Kr[a&63])}return t},za=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!==pr)return null;const o=r.batch===!0;return r.t==="ready"?{t:"ready",v:pr,batch:o}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:pr,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:o}:null},Yc=e=>({type:"fail",closeCode:At.ChannelFailure,reason:e}),Xc=async(e,t={})=>{const r=t.batch!==!1,o=await $c(e),n=await Hc(),a=Kc(),s={t:"hello",v:pr,clientPubJwk:await jc(n.publicKey),nonce:Jc(a),...r?{batch:!0}:{}};let i=!1;return{helloText:JSON.stringify(s),get established(){return i},async handleText(c){if(i)return za(c)?.t==="ready"?{type:"ignore"}:Yc("plaintext frame on established channel");const d=za(c);if(d?.t!=="ready")return{type:"ignore"};const l=await zc(n.privateKey,o,a);return i=!0,{type:"established",batch:r&&d.batch===!0,channel:{encryptor:Wc(l.clientToHost),decryptor:Vc(l.hostToClient)}}}}},Zs=4294967295;class re extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Re=(e,t,r,o=!1)=>{if(!Number.isInteger(t)||t<0||t>Zs)throw new re("invalid stream id");if(r.length>cn)throw new re("tunnel payload exceeds maximum size");const n=new Uint8Array(wr+r.length);return n[0]=o?e|uo:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(r,wr),n},Qc=e=>{if(e.length<wr)throw new re("tunnel frame too short");const t=e[0],r=(t&uo)!==0,o=t&~uo;if(!Lc(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(wr),hasMoreFragments:r}},Zc=new TextEncoder,ed=new TextDecoder,fo=e=>Zc.encode(JSON.stringify(e)),mo=(e,t)=>{let r;try{r=JSON.parse(ed.decode(e))}catch{throw new re("malformed JSON tunnel payload")}if(!t(r))throw new re("unexpected JSON tunnel payload shape");return r},ei=(e,t=cn)=>{if(t<=0||t>cn)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},qa=(e,t,r)=>{const o=ei(r);return o.map((n,a)=>Re(e,t,n,a<o.length-1))},td=(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)}}},rd=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]=Vs,a.set(n,1),a.length>Er)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>Er)throw new re("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=Js;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},od=e=>{if(e.length<1)throw new re("empty batch plaintext");const t=e[0];if(t===Vs)return[e.slice(1)];if(t!==Js)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},nd=new Set([x.HttpBody,x.WsText,x.WsBinary]),ti=150,ad=24*1024,sd=32,id=e=>{const t=e.windowMs??ti,r=e.maxBatchBytes??ad,o=e.maxBatchFrames??sd,n=e.now??(()=>Date.now()),a=e.setTimer??((p,h)=>setTimeout(p,h)),s=e.clearTimer??(p=>clearTimeout(p));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 p=i;i=[],c=0,l=n(),e.sendBatch(rd(p))};return{enqueue:p=>{if(u)return;const h=p[0]&~uo;if(!nd.has(h)){i.push(p),m();return}const E=n();if(i.length===0&&E-l>=t){i.push(p),m();return}const A=zt+p.length;if(i.length>0&&1+c+A>Er&&m(),i.push(p),c+=A,c>=r||i.length>=o){m();return}d===null&&(d=a(m,t))},flush:m,dispose(){u=!0,f(),i=[],c=0}}},cd=()=>{let e=1;return{next(){if(e>Zs)throw new re("stream id space exhausted");const t=e;return e+=2,t}}},dd=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},ld=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},Ga=0,Uo=1,Wa=2,Va=3,ud=new Set([At.AuthFailed,At.DuplicateClient,At.LimitExceeded]),fd={[At.AuthFailed]:"relay authentication failed",[At.DuplicateClient]:"relay connection replaced by another client",[At.LimitExceeded]:"relay connection limit reached"},So=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),md=e=>So(e)&&Object.values(e).every(t=>typeof t=="string"),gd=e=>So(e)&&typeof e.status=="number"&&md(e.headers),ri=e=>So(e)&&typeof e.reason=="string",pd=e=>So(e)&&typeof e.code=="number"&&typeof e.reason=="string",oi=/^[a-z][a-z\d+.-]*:\/\//i,Zn="http://tunnel.invalid",hd=e=>{try{const t=oi.test(e)?new URL(e):new URL(e,Zn);return`${t.pathname}${t.search}`}catch{return e}},zr=e=>({async*[Symbol.asyncIterator](){yield e}}),Fd=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()}}}),yd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},bd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Fd(e)};if(typeof e=="string")return{body:zr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:zr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:zr(yd(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,o=new Uint8Array(await t.arrayBuffer());return{body:zr(o),contentType:r}},Ad=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=oi.test(r)?new URL(r):new URL(r,Zn),{body:c,contentType:d}=await bd(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}},Ed="__pichamberAmbiguousTransport",wd=e=>(Object.defineProperty(e,Ed,{value:!0,enumerable:!1,configurable:!0}),e),Bd=new Uint8Array(0),Cd=new TextEncoder,vd=new TextDecoder,ln=e=>e instanceof Error?e:new Error(String(e)),Ja=()=>new DOMException("The operation was aborted.","AbortError"),kd=async(e,t,r)=>{const o=await Ad(t,r),n=o.signal;if(n?.aborted)throw Ja();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)},g=A=>{if(!l){if(l=!0,m(),!d){c(A);return}try{u?.error(A)}catch{}}},p=A=>{a.dead||a.send(Re(x.StreamAbort,s,fo({reason:A})))},h=A=>wd(new Error(A));f=()=>{p("aborted"),g(Ja())},a.streams.set(s,{handleFrame(A,C){if(A===x.HttpResponse){if(d||l)return;let y;try{y=mo(C,gd)}catch(V){p("malformed response head"),g(h(ln(V).message));return}const w=y.status===204||y.status===205||y.status===304;let R=null;w||(R=new ReadableStream({start(V){u=V},cancel(){l||(l=!0,m(),p("response body cancelled"))}})),d=!0,i(new Response(R,{status:y.status,headers:y.headers})),w&&(l=!0,m());return}if(A===x.HttpBody){if(!d||l)return;try{u?.enqueue(C)}catch{}return}if(A===x.StreamEnd){if(l)return;if(!d){g(h("tunnel stream ended before response head"));return}l=!0,m();try{u?.close()}catch{}return}if(A===x.StreamAbort){let y="stream aborted by host";try{y=mo(C,ri).reason}catch{}g(h(y))}},fail(A){g(h(A.message))}}),n&&n.addEventListener("abort",f,{once:!0});const E={method:o.method,path:o.path,query:o.query,headers:o.headers};a.send(Re(x.HttpRequest,s,fo(E))),(async()=>{try{if(o.body)for await(const A of o.body){if(l||a.dead)return;for(const C of ei(A))a.send(Re(x.HttpBody,s,C))}!l&&!a.dead&&a.send(Re(x.StreamEnd,s,Bd))}catch(A){p("request body failed"),g(h(ln(A).message))}})()})},Dd=e=>{const t=e.indexOf("?");return t===-1?{path:e,query:""}:{path:e.slice(0,t),query:e.slice(t+1)}},Sd=(e,t,r)=>{let o=Ga,n=null,a=0,s=!1;const i={get readyState(){return o},onopen:null,onmessage:null,onerror:null,onclose:null,send(d){if(o!==Uo||!n||n.dead)throw new Error("relay tunnel socket is not open");if(typeof d=="string"){for(const u of qa(x.WsText,a,Cd.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 qa(x.WsBinary,a,l))n.send(u)},close(d=1e3,l=""){o===Va||o===Wa||(o===Uo&&n&&!n.dead&&(o=Wa,n.send(Re(x.WsClose,a,fo({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=Va,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,ln(m).message,!0);return}if(s)return;n=d,a=d.nextStreamId(),d.streams.set(a,{handleFrame(m,g){if(m===x.WsOpened){if(o===Ga){o=Uo;try{i.onopen?.()}catch{}}return}if(m===x.WsText){try{i.onmessage?.({data:vd.decode(g)})}catch{}return}if(m===x.WsBinary){const p=new ArrayBuffer(g.byteLength);new Uint8Array(p).set(g);try{i.onmessage?.({data:p})}catch{}return}if(m===x.WsClose){let p=1e3,h="";try{const E=mo(g,pd);p=E.code,h=E.reason}catch{}c(p,h);return}if(m===x.StreamAbort){let p="stream aborted";try{p=mo(g,ri).reason}catch{}c(1006,p,!0)}},fail(m){c(1012,m.message,!0)}});const{path:l,query:u}=Dd(t),f=r&&r.length>0?{path:l,query:u,protocols:r}:{path:l,query:u};d.send(Re(x.WsOpen,a,fo(f)))})(),i},Ho=new Uint8Array(0),He=e=>e instanceof Error?e:new Error(String(e)),Ya=()=>new DOMException("The operation was aborted.","AbortError"),Xa=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ea=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??ti,i=e.batch!==!1,c=e.reconnectBaseDelayMs??1e3,d=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(v=>dd(new WebSocket(v)));let f=!1,m={state:"idle"};const g=new Set;let p=null,h=null,E=null,A=null,C=0,y=0,w=null,R=[];const V=v=>{if(!(m.state===v.state&&m.lastError===v.lastError)){m=v;for(const N of g)try{N(m)}catch{}}},oe=v=>{const N=R;R=[];for(const L of N)L.reject(v)},ve=v=>{const N=R;R=[];for(const L of N)L.resolve(v)},Oe=(v,N)=>{v.dead=!0;const L=Array.from(v.streams.values());v.streams.clear();for(const O of L)try{O.fail(N)}catch{}},ae=()=>{w!==null&&(clearTimeout(w),w=null)},ye=()=>{if(!(f||Xa())){if(w!==null){ae(),St();return}m.state==="connecting"||m.state==="reconnecting"||p&&!p.dead&&A?.()}},tr=()=>{typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",ye),window.addEventListener("pichamber:system-resume",ye))},Ur=()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",ye),window.removeEventListener("pichamber:system-resume",ye))},rr=()=>{if(f||w!==null)return;const v=c*Math.pow(1.5,Math.min(y,8)),N=Math.random()*.3*v,L=Math.min(d,Math.round(v+N)),O=Xa()?Math.max(L,l):L;w=setTimeout(()=>{w=null,St()},O)},dt=()=>{const v=new URL(e.relayUrl);return v.searchParams.set("v",String(pr)),v.searchParams.set("role","client"),v.searchParams.set("serverId",e.serverId),e.grant&&v.searchParams.set("grant",e.grant),v.toString()},St=async()=>{if(f)return;const v=++C;ae(),E?.(),E=null,V({state:y===0?"connecting":"reconnecting"});let N;try{N=await Xc(e.hostEncPubJwk,{batch:i})}catch(H){Le(v,He(H),!0);return}if(f||v!==C)return;let L;try{L=u(dt())}catch(H){Le(v,He(H));return}h=L;let O=null,se=null,me=null,ee=null,lt=!1,Mt=null,de=!1,le=null,Tt=null,Ne=Date.now(),b=!1,P=Promise.resolve();const U=()=>{A===ue&&(A=null),lt=!1,O!==null&&(clearInterval(O),O=null),se!==null&&(clearTimeout(se),se=null),me!==null&&(clearInterval(me),me=null),ee!==null&&(clearTimeout(ee),ee=null),Mt?.dispose(),Mt=null};E=U;const T=(H,J={})=>{const{terminal:W=!1,asErrorState:q=!1}=J;if(!(de||v!==C)){de=!0,U(),E===U&&(E=null),le&&Oe(le,H),p===le&&(p=null);try{L.close()}catch{}if(h===L&&(h=null),W){f=!0,oe(H),V({state:"error",lastError:H.message});return}Le(v,H,q)}},ue=()=>{de||v!==C||!le||le.dead||lt||(lt=!0,Ne=Date.now(),ee!==null&&(clearTimeout(ee),ee=null),le.send(Re(x.Ping,0,Ho)),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(He(H))}},jr=(H,J)=>{Tt=H,b=J,O!==null&&(clearInterval(O),O=null),se!==null&&(clearTimeout(se),se=null),y=0;const W=new Map,q=cd(),ut=td();let ge=Promise.resolve();const Ue=ar=>{ge=ge.then(async()=>{if(nr.dead)return;const Rc=await H.encryptor.encrypt(ar);L.send(Rc)}).catch(()=>{})},ft=J?id({windowMs:s,sendBatch:Ue}):null;Mt=ft;const nr={streams:W,assembler:ut,nextStreamId:()=>q.next(),send:ar=>{if(Ne=Date.now(),ft){ft.enqueue(ar);return}Ue(ar)},dead:!1};le=nr,p=nr,A=ue,V({state:"connected"}),ve(nr),me=setInterval(()=>{Date.now()-Ne<o||(nr.send(Re(x.Ping,0,Ho)),ee===null&&(ee=setTimeout(()=>{ee=null,T(new Error("relay keepalive timeout"))},n)))},o)},$r=(H,J)=>{let W;try{W=Qc(J)}catch(ge){T(He(ge));return}if(ee!==null&&(clearTimeout(ee),ee=null),lt=!1,W.frameType===x.Ping){H.send(Re(x.Pong,W.streamId,Ho));return}if(W.frameType===x.Pong)return;Ne=Date.now();let q=W.payload;if(W.frameType===x.WsText||W.frameType===x.WsBinary){let ge;try{ge=H.assembler.push(W)}catch(Ue){T(He(Ue));return}if(ge===null)return;q=ge}else if(W.hasMoreFragments){T(new Error("unexpected fragmented tunnel frame"));return}const ut=H.streams.get(W.streamId);ut&&ut.handleFrame(W.frameType,q)};L.onopen=()=>{de||v!==C||(be(),O=setInterval(be,t))},L.onmessage=H=>{if(de||v!==C)return;const J=H.data;if(typeof J=="string"){P=P.then(async()=>{if(de||v!==C)return;const q=await N.handleText(J);if(q.type==="established"){if(Tt)return;jr(q.channel,q.batch)}else q.type==="fail"&&T(new Error(`relay handshake failed: ${q.reason}`))}).catch(q=>{T(He(q))});return}const W=J instanceof ArrayBuffer?new Uint8Array(J):J instanceof Uint8Array?J:null;W&&(P=P.then(async()=>{if(de||v!==C)return;const q=le,ut=Tt;if(!q||!ut){T(new Error("encrypted frame before handshake completed"));return}let ge;try{ge=await ut.decryptor.decrypt(W)}catch(Ue){T(He(Ue));return}if(b){let Ue;try{Ue=od(ge)}catch(ft){T(He(ft));return}for(const ft of Ue){if(de||v!==C||q.dead)return;$r(q,ft)}return}$r(q,ge)}).catch(q=>{T(He(q))}))},L.onclose=H=>{const J=ud.has(H.code);T(new Error(fd[H.code]??`relay socket closed (code ${H.code})`),{terminal:J,asErrorState:J})},L.onerror=()=>{},se=setTimeout(()=>{se=null,T(new Error("relay handshake timeout"),{asErrorState:!0})},r);function Le(H,J,W=!1){H!==C||f||(oe(J),y+=1,V({state:W?"error":"reconnecting",lastError:J.message}),rr())}},Hr=v=>f?Promise.reject(new Error("relay tunnel closed")):v?.aborted?Promise.reject(Ya()):p&&!p.dead?Promise.resolve(p):new Promise((N,L)=>{let O=null;const se={resolve(me){O&&v&&v.removeEventListener("abort",O),N(me)},reject(me){O&&v&&v.removeEventListener("abort",O),L(me)}};v&&(O=()=>{R=R.filter(me=>me!==se),L(Ya())},v.addEventListener("abort",O,{once:!0})),R.push(se)}),or=()=>{if(f)return;f=!0,C+=1,ae(),Ur(),E?.(),E=null;const v=p;p=null;const N=new Error("relay tunnel closed");v&&Oe(v,N),oe(N);try{h?.close()}catch{}h=null,V({state:"idle"})};return tr(),St(),{fetch:(v,N)=>kd(Hr,v,N),openWebSocket:(v,N)=>Sd(()=>Hr(),v,N),getStatus:()=>m,subscribeStatus(v){return g.add(v),()=>{g.delete(v)}},close:or}};let he=null,Fr=null;const Md=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Rr=()=>he,Yt=()=>he!==null,un=new Set,by=e=>(un.add(e),()=>{un.delete(e)}),ta=e=>{if(e!==Yt())for(const t of[...un])t()},Td=e=>{if(he&&Fr&&Md(Fr,e))return he;const t=Yt();return he?.close(),Fr=e,he=ea(e),ta(t),he},Ay=(e,t)=>{if(he===t)return;const r=Yt();he?.close(),Fr=e,he=t,ta(r)},Rd=()=>{const e=Yt();he?.close(),he=null,Fr=null,ta(e)};let ni=()=>null,ai="",go={},at="",Br=0,ht=null,Ut="",Cr=0,wt="",Ft=null,Qe="",to=0,ro=0;const ra=1e4,Pd=e=>e.toLowerCase()==="authorization",si=e=>{const t={};for(const[r,o]of Object.entries(e||{})){const n=r.trim(),a=o.trim();n&&a&&!Pd(n)&&(t[n]=a)}return t},Id=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([o,n])=>t[o]===n)},Pr=e=>typeof e!="string"?"":e.trim(),_d=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_CLIENT_TOKEN__;return Pr(e)},xd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},ii=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():xd();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},oa=e=>{try{return new URL(e).origin}catch{return""}},ci=()=>{Ut="",Cr=0,wt="",Ft=null,Qe="",to+=1},Ir=e=>{e!==void 0&&Pr(e)!==at||(at="",Br=0,ci())},di=()=>{ro+=1,ht=null,Ir(),aa()},li=e=>{const t=Pr(e);ai=t,di(),ni=()=>t?{type:"bearer",token:t}:null},ui=e=>{const t=si(e);Id(go,t)||(go=t,di())},na=()=>{if(Object.keys(go).length>0)return go;if(typeof window>"u")return{};const e=window.__PICHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?si(e):{}},Mo=()=>ai||_d(),Od=(e,t)=>{const r=Pr(e);if(!r||typeof t!="number"||!Number.isFinite(t)){Ir();return}const o=at;at=r,Br=t,o&&o!==r&&$d()},fi=()=>!at||Br<=Date.now()+ra?(Ir(),""):at,Nd=e=>{const t=oa(e);return!t||wt!==t?"":!Ut||Cr<=Date.now()+ra?(Ut="",Cr=0,wt="",""):Ut},Ld=()=>{const e=fi();return!e&&(Mo()||typeof window<"u")&&_r().catch(()=>{}),e},mi=async()=>{const e=await ni(),t=e?.type==="bearer"?Pr(e.token):Mo();return t?{type:"bearer",token:t}:null},gi=e=>{if(ht)return ht;const t=ro,o=(async()=>{const n=await mi(),a=new Headers;for(const[u,f]of Object.entries(na()))a.set(u,f);n?.type==="bearer"&&a.set("Authorization",`Bearer ${n.token}`);const s=Rr(),i=s?await s.fetch("/auth/url-token",{method:"POST",headers:a}):await fetch(ii(e,"/auth/url-token"),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw t===ro&&Ir(),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!==ro)throw new Error("Runtime URL auth token response is stale");if(Od(d,l),!at)throw new Error("Runtime URL auth token response was invalid");return at})().finally(()=>{ht===o&&(ht=null)});return ht=o,ht},Ud=e=>{const t=oa(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Ft&&Qe===t)return Ft;const r=to,n=(async()=>{const a=await fetch(ii(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!a.ok)throw r===to&&t===Qe&&(Ut="",Cr=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!==to||t!==Qe)throw new Error("Local runtime URL auth token response is stale");return Ut=i,Cr=c,wt=t,i})().finally(()=>{Ft===n&&(Ft=null,Qe="")});return Ft=n,Qe=t,Ft},_r=async e=>{const t=fi();return t||gi(e)},Hd=async e=>{const t=oa(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const r=Nd(t);return r||((wt&&wt!==t||Qe&&Qe!==t)&&ci(),Ud(t))};let _t=0,yr=null,pi=null;const fn=new Set,jd=5e3,$d=()=>{for(const e of fn)try{e()}catch{}},hi=()=>{yr!==null&&(clearTimeout(yr),yr=null)},aa=()=>{if(hi(),_t<=0||typeof window>"u")return;const e=Br-ra-jd,t=Br>0?Math.max(0,e-Date.now()):0;yr=setTimeout(()=>{yr=null,!(_t<=0)&&gi(pi).catch(()=>{}).finally(()=>{aa()})},t)},Ey=e=>{typeof e=="string"&&e.trim()&&(pi=e.trim()),_t+=1,aa();let t=!1;return()=>{t||(t=!0,_t=Math.max(0,_t-1),_t===0&&hi())}},wy=e=>(fn.add(e),()=>{fn.delete(e)}),Kd=async e=>{const t=new Headers(e);for(const[o,n]of Object.entries(na()))t.has(o)||t.set(o,n);if(t.has("Authorization"))return t;const r=await mi();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},mn="pichamber:auth-expired",By=()=>{typeof window>"u"||window.dispatchEvent(new Event(mn))},Cy=e=>typeof window>"u"?()=>{}:(window.addEventListener(mn,e),()=>{window.removeEventListener(mn,e)}),vy=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},Qa=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},Fi=(e,t)=>t?t.aborted?Promise.reject(Qa(t.reason)):new Promise((r,o)=>{let n=!1;const a=()=>{n||(n=!0,o(Qa(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(),zd=["local","remote",null],qd=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function yi(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"||!zd.includes(o)))return{valid:!1};if(typeof n!="string"||!qd.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 Gd(){if(Wd()!=="valid")return null;const t=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__,r=yi(t);return r.valid?r.outcome:null}function Wd(){if(typeof window>"u")return"not-injected";const e=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":yi(e).valid?"valid":"malformed"}const po=/^[a-z][a-z\d+.-]*:\/\//i,Vd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},gn=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Jd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return gn(e)},Yd=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},pn=(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))},Xd=(e,t)=>{if(!t)return e;const r=new URLSearchParams;pn({searchParams:r},t);const o=r.toString();return o?e.includes("?")?`${e}&${o}`:`${e}?${o}`:e},Za=(e,t,r)=>{if(po.test(t)){const a=new URL(t);return pn(a,r),a.toString()}const o=Vd(t);if(!e)return Xd(o,r);const n=new URL(o,`${e}/`);return pn(n,r),n.toString()},jo=(e,t)=>{const r=t===void 0?Ld():t;if(!r)return e;const o=po.test(e)?new URL(e):new URL(e,"http://pichamber.local");return o.searchParams.set("oc_url_token",r),po.test(e)?o.toString():`${o.pathname}${o.search}${o.hash}`},Qd=(e,t)=>{const r=po.test(e)?new URL(e):new URL(e,Yd(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},sa=(e={})=>{const t=gn(e.apiBaseUrl),r=gn(e.realtimeBaseUrl),o=()=>t||Jd(),n=()=>r||o(),a=(i,c)=>Za(o(),i,c),s=(i,c)=>Za(n(),i,c);return{api:a,authenticatedAsset:(i,c)=>jo(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)=>jo(s(i,c)),websocket:(i,c,d)=>Qd(jo(s(i,c),d),e)}};let ho=sa();const Ie=()=>ho,Zd=e=>{ho=e},ia=e=>(ho=sa(e),ho);let $o=null,Ko=null,zo=null;const es=new Set;let ts=!1;const bi=e=>{if(es.add(e),ts||typeof window>"u")return;ts=!0;const t=()=>{for(const r of es)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{}},el=(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 bi(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()}}},ca=e=>el(()=>wi(),e),tl=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 bi(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}}},Ai=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},da=()=>{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}}},Ei=e=>{const t=da(),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}}},rl=()=>{const e=Ai("localStorage");return e?Ei(e):da()},wi=()=>($o||($o=rl()),$o),xr=()=>(zo||(zo=tl(wi())),zo),ol=()=>{const e=Ai("sessionStorage");return e?Ei(e):da()},ky=()=>(Ko||(Ko=ol()),Ko),hn="pichamber:runtime-endpoint-changed",Fn="pichamber:runtime-endpoint-will-change";let st="",Bt="",Bi=0;const Dy=()=>(To(),Bi),yn="pichamber:lastRuntimeEndpoint.v1",nl=()=>{try{const e=xr().getItem(yn);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}},al=(e,t)=>{try{const r=xr();if(t==="mobile-disconnected"||!e){r.removeItem(yn);return}r.setItem(yn,JSON.stringify({apiBaseUrl:e,runtimeKey:t}))}catch{}},To=()=>{if(st||Bt||typeof window>"u")return;const e=nl();if(e){st=e.apiBaseUrl,Bt=e.runtimeKey;try{window.__PICHAMBER_API_BASE_URL__=e.apiBaseUrl}catch{}ia({apiBaseUrl:e.apiBaseUrl,realtimeBaseUrl:e.apiBaseUrl})}},qo=(e,t,r)=>{try{e[t]=r}catch{}},la=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"}`}},Ci=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},vi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},ki=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ge=()=>(To(),st||Ci());let Go="",rs=null,os,ns;const as=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(To(),Bt)return Bt;const e=as("__PICHAMBER_API_BASE_URL__"),t=as("__PICHAMBER_LOCAL_ORIGIN__");if(rs===st&&os===e&&ns===t)return Go;const r=Ge();return Go=ki(r,vi())?"local":la(r),rs=st,os=e,ns=t,Go},sl=(e={})=>{if(To(),st||Bt)return;const t=e.apiBaseUrl?.trim()||Ci();t&&(st=t,Bt=e.runtimeKey?.trim()||(ki(t,vi())?"local":la(t)))},Ht=e=>{const t=e.apiBaseUrl.trim(),r=Ge(),o=D(),n=e.runtimeKey?.trim()||la(t);Bi+=1,al(t,n);const a={apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fn,{detail:a})),st=t,Bt=n,typeof window<"u"){const s=window;qo(s,"__PICHAMBER_API_BASE_URL__",t),qo(s,"__PICHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),qo(s,"__PICHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}ia({apiBaseUrl:t,realtimeBaseUrl:t}),ui(e.requestHeaders||null),li(e.clientToken||null),e.relay?Td(e.relay):Rd(),_r(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(hn,{detail:a}))},il=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(Fn,t),()=>window.removeEventListener(Fn,t)},Di=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(hn,t),()=>window.removeEventListener(hn,t)};let bn=null;const cl=e=>{bn=e},ua=()=>bn||(typeof window>"u"?null:window.__PICHAMBER_RUNTIME_APIS__??null),Sy=Object.freeze(Object.defineProperty({__proto__:null,getRegisteredRuntimeAPIs:ua,registerRuntimeAPIs:cl},Symbol.toStringTag,{value:"Module"})),dl=()=>typeof window>"u"?null:window.__PICHAMBER_ELECTRON__??null,Xt=()=>typeof window>"u"?null:window.__PICHAMBER_DESKTOP__??null,Ro=()=>dl()?.runtime==="electron",My=()=>{if(typeof window>"u")return null;const e=window.__PICHAMBER_PLATFORM__;return typeof e=="string"?e:null},Z=()=>typeof Xt()?.invoke=="function",xe=()=>Ro()&&Z(),z=async(e,t)=>{const r=Xt();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},ss=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}}},Wo=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}}},ll=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),sr=e=>{const t=ll(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ce=()=>typeof window>"u"?!1:Ro(),ce=()=>{if(typeof window>"u"||!Ce())return!1;if(D()==="local")return!0;const e=typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",t=Wo(e),r=Wo(Ge());if(!r&&t&&Gd()?.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&&sr(t.hostname)&&sr(r.hostname)}const o=Wo(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&&sr(t.hostname)&&sr(o.hostname)}const n=ss(e),a=ss(window.location.origin)||window.location.origin;return n&&a&&n===a?!0:!!(o&&sr(o.hostname))},Ty=()=>{const t=ua()?.runtime?.platform;return t==="web"?!0:t!=="desktop"},Ry=(e,t=Ce())=>e==="web"&&!t,Py=async()=>{if(!xe())return null;try{const e=await z("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}},Iy=async e=>{if(!xe())return null;try{const t=await z("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}},_y=async()=>{if(!xe())return null;try{const e=await z("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}},xy=async e=>{if(!xe())return null;try{const t=await z("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}},Oy=async()=>{if(!xe())return null;try{const e=await z("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}},Ny=async e=>{if(!xe())return null;try{const t=await z("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(!xe())return null;try{const e=await z("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(!xe())return null;try{const t=await z("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}},Hy=async()=>{if(!xe())return null;try{const e=await z("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}},jy=async e=>{if(!xe())return null;try{const t=await z("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}},ul=()=>Ce()&&Z()&&ce(),fl=async()=>{if(typeof window<"u"){const e=window.__PICHAMBER_HOME__;if(e&&e.length>0)return e}return null},$y=async e=>{if(ul())try{const t=await Xt()?.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"}},Si=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ky=async e=>{if(Z()&&ce())try{const t=await Xt()?.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(!Si(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"}},zy=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 Xt()?.grantFileAccess?.(t);if(!Si(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)}}},qy=async e=>({success:!0}),Gy=async e=>({success:!0}),Wy=async()=>Z()&&await z("desktop_get_update_channel")==="rc"?"rc":"stable",Vy=async e=>{if(!Z())throw new Error("Desktop update settings are unavailable.");const t=await z("desktop_set_update_channel",{channel:e});if(t!=="stable"&&t!=="rc")throw new Error("Unable to save the desktop update channel.");return t},Jy=async()=>Z()?await z("desktop_check_for_updates"):null,Yy=async e=>{if(!Z())return!1;const t=Xt();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 z("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{}}},ml=async()=>{if(!Z())return!1;try{return await z("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},Xy=async()=>Z()?ml():!1,Qy=async()=>{if(!Z()||!ce())return null;try{const e=await z("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}},gl=async(e,t)=>{if(!Z()||!ce())return!1;const r=e?.trim();if(!r)return!1;try{return await z("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}},Zy=async e=>{if(!Z()||!ce())return!1;const t=e?.trim();if(!t)return!1;try{return await z("desktop_reveal_path",{path:t}),!0}catch{return gl(t)}},eb=async(e,t)=>{if(!Z()||!ce())return null;const r=e?.trim();if(!r)return null;try{const o=await z("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}},tb=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 z("desktop_open_in_app",{projectPath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},rb=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 z("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}},ob=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 z("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:",nb=()=>{if(typeof window>"u"||!Qt()||pl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},pl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ce()?"desktop":"web"},ab=()=>{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",hl=()=>typeof window>"u"?"":window.location.origin||"",fa=e=>{if(typeof window>"u")return!1;const t=hl();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}},ma=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),ga=(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))},oo=e=>{try{const t=Ie().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}},Vo=e=>{if(Ct(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return fa(t)&&Ct(t.pathname)}catch{return!1}},Fl=(e,t)=>{try{const r=new URL(e);if(!fa(r))return e;const o=Et(`${r.pathname}${r.search}`,t);return!ma(o)&&(r.protocol==="http:"||r.protocol==="https:")?(ga(r,t),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return e}},Et=(e,t)=>e==="/health"?Ie().health(t):e.startsWith("/auth/")||e==="/auth"?Ie().auth(e,t):Ct(e)?Ie().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Fl(e,t):e,yl=e=>{const t=e instanceof Request?e.url:e.toString();if(!ma(t))return Ct(t);try{return oo(new URL(t))}catch{return!1}},bl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Al=(e,t)=>!bl(t),is=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)Al(n,a)?(r.push([n,encodeURIComponent(a)]),o=!0):r.push([n,a]);return o?r:void 0},je=async(e,t,r=!0)=>{const o=new Headers(is(e)??e);return t&&new Headers(is(t)??t).forEach((n,a)=>o.set(a,n)),r?Kd(o):o},El=(e,t)=>{if(!t)return e;const r=new URL(e,Zn);return ga(r,t),`${r.pathname}${r.search}`},Mi=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!ma(r))return Ct(r)?El(r,t):null;try{const o=new URL(r);return!fa(o)||!Ct(o.pathname)?null:(ga(o,t),`${o.pathname}${o.search}`)}catch{return null}},wl=async(e,t,r)=>{const o=Rr();if(!o)return null;const n=Mi(e,r);if(n===null)return null;const a=e instanceof Request?e.headers:void 0,s=await je(a,t.headers,!0);return e instanceof Request?o.fetch(e,{...t,headers:s}):o.fetch(n,{...t,headers:s})},Bl=(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)},Cl=/\/api\/pi\/(health|projects|sessions|providers|resources|runtime|settings)(\b|\/|\?|$)/,qr=new Map,vl=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!Cl.test(t)?null:`GET ${t}`,F=async(e,t={})=>{const{query:r,...o}=t,n=Rr(),a=n?Mi(e,r):null,s=o.signal??(e instanceof Request?e.signal:void 0);let i,c,d;if(n&&a!==null){const g=e instanceof Request?e.headers:void 0,p=await je(g,o.headers,!0);i=e instanceof Request?()=>n.fetch(e,{...o,headers:p}):()=>n.fetch(a,{...o,headers:p}),c=a,d=String(o.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const g=Bl(e,r),p=g instanceof Request?g.headers:void 0,h=await je(p,o.headers,yl(g));let E=g instanceof Request?()=>fetch(new Request(g,{...o,headers:h})):()=>fetch(g,{...o,headers:h});if(Qt()&&s){const A=E;E=()=>Fi(A,s)}i=E,c=g instanceof Request?g.url:g instanceof URL?g.toString():String(g),d=String(o.method??(g instanceof Request?g.method:"GET")).toUpperCase()}const l=o.signal!=null||e instanceof Request,u=vl(d,c,l);if(!u)return i();const f=qr.get(u);if(f)return f.then(g=>g.clone());const m=i();return qr.set(u,m),m.then(()=>qr.delete(u),()=>qr.delete(u)),m.then(g=>g.clone())};let cs=!1;const kl=()=>{if(cs||typeof window>"u")return;cs=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const o=await wl(t,r??{});if(o)return o;if(typeof t=="string"){if(!Vo(t)){try{const a=new URL(t);if(oo(a)){const s=await je(void 0,r?.headers);return e(t,{...r,headers:s})}}catch{}return e(t,r)}const n=await je(void 0,r?.headers);return e(Et(t),{...r,headers:n})}if(t instanceof URL){const n=t.toString();if(!Vo(n)){if(oo(t)){const s=await je(void 0,r?.headers);return e(t,{...r,headers:s})}return e(t,r)}const a=await je(void 0,r?.headers);return e(Et(n),{...r,headers:a})}if(t instanceof Request){if(!Vo(t.url)){try{const i=new URL(t.url);if(oo(i)){const c=await je(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const n=await je(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,Dl=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,"")},Ti=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}},Sl=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}},Ml=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}},ds=e=>typeof e=="string"&&e.length>0,Tl=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ds(t.x)||!ds(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Rl=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pl=e=>{if(!e||typeof e!="object")return null;const t=e,r=Rl(t.priority);if(t.type==="lan"||t.type==="tunnel"||t.type==="tailscale"){const o=Sl(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=Ml(t.relayUrl);if(!o)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const a=Tl(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},pa=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(Pl).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}},sb=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}),ib=e=>{const t=pa(e);if(!t)throw new Error("Invalid pairing connection payload");const r=new URLSearchParams;return r.set("v","2"),r.set("p",Dl(JSON.stringify(t))),`pichamber://connect?${r.toString()}`},Il=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=Ti(o);return!n||n.length>jt?null:pa(JSON.parse(n))}catch{return null}},cb=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=Ti(n);if(!a||a.length>jt)return null;try{return pa(JSON.parse(a))}catch{return null}},qt=e=>typeof e=="object"&&e!==null,_l=e=>e.trim().toLowerCase()==="authorization",xl=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)||_l(n)||(t[n]=a)}return Object.keys(t).length>0?t:void 0},Ri=e=>`relay://${e}`,Ol=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}},Nl=()=>{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"},Pi=5e3,Ll=async(e,t,r)=>{const o=Il(e);if(!o)throw new Error("invalid-connect-link");const n=await xi().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:Nl(),...n?{dedupeKey:`desktop:${n}`}:{}})},s=async y=>{if(!y.ok)return null;const w=await y.json().catch(()=>null);return(typeof w?.clientToken=="string"?w.clientToken.trim():"")||null};let i=null;const c=[...o.candidates].sort((y,w)=>(y.type==="relay"?1:0)-(w.type==="relay"?1:0));for(const y of c){if(y.type==="relay"){const R=ea({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const V=await s(await R.fetch("/api/client-auth/pairing/redeem",a));if(V){i={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:V};break}}catch{}finally{R.close()}continue}const w=X(y.url);if(w)try{const R=await s(await fetch(`${w}/api/client-auth/pairing/redeem`,a));if(R){i={directUrl:w,token:R};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const d=o.candidates.find(y=>y.type==="relay"),l=i.relay||(d?{relayUrl:d.relayUrl,serverId:d.serverId,hostEncPubJwk:d.hostEncPubJwk}:void 0),u=o.candidates.filter(y=>y.type!=="relay").map(y=>X(y.url)).find(y=>!!y),f=i.directUrl||u,m=f||(l?Ri(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");let g=null;if(i.directUrl){const y=r?.healthTimeoutMs??Pi,w=new AbortController,R=setTimeout(()=>w.abort(),y);try{const V=await fetch(`${i.directUrl}/health`,{headers:{Accept:"application/json"},signal:w.signal,credentials:"omit"});if(V.ok){const oe=await V.json().catch(()=>null),ve=typeof oe?.serverId=="string"?oe.serverId.trim():"";ve&&(g=ve)}}catch{}finally{clearTimeout(R)}}const p=new Set;l?.serverId&&p.add(l.serverId),g&&p.add(g);const h=y=>{for(const w of p)if(y.serverId===w||y.relay?.serverId===w)return!0;return!1},E=t.find(y=>{if(l){if(y.relay?.serverId===l.serverId)return!0}else if(!y.relay&&X(y.apiUrl||y.url)===m)return!(y.serverId&&g&&y.serverId!==g);return h(y)}),A=E?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),C={...E||{},id:A,label:o.label||E?.label||ha(m),url:m,apiUrl:f,clientToken:i.token,...l?{relay:l}:{}};return E?.serverId?C.serverId=E.serverId:g&&(C.serverId=g),{hostId:A,hosts:E?t.map(y=>y.id===A?C:y):[C,...t]}},Ul=/^(t|.*(?:token|auth|secret|api).*)$/i,X=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}},Hl=e=>{const t=X(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"}},ha=e=>{const t=X(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)Ul.test(n)&&r.searchParams.set(n,"[REDACTED]");return r.toString()}catch{return t}},rt=(e,t)=>{const r=X(e),o=X(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},ls=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},jl=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=xl(e.requestHeaders),i=Ol(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()}:{}}},_e=e=>X(e.apiUrl||e.url)||e.apiUrl||e.url,$l=(e,t)=>{const r={...e,url:t,apiUrl:t};return X(_e(e))!==X(t)&&delete r.serverId,r},kt=()=>Z()?(e,t)=>z(e,t):null,Fa=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(jl).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}},Ii=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})},_i=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},xi=async()=>{const e=kt();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Kl=8e3,us=async(e,t,r)=>{const o=new AbortController,n=window.setTimeout(()=>o.abort(),Kl);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(n)}},zl=async(e,t)=>{const r=ea({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),o=Date.now();let n=!1;try{if(!(await us(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 us(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()}},ya=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=ls(o,"latencyMs")??ls(o,"latency_ms")??0,i=Y(o,"reportedServerId");return{status:a,latencyMs:s,...i?.trim()?{reportedServerId:i.trim()}:{}}},ql=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})},Gl=async e=>{const t=kt();t&&await t("desktop_new_window_for_host",{hostId:e})},db=Object.freeze(Object.defineProperty({__proto__:null,DESKTOP_HOST_HEALTH_PIN_TIMEOUT_MS:Pi,desktopHostProbe:ya,desktopHostsGet:Fa,desktopHostsSet:Ii,desktopInstallIdGet:xi,desktopLocalClientTokenGet:_i,desktopOpenNewWindowAtUrl:ql,desktopOpenNewWindowForHost:Gl,getDesktopHostApiUrl:_e,importDesktopHostPairing:Ll,locationMatchesHost:rt,normalizeHostUrl:X,probeRelayDesktopHost:zl,redactSensitiveUrl:ha,relayHostDisplayUrl:Ri,resolveDesktopHostUrl:Hl,withEditedDesktopHostUrl:$l},Symbol.toStringTag,{value:"Module"})),ot="local",Wl=e=>({id:ot,label:"Local",url:e||ba()}),ba=()=>typeof window>"u"?"":window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,Aa=e=>e.id===ot?"local":`host:${e.id}`,fs="host:",Oi=e=>{const t=e.runtimeKey.trim();if(t===ot)return{kind:"local"};if(t.startsWith(fs)){const o=t.slice(fs.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,_e(o)):!1);return r?{kind:"host",host:r}:e.localOrigin&&e.apiBaseUrl&&rt(e.apiBaseUrl,e.localOrigin)?{kind:"local"}:null},Vl=e=>{const t=typeof window>"u"?"":window.location.href,r=e.find(l=>l.id===ot)?.url||ba(),o=Ge(),n=X(r)||r,a=X(t)||t,s=D(),i=e.find(l=>l.relay&&Aa(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,_e(l)):!1);if(c)return{id:c.id,label:c.label,url:X(_e(c))||_e(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:X(d.url)||d.url}:t.startsWith("pichamber-ui://")?{id:ot,label:"Local",url:n}:{id:"custom",label:ha(a||"Instance"),url:a}},lb=Object.freeze(Object.defineProperty({__proto__:null,LOCAL_HOST_ID:ot,buildLocalDesktopHost:Wl,getLocalDesktopOrigin:ba,resolveCurrentDesktopHost:Vl,resolveDesktopHostIdentity:Oi,runtimeKeyForDesktopHost:Aa},Symbol.toStringTag,{value:"Module"})),Jl=5e3,Yl=1500;let Jo=!1;const Xl=async e=>{if(!Ro()||Jo)return;const t=`host:${e}`;if(D()===t){Jo=!0;try{const r=await Fa().catch(()=>null),o=r?.hosts.find(m=>m.id===e);if(!r||!o?.relay)return;const n=o.apiUrl?X(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 g=m;if(g.type!=="lan"&&g.type!=="tailscale"||typeof g.url!="string")continue;const p=X(g.url),h=g.type==="tailscale"?d:c;p&&!h.includes(p)&&h.push(p)}const l=c.length>0?c:d;if(l.length===0)return;const u=n&&l.includes(n)?n:l[0];u!==n&&await Ii({hosts:r.hosts.map(m=>m.id===e?{...m,apiUrl:u}:m),defaultHostId:r.defaultHostId,initialHostChoiceCompleted:r.initialHostChoiceCompleted}).catch(()=>{});const f=await ya(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"||D()!==t)return;Ht({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:t})}finally{Jo=!1}}},Ql=e=>{typeof window>"u"||window.setTimeout(()=>{Xl(e).catch(()=>{})},Jl)},Zl=(e,t)=>{if(t){const o=e.hosts.find(n=>n.id===t);return o?{kind:"host",host:o}:null}const r=Oi({runtimeKey:D(),apiBaseUrl:Ge(),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"}},eu=(e,t)=>{const r=e.clientToken||"";!r||Mo()===r||Ht({apiBaseUrl:Ge()||_e(e),clientToken:r,requestHeaders:e.requestHeaders||null,runtimeKey:t,relay:Yt()?e.relay:void 0})},tu=async e=>{if(!Ro())return;const t=await Fa().catch(()=>null);if(!t)return;const r=Zl(t,e);if(!r)return;if(r.kind==="local"){const u=await _i();if(!u)return;const f=t.localOrigin||Ge();if(!f||D()==="local"&&Mo()===u)return;Ht({apiBaseUrl:f,clientToken:u,runtimeKey:"local"});return}const o=r.host,n=Aa(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}),Ql(o.id)};if(D()===n){const u=o.apiUrl?X(_e(o)):"";if(!!(u&&rt(Ge(),u))||!o.relay){eu(o,n);return}s();return}if(!o.relay){const u=_e(o);if(!u)return;a(u);return}const i=o.apiUrl?X(_e(o)):null;if(!i){s();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",d=ya(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),Yl))]);if(l){if(c(l)){a(i);return}s();return}s(),d.then(u=>{c(u)&&D()===n&&a(i)})},ru=64*1024,ou=(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+ru,e.size),s=new Uint8Array(await e.slice(o,a).arrayBuffer());o=a,n.enqueue(s),r?.({loaded:o,total:e.size})}})},nu=(e,t)=>!Qt()||e instanceof File?e:new File([e],t.filename,{type:t.mime||e.type}),au=async(e,t,r)=>{const o=!!Rr();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?ou(t,r.signal,r.onProgress):nu(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,su="events.streamEpoch",iu=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},ub="pichamber.bash",fb=64*1024,ms=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0,Ni=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return!(t.snoozedUntil!==void 0&&(!ms(t.snoozedUntil)||!ms(t.snoozedAt)))},cu=e=>{if(!e||typeof e!="object")return!1;const t=e.sessions;return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(Ni)},du=["session.snapshot","session.lifecycle","session.deleted","session.updated","session.tree.updated","session.input","session.bash","session.bash.output","session.bash.recorded","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","session.openUrl","session.archive","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.custom","extension.custom.frame","extension.custom.dismiss","extension.error"],An=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))&&du.includes(t.name)},Li=(e,t)=>{const r=Rr();return r?r.openWebSocket(hd(e),t):ld(new WebSocket(e))},Ui="pichamber.mobile.diagnostics.v1",Ea=300,lu=240,uu=1e3;let Gt=[],gs=!1,$t=null,Yo=!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,lu)||void 0,fu=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)}:{}}},Hi=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},Po=()=>{if(gs)return;gs=!0;const e=Hi();if(e)try{const t=e.getItem(Ui);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(-Ea)}catch{}},mu=()=>{$t!==null&&(clearTimeout($t),$t=null)},gu=()=>{$t===null&&($t=setTimeout(()=>{$t=null,no()},uu))},no=()=>{mu();const e=Hi();if(e)try{Po(),e.setItem(Ui,JSON.stringify(Gt.slice(-Ea)))}catch{}},G=(e,t={})=>{if(!Qt())return;Po();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(-Ea),gu()},pu=(e,t)=>{G(e,fu(t))},hu=()=>(Po(),JSON.stringify({format:"pichamber-mobile-diagnostics-v1",generatedAt:new Date().toISOString(),platform:typeof navigator>"u"?"unknown":navigator.userAgent,entries:Gt},null,2)),mb=async()=>{const e=hu(),{isShareCancelledError:t,saveOrShareFile:r}=await Pc(async()=>{const{isShareCancelledError:n,saveOrShareFile:a}=await import("./nativeFileSave-Cp9i5QGd.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")},gb=()=>{if(!Qt()||typeof window>"u"||Yo)return()=>{};Yo=!0,Po(),G("app-launch",{code:"start"});const e=n=>{G("window-error",{code:n.error?.name,detail:n.message})},t=n=>{pu("unhandled-rejection",n.reason)},r=()=>{no()},o=()=>{document.visibilityState==="hidden"&&no()};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),no(),Yo=!1}},Fu=3e4,yu=250,bu=5e3,Au=6e4,Eu=8,wu=2e3,Bu=1e4,Cu=5e3,vu=3e4,ku=5e3,It=new Map,Du=8,Su=(e,t)=>{if(!(!e||!t||t.length>128))for(It.delete(e),It.set(e,t);It.size>Du;){const r=It.keys().next();if(r.done)break;It.delete(r.value)}},Ze=(e=D())=>It.get(e),ji=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=su,t},ps=(e,t,r)=>{const o=Ie(),n=ji(t);return e==="ws"?o.websocket("/api/pi/events",n,r):o.sse("/api/pi/events",n)},Mu=()=>"/api/pi/runtime",ao=()=>Qt()&&!Yt()&&typeof EventSource<"u",Tu=3e3;let En=null,mr=null;const pb=()=>{En=null,mr=null},Ru=1e4,Gr=e=>({...e,capabilities:[...e.capabilities]}),yo=async(e,t,r)=>{const o=t??D();if(!r?.fresh){const s=En;if(s&&s.runtimeKey===o&&s.runtimeKey===D()&&Date.now()<s.expiresAt)return Gr(s.result)}const n=!r?.fresh&&!e;if(n){const s=mr;if(s&&s.runtimeKey===o&&s.runtimeKey===D())return s.promise.then(Gr)}const a=async()=>{const s=r?.timeoutMs??Ru,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(Mu(),{signal:i.signal});if(o!==D())return{state:"unavailable",protocolVersion:Pt,capabilities:[],error:{code:"DAEMON_UNAVAILABLE",message:"Runtime changed during request"}};if(!l.ok)return G("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 Fi(()=>l.json(),i.signal).catch(h=>{if((h instanceof DOMException||h instanceof Error)&&h.name==="AbortError")throw h;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,g=typeof f.streamEpoch=="string"&&f.streamEpoch.length>0&&f.streamEpoch.length<=128?f.streamEpoch:void 0;f.state==="ready"&&g&&Su(o,g);const p={state:f.state==="ready"?"ready":"unavailable",protocolVersion:typeof f.protocolVersion=="number"?f.protocolVersion:Pt,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter(h=>typeof h=="string"):[],...g?{streamEpoch:g}:{},...m?{error:{code:m,...typeof f.error?.message=="string"?{message:f.error.message}:{}}}:{}};return!r?.fresh&&p.state==="ready"&&o===D()&&(En={runtimeKey:o,result:Gr(p),expiresAt:Date.now()+Tu}),p}catch(l){const u=(l instanceof DOMException||l instanceof Error)&&l.name==="AbortError";return G("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(()=>{mr?.promise===s&&(mr=null)});return mr={runtimeKey:o,promise:s},s.then(Gr)}return a()},Pu=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 yo(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)}},Iu=(e,t,r,o,n,a,s)=>{if(ao()){const f=new EventSource(Ie().sse("/api/pi/events",e)),m=new AbortController;let g=!1,p=!1,h=setTimeout(()=>{h=null,!(p||g)&&(G("stream-connect",{code:"setup-timeout"}),C(),a("sse-setup-timeout"))},s.setupTimeoutMs);const E=()=>{h&&clearTimeout(h),h=null},A=()=>{g||o()},C=()=>{E(),m.abort(),!g&&(g=!0,f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C))},y=w=>{try{const R=JSON.parse(w);An(R)&&n(R)}catch{G("stream-frame",{code:"bad-sse-frame"})}};return f.onopen=()=>{g||(p=!0,E(),r())},f.onmessage=w=>{g||(o(),typeof w.data=="string"&&w.data.trim()&&y(w.data))},f.onerror=()=>{if(g)return;E(),f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C),g=!0,G("stream-disconnect",{code:"sse-error"});const w=s.classifySourceError;if(!w){a("sse-error");return}w(m.signal).then(R=>{m.signal.aborted||a(R==="auth"?"sse-auth-probe":"sse-error")})},f.addEventListener("heartbeat",A),t.aborted?C():t.addEventListener("abort",C,{once:!0}),C}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)&&(G("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(G("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(),g=new TextDecoder;let p="",h=[];const E=()=>{if(h.length===0)return;const A=h.join(`
|
|
3
3
|
`).trim();if(h=[],!!A)try{const C=JSON.parse(A);An(C)&&n(C)}catch{}};for(;;){const{value:A,done:C}=await m.read();if(C){E(),u(),a("sse-eof");return}o(),p+=g.decode(A,{stream:!0});let y=p.indexOf(`
|
|
4
4
|
`);for(;y!==-1;){const w=p.slice(0,y).replace(/\r$/,"");p=p.slice(y+1),w.length===0?E():w.startsWith("data:")&&h.push(w.slice(5).replace(/^ /,"")),y=p.indexOf(`
|
|
5
5
|
`)}}}).catch(f=>{if(i.signal.aborted)return;const m=f instanceof Error?f.message.slice(0,80):"fetch-failed";G("stream-connect",{code:"fetch-failed",detail:m}),a(`sse-error:${m}`)}).finally(()=>{u(),t.removeEventListener("abort",c)}),c},_u=(e,t,r,o,n,a)=>{const s=Li(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 g=JSON.parse(m);An(g)&&o(g)}catch{}},s.onerror=()=>{i||n("ws-error")},s.onclose=f=>{t.removeEventListener("abort",u),i||n(`ws-close-${f?.code??0}`)},l},hs=()=>typeof document>"u"||document.visibilityState==="visible",Fs=()=>typeof navigator>"u"||navigator.onLine!==!1,hb=(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===D();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,g=null,p=null,h=null,E=0,A=!1,C=!1;const y=t.setupTimeoutMs??Bu,w=t.authTokenTimeoutMs??Cu,R=t.healthResetMs??vu,V=t.epochProbeTimeoutMs??ku;let oe=null;const ve=new Set;let Oe=!1,ae=null,ye=null,tr=null,Ur=!1;const rr=()=>{m&&clearTimeout(m),g&&clearTimeout(g),p&&clearTimeout(p),m=null,g=null,p=null},dt=()=>{E+=1,h?.(),h=null,g&&clearTimeout(g),g=null,p&&clearTimeout(p),p=null},St=b=>{g&&clearTimeout(g),g=setTimeout(()=>{b===E&&O("heartbeat-timeout",b)},t.heartbeatTimeoutMs??Fu)},Hr=b=>{c||a.aborted||b!==E||(St(b),Ur&&ee(b),Ur=!0)},or=b=>{if(c||a.aborted||b!==E)return;const P=!A;A=!0,C=!1,P&&(p&&clearTimeout(p),p=setTimeout(()=>{p=null,b===E&&A&&(d=0)},R),G("stream-ready",{code:f}),e.onReconnect?.()),St(b)},v=()=>{const b=hs()&&Fs()?bu:Au,P=Math.min(Eu,d),U=Math.min(b,yu*2**P);return d===0&&t.reconnectDelayMs!==void 0?Math.max(0,t.reconnectDelayMs):U+Math.floor(Math.random()*100)},N=(b,P=!0)=>{c||a.aborted||m||(G("stream-reconnect",{code:b}),P&&e.onDisconnect?.(b),m=setTimeout(()=>{m=null,d+=1,de()},v()))},L=()=>{c||a.aborted||!m||(clearTimeout(m),m=null,d+=1,de())},O=(b,P)=>{if(!(c||a.aborted||P!==E)){if(dt(),!A&&f==="ws"&&t.transport!=="ws"&&(f="sse",e.onTransportSwitch?.()),A=!1,b==="runtime-change"){e.onDisconnect?.(b);return}if(b==="sse-auth-401"||b==="sse-auth-403"||b==="sse-auth-probe"){G("stream-auth",{code:b}),e.onDisconnect?.(b),e.onAuthRequired?.();return}N(b)}},se=(b,P)=>{if(c||a.aborted||P!==E)return;if(!i()){O("runtime-change",P);return}const U=typeof b.streamEpoch=="string"&&b.streamEpoch.length>0?b.streamEpoch:null;if(U&&U!==oe){if(ve.has(U)){G("stream-epoch",{code:"retired-frame"});return}const T=oe??l;if(T!==null&&T!==U){if(Oe){ye??={event:b,epoch:U,connectionId:P};return}me(b,U,T,P);return}oe=U,u=Math.max(u??0,b.sequence),T===null&&e.onEpochChange?.(U)}(u===void 0||b.sequence>u)&&(u=b.sequence),or(P),e.onEvent(b)},me=async(b,P,U,T)=>{Oe=!0,ae=new AbortController;const ue=setTimeout(()=>ae?.abort(),V);try{const be=await yo(ae.signal,s,{fresh:!0});if(c||a.aborted||T!==E)return;if(be.state==="ready"&&be.streamEpoch===P){ve.add(U),oe=P,u=b.sequence,G("stream-epoch",{code:"verified"}),e.onEpochChange?.(P),or(T),e.onEvent(b);return}if(be.state==="unavailable"&&be.error?.code==="DAEMON_AUTH_FAILED"){O("sse-auth-probe",T);return}if(be.state==="ready"){ve.add(P),G("stream-epoch",{code:"rejected"});return}G("stream-epoch",{code:"unverified"}),O("epoch-unverified",T)}finally{clearTimeout(ue),Oe=!1,ae=null,ye=null,lt()}},ee=async b=>{const P=oe??l;if(!P)return;if(Oe){tr=b;return}Oe=!0,ae=new AbortController;const U=setTimeout(()=>ae?.abort(),V);try{const T=await yo(ae.signal,s,{fresh:!0});if(c||a.aborted||b!==E)return;const ue=T.state==="ready"?T.streamEpoch:void 0;if(!ue||ue===P||ve.has(ue)||(oe??l)!==P)return;ve.add(P),oe=ue,u=void 0,G("stream-epoch",{code:"verified-on-resubscribe"}),e.onEpochChange?.(ue)}catch{}finally{clearTimeout(U),Oe=!1,ae=null;const T=ye;ye=null,T&&se(T.event,T.connectionId),lt()}},lt=()=>{const b=tr;tr=null,!(b===null||c||a.aborted||b!==E)&&ee(b)},Mt=async()=>{let b=null;try{return await Promise.race([_r(),new Promise((P,U)=>{b=setTimeout(()=>U(new Error("url-token-timeout")),w)})])}finally{b&&clearTimeout(b)}},de=async()=>{if(c||a.aborted)return;if(!i()){e.onDisconnect?.("runtime-change");return}const b=E+1;E=b;let P;if(f==="ws")try{P=await Mt()}catch{if(b!==E||c||a.aborted)return;if(t.transport!=="ws"){f="sse",e.onTransportSwitch?.(),dt(),de();return}G("stream-auth",{code:"url-token-unavailable"}),O("ws-auth-token-unavailable",b);return}if(b!==E||c||a.aborted)return;if(!i()){O("runtime-change",b);return}if(f==="sse"&&ao()){try{await Mt()}catch{if(b!==E||c||a.aborted)return;G("stream-auth",{code:"url-token-unavailable"}),O("sse-auth-token-unavailable",b);return}if(b!==E||c||a.aborted||!i())return}const U=oe??l??void 0,T=ps(f,{...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...U?{streamEpoch:U}:{}},P),ue=()=>Hr(b),be=Le=>se(Le,b),jr=Le=>O(Le,b),$r=ji({...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...U?{streamEpoch:U}:{}});h=f==="ws"?_u(T,a,ue,be,jr,wu):Iu($r,a,ue,()=>or(b),be,jr,{setupTimeoutMs:y,...ao()?{classifySourceError:Le=>Pu(s,V,Le)}:{}})},le=()=>{!hs()||!Fs()||L()},Tt=()=>{if(!(!ao()||c||a.aborted)){if(C){L();return}C=!0,rr(),dt(),A=!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 Ne=()=>{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",Ne),rr(),dt(),ae?.abort(),ae=null,a.aborted||r.abort())};return a.aborted?Ne():a.addEventListener("abort",Ne,{once:!0}),de(),{dispose:Ne,reconnect:(b="manual")=>{c||a.aborted||(rr(),dt(),N(b))},get eventsUrl(){const b=oe??l??void 0;return ps(f,{...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...b?{streamEpoch:b}:{}})}}},xu=3e4,Ou=1,Nu=300,Lu=e=>new Promise(t=>setTimeout(t,e)),k=async(e,t)=>{const r=t.runtimeKey;if(r&&r!==D())throw new j("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?Ou:0;let i;for(let c=0;c<=s;c+=1){if(c>0){if(t.signal?.aborted)break;if(r&&r!==D())throw new j("DAEMON_UNAVAILABLE","Runtime changed during request");if(await Lu(Nu),t.signal?.aborted)break;if(r&&r!==D())throw new j("DAEMON_UNAVAILABLE","Runtime changed during request")}const d=new AbortController,l=setTimeout(()=>d.abort(),xu),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 h=(await m.json().catch(()=>null))?.error??{code:"DAEMON_REQUEST_FAILED"};if(m.status===503&&(h.code==="DAEMON_UNAVAILABLE"||h.code==="DAEMON_TIMEOUT")&&c<s&&!u?.aborted){i=new j(h.code,h.message,m.status);continue}throw new j(h.code,h.message,m.status)}if(m.status===204){if(r&&r!==D())throw new j("DAEMON_UNAVAILABLE","Runtime changed during request");return}const g=await m.json();if(r&&r!==D())throw new j("DAEMON_UNAVAILABLE","Runtime changed during request");return g}catch(m){if(i=m,m instanceof j||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 j 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 ir 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 Uu=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||!iu(o.pending))return!1}return!0},Xo=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)},Hu=e=>{if(!(e instanceof j))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")},Qo=e=>e instanceof ir?e:e instanceof j?new ir(e.code,e.message,{status:e.status,cause:e}):e instanceof DOMException&&e.name==="AbortError"?new ir("DAEMON_TIMEOUT",e.message||"Send timed out",{cause:e}):e instanceof Error?new ir("DAEMON_REQUEST_FAILED",e.message,{cause:e}):new ir("DAEMON_REQUEST_FAILED",void 0,{cause:e}),B=e=>{if(e?.runtimeKey&&e.runtimeKey!==D())throw new j("DAEMON_UNAVAILABLE","Runtime changed during request")},Wr=(e,t)=>{const r=Ze(e);if(!t||!r||t!==r)throw new j("STALE_STREAM_EPOCH","The Pi runtime restarted before this send could be verified.",409);return t},$i=5e3,ys=32,Ee=new Map,Vr=new Map,Ki=new Map,ju=(e,t)=>`${e}
|
|
6
6
|
${t?.trim()??""}`,so=e=>Ki.get(e)??0,Jr=e=>{Ki.set(e,so(e)+1);const t=`${e}
|
|
7
|
-
`;for(const r of[...Ee.keys()])r.startsWith(t)&&Ee.delete(r)},$u=(e,t,r)=>{if(Ee.size>=ys){const o=Date.now();for(const[n,a]of Ee)o-a.settledAt>=$i&&Ee.delete(n);for(;Ee.size>=ys;){const n=Ee.keys().next().value;if(typeof n!="string")break;Ee.delete(n)}}Ee.set(e,{response:t,settledAt:r})};class Ku{currentDirectory;setDirectory(t){this.currentDirectory=t}getDirectory(){return this.currentDirectory}async health(t){B(t);const r=await yo(void 0,t?.runtimeKey);return r.state==="ready"?{protocolVersion:r.protocolVersion,state:"ready",capabilities:r.capabilities,...r.streamEpoch?{streamEpoch:r.streamEpoch}:{}}:{protocolVersion:r.protocolVersion,state:"unavailable",capabilities:r.capabilities,...r.error?{error:r.error}:{}}}async listProjects(t){return B(t),k("/api/pi/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async selectProject(t,r){return B(r),k("/api/pi/projects/select",{method:"POST",body:{directory:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSessions(t){B(t);const r=t?.directory??this.currentDirectory;return k("/api/pi/sessions",{method:"GET",...r?{query:{directory:r}}:{},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listPendingInput(t){B(t);const r=await k("/api/pi/sessions/pending-input",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!Uu(r))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed pending-input list");return r}async createSession(t,r){return B(r),k("/api/pi/sessions",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSession(t,r){B(r);const o=r?.directory??this.currentDirectory;return k(`/api/pi/sessions/${encodeURIComponent(t)}`,{method:"GET",...o?{query:{directory:o}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSessionMessages(t,r,o){B(o);const n=o?.directory??this.currentDirectory;return k(`/api/pi/sessions/${encodeURIComponent(t)}/messages`,{method:"GET",query:{...n?{directory:n}:{},...r.before?{before:r.before}:{},...r.limit!==void 0?{limit:r.limit}:{}},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async renameSession(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"PATCH",body:{sessionId:t.sessionId,title:t.title},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async deleteSession(t,r){B(r);try{return await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"DELETE",...r?.directory?{query:{directory:r.directory}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}),!0}catch(o){if(o instanceof j&&o.status===404)return!0;throw o}}async archiveSession(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/archive`,{method:"POST",body:{sessionId:t.sessionId,archived:t.archived,...r?.directory?{directory:r.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSessionShelf(t){B(t);const r=await k("/api/pi/session-shelf",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!cu(r))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf");return r}async setSessionShelf(t,r){B(r);const{sessionId:o,...n}=t,s=(await k(`/api/pi/sessions/${encodeURIComponent(o)}/shelf`,{method:"POST",body:{...n,...r?.directory?{directory:r.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.entry;if(s!==null&&!Ni(s))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf entry");return s}async getSessionTree(t,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t)}/tree`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async navigateSession(t,r,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t)}/navigate`,{method:"POST",body:{messageId:r},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async forkSession(t,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/fork`,{method:"POST",body:{sessionId:t.sessionId,...t.messageId?{messageId:t.messageId}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async cloneSession(t,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/clone`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async sendPrompt(t,r){return this.sendWithReceipt("prompt",t,`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/prompt`,r)}async sendSteer(t,r){return this.sendWithReceipt("steer",t,`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/steer`,r)}async sendFollowUp(t,r){return this.sendWithReceipt("followUp",t,`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/follow-up`,r)}async getSendReceipt(t,r){const o=r?.runtimeKey??D();B({...r,runtimeKey:o});const n=Wr(o,t.streamEpoch??r?.streamEpoch??Ze(o)),a=r?.directory??this.currentDirectory,s=await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/send-receipt`,{method:"POST",body:{kind:t.kind,operationId:t.operationId,streamEpoch:n},...a?{query:{directory:a}}:{},runtimeKey:o});if(B({...r,runtimeKey:o}),Wr(o,n),!s||typeof s!="object")throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");const i=s.status;if(i==="accepted"){const c=s.receipt;if(!Xo(c))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");return{status:"accepted",receipt:c}}if(i==="pending"||i==="expired"||i==="unknown")return{status:i};throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt")}async sendWithReceipt(t,r,o,n){const a=n?.runtimeKey??D();let s;try{B({...n,runtimeKey:a}),s=Wr(a,n?.streamEpoch??Ze(a))}catch(c){throw Qo(c)}const i=n?.directory??this.currentDirectory;try{const c=await k(o,{method:"POST",body:{...r,streamEpoch:s},...i?{query:{directory:i}}:{},runtimeKey:a,retry:!1});if(!Xo(c))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send response");return B({...n,runtimeKey:a}),Wr(a,s),c}catch(c){if(c instanceof j&&c.code==="STALE_STREAM_EPOCH")throw Qo(c);if(Hu(c))throw c;const d=r.operationId;if(typeof d=="string"&&d.length>0)try{B({...n,runtimeKey:a});const l=this.getSendReceipt;if(!l)throw new j("DAEMON_UNAVAILABLE","Send receipt lookup unavailable");const u=await l.call(this,{sessionId:r.sessionId,kind:t,operationId:d,streamEpoch:s},{...n,runtimeKey:a,streamEpoch:s});if(B({...n,runtimeKey:a}),typeof u=="object"&&u!==null&&u.status==="accepted"&&Xo(u.receipt))return u.receipt}catch{}throw Qo(c)}}async abortSession(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setSessionModel(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/model`,{method:"POST",body:{sessionId:t.sessionId,model:t.model},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setSessionThinking(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/thinking`,{method:"POST",body:{sessionId:t.sessionId,thinking:t.thinking},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async compactSession(t,r){if(B(r),(await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).accepted!==!0)throw new j("DAEMON_PROTOCOL_MISMATCH")}async runBash(t,r){B(r);const o=await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash`,{method:"POST",body:{command:t.command,...t.excludeFromContext?{excludeFromContext:!0}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});if(o?.accepted!==!0||typeof o.id!="string")throw new j("DAEMON_PROTOCOL_MISMATCH");return{id:o.id}}async abortBash(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listProviders(t){return B(t),k("/api/pi/providers",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listEngines(t){return B(t),k("/api/pi/engines",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async refreshProviders(t){return B(t),k("/api/pi/providers/refresh",{method:"POST",...t?.directory?{body:{directory:t.directory}}:{body:void 0},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getProviderStatus(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t)}/status`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async loginProvider(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/login`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderLogin(t,r,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async respondProviderLogin(t,r,o,n){return B(n),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}/respond`,{method:"POST",body:{value:o},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async logoutProvider(t,r){B(r),await k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/logout`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderConfig(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t)}/config`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setProviderModels(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async addProviderModel(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"POST",body:t.model,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSettings(t){return B(t),k("/api/pi/settings",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async setPiSettings(t,r){return B(r),k("/api/pi/settings/pi",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPiChamberDefaults(t,r){return B(r),k("/api/pi/settings/defaults",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listResources(t,r){const o=typeof t=="string"?r:t,n=typeof t=="string"?t:void 0;B(o);const a=o?.runtimeKey??D(),s=ju(a,n),i=so(a);if(o?.reload!==!0){const m=Ee.get(s);if(m&&Date.now()-m.settledAt<$i)return structuredClone(m.response)}const c=Vr.get(s);if(c&&c.revision===i)return structuredClone(await c.promise);const d=Date.now(),l=so(a),u={},f=(async()=>{try{const m=await k("/api/pi/resources",{method:"GET",...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});if(D()===a&&so(a)===l){const g=Ee.get(s);(!g||g.settledAt<=d)&&$u(s,m,Date.now())}return m}finally{Vr.get(s)?.promise===u.promise&&Vr.delete(s)}})();return u.promise=f,Vr.set(s,{revision:l,promise:f}),structuredClone(await f)}async listCommands(t,r){return B(r),k("/api/pi/commands",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSnippets(t,r){return B(r),k("/api/pi/snippets",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async createSnippet(t,r){return B(r),k("/api/pi/snippets",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateSnippet(t,r,o,n){return B(n),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"PUT",body:r,...o?{query:{directory:o}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deleteSnippet(t,r,o){return B(o),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"DELETE",...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateResource(t,r){B(r);const o=r?.runtimeKey??D(),n=t.directory??r?.directory,a=await k(`/api/pi/resources/${encodeURIComponent(t.resourceId)}`,{method:"PUT",body:t,...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});return Jr(o),a}async createPromptTemplate(t,r,o){const n=r??t.directory??o?.directory;B(o);const a=o?.runtimeKey??D(),s=await k("/api/pi/resources/prompts",{method:"POST",body:t,...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Jr(a),s}async updatePromptTemplate(t,r,o,n){B(n);const a=n?.runtimeKey??D(),s=o??r.directory??n?.directory,i=await k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"PUT",body:r,...s?{query:{directory:s}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}});return Jr(a),i}async deletePromptTemplate(t,r,o){B(o);const n=o?.runtimeKey??D(),a=r??o?.directory,s=await k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"DELETE",...a?{query:{directory:a}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Jr(n),s}async createAttachment(t,r){return B(r),(await k("/api/pi/attachments",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).attachment}async uploadAttachment(t,r,o){B(o);const n=await au("/api/pi/attachments",t,r);if(!n.ok){const i=(await n.json().catch(()=>null))?.error??{code:"ATTACHMENT_FAILED"};throw new j(i.code,i.message,n.status)}const a=await n.json();return B(o),a.attachment}async deleteAttachment(t,r){B(r),await k(`/api/pi/attachments/${encodeURIComponent(t)}`,{method:"DELETE",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listExtensions(t,r){return B(r),k("/api/pi/extensions",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async respondToExtensionDialog(t,r){B(r),await k("/api/pi/extensions/respond",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async sendExtensionSurface(t,r,o){B(o);const{sessionId:n,...a}=r;await k(`/api/pi/sessions/${encodeURIComponent(n)}/extensions/custom/${t}`,{method:"POST",body:a,...t==="input"?{retry:!1}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateExtensionDraft(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/editor-draft`,{method:"POST",body:{text:t.text,revision:t.revision,...t.directory?{directory:t.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}}const yt=new Ku;async function zu(e){return(await Gu(e)).home}let wn=null,gr=null;const Fb=()=>{wn=null,gr=null},qu=async()=>{let e=null,t=null;try{const r=await F("/api/fs/home",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(r.ok){const o=await r.json().catch(()=>null);typeof o?.home=="string"&&o.home.trim().length>0&&(e=o.home.trim()),typeof o?.pichamberDataDir=="string"&&o.pichamberDataDir.trim().length>0&&(t=o.pichamberDataDir.trim())}}catch{}return{home:e,pichamberDataDir:t}},Gu=async e=>{const t=D();if(!e?.fresh){const o=wn;if(o&&o.key===t)return o.state;const n=gr;if(n&&n.key===t)return n.promise}const r=(async()=>{const o=await qu();return!e?.fresh&&o.home&&D()===t&&(wn={key:t,state:o}),o})();e?.fresh||(gr={key:t,promise:r});try{return await r}finally{gr?.promise===r&&(gr=null)}};async function yb(e,t){if(!e||e.trim().length===0)return[];const r={path:e},o=Ie().api("/api/fs/list",r),n=await F(o);if(!n.ok)return[];const a=await n.json();return Array.isArray(a.entries)?a.entries:[]}async function Wu(e,t){const r=t?.directory||"";if(!r)return[];const o={directory:r,query:e};t?.limit&&(o.limit=t.limit),t?.includeHidden&&(o.includeHidden=!0),t?.respectGitignore!==void 0&&(o.respectGitignore=t.respectGitignore),t?.type&&(o.type=t.type);const n=Ie().api("/api/fs/find",o),a=await F(n);if(!a.ok)return[];const s=await a.json();return Array.isArray(s.files)?s.files:[]}async function bb(e=""){try{const t=await F("/api/fs/pick-directory",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({path:e||void 0})}),r=await t.json().catch(()=>null);return r?.cancelled===!0?{status:"cancelled"}:t.status===501?{status:"unavailable",error:typeof r?.error=="string"?r.error:"Folder picker is not available."}:t.ok?typeof r?.path=="string"&&r.path.trim()?{status:"picked",path:r.path.trim()}:{status:"failed",error:"Failed to select directory."}:{status:"failed",error:typeof r?.error=="string"?r.error:"Failed to select directory."}}catch(t){return{status:"failed",error:t instanceof Error?t.message:"Failed to select directory."}}}const Ab={explore:{label:"Explore the codebase",icon:"compass-3",text:"Explore this codebase and explain how it works. Start with an overview, then key files and data flow."},plan:{label:"Plan the work",icon:"list-check-2",text:"Plan this work before coding. Break it into small steps, list files to change, and call out risks."},review:{label:"Review my changes",icon:"file-search",text:"Review my current changes for bugs, edge cases, and regressions. Suggest specific fixes."},"find-bugs":{label:"Find bugs",icon:"bug",text:"Find bugs in the current selection. List each issue with what is wrong and a minimal fix."},"write-tests":{label:"Write tests",icon:"flask",text:"Write tests for the current selection. Cover the happy path, edge cases, and failure modes."}},Vu=e=>typeof e=="string"&&(e==="explore"||e==="plan"||e==="review"||e==="find-bugs"||e==="write-tests"),Eb=[{type:"text",key:"explore"},{type:"text",key:"plan"},{type:"text",key:"review"},{type:"text",key:"find-bugs"},{type:"text",key:"write-tests"}],wb="book-open",Ju=/^[^\s/]+$/,bs=e=>e.type==="prompt"?`prompt:${e.name}`:`text:${e.key}`,Bb=(e,t)=>e.type!==t.type?!1:e.type==="prompt"&&t.type==="prompt"?e.name===t.name:e.type==="text"&&t.type==="text"?e.key===t.key:!1,Cb=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},wa=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const n=o;if(n.type==="text"){if(!Vu(n.key))continue;const d={type:"text",key:n.key},l=bs(d);if(r.has(l))continue;r.add(l),t.push(d);continue}if(n.type!=="prompt")continue;const a=typeof n.name=="string"?n.name.trim():"";if(!a||!Ju.test(a))continue;const s=n.scope==="global"||n.scope==="project"?n.scope:void 0,i=s?{type:"prompt",name:a,scope:s}:{type:"prompt",name:a},c=bs(i);r.has(c)||(r.add(c),t.push(i))}return t},Yu=e=>{let t,r=-1;for(const o of e){const a=(o.location==="project"?2:o.location==="global"?1:0)+(o.editable?.5:0);a>r&&(t=o,r=a)}return t},vb=e=>{const t=new Map;for(const o of e){const n=t.get(o.name)??[];n.push(o),t.set(o.name,n)}const r=new Map;for(const[o,n]of t){const a=Yu(n);a&&r.set(o,a)}return r},kb=(e,t)=>{const r=new Set,o=s=>s.filter(i=>{const c=i.insertText.trim();return r.has(c)?!1:(r.add(c),!0)}),n=o(e),a=o(t);return{project:n,global:a}},Xu={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.8125rem",micro:"0.75rem",settingsPageTitle:"1.125rem"};function As(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Yr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Zo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Yr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Yr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Yr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Yr.tool.inline})},Qu=[{id:"inter",label:"Inter",description:"Modern UI sans with excellent readability at small sizes.",stack:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Inter",packageName:"@fontsource/inter",filePrefix:"inter",weights:[400,500,600]}},{id:"geist-sans",label:"Geist Sans",description:"Crisp sans-serif with a technical interface feel.",stack:'"Geist Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Geist Sans",packageName:"@fontsource/geist-sans",filePrefix:"geist-sans",weights:[400,500,600]}},{id:"atkinson-hyperlegible",label:"Atkinson Hyperlegible",description:"Accessibility-focused sans-serif optimized for character distinction.",stack:'"Atkinson Hyperlegible", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Atkinson Hyperlegible",packageName:"@fontsource/atkinson-hyperlegible",filePrefix:"atkinson-hyperlegible",weights:[400,700]}},{id:"source-sans-3",label:"Source Sans 3",description:"Adobe sans-serif tuned for clean, readable interfaces.",stack:'"Source Sans 3", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Source Sans 3",packageName:"@fontsource/source-sans-3",filePrefix:"source-sans-3",weights:[400,500,600]}},{id:"roboto",label:"Roboto",description:"Familiar Material-style sans-serif with broad UI usage.",stack:'"Roboto", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Roboto",packageName:"@fontsource/roboto",filePrefix:"roboto",weights:[400,500,600]}},{id:"noto-sans",label:"Noto Sans",description:"Readable sans-serif with strong international coverage.",stack:'"Noto Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Noto Sans",packageName:"@fontsource/noto-sans",filePrefix:"noto-sans",weights:[400,500,600]}},{id:"dm-sans",label:"DM Sans",description:"Modern product UI sans-serif with friendly proportions.",stack:'"DM Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"DM Sans",packageName:"@fontsource/dm-sans",filePrefix:"dm-sans",weights:[400,500,600]}},{id:"manrope",label:"Manrope",description:"Polished geometric sans-serif for modern app interfaces.",stack:'"Manrope", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Manrope",packageName:"@fontsource/manrope",filePrefix:"manrope",weights:[400,500,600]}},{id:"system",label:"System",description:"Native operating system interface font.",stack:'"SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'}],Zu=[{id:"jetbrains-mono",label:"JetBrains Mono",description:"Developer-focused monospace with strong punctuation clarity.",stack:'"JetBrains Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"JetBrains Mono",packageName:"@fontsource/jetbrains-mono",filePrefix:"jetbrains-mono",weights:[400,500,600]}},{id:"fira-code",label:"Fira Code",description:"Readable coding font with ligature support.",stack:'"Fira Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Fira Code",packageName:"@fontsource/fira-code",filePrefix:"fira-code",weights:[400,500,600]}},{id:"geist-mono",label:"Geist Mono",description:"Sharp monospace pair for Geist Sans.",stack:'"Geist Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Geist Mono",packageName:"@fontsource/geist-mono",filePrefix:"geist-mono",weights:[400,500,600]}},{id:"commit-mono",label:"Commit Mono",description:"Code-oriented monospace with polished editor ergonomics.",stack:'"Commit Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Commit Mono",packageName:"@fontsource/commit-mono",filePrefix:"commit-mono",weights:[400,500,600]}},{id:"source-code-pro",label:"Source Code Pro",description:"Adobe monospace designed for source code readability.",stack:'"Source Code Pro", "SFMono-Regular", "Menlo", monospace',source:{family:"Source Code Pro",packageName:"@fontsource/source-code-pro",filePrefix:"source-code-pro",weights:[400,500,600]}},{id:"cascadia-code",label:"Cascadia Code",description:"Microsoft coding font popular in terminals and editors.",stack:'"Cascadia Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Cascadia Code",packageName:"@fontsource/cascadia-code",filePrefix:"cascadia-code",weights:[400,500,600]}},{id:"roboto-mono",label:"Roboto Mono",description:"Neutral monospace companion to Roboto.",stack:'"Roboto Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Roboto Mono",packageName:"@fontsource/roboto-mono",filePrefix:"roboto-mono",weights:[400,500,600]}},{id:"iosevka",label:"Iosevka",description:"Compact monospace for dense code and terminal layouts.",stack:'"Iosevka", "SFMono-Regular", "Menlo", monospace',source:{family:"Iosevka",packageName:"@fontsource/iosevka",filePrefix:"iosevka",weights:[400,500,600]}},{id:"system-mono",label:"System Mono",description:"Native operating system monospace font.",stack:'ui-monospace, "SFMono-Regular", "Menlo", "Cascadia Mono", "Segoe UI Mono", monospace'}],zi=e=>Object.fromEntries(e.map(t=>[t.id,t])),ef=zi(Qu),tf=zi(Zu),rf="system",of="system-mono",qi=e=>typeof e=="string"&&e in ef,Gi=e=>typeof e=="string"&&e in tf,en="pichamber.pwaName",Bn="pichamber.mobileKeyboardMode",Db="pichamber.pwaRecentSessions",nf=["native","resize-content"];function af(e,t="resize-content"){return typeof e=="string"&&nf.includes(e)?e:t}const sf=64;function Wi(e,t){if(typeof e!="string")return t;const r=e.trim().replace(/\s+/g," ");return r?r.slice(0,sf):t}const Sb=()=>!0;function Ba(e,t="resize-content"){return af(e,t)??void 0}const cf=()=>{if(typeof window>"u")return"resize-content";try{return Ba(localStorage.getItem(Bn))}catch{return"resize-content"}},df=e=>{const t=Ba(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Bn):localStorage.setItem(Bn,t)}catch{}return t},K=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),r=t.startsWith("//");let o=t.replace(/\/+$/g,"").replace(/\/+/g,"/");return r&&!o.startsWith("//")&&(o=`/${o}`),o||(t.startsWith("/")?"/":"")},lf=["workspace","folder","timeline","threads"],uf="workspace",Vi=e=>typeof e=="string"&&lf.includes(e),ff=365,Wt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=ff,Mb=e=>e===1?"1 session":`${e} sessions`,Se=20,mf=8,Es=4096,gf=2160*60*6e4,$=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),r=t.startsWith("//");let o=t.replace(/\/+/g,"/");r&&!o.startsWith("//")&&(o=`/${o}`);const n=o==="/",a=/^[A-Za-z]:\/$/.test(o);return!n&&!a&&(o=o.replace(/\/+$/,"")),o},Xe=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,et=(e,t)=>{const r=$(t),o=$(e);if(!r||!o)return!1;const n=Xe(r),a=Xe(o);return a===n||a.startsWith(`${n}/`)},cr=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=$(o);if(!a||!n||typeof n!="object")continue;const s=n,i=Array.isArray(s.openPaths)?Array.from(new Set(s.openPaths.filter(m=>typeof m=="string").map(m=>$(m)).filter(m=>m.length<=Es&&et(m,a)))).slice(-50):[],c=Array.isArray(s.expandedPaths)?Array.from(new Set(s.expandedPaths.filter(m=>typeof m=="string").map(m=>$(m)).filter(m=>m.length<=Es&&et(m,a)))).slice(-500):[],d=typeof s.selectedPath=="string"?$(s.selectedPath):null,l=d&&et(d,a)?d:i[0]??null,u=typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now();if(Date.now()-u>gf)continue;const f=r[a];if(f){const m=Array.from(new Set([...f.openPaths,...i])),g=Array.from(new Set([...f.expandedPaths,...c])),p=f.selectedPath??l??m[0]??null;r[a]={openPaths:m,selectedPath:p,expandedPaths:g,touchedAt:Math.max(f.touchedAt,u)};continue}r[a]={openPaths:i,selectedPath:l,expandedPaths:c,touchedAt:u}}return Me(r,Se)},Me=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;r.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const o={};for(const[n,a]of r.slice(0,t))o[n]=a;return o},Rt=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},pf=Mr()(Tr(Qn((e,t)=>({byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{},resetForRuntimeSwitch:r=>{e(o=>{const n={...o.runtimeSnapshots,[o.activeRuntimeKey]:{byRoot:cr(o.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:r,runtimeSnapshots:n,byRoot:cr(n[r]?.byRoot)}})},addOpenPath:(r,o,n)=>{const a=$((r||"").trim()),s=$((o||"").trim());!a||!s||!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=Rt(c),l=d.openPaths.includes(s),u=l?d.openPaths:[...d.openPaths,s],f=d.selectedPath??s;if(c&&l&&c.selectedPath===f)return i;const m={...i.byRoot,[a]:{...d,openPaths:u,selectedPath:f}};return{byRoot:Me(m,Se)}})},removeOpenPath:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||e(s=>{const i=s.byRoot[n];if(!i)return s;const c=Xe(a),d=g=>Xe(g)===c,l=i.selectedPath?d(i.selectedPath):!1;if(!i.openPaths.some(d)&&!l)return s;const u=i.openPaths.filter(g=>!d(g)),f=l?u[0]??null:i.selectedPath,m={...s.byRoot,[n]:{...i,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Me(m,Se)}})},removeOpenPathsByPrefix:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||e(s=>{const i=s.byRoot[n];if(!i)return s;const c=Xe(a),d=c.endsWith("/")?c:`${c}/`,l=g=>{const p=Xe(g);return p===c||p.startsWith(d)},u=i.openPaths.filter(g=>!l(g));if(u.length===i.openPaths.length)return s;const f=i.selectedPath&&l(i.selectedPath)?u[0]??null:i.selectedPath,m={...s.byRoot,[n]:{...i,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Me(m,Se)}})},removeExpandedPathsByPrefix:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||e(s=>{const i=s.byRoot[n];if(!i)return s;const c=Xe(a),d=c.endsWith("/")?c:`${c}/`,l=i.expandedPaths.filter(f=>{const m=Xe(f);return m!==c&&!m.startsWith(d)});if(l.length===i.expandedPaths.length)return s;const u={...s.byRoot,[n]:{...i,expandedPaths:l,touchedAt:Date.now()}};return{byRoot:Me(u,Se)}})},setSelectedPath:(r,o,n)=>{const a=$((r||"").trim()),s=o?$(o.trim()):null;!a||s&&!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=Rt(c),l=s&&!d.openPaths.includes(s)?[...d.openPaths,s]:d.openPaths;if(c&&c.selectedPath===s&&l===c.openPaths)return i;const u={...i.byRoot,[a]:{...d,openPaths:l,selectedPath:s}};return{byRoot:Me(u,Se)}})},ensureSelectedPath:r=>{const o=$((r||"").trim());if(!o)return;const n=t().byRoot[o];if(!n||n.selectedPath)return;const a=n.openPaths[0]??null;a&&t().setSelectedPath(o,a)},toggleExpandedPath:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=Rt(i),l=c.expandedPaths.includes(a)?c.expandedPaths.filter(f=>f!==a):[...c.expandedPaths,a];if(i&&i.expandedPaths===l&&i.selectedPath===c.selectedPath&&i.openPaths===c.openPaths)return s;const u={...s.byRoot,[n]:{...c,expandedPaths:l}};return{byRoot:Me(u,Se)}})},collapseAllExpandedPaths:r=>{const o=$((r||"").trim());o&&e(n=>{const a=n.byRoot[o];if(!a||a.expandedPaths.length===0)return n;const s={...n.byRoot,[o]:{...Rt(a),expandedPaths:[]}};return{byRoot:Me(s,Se)}})},expandPath:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=Rt(i);if(c.expandedPaths.includes(a)&&i)return s;const l={...s.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,a]}};return{byRoot:Me(l,Se)}})},expandPaths:(r,o)=>{const n=$((r||"").trim());if(!n||!o||o.length===0)return;const a=o.map(s=>$((s||"").trim())).filter(s=>s&&et(s,n));a.length!==0&&e(s=>{const i=s.byRoot[n],c=Rt(i),d=new Set(c.expandedPaths),l=a.filter(f=>!d.has(f));if(l.length===0)return s;const u={...s.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,...l]}};return{byRoot:Me(u,Se)}})}}),{name:"files-view-tabs-store",version:3,storage:ca(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:cr(e.byRoot),updatedAt:Date.now()}},r=Object.fromEntries(Object.entries(t).sort(([,o],[,n])=>n.updatedAt-o.updatedAt).slice(0,mf).map(([o,n])=>[o,{byRoot:cr(n.byRoot),updatedAt:n.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:r}},merge:(e,t)=>{const r=e&&typeof e=="object"?e:{},o=r.runtimeSnapshots&&typeof r.runtimeSnapshots=="object"?r.runtimeSnapshots:{},n=D();return{...t,activeRuntimeKey:n,runtimeSnapshots:o,byRoot:cr(o[n]?.byRoot)}}}),{name:"files-view-tabs-store"})),Ca=12,hf=4096,Ff=200,yf=/^[A-Za-z0-9_.:-]{1,120}$/,Io=()=>`page-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36).slice(-4)}`,vr=e=>{if(typeof e!="string")return null;const t=e.trim();return!t||t==="about:blank"?null:t.slice(0,hf)},Ji=e=>{if(typeof e!="string")return null;const t=e.replace(/\s+/g," ").trim();return t?t.slice(0,Ff):null},kr=e=>e==="server"||e==="device"?e:null,Yi=(e,t)=>t&&e.some(r=>r.id===t)?t:e[0]?.id??null,bf=(e,t)=>{const r=e&&typeof e=="object"?e:null,o=[],n=new Set;if(r&&Array.isArray(r.pages))for(const s of r.pages){if(!s||typeof s!="object")continue;const i=s,c=typeof i.id=="string"?i.id:"";if(!(!yf.test(c)||n.has(c))&&(n.add(c),o.push({id:c,url:vr(i.url),route:kr(i.route),title:Ji(i.title)}),o.length>=Ca))break}o.length===0&&o.push({id:t.tabId,url:vr(t.url),route:t.route,title:null});const a=typeof r?.activePageId=="string"?r.activePageId:null;return{pages:o,activePageId:Yi(o,a)}},Af=(e,t=Io)=>{const r=t();return{pages:[{id:r,url:vr(e.url),route:kr(e.route),title:null}],activePageId:r}},Ef=(e,t,r=Io)=>{const o=vr(t.url),n=kr(t.route),a=e.pages.find(l=>l.id===e.activePageId)??null,s=a&&(t.target==="current"||o!==null&&a.url===null||e.pages.length>=Ca);if(a&&s)return{pages:e.pages.map(u=>u.id===a.id?{...u,url:o??u.url,route:n??u.route,title:o&&o!==u.url?null:u.title}:u),activePageId:a.id,pageId:a.id};const i={id:r(),url:o,route:n,title:null},c=a?e.pages.indexOf(a):e.pages.length-1;return{pages:[...e.pages.slice(0,c+1),i,...e.pages.slice(c+1)],activePageId:i.id,pageId:i.id}},wf=(e,t,r=Io)=>{if(e.pages.length>=Ca)return null;const o={id:r(),url:null,route:"server",title:null,popupId:t.popupId},n=e.pages.findIndex(i=>i.id===t.openerPageId),a=n===-1?e.pages.length-1:n;return{pages:[...e.pages.slice(0,a+1),o,...e.pages.slice(a+1)],activePageId:o.id,pageId:o.id}},Bf=(e,t,r=Io)=>{const o=e.pages.findIndex(s=>s.id===t);if(o===-1)return e;const n=e.pages.filter(s=>s.id!==t);if(n.length===0){const s={id:r(),url:null,route:e.pages[o].route,title:null};return{pages:[s],activePageId:s.id}}if(e.activePageId!==t)return{pages:n,activePageId:Yi(n,e.activePageId)};const a=n[Math.min(o,n.length-1)];return{pages:n,activePageId:a.id}},Cf=(e,t)=>e.activePageId!==t&&e.pages.some(r=>r.id===t)?{...e,activePageId:t}:e,vf=(e,t,r)=>{let o=!1;const n=e.pages.map(a=>{if(a.id!==t)return a;const s={...a};if(r.url!==void 0){const i=vr(r.url);i&&i!==a.url&&(s.url=i)}return r.title!==void 0&&(s.title=Ji(r.title)),r.route!==void 0&&(s.route=kr(r.route)??a.route),r.defaultRoute!==void 0&&s.route===null&&(s.route=kr(r.defaultRoute)),r.popupId===null&&delete s.popupId,(s.url!==a.url||s.title!==a.title||s.route!==a.route||s.popupId!==a.popupId)&&(o=!0),o?s:a});return o?{...e,pages:n}:e},Tb=e=>{if(e.title)return e.title;if(!e.url)return"New tab";try{return new URL(e.url).host||e.url}catch{return e.url}},kf=380,Df=380,Sf=1400,Xi=12,ws=120,Mf=["git","file","diff","context","terminal","browser","preview","pull-requests","issues","extensions"],Tf=K,io=e=>Number.isFinite(e)?Math.min(Sf,Math.max(Df,Math.round(e))):kf,Rf=e=>{if(typeof e.width=="number"&&Number.isFinite(e.width))return io(e.width);if(!e.widthByMode||typeof e.widthByMode!="object")return;const t=e.widthByMode;for(const r of Mf){const o=t[r];if(typeof o=="number"&&Number.isFinite(o))return io(o)}for(const r of Object.values(t))if(typeof r=="number"&&Number.isFinite(r))return io(r)},bo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Ao=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>ws?t.slice(0,ws):t:null},va=e=>e==="server"||e==="device"?e:null,ka=e=>e==="all"||e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,Pf=(e,t)=>(e==="file"||e==="preview")&&t||e,Qi=(e,t,r)=>{if(e==="diff")return e;if(e==="browser")return Da;if(typeof r=="string"){const o=r.trim();if(o)return o}return Pf(e,t)},Cn=(e,t)=>t===e?e:`${e}:${t}`,Da="desktop-browser",Zi=`browser:${Da}`,If=(e,t)=>{let r=!1;const o=e.tabs.map(n=>{if(n.id!==Zi||!n.browser)return n;const a=t(n.browser);return a===n.browser?n:(r=!0,{...n,browser:{pages:a.pages,activePageId:a.activePageId}})});return r?{...e,tabs:o}:e},Sa=e=>{const t=bo(e.targetPath),r=Qi(e.mode,t,e.dedupeKey),o=Cn(e.mode,r),n=e.mode==="browser";return{id:o,mode:e.mode,targetPath:n?null:t,dedupeKey:r,label:Ao(e.label),sessionTitleFallback:Ao(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:ka(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),browser:n?Af({url:t,route:va(e.browserRoute)}):null,touchedAt:Date.now()}},ec=(e,t,r)=>{if(e.length<=t)return e;const n=[...e].sort((i,c)=>i.touchedAt-c.touchedAt).filter(i=>i.id!==r),a=e.length-t;if(a<=0||n.length===0)return e.slice(-t);const s=new Set(n.slice(0,a).map(i=>i.id));return e.filter(i=>!s.has(i.id))},tc=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const n=o;if(n.mode!=="diff"&&n.mode!=="file"&&n.mode!=="context"&&n.mode!=="preview"&&n.mode!=="browser"&&n.mode!=="git"&&n.mode!=="terminal"&&n.mode!=="pull-requests"&&n.mode!=="issues"&&n.mode!=="extensions")continue;const a=bo(typeof n.targetPath=="string"?n.targetPath:null),s=Qi(n.mode,a,typeof n.dedupeKey=="string"?n.dedupeKey:null),i=Cn(n.mode,s);if(!i||r.has(i))continue;r.add(i);const c=n.mode==="browser",d=typeof n.dedupeKey=="string"&&n.dedupeKey.trim()?n.dedupeKey.trim():"browser";t.push({id:i,mode:n.mode,targetPath:c?null:a,dedupeKey:s,label:Ao(typeof n.label=="string"?n.label:null),sessionTitleFallback:Ao(typeof n.sessionTitleFallback=="string"?n.sessionTitleFallback:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,diffScope:ka(n.diffScope)??(n.stagedDiff===!0?"staged":"working"),browser:c?bf(n.browser,{tabId:Cn("browser",d),url:a,route:va(n.browserRoute)}):null,touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()})}return t},Vt=(e,t)=>t&&e.some(r=>r.id===t)?t:e.length===0?null:e[e.length-1].id,mt=e=>{if(e){const t=tc(e.tabs),r=Vt(t,e.activeTabId);return{...e,tabs:t,activeTabId:r,width:e.width,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,touchedAt:Date.now()}},_f=(e,t)=>{const r=Sa(t),o=r.mode==="file"&&r.targetPath?e.tabs.filter(c=>!(c.mode==="file"&&!c.targetPath)):e.tabs,n=o.findIndex(c=>c.id===r.id),a=n===-1?[...o,r]:o.map((c,d)=>d===n?{...c,mode:r.mode,targetPath:r.targetPath||c.targetPath,dedupeKey:r.dedupeKey,label:r.label,sessionTitleFallback:r.sessionTitleFallback||c.sessionTitleFallback,stagedDiff:r.stagedDiff,diffScope:r.diffScope,browser:c.browser??r.browser,readOnly:r.readOnly,touchedAt:Date.now()}:c),s=r.id,i=ec(a,Xi,s);return{...e,isOpen:!0,tabs:i,activeTabId:Vt(i,s),touchedAt:Date.now()}},xf=(e,t)=>{const r=e.tabs.find(s=>s.id===t)??null,o=e.tabs.filter(s=>s.id!==t);if(e.activeTabId!==t)return{...e,tabs:o,activeTabId:Vt(o,e.activeTabId),isOpen:o.length>0?e.isOpen:!1,touchedAt:Date.now()};const n=r?o.filter(s=>s.mode===r.mode):[],a=n.length>0?n.reduce((s,i)=>i.touchedAt>=s.touchedAt?i:s):null;return{...e,tabs:o,activeTabId:a?.id??Vt(o,null),isOpen:a?e.isOpen:!1,touchedAt:Date.now()}},Of=(e,t,r)=>{if(t===r)return e;const o=e.tabs.findIndex(i=>i.id===t),n=e.tabs.findIndex(i=>i.id===r);if(o===-1||n===-1)return e;const a=[...e.tabs],[s]=a.splice(o,1);return s?(a.splice(n,0,s),{...e,tabs:a,touchedAt:Date.now()}):e},Nf=(e,t,r)=>({...e,tabs:e.tabs.map(o=>o.id===t?{...o,targetPath:r}:o)}),Lf=e=>{const t=[];let r=!1;for(const o of e){if(o.mode!=="diff"&&o.mode!=="git"){t.push(o);continue}r||(r=!0,t.push(o.mode==="git"?o:Sa({mode:"git"})))}return t},Ve=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=K(o);if(!a||!n||typeof n!="object")continue;const s=n;let i=Lf(tc(s.tabs)),c=typeof s.activeTabId=="string"?s.activeTabId:null;i.length===0&&(s.mode==="diff"||s.mode==="file"||s.mode==="context")&&(i=[Sa({mode:s.mode,targetPath:typeof s.targetPath=="string"?s.targetPath:null,dedupeKey:typeof s.dedupeKey=="string"?s.dedupeKey:null,label:typeof s.label=="string"?s.label:null})],c=i[0]?.id??null);const d=Vt(i,c),l=ec(i,Xi,d),u=Rf(s);r[a]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:l,activeTabId:Vt(l,d),...u!==void 0?{width:u}:{},touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},gt=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;r.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const o={};for(const[n,a]of r.slice(0,t))o[n]=a;return o},Bs=50,Uf=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const r=t.split("/");if(r.length!==3)return null;const[o,n,a]=r.map(s=>s.trim());return!o||!n||!a||n.length>100||a.length>100||o.length>253?null:`${o}/${n}/${a}`},Hf=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=K(o),s=Uf(n);!a||!s||(r[a]=s)}return r},Cs=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;const o={};for(const[n,a]of r.slice(-t))o[n]=a;return o};function vs(e){return e==="vim"?"vim":"default"}const dr=280,tn=new Map,rn=e=>(e??D()).trim()||"default",lr=(e,t,r,o)=>{const n=t(),a=n.contextPanelByDirectory[r];if(!a)return;const s=If(a,o);s!==a&&e({contextPanelByDirectory:{...n.contextPanelByDirectory,[r]:s}})},ie=Mr()(Tr(Qn((e,t)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:dr,hasManuallyResizedLeftSidebar:!1,contextPanelByDirectory:{},browserRoutePreference:null,chatLinkTarget:"system",contextRailOrder:[],contextEditorTreeVisible:!0,fileTreeReveal:null,gitReturnToFile:null,contextEditorTreeWidth:240,githubSelectedRepoByDirectory:{},isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingDiagramFile:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isSessionCreateDialogOpen:!1,isArchivePageOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showDeletionDialog:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:rf,monoFont:of,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:cf(),favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLinesOverride:null,wrapLinesByDefault:!0,walkthroughTocWidth:224,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnInputNeeded:!0,summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,timeFormatPreference:"auto",weekStartPreference:"auto",sidebarViewMode:uf,sessionAutoArchiveAfterDays:0,sessionAutoDeleteAfterDays:0,expandedEditorToolbar:!1,draftStartersVisible:!0,isExpandedInput:!1,shortcutOverrides:{},commandTriggers:[],fileEditorKeymap:"default",setTheme:r=>{e({theme:r}),t().applyTheme()},toggleSidebar:()=>{e(r=>{const o=!r.isSidebarOpen;return o&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:o,sidebarWidth:dr}:{isSidebarOpen:o}})},setSidebarOpen:r=>{e(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==dr?{isSidebarOpen:r,sidebarWidth:dr}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:dr}:{isSidebarOpen:r})},setSidebarWidth:r=>{e({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},setContextRailOrder:r=>{const o=Array.isArray(r)?r.filter((n,a)=>typeof n=="string"&&n.trim()!==""&&r.indexOf(n)===a):[];e({contextRailOrder:o})},toggleContextEditorTree:()=>{e(r=>({contextEditorTreeVisible:!r.contextEditorTreeVisible}))},revealInFileTree:r=>{e(o=>({fileTreeReveal:{path:r,nonce:(o.fileTreeReveal?.nonce??0)+1}}))},clearGitReturnToFile:()=>{t().gitReturnToFile&&e({gitReturnToFile:null})},showAllGitChanges:()=>{const r=t().gitReturnToFile;r?.focusPath&&e({gitReturnToFile:{...r,focusPath:null}})},clearFileTreeReveal:()=>{e({fileTreeReveal:null})},setContextEditorTreeWidth:r=>{Number.isFinite(r)&&e({contextEditorTreeWidth:Math.min(480,Math.max(200,Math.round(r)))})},setGitHubSelectedRepo:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{if(o==null){if(!(n in a.githubSelectedRepoByDirectory))return a;const i={...a.githubSelectedRepoByDirectory};return delete i[n],{githubSelectedRepoByDirectory:i}}const s=o.trim();return!s||a.githubSelectedRepoByDirectory[n]===s?a:{githubSelectedRepoByDirectory:Cs({...a.githubSelectedRepoByDirectory,[n]:s},Bs)}})},openContextSurface:(r,o)=>{const n=o==="diff"?"git":o,a=K((r||"").trim());if(!a)return;const s=t(),i=s.contextPanelByDirectory[a],c=i?.tabs??[],d=c.find(u=>u.id===i?.activeTabId)??null;if(i?.isOpen&&d?.mode===n){s.closeContextPanel(a);return}const l=c.filter(u=>u.mode===n);if(l.length>0){const u=l.reduce((f,m)=>m.touchedAt>=f.touchedAt?m:f);s.setActiveContextPanelTab(a,u.id);return}n!=="preview"&&s.openContextPanelTab(a,{mode:n})},openContextPanelTab:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{const s=a.contextPanelByDirectory[n],i=mt(s),c={...a.contextPanelByDirectory,[n]:_f(i,o)};return{contextPanelByDirectory:gt(c,20)}})},openContextDiff:(r,o,n=!1,a=null)=>{const s=K((r||"").trim()),i=(o||"").trim();if(!s||!i)return;const c=ka(a)??(n?"staged":"working"),d=t().contextPanelByDirectory[s],l=d?.isOpen?d.tabs.find(u=>u.id===d.activeTabId):void 0;t().setPendingDiffFile(i,n,c),t().openContextPanelTab(s,{mode:"git"}),e({gitReturnToFile:l?.mode==="file"?{directory:s,tabId:l.id,focusPath:i}:null})},openContextFile:(r,o)=>{const n=K((r||"").trim()),a=bo(o);!n||!a||(t().openContextPanelTab(n,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(a),t().setPendingFileNavigation(null))},openContextFileAtLine:(r,o,n,a)=>{const s=K((r||"").trim()),i=bo(o),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,d=Number.isFinite(a)?Math.max(1,Math.trunc(a)):1;!s||!i||(t().openContextPanelTab(s,{mode:"file",targetPath:i}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:i,line:c,column:d}))},openContextOverview:r=>{const o=K((r||"").trim());o&&t().openContextPanelTab(o,{mode:"context"})},openContextPreview:(r,o)=>{const n=K((r||"").trim()),a=(o||"").trim();if(!n||!a)return;let s=null;try{const i=new URL(a);(i.protocol==="http:"||i.protocol==="https:")&&(s=i.host||i.hostname||"Preview")}catch{}t().openContextPanelTab(n,{mode:"preview",targetPath:a,dedupeKey:a,label:s})},openContextBrowser:(r,o="",n)=>{const a=K((r||"").trim());if(!a)return;const s=typeof o=="string"&&o.trim().length>0?o.trim():"",i=!!t().contextPanelByDirectory[a]?.tabs.some(d=>d.id===Zi);if(t().openContextPanelTab(a,{mode:"browser",targetPath:i?null:s,dedupeKey:Da,label:"Browser",browserRoute:i?null:n?.route??null}),!i)return;const c=n?.target??(s?"new":null);c&&lr(e,t,a,d=>Ef(d,{url:s||null,route:n?.route??null,target:c}))},openBrowserPopup:(r,o,n)=>{const a=K((r||"").trim());if(!a)return!1;let s=!1;return lr(e,t,a,i=>{const c=wf(i,{openerPageId:o,popupId:n});return s=c!==null,c??i}),s},closeBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&lr(e,t,n,a=>Bf(a,o))},activateBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&lr(e,t,n,a=>Cf(a,o))},updateBrowserPage:(r,o,n)=>{const a=K((r||"").trim());a&&lr(e,t,a,s=>vf(s,o,n))},setBrowserRoutePreference:r=>{e({browserRoutePreference:va(r)})},setChatLinkTarget:r=>{e({chatLinkTarget:r==="pichamber"?"pichamber":"system"})},setContextPanelTabTargetPath:(r,o,n)=>{const a=K((r||"").trim()),s=(o||"").trim();!a||!s||e(i=>{const c=i.contextPanelByDirectory[a];return c?{contextPanelByDirectory:{...i.contextPanelByDirectory,[a]:Nf(c,s,n)}}:i})},setActiveContextPanelTab:(r,o)=>{const n=K((r||"").trim()),a=(o||"").trim();!n||!a||e(s=>{const i=s.contextPanelByDirectory[n],c=mt(i);if(!c.tabs.some(l=>l.id===a)||c.activeTabId===a&&c.isOpen)return s;const d={...s.contextPanelByDirectory,[n]:{...c,isOpen:!0,activeTabId:a,touchedAt:Date.now(),tabs:c.tabs.map(l=>l.id===a?{...l,touchedAt:Date.now()}:l)}};return{contextPanelByDirectory:gt(d,20)}})},reorderContextPanelTabs:(r,o,n)=>{const a=K((r||"").trim()),s=(o||"").trim(),i=(n||"").trim();!a||!s||!i||e(c=>{const d=c.contextPanelByDirectory[a],l=mt(d);if(!l.tabs.some(m=>m.id===s)||!l.tabs.some(m=>m.id===i))return c;const u=Of(l,s,i);if(u.tabs===l.tabs)return c;const f={...c.contextPanelByDirectory,[a]:u};return{contextPanelByDirectory:gt(f,20)}})},closeContextPanelTab:(r,o)=>{const n=K((r||"").trim()),a=(o||"").trim();if(!n||!a)return;const s=t().contextPanelByDirectory[n]?.tabs.find(i=>i.id===a);e(i=>{const c=i.contextPanelByDirectory[n],d=mt(c);if(!d.tabs.some(u=>u.id===a))return i;const l={...i.contextPanelByDirectory,[n]:xf(d,a)};return{contextPanelByDirectory:gt(l,20)}}),s?.mode==="file"&&s.targetPath&&pf.getState().removeOpenPath(n,s.targetPath)},closeContextPanel:r=>{const o=K((r||"").trim());o&&e(n=>{const a=n.contextPanelByDirectory[o];if(!a||!a.isOpen)return n;const s={...n.contextPanelByDirectory,[o]:{...mt(a),isOpen:!1}};return{contextPanelByDirectory:gt(s,20)}})},toggleContextPanelExpanded:r=>{const o=K((r||"").trim());o&&e(n=>{const a=n.contextPanelByDirectory[o],s=mt(a),i={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:gt(i,20)}})},setContextPanelWidth:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{const s=a.contextPanelByDirectory[n],i=mt(s),c={...a.contextPanelByDirectory,[n]:{...i,width:io(o)}};return{contextPanelByDirectory:gt(c,20)}})},setSessionSwitcherOpen:r=>{t().isSessionSwitcherOpen!==r&&e({isSessionSwitcherOpen:r})},setSessionDropdownOpen:r=>{t().isSessionDropdownOpen!==r&&e({isSessionDropdownOpen:r})},setMainTabGuard:r=>{t().mainTabGuard!==r&&e({mainTabGuard:r})},setActiveMainTab:r=>{const o=t().mainTabGuard;o&&!o(r)||(tn.set(rn(),r),e({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{tn.set(rn(r),t().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=tn.get(rn(r))??"chat";e({activeMainTab:o})},setPendingDiffFile:(r,o=!1,n=null)=>{e({pendingDiffFile:r,pendingDiffStaged:r?o:!1,pendingDiffScope:r?n:null})},setPendingDiagramFile:r=>{e({pendingDiagramFile:r})},setPendingFileNavigation:r=>{e({pendingFileNavigation:r})},setPendingFileFocusPath:r=>{e({pendingFileFocusPath:r})},navigateToDiff:(r,o=!1,n=null)=>{const a=t().mainTabGuard;a&&!a("diff")||e({pendingDiffFile:r,pendingDiffStaged:o,pendingDiffScope:n,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:r}=t();return r&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),r},navigateToDiagram:r=>{const o=t().mainTabGuard;o&&!o("diagram")||e({pendingDiagramFile:r,activeMainTab:"diagram"})},consumePendingDiagramFile:()=>{const{pendingDiagramFile:r}=t();return r&&e({pendingDiagramFile:null}),r},setIsMobile:r=>{e({isMobile:r})},toggleCommandPalette:()=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen}))},setCommandPaletteOpen:r=>{e({isCommandPaletteOpen:r})},toggleHelpDialog:()=>{e(r=>({isHelpDialogOpen:!r.isHelpDialogOpen}))},setHelpDialogOpen:r=>{e({isHelpDialogOpen:r})},setSessionCreateDialogOpen:r=>{e({isSessionCreateDialogOpen:r})},setArchivePageOpen:r=>{e({isArchivePageOpen:r})},closeMainSurfaces:()=>{t().isArchivePageOpen&&e({isArchivePageOpen:!1})},setSettingsDialogOpen:r=>{e(o=>r?o.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setModelSelectorOpen:r=>{e({isModelSelectorOpen:r})},setSidebarSection:r=>{e({sidebarSection:r})},setSettingsPage:r=>{e({settingsPage:r})},setSettingsProjectsSelectedId:r=>{e({settingsProjectsSelectedId:r})},setSettingsRemoteInstancesSelectedId:r=>{e({settingsRemoteInstancesSelectedId:r})},setEventStreamStatus:(r,o)=>{e({eventStreamStatus:r,eventStreamHint:o??null})},setShowDeletionDialog:r=>{e({showDeletionDialog:r})},setAutoDeleteEnabled:r=>{e({autoDeleteEnabled:r})},setAutoSaveEnabled:r=>{e({autoSaveEnabled:r})},setAutoDeleteAfterDays:r=>{const o=Math.max(1,Math.min(365,r));e({autoDeleteAfterDays:o})},setSessionRetentionAction:r=>{e({sessionRetentionAction:r})},setAutoDeleteLastRunAt:r=>{e({autoDeleteLastRunAt:r})},setMessageLimit:r=>{const o=Math.max(10,Math.min(500,Math.round(r)));e({messageLimit:o})},setFontSize:r=>{const o=Math.max(50,Math.min(200,r));e({fontSize:o}),t().applyTypography()},setGlobalDraftStarters:r=>{e({globalDraftStarters:r})},setDraftStartersVisible:r=>{e({draftStartersVisible:r})},setTerminalFontSize:r=>{const o=Math.round(r),n=Math.max(9,Math.min(52,o));e({terminalFontSize:n})},setTerminalShell:r=>{e({terminalShell:r})},setTerminalLoginShells:r=>{e({terminalLoginShells:[...new Set(r)]})},setEditorFontSize:r=>{const o=Math.round(r),n=Math.max(9,Math.min(32,o));e({editorFontSize:n})},setUiFont:r=>{e({uiFont:r})},setMonoFont:r=>{e({monoFont:r})},setPadding:r=>{const o=Math.max(50,Math.min(200,r));e({padding:o}),t().applyPadding()},setCornerRadius:r=>{e({cornerRadius:r})},applyTypography:()=>{const{fontSize:r}=t(),o=document.documentElement,n=r/100,a=Object.entries(Xu);if(n===1){for(const[s]of a)o.style.removeProperty(As(s));return}for(const[s,i]of a){const c=parseFloat(i);Number.isFinite(c)&&o.style.setProperty(As(s),`${c*n}rem`)}},applyPadding:()=>{const{padding:r}=t(),o=document.documentElement,n=r/100;if(n===1){o.style.removeProperty("--padding-scale"),o.style.removeProperty("--line-height-tight"),o.style.removeProperty("--line-height-normal"),o.style.removeProperty("--line-height-relaxed"),o.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(n);o.style.setProperty("--padding-scale",a.toString());const s=1+(n-1)*.15;o.style.setProperty("--line-height-tight",(1.25*s).toFixed(3)),o.style.setProperty("--line-height-normal",(1.5*s).toFixed(3)),o.style.setProperty("--line-height-relaxed",(1.625*s).toFixed(3)),o.style.setProperty("--line-height-loose",(2*s).toFixed(3))},setDiffLayoutPreference:r=>{e({diffLayoutPreference:r})},setDiffFileLayout:(r,o)=>{e(n=>({diffFileLayout:{...n.diffFileLayout,[r]:o}}))},setDiffWrapLines:r=>{e({diffWrapLinesOverride:r})},setWrapLinesByDefault:r=>{e({wrapLinesByDefault:r,diffWrapLinesOverride:null})},setWalkthroughTocWidth:r=>{e({walkthroughTocWidth:Math.round(r)})},setGitChangesViewMode:r=>{e({gitChangesViewMode:r})},setInputBarOffset:r=>{e({inputBarOffset:r})},setMobileKeyboardMode:r=>{e(o=>o.mobileKeyboardMode===r?o:{mobileKeyboardMode:r})},toggleFavoriteModel:(r,o)=>{e(n=>n.favoriteModels.some(s=>s.providerID===r&&s.modelID===o)?{favoriteModels:n.favoriteModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{favoriteModels:[{providerID:r,modelID:o},...n.favoriteModels]})},reorderFavoriteModel:(r,o,n,a)=>{e(s=>{const i=s.favoriteModels.findIndex(u=>u.providerID===r&&u.modelID===o),c=s.favoriteModels.findIndex(u=>u.providerID===n&&u.modelID===a);if(i===-1||c===-1||i===c)return s;const d=s.favoriteModels.slice(),[l]=d.splice(i,1);return l?(d.splice(c,0,l),{favoriteModels:d}):s})},toggleHiddenModel:(r,o)=>{e(n=>n.hiddenModels.some(s=>s.providerID===r&&s.modelID===o)?{hiddenModels:n.hiddenModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{hiddenModels:[{providerID:r,modelID:o},...n.hiddenModels]})},isHiddenModel:(r,o)=>{const{hiddenModels:n}=t();return n.some(a=>a.providerID===r&&a.modelID===o)},hideAllModels:(r,o)=>{e(n=>{const a=n.hiddenModels.filter(i=>i.providerID!==r);return{hiddenModels:[...[...new Set(o.filter(i=>typeof i=="string"&&i.length>0))].map(i=>({providerID:r,modelID:i})),...a]}})},showAllModels:r=>{e(o=>({hiddenModels:o.hiddenModels.filter(n=>n.providerID!==r)}))},toggleModelProviderCollapsed:r=>{const o=typeof r=="string"?r.trim():"";o&&e(n=>n.collapsedModelProviders.includes(o)?{collapsedModelProviders:n.collapsedModelProviders.filter(s=>s!==o)}:{collapsedModelProviders:[...n.collapsedModelProviders,o]})},setModelProvidersCollapsed:(r,o)=>{const n=Array.from(new Set(r.filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean)));n.length!==0&&e(a=>{const s=new Set(n),i=a.collapsedModelProviders.filter(c=>!s.has(c));return{collapsedModelProviders:o?[...i,...n]:i}})},isFavoriteModel:(r,o)=>{const{favoriteModels:n}=t();return n.some(a=>a.providerID===r&&a.modelID===o)},addRecentModel:(r,o)=>{e(n=>{const a=n.recentModels.filter(s=>!(s.providerID===r&&s.modelID===o));return{recentModels:[{providerID:r,modelID:o},...a].slice(0,5)}})},addRecentAgent:r=>{const o=typeof r=="string"?r.trim():"";o&&e(n=>{if(n.recentAgents.includes(o))return n;const a=n.recentAgents;return{recentAgents:[o,...a].slice(0,5)}})},addRecentEffort:(r,o,n)=>{const a=typeof r=="string"?r.trim():"",s=typeof o=="string"?o.trim():"";if(!a||!s)return;const i=`${a}/${s}`,c=typeof n=="string"&&n.trim().length>0?n.trim():"default";e(d=>{const l=d.recentEfforts[i]??[];if(l.includes(c))return d;const u=l;return{recentEfforts:{...d.recentEfforts,[i]:[c,...u].slice(0,5)}}})},applyTheme:()=>{const{theme:r}=t(),o=document.documentElement;if(o.classList.remove("light","dark"),r==="system"){const n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(n)}else o.classList.add(r)},setTimelineDialogOpen:r=>{e({isTimelineDialogOpen:r})},setPromptNavigatorPanelOpen:r=>{e({isPromptNavigatorPanelOpen:r})},togglePromptNavigatorPanel:()=>{e(r=>({isPromptNavigatorPanelOpen:!r.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:r=>{e({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{e({nativeNotificationsEnabled:r})},setNotificationMode:r=>{e({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{e({showTerminalQuickKeysOnDesktop:r})},setDockBadgeEnabled:r=>{e({dockBadgeEnabled:r})},setNotifyOnCompletion:r=>{e({notifyOnCompletion:r})},setNotifyOnError:r=>{e({notifyOnError:r})},setNotifyOnInputNeeded:r=>{e({notifyOnInputNeeded:r})},setSummarizeLastMessage:r=>{e({summarizeLastMessage:r})},setSummaryThreshold:r=>{e({summaryThreshold:r})},setSummaryLength:r=>{e({summaryLength:r})},setMaxLastMessageLength:r=>{e({maxLastMessageLength:r})},setTimeFormatPreference:r=>{e({timeFormatPreference:r})},setWeekStartPreference:r=>{e({weekStartPreference:r})},setSidebarViewMode:r=>{e({sidebarViewMode:r})},setSessionAutoArchiveAfterDays:r=>{Wt(r)&&e({sessionAutoArchiveAfterDays:r})},setSessionAutoDeleteAfterDays:r=>{Wt(r)&&e({sessionAutoDeleteAfterDays:r})},setExpandedEditorToolbar:r=>{e({expandedEditorToolbar:r})},viewPagerPage:"center",setViewPagerPage:r=>{e({viewPagerPage:r}),e({isSessionSwitcherOpen:r==="left"})},setShortcutOverride:(r,o)=>{e(n=>({shortcutOverrides:{...n.shortcutOverrides,[r]:o}}))},clearShortcutOverride:r=>{e(o=>{const n={...o.shortcutOverrides};return delete n[r],{shortcutOverrides:n}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:r=>{e({fileEditorKeymap:vs(r)})},toggleExpandedInput:()=>{e(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{e({isExpandedInput:r})}}),{name:"ui-store",storage:ca(),version:21,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const r=e;if(t<21&&(delete r.diffWrapLines,delete r.diffWrapLinesOverride,typeof r.wrapLinesByDefault!="boolean"&&(r.wrapLinesByDefault=!0)),t<20&&(delete r.notifyOnSubtasks,delete r.notifyOnQuestion,delete r.notificationTemplates),t<19&&(delete r.showReasoningTraces,delete r.collapsibleThinkingBlocks,delete r.collapseThinkingByDefault,delete r.persistChatDraft,delete r.inputSpellcheckEnabled,delete r.wideChatLayoutEnabled,delete r.codeBlockLineWrap,delete r.showToolFileIcons,delete r.showTurnChangedFiles,delete r.showExpandedBashTools,delete r.showExpandedEditTools,delete r.desktopWindowControlsPosition,delete r.desktopWindowControlsStyle,delete r.mermaidRenderingMode,delete r.userMessageRenderingMode,delete r.collapsibleUserMessages,delete r.stickyUserHeader,delete r.promptNavigatorEnabled,delete r.showSplitAssistantMessageActions),t<18&&(delete r.notesPanelHeight,delete r.todoPanelHeight,r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="notes"))),t<17&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="chat"))),t<16&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="chat"))),t<15&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="pr"))),t<14&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="diff"))),t<13&&typeof r.autoSaveEnabled!="boolean"){let o=!0;try{if(typeof localStorage<"u"){const n=localStorage.getItem("pichamber:files:auto-save-enabled");n!==null&&(o=n!=="false",localStorage.removeItem("pichamber:files:auto-save-enabled"))}}catch{o=!0}r.autoSaveEnabled=o}if(t<12&&(delete r.desktopWindowControlsPosition,delete r.desktopWindowControlsStyle),t<11&&r.terminalFontSize===13&&(r.terminalFontSize=14),t<10&&delete r.diffViewMode,t<9&&((typeof r.notesPanelHeight!="number"||!Number.isFinite(r.notesPanelHeight))&&(r.notesPanelHeight=112),(typeof r.todoPanelHeight!="number"||!Number.isFinite(r.todoPanelHeight))&&(r.todoPanelHeight=259)),t<3){const o=new Set([90,120,180,220]),n=r.memoryLimitHistorical,a=r.memoryLimitActiveSession;typeof n=="number"&&!o.has(n)?r.messageLimit=n:typeof a=="number"&&!o.has(a)&&(r.messageLimit=a),delete r.memoryLimitHistorical,delete r.memoryLimitViewport,delete r.memoryLimitActiveSession}if(delete r.isRightSidebarOpen,delete r.rightSidebarWidth,delete r.rightSidebarTab,delete r.workStatusExpandedSections,delete r.workStatusScrollTop,delete r.workStatusPanelEnabled,delete r.workStatusHiddenSections,delete r.showReasoningTraces,delete r.collapsibleThinkingBlocks,delete r.collapseThinkingByDefault,delete r.persistChatDraft,delete r.inputSpellcheckEnabled,delete r.wideChatLayoutEnabled,delete r.codeBlockLineWrap,delete r.showToolFileIcons,delete r.showTurnChangedFiles,delete r.showExpandedBashTools,delete r.showExpandedEditTools,delete r.desktopWindowControlsPosition,delete r.desktopWindowControlsStyle,delete r.mermaidRenderingMode,delete r.userMessageRenderingMode,delete r.collapsibleUserMessages,delete r.stickyUserHeader,delete r.promptNavigatorEnabled,delete r.showSplitAssistantMessageActions,delete r.diffWrapLines,r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),t<5)if(!r.shortcutOverrides||typeof r.shortcutOverrides!="object")r.shortcutOverrides={};else{const o=r.shortcutOverrides,n={};for(const[a,s]of Object.entries(o))typeof a=="string"&&typeof s=="string"&&(n[a]=s);r.shortcutOverrides=n}return t<6&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory)),t<7&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory)),t<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=vs(r.fileEditorKeymap),r.githubSelectedRepoByDirectory=Cs(Hf(r.githubSelectedRepoByDirectory),Bs),typeof r.autoSaveEnabled!="boolean"&&(r.autoSaveEnabled=!0),typeof r.wrapLinesByDefault!="boolean"&&(r.wrapLinesByDefault=!0),r.contextRailOrder=Array.isArray(r.contextRailOrder)?r.contextRailOrder.filter(o=>typeof o=="string"&&o.trim()!==""&&o!=="pr"&&o!=="diff"&&o!=="chat"&&o!=="notes"):[],r},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,browserRoutePreference:e.browserRoutePreference,chatLinkTarget:e.chatLinkTarget,contextRailOrder:e.contextRailOrder,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,githubSelectedRepoByDirectory:e.githubSelectedRepoByDirectory,isSessionSwitcherOpen:e.isSessionSwitcherOpen,activeMainTab:e.activeMainTab,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showDeletionDialog:e.showDeletionDialog,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,wrapLinesByDefault:e.wrapLinesByDefault,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnInputNeeded:e.notifyOnInputNeeded,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,sidebarViewMode:e.sidebarViewMode,sessionAutoArchiveAfterDays:e.sessionAutoArchiveAfterDays,sessionAutoDeleteAfterDays:e.sessionAutoDeleteAfterDays,expandedEditorToolbar:e.expandedEditorToolbar,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Rb=Object.freeze(Object.defineProperty({__proto__:null,normalizeContextPanelDirectoryKey:Tf,useUIStore:ie},Symbol.toStringTag,{value:"Module"}));let ks="idle";const jf=new Set;let Xr=null;const Ae=e=>{Xr&&(clearTimeout(Xr),Xr=null);const t=e==="saved"?"idle":e;t!==ks&&(ks=t,jf.forEach(r=>r())),t==="error"&&(Xr=setTimeout(()=>Ae("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("pichamber:settings-save-state",{detail:e}))},Pb=e=>{Ae(e)},$f=e=>{if(!(typeof window>"u")&&!(typeof window.__PICHAMBER_HOME__=="string"&&window.__PICHAMBER_HOME__.length>0))try{window.__PICHAMBER_HOME__=e}catch{}},Ds="pichamber.settingsMirror.v2.index",Kf="pichamber.settingsMirror.v2:",zf=5,Ss=e=>`${Kf}${encodeURIComponent(e)}`,pt=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},qf=(e,t)=>{const r={themeId:e.themeId,themeVariant:e.themeVariant,lightThemeId:e.lightThemeId,darkThemeId:e.darkThemeId,useSystemTheme:e.useSystemTheme,lastDirectory:e.lastDirectory,homeDirectory:e.homeDirectory,projects:e.projects,activeProjectId:e.activeProjectId,pinnedDirectories:e.pinnedDirectories,filesViewShowGitignored:e.filesViewShowGitignored,openInAppId:e.openInAppId,pwaAppName:e.pwaAppName,mobileKeyboardMode:e.mobileKeyboardMode};localStorage.setItem(Ss(t),JSON.stringify(r));let o=[];try{const a=JSON.parse(localStorage.getItem(Ds)??"[]");Array.isArray(a)&&(o=a.filter(s=>typeof s=="string"))}catch{o=[]}const n=[t,...o.filter(a=>a!==t)].slice(0,zf);for(const a of o)n.includes(a)||localStorage.removeItem(Ss(a));localStorage.setItem(Ds,JSON.stringify(n))},Gf=e=>{if(!(typeof window>"u")){if(qf(e,D()),pt("selectedThemeId",e.themeId||null),pt("selectedThemeVariant",e.themeVariant||null),pt("lightThemeId",e.lightThemeId||null),pt("darkThemeId",e.darkThemeId||null),pt("useSystemTheme",typeof e.useSystemTheme=="boolean"?String(e.useSystemTheme):null),pt("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),$f(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(r=>r.sidebarCollapsed===!0).map(r=>r.id).filter(r=>typeof r=="string"&&r.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),pt("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=Wi(e.pwaAppName,"");t.length>0?localStorage.setItem(en,t):localStorage.removeItem(en)}else localStorage.removeItem(en);df(e.mobileKeyboardMode)}},vn=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("pichamber:settings-synced",{detail:e}))},Wf=()=>{const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();if(typeof e?.getRandomValues!="function")throw new Error("Secure random UUID is unavailable in this browser context");const t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const r=Array.from(t,o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},Vf=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const r=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,a)=>a.toUpperCase()+":");return r==="/"?"/":(r.length>1?r.replace(/\/+$/,""):r)||null},Ma="queue",Ta=e=>e==="steer"||e==="queue",Ra=(e,t)=>e==="immediate"?"steer":Ta(e)?e:t===!1?"steer":t===!0?"queue":Ma,Ms=50,Ts=20,on=(e,t)=>{if(e.runtimeKey!==D())return;const r=t.flatMap(o=>(o.attachments??[]).flatMap(n=>n.uploadState?.status==="ready"?[n.uploadState.attachmentId]:[]));for(const o of new Set(r))yt.deleteAttachment(o,{runtimeKey:e.runtimeKey}).catch(()=>{})},Jf=(e,t,r=D())=>{const o=Vf(t);return!r||!o||!e?null:{runtimeKey:r,directory:o,sessionId:e}},ne=e=>`${e.runtimeKey}
|
|
7
|
+
`;for(const r of[...Ee.keys()])r.startsWith(t)&&Ee.delete(r)},$u=(e,t,r)=>{if(Ee.size>=ys){const o=Date.now();for(const[n,a]of Ee)o-a.settledAt>=$i&&Ee.delete(n);for(;Ee.size>=ys;){const n=Ee.keys().next().value;if(typeof n!="string")break;Ee.delete(n)}}Ee.set(e,{response:t,settledAt:r})};class Ku{currentDirectory;setDirectory(t){this.currentDirectory=t}getDirectory(){return this.currentDirectory}async health(t){B(t);const r=await yo(void 0,t?.runtimeKey);return r.state==="ready"?{protocolVersion:r.protocolVersion,state:"ready",capabilities:r.capabilities,...r.streamEpoch?{streamEpoch:r.streamEpoch}:{}}:{protocolVersion:r.protocolVersion,state:"unavailable",capabilities:r.capabilities,...r.error?{error:r.error}:{}}}async listProjects(t){return B(t),k("/api/pi/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async selectProject(t,r){return B(r),k("/api/pi/projects/select",{method:"POST",body:{directory:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSessions(t){B(t);const r=t?.directory??this.currentDirectory;return k("/api/pi/sessions",{method:"GET",...r?{query:{directory:r}}:{},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listPendingInput(t){B(t);const r=await k("/api/pi/sessions/pending-input",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!Uu(r))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed pending-input list");return r}async createSession(t,r){return B(r),k("/api/pi/sessions",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSession(t,r){B(r);const o=r?.directory??this.currentDirectory;return k(`/api/pi/sessions/${encodeURIComponent(t)}`,{method:"GET",...o?{query:{directory:o}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSessionMessages(t,r,o){B(o);const n=o?.directory??this.currentDirectory;return k(`/api/pi/sessions/${encodeURIComponent(t)}/messages`,{method:"GET",query:{...n?{directory:n}:{},...r.before?{before:r.before}:{},...r.limit!==void 0?{limit:r.limit}:{}},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async renameSession(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"PATCH",body:{sessionId:t.sessionId,title:t.title},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async deleteSession(t,r){B(r);try{return await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"DELETE",...r?.directory?{query:{directory:r.directory}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}),!0}catch(o){if(o instanceof j&&o.status===404)return!0;throw o}}async archiveSession(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/archive`,{method:"POST",body:{sessionId:t.sessionId,archived:t.archived,...r?.directory?{directory:r.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSessionShelf(t){B(t);const r=await k("/api/pi/session-shelf",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!cu(r))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf");return r}async setSessionShelf(t,r){B(r);const{sessionId:o,...n}=t,s=(await k(`/api/pi/sessions/${encodeURIComponent(o)}/shelf`,{method:"POST",body:{...n,...r?.directory?{directory:r.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.entry;if(s!==null&&!Ni(s))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf entry");return s}async getSessionTree(t,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t)}/tree`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async navigateSession(t,r,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t)}/navigate`,{method:"POST",body:{messageId:r},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async forkSession(t,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/fork`,{method:"POST",body:{sessionId:t.sessionId,...t.messageId?{messageId:t.messageId}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async cloneSession(t,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/clone`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async sendPrompt(t,r){return this.sendWithReceipt("prompt",t,`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/prompt`,r)}async sendSteer(t,r){return this.sendWithReceipt("steer",t,`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/steer`,r)}async sendFollowUp(t,r){return this.sendWithReceipt("followUp",t,`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/follow-up`,r)}async getSendReceipt(t,r){const o=r?.runtimeKey??D();B({...r,runtimeKey:o});const n=Wr(o,t.streamEpoch??r?.streamEpoch??Ze(o)),a=r?.directory??this.currentDirectory,s=await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/send-receipt`,{method:"POST",body:{kind:t.kind,operationId:t.operationId,streamEpoch:n},...a?{query:{directory:a}}:{},runtimeKey:o});if(B({...r,runtimeKey:o}),Wr(o,n),!s||typeof s!="object")throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");const i=s.status;if(i==="accepted"){const c=s.receipt;if(!Xo(c))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");return{status:"accepted",receipt:c}}if(i==="pending"||i==="expired"||i==="unknown")return{status:i};throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt")}async sendWithReceipt(t,r,o,n){const a=n?.runtimeKey??D();let s;try{B({...n,runtimeKey:a}),s=Wr(a,n?.streamEpoch??Ze(a))}catch(c){throw Qo(c)}const i=n?.directory??this.currentDirectory;try{const c=await k(o,{method:"POST",body:{...r,streamEpoch:s},...i?{query:{directory:i}}:{},runtimeKey:a,retry:!1});if(!Xo(c))throw new j("DAEMON_PROTOCOL_MISMATCH","Malformed send response");return B({...n,runtimeKey:a}),Wr(a,s),c}catch(c){if(c instanceof j&&c.code==="STALE_STREAM_EPOCH")throw Qo(c);if(Hu(c))throw c;const d=r.operationId;if(typeof d=="string"&&d.length>0)try{B({...n,runtimeKey:a});const l=this.getSendReceipt;if(!l)throw new j("DAEMON_UNAVAILABLE","Send receipt lookup unavailable");const u=await l.call(this,{sessionId:r.sessionId,kind:t,operationId:d,streamEpoch:s},{...n,runtimeKey:a,streamEpoch:s});if(B({...n,runtimeKey:a}),typeof u=="object"&&u!==null&&u.status==="accepted"&&Xo(u.receipt))return u.receipt}catch{}throw Qo(c)}}async abortSession(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setSessionModel(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/model`,{method:"POST",body:{sessionId:t.sessionId,model:t.model},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setSessionThinking(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/thinking`,{method:"POST",body:{sessionId:t.sessionId,thinking:t.thinking},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async compactSession(t,r){if(B(r),(await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).accepted!==!0)throw new j("DAEMON_PROTOCOL_MISMATCH")}async runBash(t,r){B(r);const o=await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash`,{method:"POST",body:{command:t.command,...t.excludeFromContext?{excludeFromContext:!0}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});if(o?.accepted!==!0||typeof o.id!="string")throw new j("DAEMON_PROTOCOL_MISMATCH");return{id:o.id}}async abortBash(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listProviders(t){return B(t),k("/api/pi/providers",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listEngines(t){return B(t),k("/api/pi/engines",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async refreshProviders(t){return B(t),k("/api/pi/providers/refresh",{method:"POST",...t?.directory?{body:{directory:t.directory}}:{body:void 0},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getProviderStatus(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t)}/status`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async loginProvider(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/login`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderLogin(t,r,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async respondProviderLogin(t,r,o,n){return B(n),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}/respond`,{method:"POST",body:{value:o},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async logoutProvider(t,r){B(r),await k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/logout`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderConfig(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t)}/config`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setProviderModels(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async addProviderModel(t,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"POST",body:t.model,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSettings(t){return B(t),k("/api/pi/settings",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async setPiSettings(t,r){return B(r),k("/api/pi/settings/pi",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPiChamberDefaults(t,r){return B(r),k("/api/pi/settings/defaults",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listResources(t,r){const o=typeof t=="string"?r:t,n=typeof t=="string"?t:void 0;B(o);const a=o?.runtimeKey??D(),s=ju(a,n),i=so(a);if(o?.reload!==!0){const m=Ee.get(s);if(m&&Date.now()-m.settledAt<$i)return structuredClone(m.response)}const c=Vr.get(s);if(c&&c.revision===i)return structuredClone(await c.promise);const d=Date.now(),l=so(a),u={},f=(async()=>{try{const m=await k("/api/pi/resources",{method:"GET",...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});if(D()===a&&so(a)===l){const g=Ee.get(s);(!g||g.settledAt<=d)&&$u(s,m,Date.now())}return m}finally{Vr.get(s)?.promise===u.promise&&Vr.delete(s)}})();return u.promise=f,Vr.set(s,{revision:l,promise:f}),structuredClone(await f)}async listCommands(t,r){return B(r),k("/api/pi/commands",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSnippets(t,r){return B(r),k("/api/pi/snippets",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async createSnippet(t,r){return B(r),k("/api/pi/snippets",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateSnippet(t,r,o,n){return B(n),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"PUT",body:r,...o?{query:{directory:o}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deleteSnippet(t,r,o){return B(o),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"DELETE",...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateResource(t,r){B(r);const o=r?.runtimeKey??D(),n=t.directory??r?.directory,a=await k(`/api/pi/resources/${encodeURIComponent(t.resourceId)}`,{method:"PUT",body:t,...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});return Jr(o),a}async createPromptTemplate(t,r,o){const n=r??t.directory??o?.directory;B(o);const a=o?.runtimeKey??D(),s=await k("/api/pi/resources/prompts",{method:"POST",body:t,...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Jr(a),s}async updatePromptTemplate(t,r,o,n){B(n);const a=n?.runtimeKey??D(),s=o??r.directory??n?.directory,i=await k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"PUT",body:r,...s?{query:{directory:s}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}});return Jr(a),i}async deletePromptTemplate(t,r,o){B(o);const n=o?.runtimeKey??D(),a=r??o?.directory,s=await k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"DELETE",...a?{query:{directory:a}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Jr(n),s}async createAttachment(t,r){return B(r),(await k("/api/pi/attachments",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).attachment}async uploadAttachment(t,r,o){B(o);const n=await au("/api/pi/attachments",t,r);if(!n.ok){const i=(await n.json().catch(()=>null))?.error??{code:"ATTACHMENT_FAILED"};throw new j(i.code,i.message,n.status)}const a=await n.json();return B(o),a.attachment}async deleteAttachment(t,r){B(r),await k(`/api/pi/attachments/${encodeURIComponent(t)}`,{method:"DELETE",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listExtensions(t,r){return B(r),k("/api/pi/extensions",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async respondToExtensionDialog(t,r){B(r),await k("/api/pi/extensions/respond",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async sendExtensionSurface(t,r,o){B(o);const{sessionId:n,...a}=r;await k(`/api/pi/sessions/${encodeURIComponent(n)}/extensions/custom/${t}`,{method:"POST",body:a,...t==="input"||t==="close"?{retry:!1}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateExtensionDraft(t,r){B(r),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/editor-draft`,{method:"POST",body:{text:t.text,revision:t.revision,...t.directory?{directory:t.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}}const yt=new Ku;async function zu(e){return(await Gu(e)).home}let wn=null,gr=null;const Fb=()=>{wn=null,gr=null},qu=async()=>{let e=null,t=null;try{const r=await F("/api/fs/home",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(r.ok){const o=await r.json().catch(()=>null);typeof o?.home=="string"&&o.home.trim().length>0&&(e=o.home.trim()),typeof o?.pichamberDataDir=="string"&&o.pichamberDataDir.trim().length>0&&(t=o.pichamberDataDir.trim())}}catch{}return{home:e,pichamberDataDir:t}},Gu=async e=>{const t=D();if(!e?.fresh){const o=wn;if(o&&o.key===t)return o.state;const n=gr;if(n&&n.key===t)return n.promise}const r=(async()=>{const o=await qu();return!e?.fresh&&o.home&&D()===t&&(wn={key:t,state:o}),o})();e?.fresh||(gr={key:t,promise:r});try{return await r}finally{gr?.promise===r&&(gr=null)}};async function yb(e,t){if(!e||e.trim().length===0)return[];const r={path:e},o=Ie().api("/api/fs/list",r),n=await F(o);if(!n.ok)return[];const a=await n.json();return Array.isArray(a.entries)?a.entries:[]}async function Wu(e,t){const r=t?.directory||"";if(!r)return[];const o={directory:r,query:e};t?.limit&&(o.limit=t.limit),t?.includeHidden&&(o.includeHidden=!0),t?.respectGitignore!==void 0&&(o.respectGitignore=t.respectGitignore),t?.type&&(o.type=t.type);const n=Ie().api("/api/fs/find",o),a=await F(n);if(!a.ok)return[];const s=await a.json();return Array.isArray(s.files)?s.files:[]}async function bb(e=""){try{const t=await F("/api/fs/pick-directory",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({path:e||void 0})}),r=await t.json().catch(()=>null);return r?.cancelled===!0?{status:"cancelled"}:t.status===501?{status:"unavailable",error:typeof r?.error=="string"?r.error:"Folder picker is not available."}:t.ok?typeof r?.path=="string"&&r.path.trim()?{status:"picked",path:r.path.trim()}:{status:"failed",error:"Failed to select directory."}:{status:"failed",error:typeof r?.error=="string"?r.error:"Failed to select directory."}}catch(t){return{status:"failed",error:t instanceof Error?t.message:"Failed to select directory."}}}const Ab={explore:{label:"Explore the codebase",icon:"compass-3",text:"Explore this codebase and explain how it works. Start with an overview, then key files and data flow."},plan:{label:"Plan the work",icon:"list-check-2",text:"Plan this work before coding. Break it into small steps, list files to change, and call out risks."},review:{label:"Review my changes",icon:"file-search",text:"Review my current changes for bugs, edge cases, and regressions. Suggest specific fixes."},"find-bugs":{label:"Find bugs",icon:"bug",text:"Find bugs in the current selection. List each issue with what is wrong and a minimal fix."},"write-tests":{label:"Write tests",icon:"flask",text:"Write tests for the current selection. Cover the happy path, edge cases, and failure modes."}},Vu=e=>typeof e=="string"&&(e==="explore"||e==="plan"||e==="review"||e==="find-bugs"||e==="write-tests"),Eb=[{type:"text",key:"explore"},{type:"text",key:"plan"},{type:"text",key:"review"},{type:"text",key:"find-bugs"},{type:"text",key:"write-tests"}],wb="book-open",Ju=/^[^\s/]+$/,bs=e=>e.type==="prompt"?`prompt:${e.name}`:`text:${e.key}`,Bb=(e,t)=>e.type!==t.type?!1:e.type==="prompt"&&t.type==="prompt"?e.name===t.name:e.type==="text"&&t.type==="text"?e.key===t.key:!1,Cb=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},wa=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const n=o;if(n.type==="text"){if(!Vu(n.key))continue;const d={type:"text",key:n.key},l=bs(d);if(r.has(l))continue;r.add(l),t.push(d);continue}if(n.type!=="prompt")continue;const a=typeof n.name=="string"?n.name.trim():"";if(!a||!Ju.test(a))continue;const s=n.scope==="global"||n.scope==="project"?n.scope:void 0,i=s?{type:"prompt",name:a,scope:s}:{type:"prompt",name:a},c=bs(i);r.has(c)||(r.add(c),t.push(i))}return t},Yu=e=>{let t,r=-1;for(const o of e){const a=(o.location==="project"?2:o.location==="global"?1:0)+(o.editable?.5:0);a>r&&(t=o,r=a)}return t},vb=e=>{const t=new Map;for(const o of e){const n=t.get(o.name)??[];n.push(o),t.set(o.name,n)}const r=new Map;for(const[o,n]of t){const a=Yu(n);a&&r.set(o,a)}return r},kb=(e,t)=>{const r=new Set,o=s=>s.filter(i=>{const c=i.insertText.trim();return r.has(c)?!1:(r.add(c),!0)}),n=o(e),a=o(t);return{project:n,global:a}},Xu={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.8125rem",micro:"0.75rem",settingsPageTitle:"1.125rem"};function As(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Yr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Zo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Yr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Yr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Yr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Yr.tool.inline})},Qu=[{id:"inter",label:"Inter",description:"Modern UI sans with excellent readability at small sizes.",stack:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Inter",packageName:"@fontsource/inter",filePrefix:"inter",weights:[400,500,600]}},{id:"geist-sans",label:"Geist Sans",description:"Crisp sans-serif with a technical interface feel.",stack:'"Geist Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Geist Sans",packageName:"@fontsource/geist-sans",filePrefix:"geist-sans",weights:[400,500,600]}},{id:"atkinson-hyperlegible",label:"Atkinson Hyperlegible",description:"Accessibility-focused sans-serif optimized for character distinction.",stack:'"Atkinson Hyperlegible", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Atkinson Hyperlegible",packageName:"@fontsource/atkinson-hyperlegible",filePrefix:"atkinson-hyperlegible",weights:[400,700]}},{id:"source-sans-3",label:"Source Sans 3",description:"Adobe sans-serif tuned for clean, readable interfaces.",stack:'"Source Sans 3", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Source Sans 3",packageName:"@fontsource/source-sans-3",filePrefix:"source-sans-3",weights:[400,500,600]}},{id:"roboto",label:"Roboto",description:"Familiar Material-style sans-serif with broad UI usage.",stack:'"Roboto", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Roboto",packageName:"@fontsource/roboto",filePrefix:"roboto",weights:[400,500,600]}},{id:"noto-sans",label:"Noto Sans",description:"Readable sans-serif with strong international coverage.",stack:'"Noto Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Noto Sans",packageName:"@fontsource/noto-sans",filePrefix:"noto-sans",weights:[400,500,600]}},{id:"dm-sans",label:"DM Sans",description:"Modern product UI sans-serif with friendly proportions.",stack:'"DM Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"DM Sans",packageName:"@fontsource/dm-sans",filePrefix:"dm-sans",weights:[400,500,600]}},{id:"manrope",label:"Manrope",description:"Polished geometric sans-serif for modern app interfaces.",stack:'"Manrope", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Manrope",packageName:"@fontsource/manrope",filePrefix:"manrope",weights:[400,500,600]}},{id:"system",label:"System",description:"Native operating system interface font.",stack:'"SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'}],Zu=[{id:"jetbrains-mono",label:"JetBrains Mono",description:"Developer-focused monospace with strong punctuation clarity.",stack:'"JetBrains Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"JetBrains Mono",packageName:"@fontsource/jetbrains-mono",filePrefix:"jetbrains-mono",weights:[400,500,600]}},{id:"fira-code",label:"Fira Code",description:"Readable coding font with ligature support.",stack:'"Fira Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Fira Code",packageName:"@fontsource/fira-code",filePrefix:"fira-code",weights:[400,500,600]}},{id:"geist-mono",label:"Geist Mono",description:"Sharp monospace pair for Geist Sans.",stack:'"Geist Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Geist Mono",packageName:"@fontsource/geist-mono",filePrefix:"geist-mono",weights:[400,500,600]}},{id:"commit-mono",label:"Commit Mono",description:"Code-oriented monospace with polished editor ergonomics.",stack:'"Commit Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Commit Mono",packageName:"@fontsource/commit-mono",filePrefix:"commit-mono",weights:[400,500,600]}},{id:"source-code-pro",label:"Source Code Pro",description:"Adobe monospace designed for source code readability.",stack:'"Source Code Pro", "SFMono-Regular", "Menlo", monospace',source:{family:"Source Code Pro",packageName:"@fontsource/source-code-pro",filePrefix:"source-code-pro",weights:[400,500,600]}},{id:"cascadia-code",label:"Cascadia Code",description:"Microsoft coding font popular in terminals and editors.",stack:'"Cascadia Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Cascadia Code",packageName:"@fontsource/cascadia-code",filePrefix:"cascadia-code",weights:[400,500,600]}},{id:"roboto-mono",label:"Roboto Mono",description:"Neutral monospace companion to Roboto.",stack:'"Roboto Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Roboto Mono",packageName:"@fontsource/roboto-mono",filePrefix:"roboto-mono",weights:[400,500,600]}},{id:"iosevka",label:"Iosevka",description:"Compact monospace for dense code and terminal layouts.",stack:'"Iosevka", "SFMono-Regular", "Menlo", monospace',source:{family:"Iosevka",packageName:"@fontsource/iosevka",filePrefix:"iosevka",weights:[400,500,600]}},{id:"system-mono",label:"System Mono",description:"Native operating system monospace font.",stack:'ui-monospace, "SFMono-Regular", "Menlo", "Cascadia Mono", "Segoe UI Mono", monospace'}],zi=e=>Object.fromEntries(e.map(t=>[t.id,t])),ef=zi(Qu),tf=zi(Zu),rf="system",of="system-mono",qi=e=>typeof e=="string"&&e in ef,Gi=e=>typeof e=="string"&&e in tf,en="pichamber.pwaName",Bn="pichamber.mobileKeyboardMode",Db="pichamber.pwaRecentSessions",nf=["native","resize-content"];function af(e,t="resize-content"){return typeof e=="string"&&nf.includes(e)?e:t}const sf=64;function Wi(e,t){if(typeof e!="string")return t;const r=e.trim().replace(/\s+/g," ");return r?r.slice(0,sf):t}const Sb=()=>!0;function Ba(e,t="resize-content"){return af(e,t)??void 0}const cf=()=>{if(typeof window>"u")return"resize-content";try{return Ba(localStorage.getItem(Bn))}catch{return"resize-content"}},df=e=>{const t=Ba(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Bn):localStorage.setItem(Bn,t)}catch{}return t},K=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),r=t.startsWith("//");let o=t.replace(/\/+$/g,"").replace(/\/+/g,"/");return r&&!o.startsWith("//")&&(o=`/${o}`),o||(t.startsWith("/")?"/":"")},lf=["workspace","folder","timeline","threads"],uf="workspace",Vi=e=>typeof e=="string"&&lf.includes(e),ff=365,Wt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=ff,Mb=e=>e===1?"1 session":`${e} sessions`,Se=20,mf=8,Es=4096,gf=2160*60*6e4,$=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),r=t.startsWith("//");let o=t.replace(/\/+/g,"/");r&&!o.startsWith("//")&&(o=`/${o}`);const n=o==="/",a=/^[A-Za-z]:\/$/.test(o);return!n&&!a&&(o=o.replace(/\/+$/,"")),o},Xe=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,et=(e,t)=>{const r=$(t),o=$(e);if(!r||!o)return!1;const n=Xe(r),a=Xe(o);return a===n||a.startsWith(`${n}/`)},cr=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=$(o);if(!a||!n||typeof n!="object")continue;const s=n,i=Array.isArray(s.openPaths)?Array.from(new Set(s.openPaths.filter(m=>typeof m=="string").map(m=>$(m)).filter(m=>m.length<=Es&&et(m,a)))).slice(-50):[],c=Array.isArray(s.expandedPaths)?Array.from(new Set(s.expandedPaths.filter(m=>typeof m=="string").map(m=>$(m)).filter(m=>m.length<=Es&&et(m,a)))).slice(-500):[],d=typeof s.selectedPath=="string"?$(s.selectedPath):null,l=d&&et(d,a)?d:i[0]??null,u=typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now();if(Date.now()-u>gf)continue;const f=r[a];if(f){const m=Array.from(new Set([...f.openPaths,...i])),g=Array.from(new Set([...f.expandedPaths,...c])),p=f.selectedPath??l??m[0]??null;r[a]={openPaths:m,selectedPath:p,expandedPaths:g,touchedAt:Math.max(f.touchedAt,u)};continue}r[a]={openPaths:i,selectedPath:l,expandedPaths:c,touchedAt:u}}return Me(r,Se)},Me=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;r.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const o={};for(const[n,a]of r.slice(0,t))o[n]=a;return o},Rt=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},pf=Mr()(Tr(Qn((e,t)=>({byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{},resetForRuntimeSwitch:r=>{e(o=>{const n={...o.runtimeSnapshots,[o.activeRuntimeKey]:{byRoot:cr(o.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:r,runtimeSnapshots:n,byRoot:cr(n[r]?.byRoot)}})},addOpenPath:(r,o,n)=>{const a=$((r||"").trim()),s=$((o||"").trim());!a||!s||!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=Rt(c),l=d.openPaths.includes(s),u=l?d.openPaths:[...d.openPaths,s],f=d.selectedPath??s;if(c&&l&&c.selectedPath===f)return i;const m={...i.byRoot,[a]:{...d,openPaths:u,selectedPath:f}};return{byRoot:Me(m,Se)}})},removeOpenPath:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||e(s=>{const i=s.byRoot[n];if(!i)return s;const c=Xe(a),d=g=>Xe(g)===c,l=i.selectedPath?d(i.selectedPath):!1;if(!i.openPaths.some(d)&&!l)return s;const u=i.openPaths.filter(g=>!d(g)),f=l?u[0]??null:i.selectedPath,m={...s.byRoot,[n]:{...i,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Me(m,Se)}})},removeOpenPathsByPrefix:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||e(s=>{const i=s.byRoot[n];if(!i)return s;const c=Xe(a),d=c.endsWith("/")?c:`${c}/`,l=g=>{const p=Xe(g);return p===c||p.startsWith(d)},u=i.openPaths.filter(g=>!l(g));if(u.length===i.openPaths.length)return s;const f=i.selectedPath&&l(i.selectedPath)?u[0]??null:i.selectedPath,m={...s.byRoot,[n]:{...i,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Me(m,Se)}})},removeExpandedPathsByPrefix:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||e(s=>{const i=s.byRoot[n];if(!i)return s;const c=Xe(a),d=c.endsWith("/")?c:`${c}/`,l=i.expandedPaths.filter(f=>{const m=Xe(f);return m!==c&&!m.startsWith(d)});if(l.length===i.expandedPaths.length)return s;const u={...s.byRoot,[n]:{...i,expandedPaths:l,touchedAt:Date.now()}};return{byRoot:Me(u,Se)}})},setSelectedPath:(r,o,n)=>{const a=$((r||"").trim()),s=o?$(o.trim()):null;!a||s&&!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=Rt(c),l=s&&!d.openPaths.includes(s)?[...d.openPaths,s]:d.openPaths;if(c&&c.selectedPath===s&&l===c.openPaths)return i;const u={...i.byRoot,[a]:{...d,openPaths:l,selectedPath:s}};return{byRoot:Me(u,Se)}})},ensureSelectedPath:r=>{const o=$((r||"").trim());if(!o)return;const n=t().byRoot[o];if(!n||n.selectedPath)return;const a=n.openPaths[0]??null;a&&t().setSelectedPath(o,a)},toggleExpandedPath:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=Rt(i),l=c.expandedPaths.includes(a)?c.expandedPaths.filter(f=>f!==a):[...c.expandedPaths,a];if(i&&i.expandedPaths===l&&i.selectedPath===c.selectedPath&&i.openPaths===c.openPaths)return s;const u={...s.byRoot,[n]:{...c,expandedPaths:l}};return{byRoot:Me(u,Se)}})},collapseAllExpandedPaths:r=>{const o=$((r||"").trim());o&&e(n=>{const a=n.byRoot[o];if(!a||a.expandedPaths.length===0)return n;const s={...n.byRoot,[o]:{...Rt(a),expandedPaths:[]}};return{byRoot:Me(s,Se)}})},expandPath:(r,o)=>{const n=$((r||"").trim()),a=$((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=Rt(i);if(c.expandedPaths.includes(a)&&i)return s;const l={...s.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,a]}};return{byRoot:Me(l,Se)}})},expandPaths:(r,o)=>{const n=$((r||"").trim());if(!n||!o||o.length===0)return;const a=o.map(s=>$((s||"").trim())).filter(s=>s&&et(s,n));a.length!==0&&e(s=>{const i=s.byRoot[n],c=Rt(i),d=new Set(c.expandedPaths),l=a.filter(f=>!d.has(f));if(l.length===0)return s;const u={...s.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,...l]}};return{byRoot:Me(u,Se)}})}}),{name:"files-view-tabs-store",version:3,storage:ca(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:cr(e.byRoot),updatedAt:Date.now()}},r=Object.fromEntries(Object.entries(t).sort(([,o],[,n])=>n.updatedAt-o.updatedAt).slice(0,mf).map(([o,n])=>[o,{byRoot:cr(n.byRoot),updatedAt:n.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:r}},merge:(e,t)=>{const r=e&&typeof e=="object"?e:{},o=r.runtimeSnapshots&&typeof r.runtimeSnapshots=="object"?r.runtimeSnapshots:{},n=D();return{...t,activeRuntimeKey:n,runtimeSnapshots:o,byRoot:cr(o[n]?.byRoot)}}}),{name:"files-view-tabs-store"})),Ca=12,hf=4096,Ff=200,yf=/^[A-Za-z0-9_.:-]{1,120}$/,Io=()=>`page-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36).slice(-4)}`,vr=e=>{if(typeof e!="string")return null;const t=e.trim();return!t||t==="about:blank"?null:t.slice(0,hf)},Ji=e=>{if(typeof e!="string")return null;const t=e.replace(/\s+/g," ").trim();return t?t.slice(0,Ff):null},kr=e=>e==="server"||e==="device"?e:null,Yi=(e,t)=>t&&e.some(r=>r.id===t)?t:e[0]?.id??null,bf=(e,t)=>{const r=e&&typeof e=="object"?e:null,o=[],n=new Set;if(r&&Array.isArray(r.pages))for(const s of r.pages){if(!s||typeof s!="object")continue;const i=s,c=typeof i.id=="string"?i.id:"";if(!(!yf.test(c)||n.has(c))&&(n.add(c),o.push({id:c,url:vr(i.url),route:kr(i.route),title:Ji(i.title)}),o.length>=Ca))break}o.length===0&&o.push({id:t.tabId,url:vr(t.url),route:t.route,title:null});const a=typeof r?.activePageId=="string"?r.activePageId:null;return{pages:o,activePageId:Yi(o,a)}},Af=(e,t=Io)=>{const r=t();return{pages:[{id:r,url:vr(e.url),route:kr(e.route),title:null}],activePageId:r}},Ef=(e,t,r=Io)=>{const o=vr(t.url),n=kr(t.route),a=e.pages.find(l=>l.id===e.activePageId)??null,s=a&&(t.target==="current"||o!==null&&a.url===null||e.pages.length>=Ca);if(a&&s)return{pages:e.pages.map(u=>u.id===a.id?{...u,url:o??u.url,route:n??u.route,title:o&&o!==u.url?null:u.title}:u),activePageId:a.id,pageId:a.id};const i={id:r(),url:o,route:n,title:null},c=a?e.pages.indexOf(a):e.pages.length-1;return{pages:[...e.pages.slice(0,c+1),i,...e.pages.slice(c+1)],activePageId:i.id,pageId:i.id}},wf=(e,t,r=Io)=>{if(e.pages.length>=Ca)return null;const o={id:r(),url:null,route:"server",title:null,popupId:t.popupId},n=e.pages.findIndex(i=>i.id===t.openerPageId),a=n===-1?e.pages.length-1:n;return{pages:[...e.pages.slice(0,a+1),o,...e.pages.slice(a+1)],activePageId:o.id,pageId:o.id}},Bf=(e,t,r=Io)=>{const o=e.pages.findIndex(s=>s.id===t);if(o===-1)return e;const n=e.pages.filter(s=>s.id!==t);if(n.length===0){const s={id:r(),url:null,route:e.pages[o].route,title:null};return{pages:[s],activePageId:s.id}}if(e.activePageId!==t)return{pages:n,activePageId:Yi(n,e.activePageId)};const a=n[Math.min(o,n.length-1)];return{pages:n,activePageId:a.id}},Cf=(e,t)=>e.activePageId!==t&&e.pages.some(r=>r.id===t)?{...e,activePageId:t}:e,vf=(e,t,r)=>{let o=!1;const n=e.pages.map(a=>{if(a.id!==t)return a;const s={...a};if(r.url!==void 0){const i=vr(r.url);i&&i!==a.url&&(s.url=i)}return r.title!==void 0&&(s.title=Ji(r.title)),r.route!==void 0&&(s.route=kr(r.route)??a.route),r.defaultRoute!==void 0&&s.route===null&&(s.route=kr(r.defaultRoute)),r.popupId===null&&delete s.popupId,(s.url!==a.url||s.title!==a.title||s.route!==a.route||s.popupId!==a.popupId)&&(o=!0),o?s:a});return o?{...e,pages:n}:e},Tb=e=>{if(e.title)return e.title;if(!e.url)return"New tab";try{return new URL(e.url).host||e.url}catch{return e.url}},kf=380,Df=380,Sf=1400,Xi=12,ws=120,Mf=["git","file","diff","context","terminal","browser","preview","pull-requests","issues","extensions"],Tf=K,io=e=>Number.isFinite(e)?Math.min(Sf,Math.max(Df,Math.round(e))):kf,Rf=e=>{if(typeof e.width=="number"&&Number.isFinite(e.width))return io(e.width);if(!e.widthByMode||typeof e.widthByMode!="object")return;const t=e.widthByMode;for(const r of Mf){const o=t[r];if(typeof o=="number"&&Number.isFinite(o))return io(o)}for(const r of Object.values(t))if(typeof r=="number"&&Number.isFinite(r))return io(r)},bo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Ao=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>ws?t.slice(0,ws):t:null},va=e=>e==="server"||e==="device"?e:null,ka=e=>e==="all"||e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,Pf=(e,t)=>(e==="file"||e==="preview")&&t||e,Qi=(e,t,r)=>{if(e==="diff")return e;if(e==="browser")return Da;if(typeof r=="string"){const o=r.trim();if(o)return o}return Pf(e,t)},Cn=(e,t)=>t===e?e:`${e}:${t}`,Da="desktop-browser",Zi=`browser:${Da}`,If=(e,t)=>{let r=!1;const o=e.tabs.map(n=>{if(n.id!==Zi||!n.browser)return n;const a=t(n.browser);return a===n.browser?n:(r=!0,{...n,browser:{pages:a.pages,activePageId:a.activePageId}})});return r?{...e,tabs:o}:e},Sa=e=>{const t=bo(e.targetPath),r=Qi(e.mode,t,e.dedupeKey),o=Cn(e.mode,r),n=e.mode==="browser";return{id:o,mode:e.mode,targetPath:n?null:t,dedupeKey:r,label:Ao(e.label),sessionTitleFallback:Ao(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:ka(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),browser:n?Af({url:t,route:va(e.browserRoute)}):null,touchedAt:Date.now()}},ec=(e,t,r)=>{if(e.length<=t)return e;const n=[...e].sort((i,c)=>i.touchedAt-c.touchedAt).filter(i=>i.id!==r),a=e.length-t;if(a<=0||n.length===0)return e.slice(-t);const s=new Set(n.slice(0,a).map(i=>i.id));return e.filter(i=>!s.has(i.id))},tc=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const n=o;if(n.mode!=="diff"&&n.mode!=="file"&&n.mode!=="context"&&n.mode!=="preview"&&n.mode!=="browser"&&n.mode!=="git"&&n.mode!=="terminal"&&n.mode!=="pull-requests"&&n.mode!=="issues"&&n.mode!=="extensions")continue;const a=bo(typeof n.targetPath=="string"?n.targetPath:null),s=Qi(n.mode,a,typeof n.dedupeKey=="string"?n.dedupeKey:null),i=Cn(n.mode,s);if(!i||r.has(i))continue;r.add(i);const c=n.mode==="browser",d=typeof n.dedupeKey=="string"&&n.dedupeKey.trim()?n.dedupeKey.trim():"browser";t.push({id:i,mode:n.mode,targetPath:c?null:a,dedupeKey:s,label:Ao(typeof n.label=="string"?n.label:null),sessionTitleFallback:Ao(typeof n.sessionTitleFallback=="string"?n.sessionTitleFallback:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,diffScope:ka(n.diffScope)??(n.stagedDiff===!0?"staged":"working"),browser:c?bf(n.browser,{tabId:Cn("browser",d),url:a,route:va(n.browserRoute)}):null,touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()})}return t},Vt=(e,t)=>t&&e.some(r=>r.id===t)?t:e.length===0?null:e[e.length-1].id,mt=e=>{if(e){const t=tc(e.tabs),r=Vt(t,e.activeTabId);return{...e,tabs:t,activeTabId:r,width:e.width,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,touchedAt:Date.now()}},_f=(e,t)=>{const r=Sa(t),o=r.mode==="file"&&r.targetPath?e.tabs.filter(c=>!(c.mode==="file"&&!c.targetPath)):e.tabs,n=o.findIndex(c=>c.id===r.id),a=n===-1?[...o,r]:o.map((c,d)=>d===n?{...c,mode:r.mode,targetPath:r.targetPath||c.targetPath,dedupeKey:r.dedupeKey,label:r.label,sessionTitleFallback:r.sessionTitleFallback||c.sessionTitleFallback,stagedDiff:r.stagedDiff,diffScope:r.diffScope,browser:c.browser??r.browser,readOnly:r.readOnly,touchedAt:Date.now()}:c),s=r.id,i=ec(a,Xi,s);return{...e,isOpen:!0,tabs:i,activeTabId:Vt(i,s),touchedAt:Date.now()}},xf=(e,t)=>{const r=e.tabs.find(s=>s.id===t)??null,o=e.tabs.filter(s=>s.id!==t);if(e.activeTabId!==t)return{...e,tabs:o,activeTabId:Vt(o,e.activeTabId),isOpen:o.length>0?e.isOpen:!1,touchedAt:Date.now()};const n=r?o.filter(s=>s.mode===r.mode):[],a=n.length>0?n.reduce((s,i)=>i.touchedAt>=s.touchedAt?i:s):null;return{...e,tabs:o,activeTabId:a?.id??Vt(o,null),isOpen:a?e.isOpen:!1,touchedAt:Date.now()}},Of=(e,t,r)=>{if(t===r)return e;const o=e.tabs.findIndex(i=>i.id===t),n=e.tabs.findIndex(i=>i.id===r);if(o===-1||n===-1)return e;const a=[...e.tabs],[s]=a.splice(o,1);return s?(a.splice(n,0,s),{...e,tabs:a,touchedAt:Date.now()}):e},Nf=(e,t,r)=>({...e,tabs:e.tabs.map(o=>o.id===t?{...o,targetPath:r}:o)}),Lf=e=>{const t=[];let r=!1;for(const o of e){if(o.mode!=="diff"&&o.mode!=="git"){t.push(o);continue}r||(r=!0,t.push(o.mode==="git"?o:Sa({mode:"git"})))}return t},Ve=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=K(o);if(!a||!n||typeof n!="object")continue;const s=n;let i=Lf(tc(s.tabs)),c=typeof s.activeTabId=="string"?s.activeTabId:null;i.length===0&&(s.mode==="diff"||s.mode==="file"||s.mode==="context")&&(i=[Sa({mode:s.mode,targetPath:typeof s.targetPath=="string"?s.targetPath:null,dedupeKey:typeof s.dedupeKey=="string"?s.dedupeKey:null,label:typeof s.label=="string"?s.label:null})],c=i[0]?.id??null);const d=Vt(i,c),l=ec(i,Xi,d),u=Rf(s);r[a]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:l,activeTabId:Vt(l,d),...u!==void 0?{width:u}:{},touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},gt=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;r.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const o={};for(const[n,a]of r.slice(0,t))o[n]=a;return o},Bs=50,Uf=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const r=t.split("/");if(r.length!==3)return null;const[o,n,a]=r.map(s=>s.trim());return!o||!n||!a||n.length>100||a.length>100||o.length>253?null:`${o}/${n}/${a}`},Hf=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=K(o),s=Uf(n);!a||!s||(r[a]=s)}return r},Cs=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;const o={};for(const[n,a]of r.slice(-t))o[n]=a;return o};function vs(e){return e==="vim"?"vim":"default"}const dr=280,tn=new Map,rn=e=>(e??D()).trim()||"default",lr=(e,t,r,o)=>{const n=t(),a=n.contextPanelByDirectory[r];if(!a)return;const s=If(a,o);s!==a&&e({contextPanelByDirectory:{...n.contextPanelByDirectory,[r]:s}})},ie=Mr()(Tr(Qn((e,t)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:dr,hasManuallyResizedLeftSidebar:!1,contextPanelByDirectory:{},browserRoutePreference:null,chatLinkTarget:"system",contextRailOrder:[],contextEditorTreeVisible:!0,fileTreeReveal:null,gitReturnToFile:null,contextEditorTreeWidth:240,githubSelectedRepoByDirectory:{},isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingDiagramFile:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isSessionCreateDialogOpen:!1,isArchivePageOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showDeletionDialog:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:rf,monoFont:of,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:cf(),favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLinesOverride:null,wrapLinesByDefault:!0,walkthroughTocWidth:224,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnInputNeeded:!0,summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,timeFormatPreference:"auto",weekStartPreference:"auto",sidebarViewMode:uf,sessionAutoArchiveAfterDays:0,sessionAutoDeleteAfterDays:0,expandedEditorToolbar:!1,draftStartersVisible:!0,isExpandedInput:!1,shortcutOverrides:{},commandTriggers:[],fileEditorKeymap:"default",setTheme:r=>{e({theme:r}),t().applyTheme()},toggleSidebar:()=>{e(r=>{const o=!r.isSidebarOpen;return o&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:o,sidebarWidth:dr}:{isSidebarOpen:o}})},setSidebarOpen:r=>{e(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==dr?{isSidebarOpen:r,sidebarWidth:dr}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:dr}:{isSidebarOpen:r})},setSidebarWidth:r=>{e({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},setContextRailOrder:r=>{const o=Array.isArray(r)?r.filter((n,a)=>typeof n=="string"&&n.trim()!==""&&r.indexOf(n)===a):[];e({contextRailOrder:o})},toggleContextEditorTree:()=>{e(r=>({contextEditorTreeVisible:!r.contextEditorTreeVisible}))},revealInFileTree:r=>{e(o=>({fileTreeReveal:{path:r,nonce:(o.fileTreeReveal?.nonce??0)+1}}))},clearGitReturnToFile:()=>{t().gitReturnToFile&&e({gitReturnToFile:null})},showAllGitChanges:()=>{const r=t().gitReturnToFile;r?.focusPath&&e({gitReturnToFile:{...r,focusPath:null}})},clearFileTreeReveal:()=>{e({fileTreeReveal:null})},setContextEditorTreeWidth:r=>{Number.isFinite(r)&&e({contextEditorTreeWidth:Math.min(480,Math.max(200,Math.round(r)))})},setGitHubSelectedRepo:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{if(o==null){if(!(n in a.githubSelectedRepoByDirectory))return a;const i={...a.githubSelectedRepoByDirectory};return delete i[n],{githubSelectedRepoByDirectory:i}}const s=o.trim();return!s||a.githubSelectedRepoByDirectory[n]===s?a:{githubSelectedRepoByDirectory:Cs({...a.githubSelectedRepoByDirectory,[n]:s},Bs)}})},openContextSurface:(r,o)=>{const n=o==="diff"?"git":o,a=K((r||"").trim());if(!a)return;const s=t(),i=s.contextPanelByDirectory[a],c=i?.tabs??[],d=c.find(u=>u.id===i?.activeTabId)??null;if(i?.isOpen&&d?.mode===n){s.closeContextPanel(a);return}const l=c.filter(u=>u.mode===n);if(l.length>0){const u=l.reduce((f,m)=>m.touchedAt>=f.touchedAt?m:f);s.setActiveContextPanelTab(a,u.id);return}n!=="preview"&&s.openContextPanelTab(a,{mode:n})},openContextPanelTab:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{const s=a.contextPanelByDirectory[n],i=mt(s),c={...a.contextPanelByDirectory,[n]:_f(i,o)};return{contextPanelByDirectory:gt(c,20)}})},openContextDiff:(r,o,n=!1,a=null)=>{const s=K((r||"").trim()),i=(o||"").trim();if(!s||!i)return;const c=ka(a)??(n?"staged":"working"),d=t().contextPanelByDirectory[s],l=d?.isOpen?d.tabs.find(u=>u.id===d.activeTabId):void 0;t().setPendingDiffFile(i,n,c),t().openContextPanelTab(s,{mode:"git"}),e({gitReturnToFile:l?.mode==="file"?{directory:s,tabId:l.id,focusPath:i}:null})},openContextFile:(r,o)=>{const n=K((r||"").trim()),a=bo(o);!n||!a||(t().openContextPanelTab(n,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(a),t().setPendingFileNavigation(null))},openContextFileAtLine:(r,o,n,a)=>{const s=K((r||"").trim()),i=bo(o),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,d=Number.isFinite(a)?Math.max(1,Math.trunc(a)):1;!s||!i||(t().openContextPanelTab(s,{mode:"file",targetPath:i}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:i,line:c,column:d}))},openContextOverview:r=>{const o=K((r||"").trim());o&&t().openContextPanelTab(o,{mode:"context"})},openContextPreview:(r,o)=>{const n=K((r||"").trim()),a=(o||"").trim();if(!n||!a)return;let s=null;try{const i=new URL(a);(i.protocol==="http:"||i.protocol==="https:")&&(s=i.host||i.hostname||"Preview")}catch{}t().openContextPanelTab(n,{mode:"preview",targetPath:a,dedupeKey:a,label:s})},openContextBrowser:(r,o="",n)=>{const a=K((r||"").trim());if(!a)return;const s=typeof o=="string"&&o.trim().length>0?o.trim():"",i=!!t().contextPanelByDirectory[a]?.tabs.some(d=>d.id===Zi);if(t().openContextPanelTab(a,{mode:"browser",targetPath:i?null:s,dedupeKey:Da,label:"Browser",browserRoute:i?null:n?.route??null}),!i)return;const c=n?.target??(s?"new":null);c&&lr(e,t,a,d=>Ef(d,{url:s||null,route:n?.route??null,target:c}))},openBrowserPopup:(r,o,n)=>{const a=K((r||"").trim());if(!a)return!1;let s=!1;return lr(e,t,a,i=>{const c=wf(i,{openerPageId:o,popupId:n});return s=c!==null,c??i}),s},closeBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&lr(e,t,n,a=>Bf(a,o))},activateBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&lr(e,t,n,a=>Cf(a,o))},updateBrowserPage:(r,o,n)=>{const a=K((r||"").trim());a&&lr(e,t,a,s=>vf(s,o,n))},setBrowserRoutePreference:r=>{e({browserRoutePreference:va(r)})},setChatLinkTarget:r=>{e({chatLinkTarget:r==="pichamber"?"pichamber":"system"})},setContextPanelTabTargetPath:(r,o,n)=>{const a=K((r||"").trim()),s=(o||"").trim();!a||!s||e(i=>{const c=i.contextPanelByDirectory[a];return c?{contextPanelByDirectory:{...i.contextPanelByDirectory,[a]:Nf(c,s,n)}}:i})},setActiveContextPanelTab:(r,o)=>{const n=K((r||"").trim()),a=(o||"").trim();!n||!a||e(s=>{const i=s.contextPanelByDirectory[n],c=mt(i);if(!c.tabs.some(l=>l.id===a)||c.activeTabId===a&&c.isOpen)return s;const d={...s.contextPanelByDirectory,[n]:{...c,isOpen:!0,activeTabId:a,touchedAt:Date.now(),tabs:c.tabs.map(l=>l.id===a?{...l,touchedAt:Date.now()}:l)}};return{contextPanelByDirectory:gt(d,20)}})},reorderContextPanelTabs:(r,o,n)=>{const a=K((r||"").trim()),s=(o||"").trim(),i=(n||"").trim();!a||!s||!i||e(c=>{const d=c.contextPanelByDirectory[a],l=mt(d);if(!l.tabs.some(m=>m.id===s)||!l.tabs.some(m=>m.id===i))return c;const u=Of(l,s,i);if(u.tabs===l.tabs)return c;const f={...c.contextPanelByDirectory,[a]:u};return{contextPanelByDirectory:gt(f,20)}})},closeContextPanelTab:(r,o)=>{const n=K((r||"").trim()),a=(o||"").trim();if(!n||!a)return;const s=t().contextPanelByDirectory[n]?.tabs.find(i=>i.id===a);e(i=>{const c=i.contextPanelByDirectory[n],d=mt(c);if(!d.tabs.some(u=>u.id===a))return i;const l={...i.contextPanelByDirectory,[n]:xf(d,a)};return{contextPanelByDirectory:gt(l,20)}}),s?.mode==="file"&&s.targetPath&&pf.getState().removeOpenPath(n,s.targetPath)},closeContextPanel:r=>{const o=K((r||"").trim());o&&e(n=>{const a=n.contextPanelByDirectory[o];if(!a||!a.isOpen)return n;const s={...n.contextPanelByDirectory,[o]:{...mt(a),isOpen:!1}};return{contextPanelByDirectory:gt(s,20)}})},toggleContextPanelExpanded:r=>{const o=K((r||"").trim());o&&e(n=>{const a=n.contextPanelByDirectory[o],s=mt(a),i={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:gt(i,20)}})},setContextPanelWidth:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{const s=a.contextPanelByDirectory[n],i=mt(s),c={...a.contextPanelByDirectory,[n]:{...i,width:io(o)}};return{contextPanelByDirectory:gt(c,20)}})},setSessionSwitcherOpen:r=>{t().isSessionSwitcherOpen!==r&&e({isSessionSwitcherOpen:r})},setSessionDropdownOpen:r=>{t().isSessionDropdownOpen!==r&&e({isSessionDropdownOpen:r})},setMainTabGuard:r=>{t().mainTabGuard!==r&&e({mainTabGuard:r})},setActiveMainTab:r=>{const o=t().mainTabGuard;o&&!o(r)||(tn.set(rn(),r),e({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{tn.set(rn(r),t().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=tn.get(rn(r))??"chat";e({activeMainTab:o})},setPendingDiffFile:(r,o=!1,n=null)=>{e({pendingDiffFile:r,pendingDiffStaged:r?o:!1,pendingDiffScope:r?n:null})},setPendingDiagramFile:r=>{e({pendingDiagramFile:r})},setPendingFileNavigation:r=>{e({pendingFileNavigation:r})},setPendingFileFocusPath:r=>{e({pendingFileFocusPath:r})},navigateToDiff:(r,o=!1,n=null)=>{const a=t().mainTabGuard;a&&!a("diff")||e({pendingDiffFile:r,pendingDiffStaged:o,pendingDiffScope:n,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:r}=t();return r&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),r},navigateToDiagram:r=>{const o=t().mainTabGuard;o&&!o("diagram")||e({pendingDiagramFile:r,activeMainTab:"diagram"})},consumePendingDiagramFile:()=>{const{pendingDiagramFile:r}=t();return r&&e({pendingDiagramFile:null}),r},setIsMobile:r=>{e({isMobile:r})},toggleCommandPalette:()=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen}))},setCommandPaletteOpen:r=>{e({isCommandPaletteOpen:r})},toggleHelpDialog:()=>{e(r=>({isHelpDialogOpen:!r.isHelpDialogOpen}))},setHelpDialogOpen:r=>{e({isHelpDialogOpen:r})},setSessionCreateDialogOpen:r=>{e({isSessionCreateDialogOpen:r})},setArchivePageOpen:r=>{e({isArchivePageOpen:r})},closeMainSurfaces:()=>{t().isArchivePageOpen&&e({isArchivePageOpen:!1})},setSettingsDialogOpen:r=>{e(o=>r?o.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setModelSelectorOpen:r=>{e({isModelSelectorOpen:r})},setSidebarSection:r=>{e({sidebarSection:r})},setSettingsPage:r=>{e({settingsPage:r})},setSettingsProjectsSelectedId:r=>{e({settingsProjectsSelectedId:r})},setSettingsRemoteInstancesSelectedId:r=>{e({settingsRemoteInstancesSelectedId:r})},setEventStreamStatus:(r,o)=>{e({eventStreamStatus:r,eventStreamHint:o??null})},setShowDeletionDialog:r=>{e({showDeletionDialog:r})},setAutoDeleteEnabled:r=>{e({autoDeleteEnabled:r})},setAutoSaveEnabled:r=>{e({autoSaveEnabled:r})},setAutoDeleteAfterDays:r=>{const o=Math.max(1,Math.min(365,r));e({autoDeleteAfterDays:o})},setSessionRetentionAction:r=>{e({sessionRetentionAction:r})},setAutoDeleteLastRunAt:r=>{e({autoDeleteLastRunAt:r})},setMessageLimit:r=>{const o=Math.max(10,Math.min(500,Math.round(r)));e({messageLimit:o})},setFontSize:r=>{const o=Math.max(50,Math.min(200,r));e({fontSize:o}),t().applyTypography()},setGlobalDraftStarters:r=>{e({globalDraftStarters:r})},setDraftStartersVisible:r=>{e({draftStartersVisible:r})},setTerminalFontSize:r=>{const o=Math.round(r),n=Math.max(9,Math.min(52,o));e({terminalFontSize:n})},setTerminalShell:r=>{e({terminalShell:r})},setTerminalLoginShells:r=>{e({terminalLoginShells:[...new Set(r)]})},setEditorFontSize:r=>{const o=Math.round(r),n=Math.max(9,Math.min(32,o));e({editorFontSize:n})},setUiFont:r=>{e({uiFont:r})},setMonoFont:r=>{e({monoFont:r})},setPadding:r=>{const o=Math.max(50,Math.min(200,r));e({padding:o}),t().applyPadding()},setCornerRadius:r=>{e({cornerRadius:r})},applyTypography:()=>{const{fontSize:r}=t(),o=document.documentElement,n=r/100,a=Object.entries(Xu);if(n===1){for(const[s]of a)o.style.removeProperty(As(s));return}for(const[s,i]of a){const c=parseFloat(i);Number.isFinite(c)&&o.style.setProperty(As(s),`${c*n}rem`)}},applyPadding:()=>{const{padding:r}=t(),o=document.documentElement,n=r/100;if(n===1){o.style.removeProperty("--padding-scale"),o.style.removeProperty("--line-height-tight"),o.style.removeProperty("--line-height-normal"),o.style.removeProperty("--line-height-relaxed"),o.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(n);o.style.setProperty("--padding-scale",a.toString());const s=1+(n-1)*.15;o.style.setProperty("--line-height-tight",(1.25*s).toFixed(3)),o.style.setProperty("--line-height-normal",(1.5*s).toFixed(3)),o.style.setProperty("--line-height-relaxed",(1.625*s).toFixed(3)),o.style.setProperty("--line-height-loose",(2*s).toFixed(3))},setDiffLayoutPreference:r=>{e({diffLayoutPreference:r})},setDiffFileLayout:(r,o)=>{e(n=>({diffFileLayout:{...n.diffFileLayout,[r]:o}}))},setDiffWrapLines:r=>{e({diffWrapLinesOverride:r})},setWrapLinesByDefault:r=>{e({wrapLinesByDefault:r,diffWrapLinesOverride:null})},setWalkthroughTocWidth:r=>{e({walkthroughTocWidth:Math.round(r)})},setGitChangesViewMode:r=>{e({gitChangesViewMode:r})},setInputBarOffset:r=>{e({inputBarOffset:r})},setMobileKeyboardMode:r=>{e(o=>o.mobileKeyboardMode===r?o:{mobileKeyboardMode:r})},toggleFavoriteModel:(r,o)=>{e(n=>n.favoriteModels.some(s=>s.providerID===r&&s.modelID===o)?{favoriteModels:n.favoriteModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{favoriteModels:[{providerID:r,modelID:o},...n.favoriteModels]})},reorderFavoriteModel:(r,o,n,a)=>{e(s=>{const i=s.favoriteModels.findIndex(u=>u.providerID===r&&u.modelID===o),c=s.favoriteModels.findIndex(u=>u.providerID===n&&u.modelID===a);if(i===-1||c===-1||i===c)return s;const d=s.favoriteModels.slice(),[l]=d.splice(i,1);return l?(d.splice(c,0,l),{favoriteModels:d}):s})},toggleHiddenModel:(r,o)=>{e(n=>n.hiddenModels.some(s=>s.providerID===r&&s.modelID===o)?{hiddenModels:n.hiddenModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{hiddenModels:[{providerID:r,modelID:o},...n.hiddenModels]})},isHiddenModel:(r,o)=>{const{hiddenModels:n}=t();return n.some(a=>a.providerID===r&&a.modelID===o)},hideAllModels:(r,o)=>{e(n=>{const a=n.hiddenModels.filter(i=>i.providerID!==r);return{hiddenModels:[...[...new Set(o.filter(i=>typeof i=="string"&&i.length>0))].map(i=>({providerID:r,modelID:i})),...a]}})},showAllModels:r=>{e(o=>({hiddenModels:o.hiddenModels.filter(n=>n.providerID!==r)}))},toggleModelProviderCollapsed:r=>{const o=typeof r=="string"?r.trim():"";o&&e(n=>n.collapsedModelProviders.includes(o)?{collapsedModelProviders:n.collapsedModelProviders.filter(s=>s!==o)}:{collapsedModelProviders:[...n.collapsedModelProviders,o]})},setModelProvidersCollapsed:(r,o)=>{const n=Array.from(new Set(r.filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean)));n.length!==0&&e(a=>{const s=new Set(n),i=a.collapsedModelProviders.filter(c=>!s.has(c));return{collapsedModelProviders:o?[...i,...n]:i}})},isFavoriteModel:(r,o)=>{const{favoriteModels:n}=t();return n.some(a=>a.providerID===r&&a.modelID===o)},addRecentModel:(r,o)=>{e(n=>{const a=n.recentModels.filter(s=>!(s.providerID===r&&s.modelID===o));return{recentModels:[{providerID:r,modelID:o},...a].slice(0,5)}})},addRecentAgent:r=>{const o=typeof r=="string"?r.trim():"";o&&e(n=>{if(n.recentAgents.includes(o))return n;const a=n.recentAgents;return{recentAgents:[o,...a].slice(0,5)}})},addRecentEffort:(r,o,n)=>{const a=typeof r=="string"?r.trim():"",s=typeof o=="string"?o.trim():"";if(!a||!s)return;const i=`${a}/${s}`,c=typeof n=="string"&&n.trim().length>0?n.trim():"default";e(d=>{const l=d.recentEfforts[i]??[];if(l.includes(c))return d;const u=l;return{recentEfforts:{...d.recentEfforts,[i]:[c,...u].slice(0,5)}}})},applyTheme:()=>{const{theme:r}=t(),o=document.documentElement;if(o.classList.remove("light","dark"),r==="system"){const n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(n)}else o.classList.add(r)},setTimelineDialogOpen:r=>{e({isTimelineDialogOpen:r})},setPromptNavigatorPanelOpen:r=>{e({isPromptNavigatorPanelOpen:r})},togglePromptNavigatorPanel:()=>{e(r=>({isPromptNavigatorPanelOpen:!r.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:r=>{e({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{e({nativeNotificationsEnabled:r})},setNotificationMode:r=>{e({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{e({showTerminalQuickKeysOnDesktop:r})},setDockBadgeEnabled:r=>{e({dockBadgeEnabled:r})},setNotifyOnCompletion:r=>{e({notifyOnCompletion:r})},setNotifyOnError:r=>{e({notifyOnError:r})},setNotifyOnInputNeeded:r=>{e({notifyOnInputNeeded:r})},setSummarizeLastMessage:r=>{e({summarizeLastMessage:r})},setSummaryThreshold:r=>{e({summaryThreshold:r})},setSummaryLength:r=>{e({summaryLength:r})},setMaxLastMessageLength:r=>{e({maxLastMessageLength:r})},setTimeFormatPreference:r=>{e({timeFormatPreference:r})},setWeekStartPreference:r=>{e({weekStartPreference:r})},setSidebarViewMode:r=>{e({sidebarViewMode:r})},setSessionAutoArchiveAfterDays:r=>{Wt(r)&&e({sessionAutoArchiveAfterDays:r})},setSessionAutoDeleteAfterDays:r=>{Wt(r)&&e({sessionAutoDeleteAfterDays:r})},setExpandedEditorToolbar:r=>{e({expandedEditorToolbar:r})},viewPagerPage:"center",setViewPagerPage:r=>{e({viewPagerPage:r}),e({isSessionSwitcherOpen:r==="left"})},setShortcutOverride:(r,o)=>{e(n=>({shortcutOverrides:{...n.shortcutOverrides,[r]:o}}))},clearShortcutOverride:r=>{e(o=>{const n={...o.shortcutOverrides};return delete n[r],{shortcutOverrides:n}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:r=>{e({fileEditorKeymap:vs(r)})},toggleExpandedInput:()=>{e(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{e({isExpandedInput:r})}}),{name:"ui-store",storage:ca(),version:21,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const r=e;if(t<21&&(delete r.diffWrapLines,delete r.diffWrapLinesOverride,typeof r.wrapLinesByDefault!="boolean"&&(r.wrapLinesByDefault=!0)),t<20&&(delete r.notifyOnSubtasks,delete r.notifyOnQuestion,delete r.notificationTemplates),t<19&&(delete r.showReasoningTraces,delete r.collapsibleThinkingBlocks,delete r.collapseThinkingByDefault,delete r.persistChatDraft,delete r.inputSpellcheckEnabled,delete r.wideChatLayoutEnabled,delete r.codeBlockLineWrap,delete r.showToolFileIcons,delete r.showTurnChangedFiles,delete r.showExpandedBashTools,delete r.showExpandedEditTools,delete r.desktopWindowControlsPosition,delete r.desktopWindowControlsStyle,delete r.mermaidRenderingMode,delete r.userMessageRenderingMode,delete r.collapsibleUserMessages,delete r.stickyUserHeader,delete r.promptNavigatorEnabled,delete r.showSplitAssistantMessageActions),t<18&&(delete r.notesPanelHeight,delete r.todoPanelHeight,r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="notes"))),t<17&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="chat"))),t<16&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="chat"))),t<15&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="pr"))),t<14&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),Array.isArray(r.contextRailOrder)&&(r.contextRailOrder=r.contextRailOrder.filter(o=>o!=="diff"))),t<13&&typeof r.autoSaveEnabled!="boolean"){let o=!0;try{if(typeof localStorage<"u"){const n=localStorage.getItem("pichamber:files:auto-save-enabled");n!==null&&(o=n!=="false",localStorage.removeItem("pichamber:files:auto-save-enabled"))}}catch{o=!0}r.autoSaveEnabled=o}if(t<12&&(delete r.desktopWindowControlsPosition,delete r.desktopWindowControlsStyle),t<11&&r.terminalFontSize===13&&(r.terminalFontSize=14),t<10&&delete r.diffViewMode,t<9&&((typeof r.notesPanelHeight!="number"||!Number.isFinite(r.notesPanelHeight))&&(r.notesPanelHeight=112),(typeof r.todoPanelHeight!="number"||!Number.isFinite(r.todoPanelHeight))&&(r.todoPanelHeight=259)),t<3){const o=new Set([90,120,180,220]),n=r.memoryLimitHistorical,a=r.memoryLimitActiveSession;typeof n=="number"&&!o.has(n)?r.messageLimit=n:typeof a=="number"&&!o.has(a)&&(r.messageLimit=a),delete r.memoryLimitHistorical,delete r.memoryLimitViewport,delete r.memoryLimitActiveSession}if(delete r.isRightSidebarOpen,delete r.rightSidebarWidth,delete r.rightSidebarTab,delete r.workStatusExpandedSections,delete r.workStatusScrollTop,delete r.workStatusPanelEnabled,delete r.workStatusHiddenSections,delete r.showReasoningTraces,delete r.collapsibleThinkingBlocks,delete r.collapseThinkingByDefault,delete r.persistChatDraft,delete r.inputSpellcheckEnabled,delete r.wideChatLayoutEnabled,delete r.codeBlockLineWrap,delete r.showToolFileIcons,delete r.showTurnChangedFiles,delete r.showExpandedBashTools,delete r.showExpandedEditTools,delete r.desktopWindowControlsPosition,delete r.desktopWindowControlsStyle,delete r.mermaidRenderingMode,delete r.userMessageRenderingMode,delete r.collapsibleUserMessages,delete r.stickyUserHeader,delete r.promptNavigatorEnabled,delete r.showSplitAssistantMessageActions,delete r.diffWrapLines,r.contextPanelByDirectory=Ve(r.contextPanelByDirectory),t<5)if(!r.shortcutOverrides||typeof r.shortcutOverrides!="object")r.shortcutOverrides={};else{const o=r.shortcutOverrides,n={};for(const[a,s]of Object.entries(o))typeof a=="string"&&typeof s=="string"&&(n[a]=s);r.shortcutOverrides=n}return t<6&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory)),t<7&&(r.contextPanelByDirectory=Ve(r.contextPanelByDirectory)),t<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=vs(r.fileEditorKeymap),r.githubSelectedRepoByDirectory=Cs(Hf(r.githubSelectedRepoByDirectory),Bs),typeof r.autoSaveEnabled!="boolean"&&(r.autoSaveEnabled=!0),typeof r.wrapLinesByDefault!="boolean"&&(r.wrapLinesByDefault=!0),r.contextRailOrder=Array.isArray(r.contextRailOrder)?r.contextRailOrder.filter(o=>typeof o=="string"&&o.trim()!==""&&o!=="pr"&&o!=="diff"&&o!=="chat"&&o!=="notes"):[],r},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,browserRoutePreference:e.browserRoutePreference,chatLinkTarget:e.chatLinkTarget,contextRailOrder:e.contextRailOrder,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,githubSelectedRepoByDirectory:e.githubSelectedRepoByDirectory,isSessionSwitcherOpen:e.isSessionSwitcherOpen,activeMainTab:e.activeMainTab,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showDeletionDialog:e.showDeletionDialog,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,wrapLinesByDefault:e.wrapLinesByDefault,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnInputNeeded:e.notifyOnInputNeeded,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,sidebarViewMode:e.sidebarViewMode,sessionAutoArchiveAfterDays:e.sessionAutoArchiveAfterDays,sessionAutoDeleteAfterDays:e.sessionAutoDeleteAfterDays,expandedEditorToolbar:e.expandedEditorToolbar,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Rb=Object.freeze(Object.defineProperty({__proto__:null,normalizeContextPanelDirectoryKey:Tf,useUIStore:ie},Symbol.toStringTag,{value:"Module"}));let ks="idle";const jf=new Set;let Xr=null;const Ae=e=>{Xr&&(clearTimeout(Xr),Xr=null);const t=e==="saved"?"idle":e;t!==ks&&(ks=t,jf.forEach(r=>r())),t==="error"&&(Xr=setTimeout(()=>Ae("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("pichamber:settings-save-state",{detail:e}))},Pb=e=>{Ae(e)},$f=e=>{if(!(typeof window>"u")&&!(typeof window.__PICHAMBER_HOME__=="string"&&window.__PICHAMBER_HOME__.length>0))try{window.__PICHAMBER_HOME__=e}catch{}},Ds="pichamber.settingsMirror.v2.index",Kf="pichamber.settingsMirror.v2:",zf=5,Ss=e=>`${Kf}${encodeURIComponent(e)}`,pt=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},qf=(e,t)=>{const r={themeId:e.themeId,themeVariant:e.themeVariant,lightThemeId:e.lightThemeId,darkThemeId:e.darkThemeId,useSystemTheme:e.useSystemTheme,lastDirectory:e.lastDirectory,homeDirectory:e.homeDirectory,projects:e.projects,activeProjectId:e.activeProjectId,pinnedDirectories:e.pinnedDirectories,filesViewShowGitignored:e.filesViewShowGitignored,openInAppId:e.openInAppId,pwaAppName:e.pwaAppName,mobileKeyboardMode:e.mobileKeyboardMode};localStorage.setItem(Ss(t),JSON.stringify(r));let o=[];try{const a=JSON.parse(localStorage.getItem(Ds)??"[]");Array.isArray(a)&&(o=a.filter(s=>typeof s=="string"))}catch{o=[]}const n=[t,...o.filter(a=>a!==t)].slice(0,zf);for(const a of o)n.includes(a)||localStorage.removeItem(Ss(a));localStorage.setItem(Ds,JSON.stringify(n))},Gf=e=>{if(!(typeof window>"u")){if(qf(e,D()),pt("selectedThemeId",e.themeId||null),pt("selectedThemeVariant",e.themeVariant||null),pt("lightThemeId",e.lightThemeId||null),pt("darkThemeId",e.darkThemeId||null),pt("useSystemTheme",typeof e.useSystemTheme=="boolean"?String(e.useSystemTheme):null),pt("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),$f(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(r=>r.sidebarCollapsed===!0).map(r=>r.id).filter(r=>typeof r=="string"&&r.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),pt("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=Wi(e.pwaAppName,"");t.length>0?localStorage.setItem(en,t):localStorage.removeItem(en)}else localStorage.removeItem(en);df(e.mobileKeyboardMode)}},vn=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("pichamber:settings-synced",{detail:e}))},Wf=()=>{const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();if(typeof e?.getRandomValues!="function")throw new Error("Secure random UUID is unavailable in this browser context");const t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const r=Array.from(t,o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},Vf=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const r=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,a)=>a.toUpperCase()+":");return r==="/"?"/":(r.length>1?r.replace(/\/+$/,""):r)||null},Ma="queue",Ta=e=>e==="steer"||e==="queue",Ra=(e,t)=>e==="immediate"?"steer":Ta(e)?e:t===!1?"steer":t===!0?"queue":Ma,Ms=50,Ts=20,on=(e,t)=>{if(e.runtimeKey!==D())return;const r=t.flatMap(o=>(o.attachments??[]).flatMap(n=>n.uploadState?.status==="ready"?[n.uploadState.attachmentId]:[]));for(const o of new Set(r))yt.deleteAttachment(o,{runtimeKey:e.runtimeKey}).catch(()=>{})},Jf=(e,t,r=D())=>{const o=Vf(t);return!r||!o||!e?null:{runtimeKey:r,directory:o,sessionId:e}},ne=e=>`${e.runtimeKey}
|
|
8
8
|
${e.directory}
|
|
9
9
|
${e.sessionId}`,Yf=e=>{const[t,r,...o]=e.split(`
|
|
10
10
|
`);return Jf(o.join(`
|