@pi-chamber/web 1.0.8-rc.3 → 1.0.8-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/assets/{AgentsSurface-wsW9VCRp.js → AgentsSurface-DbCBygRD.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-EwCf4Yxu.js → ChoicesArtifact-DUqhCvXh.js} +1 -1
  3. package/dist/assets/{DiagramView-BX6N99cQ.js → DiagramView-CnVOyJd2.js} +1 -1
  4. package/dist/assets/{DiffView-CI0eSnPP.js → DiffView-Db8JXsvA.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-GLj2W7VE.js → FileSaveConflictDialog-D6xyf709.js} +1 -1
  6. package/dist/assets/{FilesView-CI0tfZQL.js → FilesView-Cir0Wl9F.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-B85tZ9m7.js → GitHubDetailScaffold-US37Di_K.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-Y6AuNiGl.js → GitHubLinkPicker-k_D-sk-e.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-BJHBud6i.js → GitHubListPrimitives-DuUXrJGk.js} +1 -1
  10. package/dist/assets/{GitView-DueE69kW.js → GitView-BdX_3XRr.js} +3 -3
  11. package/dist/assets/{IssuesSurface-Cg-xkdIu.js → IssuesSurface-Cw93HC0G.js} +2 -2
  12. package/dist/assets/{JsonTreeView-Cvg6lc40.js → JsonTreeView-Bze4htWt.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-DExPx-QM.js → MarkdownRendererImpl-Ch7NDkF9.js} +1 -1
  14. package/dist/assets/{PatchDiff-_c3HZ34I.js → PatchDiff-l68Yz45X.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-CZnaqO-_.js → PierreDiffViewer-BHBySiXQ.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-C9AYPiwo.js → PullRequestsSurface-CGD4_ljc.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-DOpnN-8S.js → SessionSwitcherContent-DqP8OWzB.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-CmHMPZ69.js → SessionSwitcherDropdown-BkTg-cVd.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-CZCQ4t1J.js → SessionUnreadDot-CgvC3F5e.js} +1 -1
  20. package/dist/assets/{SettingsView-D5PO5M3z.js → SettingsView-CkIxCYhs.js} +3 -3
  21. package/dist/assets/{SettingsWindow-DXV5UOE8.js → SettingsWindow-DSdhzapT.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-CO1ZiI1x.js → SubagentsArtifact-BN3aX_8M.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-GOwNLj-y.js → ToolOutputDialog-CLwm4TjA.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-BoaiZji6.js → ToolPartDiffPreview-ERAStEKA.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-Chq1X8nw.js → VirtualizedFileDiff-DwR2fZHv.js} +1 -1
  26. package/dist/assets/{VisualFrame-u7aRcX7O.js → VisualFrame-Dwp7B_st.js} +1 -1
  27. package/dist/assets/{VisualsArtifact-D9vPjihW.js → VisualsArtifact-DlOxifHd.js} +1 -1
  28. package/dist/assets/{collapsible-BjpDEohv.js → collapsible-CW-_qd6v.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DmPCxbok.js → computeVirtualFileMetrics-SlBfr8LB.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-CukNcUeY.js → contextFileOpenGuard-CHoFT50j.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CDyfNPYO.js → fileTreeStatus-D0uiC1D0.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-uI7Y7L5k.js → gitStatusPredicates-Bj3pkh2e.js} +1 -1
  33. package/dist/assets/{githubLink-B9Mxac4R.js → githubLink-CheLNuP0.js} +1 -1
  34. package/dist/assets/{index-BxKPJ9uG.js → index-BFkW-BPM.js} +3 -3
  35. package/dist/assets/{index-BWq2ibCw.js → index-C8zaLvup.js} +1 -1
  36. package/dist/assets/{main-ckQ0ciIN.js → main-CUEqZRu1.js} +2 -2
  37. package/dist/assets/{main-CWfC-9xT.js → main-V66ie29o.js} +4 -4
  38. package/dist/assets/{markdownCore-p2q2Kxwo.js → markdownCore-BRedKgCo.js} +1 -1
  39. package/dist/assets/{miniChat-x2TrwRYA.js → miniChat-BXwuEQhz.js} +2 -2
  40. package/dist/assets/{mobile-B0x2G8h1.js → mobile-7s-xLDG3.js} +2 -2
  41. package/dist/assets/{nativeFileSave-D542OJlG.js → nativeFileSave-Bj-V_9ae.js} +1 -1
  42. package/dist/assets/{pi-session-focus-preference-Q_RZUCnt.js → pi-session-focus-preference-clbekCjz.js} +1 -1
  43. package/dist/assets/{renderDiffWithHighlighter-CSFGSknx.js → renderDiffWithHighlighter-g9eKWi78.js} +1 -1
  44. package/dist/assets/{renderElectronMiniChatApp-CFIdesZT.js → renderElectronMiniChatApp-B6BN8YgC.js} +2 -2
  45. package/dist/assets/{renderFileWithHighlighter-C5JE0mRX.js → renderFileWithHighlighter-DKl6vubK.js} +1 -1
  46. package/dist/assets/{renderMobileApp-B1ybjcGM.js → renderMobileApp-Bp735rW7.js} +3 -3
  47. package/dist/assets/{runtimeEndpointReset-DyZSKCYM.js → runtimeEndpointReset-CtHv_OMT.js} +7 -7
  48. package/dist/assets/{runtimeSurface-BR_dhe7_.js → runtimeSurface-DD4Vn4HC.js} +1 -1
  49. package/dist/assets/{selection-CfOpW4rA.js → selection-DDT954wY.js} +1 -1
  50. package/dist/assets/useAppFontEffects-DJCrUN2D.js +226 -0
  51. package/dist/assets/{useGitHubRemoteSearch-M1AE2YuX.js → useGitHubRemoteSearch-B77fMiwQ.js} +1 -1
  52. package/dist/assets/{useSwitcherItems-D0i2BYYP.js → useSwitcherItems-CFY3mP06.js} +1 -1
  53. package/dist/assets/{web-components-wOQkOurQ.js → web-components-XIP_3VZv.js} +1 -1
  54. package/dist/index.html +3 -3
  55. package/dist/mini-chat.html +2 -2
  56. package/dist/mobile.html +2 -2
  57. package/package.json +2 -1
  58. package/pichamber.d.ts +139 -0
  59. package/plugins/subagents/extension.js +5 -5
  60. package/plugins/subagents/package.json +3 -2
  61. package/plugins/visuals/choices.js +8 -7
  62. package/plugins/visuals/extension.js +4 -4
  63. package/plugins/visuals/package.json +1 -1
  64. package/server/lib/marketplace/DOCUMENTATION.md +2 -2
  65. package/server/lib/marketplace/npm-registry.js +1 -1
  66. package/server/lib/marketplace/npm-registry.test.js +1 -1
  67. package/server/lib/marketplace/service.test.js +4 -4
  68. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  69. package/server/lib/pi/extension-card.js +48 -0
  70. package/server/lib/pi/extension-card.test.js +35 -0
  71. package/server/lib/pi/extension-commands.js +49 -0
  72. package/server/lib/pi/extension-commands.test.js +38 -0
  73. package/server/lib/pi/extension-protocol.js +1 -2
  74. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +52 -223
  75. package/server/lib/pi/routes-extension-events.test.js +35 -48
  76. package/server/lib/pi/routes.js +44 -54
  77. package/server/lib/pi/routes.test.js +32 -0
  78. package/server/lib/pi/session-daemon/DOCUMENTATION.md +7 -7
  79. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +0 -54
  80. package/server/lib/pi/session-daemon/extension-bridge.js +39 -162
  81. package/server/lib/pi/session-daemon/extension-controls.js +12 -57
  82. package/server/lib/pi/session-daemon/extension-controls.test.js +4 -34
  83. package/server/lib/pi/session-daemon/pichamber-api.js +38 -0
  84. package/server/lib/pi/session-daemon/pichamber-api.test.js +24 -0
  85. package/server/lib/pi/session-daemon/plugin-host.js +5 -7
  86. package/server/lib/pi/session-daemon/plugin-host.test.js +2 -3
  87. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +53 -7
  88. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +5 -5
  89. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +9 -4
  90. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +28 -71
  91. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +1 -1
  92. package/server/lib/pi/session-daemon/session-daemon.js +138 -78
  93. package/server/lib/pi/session-daemon/session-daemon.test.js +68 -0
  94. package/server/lib/plugins/DOCUMENTATION.md +3 -3
  95. package/server/lib/plugins/impact.js +2 -4
  96. package/server/lib/plugins/impact.test.js +0 -1
  97. package/server/lib/plugins/manifest.js +9 -5
  98. package/server/lib/plugins/manifest.test.js +5 -4
  99. package/server/lib/plugins/store.test.js +1 -1
  100. package/server/lib/plugins/visuals-extension.test.js +16 -14
  101. package/dist/assets/useAppFontEffects-COMvkffC.js +0 -226
  102. package/server/lib/pi/session-daemon/pichamber-ui.js +0 -44
@@ -1,10 +1,10 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nativeFileSave-D542OJlG.js","assets/vendor-boot-D-KEJjsM.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 xr,d as Or,p as aa}from"./vendor-zustand-CXhN0IMY.js";import{_ as qc}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Wc}from"./vendor-clsx-B-dksMZM.js";import{t as Gc}from"./vendor-tailwind-merge-BKkUfl9q.js";import{e as ri}from"./vendor-fuse.js-t_7AcMTv.js";import{R as Xa}from"./vendor-react-Bz1tRBxM.js";const br=1,Vc="pichamber-relay-v1",oi=1,ni=12,Ar=1+ni,Dr=64*1024,Sr=5,go=128,ai=0,si=1,Wt=4,Jc=1+Wt,gn=Dr-Sr-Jc,O={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Yc=new Set(Object.values(O)),Xc=e=>Yc.has(e),wt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},je=globalThis.crypto.subtle,ii={name:"ECDH",namedCurve:"P-256"},ci=16,zo=32,Qc=16,pn=4,di=8;class tt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Zc=()=>je.generateKey(ii,!0,["deriveBits"]),ed=async e=>{const t=await je.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},td=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 je.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},ii,!0,[])}catch{throw new tt("invalid ECDH public key JWK")}},rd=()=>{const e=new Uint8Array(ci);return globalThis.crypto.getRandomValues(e),e},od=async(e,t,r)=>{if(r.length!==ci)throw new tt("invalid handshake nonce length");const o=await je.deriveBits({name:"ECDH",public:t},e,256),n=await je.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=new Uint8Array(await je.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(Vc)},n,zo*2*8)),s=(i,c)=>je.importKey("raw",i,{name:"AES-GCM"},!1,c);return{clientToHost:await s(a.slice(0,zo),["encrypt","decrypt"]),hostToClient:await s(a.slice(zo),["encrypt","decrypt"])}},nd=(e,t,r)=>{for(let o=di-1;o>=0;o-=1)e[t+o]=Number(r&0xffn),r>>=8n},ad=(e,t)=>{let r=0n;for(let o=0;o<di;o+=1)r=r<<8n|BigInt(e[t+o]);return r},sd=e=>{const t=new Uint8Array(pn);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(o){if(o.length>Dr)throw new tt("plaintext frame exceeds maximum size");r+=1n;const n=new Uint8Array(ni);n.set(t,0),nd(n,pn,r);const a=new Uint8Array(await je.encrypt({name:"AES-GCM",iv:n},e,o)),s=new Uint8Array(Ar+a.length);return s[0]=oi,s.set(n,1),s.set(a,Ar),s}}},id=e=>{let t=0n;return{async decrypt(r){if(r.length<Ar+Qc)throw new tt("encrypted frame too short");if(r[0]!==oi)throw new tt("unsupported encrypted frame version");const o=r.slice(1,Ar),n=ad(o,pn);if(n<=t)throw new tt("frame counter regression");let a;try{a=await je.decrypt({name:"AES-GCM",iv:o},e,r.slice(Ar))}catch{throw new tt("frame decryption failed")}return t=n,new Uint8Array(a)}}},Wr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",cd=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+=Wr[o>>2],t+=Wr[(o&3)<<4|(n??0)>>4],n!==void 0&&(t+=Wr[(n&15)<<2|(a??0)>>6]),a!==void 0&&(t+=Wr[a&63])}return t},Qa=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!==br)return null;const o=r.batch===!0;return r.t==="ready"?{t:"ready",v:br,batch:o}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:br,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:o}:null},dd=e=>({type:"fail",closeCode:wt.ChannelFailure,reason:e}),ld=async(e,t={})=>{const r=t.batch!==!1,o=await td(e),n=await Zc(),a=rd(),s={t:"hello",v:br,clientPubJwk:await ed(n.publicKey),nonce:cd(a),...r?{batch:!0}:{}};let i=!1;return{helloText:JSON.stringify(s),get established(){return i},async handleText(c){if(i)return Qa(c)?.t==="ready"?{type:"ignore"}:dd("plaintext frame on established channel");const d=Qa(c);if(d?.t!=="ready")return{type:"ignore"};const l=await od(n.privateKey,o,a);return i=!0,{type:"established",batch:r&&d.batch===!0,channel:{encryptor:sd(l.clientToHost),decryptor:id(l.hostToClient)}}}}},li=4294967295;class ne extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Pe=(e,t,r,o=!1)=>{if(!Number.isInteger(t)||t<0||t>li)throw new ne("invalid stream id");if(r.length>gn)throw new ne("tunnel payload exceeds maximum size");const n=new Uint8Array(Sr+r.length);return n[0]=o?e|go:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(r,Sr),n},ud=e=>{if(e.length<Sr)throw new ne("tunnel frame too short");const t=e[0],r=(t&go)!==0,o=t&~go;if(!Xc(o))throw new ne(`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(Sr),hasMoreFragments:r}},fd=new TextEncoder,md=new TextDecoder,po=e=>fd.encode(JSON.stringify(e)),ho=(e,t)=>{let r;try{r=JSON.parse(md.decode(e))}catch{throw new ne("malformed JSON tunnel payload")}if(!t(r))throw new ne("unexpected JSON tunnel payload shape");return r},ui=(e,t=gn)=>{if(t<=0||t>gn)throw new ne("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},Za=(e,t,r)=>{const o=ui(r);return o.map((n,a)=>Pe(e,t,n,a<o.length-1))},gd=(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 ne("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)}}},pd=e=>{if(e.length===0)throw new ne("cannot encode an empty frame batch");if(e.length===1){const n=e[0],a=new Uint8Array(1+n.length);if(a[0]=ai,a.set(n,1),a.length>Dr)throw new ne("frame batch exceeds maximum plaintext size");return a}let t=1;for(const n of e)t+=Wt+n.length;if(t>Dr)throw new ne("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=si;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+=Wt,r.set(n,o),o+=n.length;return r},hd=e=>{if(e.length<1)throw new ne("empty batch plaintext");const t=e[0];if(t===ai)return[e.slice(1)];if(t!==si)throw new ne(`unknown batch container tag ${t}`);const r=[];let o=1;for(;o<e.length;){if(o+Wt>e.length)throw new ne("truncated batch frame length");const n=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;if(o+=Wt,o+n>e.length)throw new ne("truncated batch frame body");r.push(e.slice(o,o+n)),o+=n}if(r.length===0)throw new ne("empty frame batch");return r},Fd=new Set([O.HttpBody,O.WsText,O.WsBinary]),fi=150,yd=24*1024,bd=32,Ad=e=>{const t=e.windowMs??fi,r=e.maxBatchBytes??yd,o=e.maxBatchFrames??bd,n=e.now??(()=>Date.now()),a=e.setTimer??((h,p)=>setTimeout(h,p)),s=e.clearTimer??(h=>clearTimeout(h));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 h=i;i=[],c=0,l=n(),e.sendBatch(pd(h))};return{enqueue:h=>{if(u)return;const p=h[0]&~go;if(!Fd.has(p)){i.push(h),m();return}const k=n();if(i.length===0&&k-l>=t){i.push(h),m();return}const A=Wt+h.length;if(i.length>0&&1+c+A>Dr&&m(),i.push(h),c+=A,c>=r||i.length>=o){m();return}d===null&&(d=a(m,t))},flush:m,dispose(){u=!0,f(),i=[],c=0}}},Ed=()=>{let e=1;return{next(){if(e>li)throw new ne("stream id space exhausted");const t=e;return e+=2,t}}},wd=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},Bd=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},es=0,qo=1,ts=2,rs=3,Cd=new Set([wt.AuthFailed,wt.DuplicateClient,wt.LimitExceeded]),vd={[wt.AuthFailed]:"relay authentication failed",[wt.DuplicateClient]:"relay connection replaced by another client",[wt.LimitExceeded]:"relay connection limit reached"},Po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kd=e=>Po(e)&&Object.values(e).every(t=>typeof t=="string"),Dd=e=>Po(e)&&typeof e.status=="number"&&kd(e.headers),mi=e=>Po(e)&&typeof e.reason=="string",Sd=e=>Po(e)&&typeof e.code=="number"&&typeof e.reason=="string",gi=/^[a-z][a-z\d+.-]*:\/\//i,sa="http://tunnel.invalid",Md=e=>{try{const t=gi.test(e)?new URL(e):new URL(e,sa);return`${t.pathname}${t.search}`}catch{return e}},Gr=e=>({async*[Symbol.asyncIterator](){yield e}}),Td=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()}}}),Pd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Rd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Td(e)};if(typeof e=="string")return{body:Gr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Gr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Gr(Pd(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,o=new Uint8Array(await t.arrayBuffer());return{body:Gr(o),contentType:r}},Id=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=gi.test(r)?new URL(r):new URL(r,sa),{body:c,contentType:d}=await Rd(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}},_d="__pichamberAmbiguousTransport",xd=e=>(Object.defineProperty(e,_d,{value:!0,enumerable:!1,configurable:!0}),e),Od=new Uint8Array(0),Nd=new TextEncoder,Ld=new TextDecoder,hn=e=>e instanceof Error?e:new Error(String(e)),os=()=>new DOMException("The operation was aborted.","AbortError"),Ud=async(e,t,r)=>{const o=await Id(t,r),n=o.signal;if(n?.aborted)throw os();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{}}},h=A=>{a.dead||a.send(Pe(O.StreamAbort,s,po({reason:A})))},p=A=>xd(new Error(A));f=()=>{h("aborted"),g(os())},a.streams.set(s,{handleFrame(A,C){if(A===O.HttpResponse){if(d||l)return;let w;try{w=ho(C,Dd)}catch(ee){h("malformed response head"),g(p(hn(ee).message));return}const B=w.status===204||w.status===205||w.status===304;let P=null;B||(P=new ReadableStream({start(ee){u=ee},cancel(){l||(l=!0,m(),h("response body cancelled"))}})),d=!0,i(new Response(P,{status:w.status,headers:w.headers})),B&&(l=!0,m());return}if(A===O.HttpBody){if(!d||l)return;try{u?.enqueue(C)}catch{}return}if(A===O.StreamEnd){if(l)return;if(!d){g(p("tunnel stream ended before response head"));return}l=!0,m();try{u?.close()}catch{}return}if(A===O.StreamAbort){let w="stream aborted by host";try{w=ho(C,mi).reason}catch{}g(p(w))}},fail(A){g(p(A.message))}}),n&&n.addEventListener("abort",f,{once:!0});const k={method:o.method,path:o.path,query:o.query,headers:o.headers};a.send(Pe(O.HttpRequest,s,po(k))),(async()=>{try{if(o.body)for await(const A of o.body){if(l||a.dead)return;for(const C of ui(A))a.send(Pe(O.HttpBody,s,C))}!l&&!a.dead&&a.send(Pe(O.StreamEnd,s,Od))}catch(A){h("request body failed"),g(p(hn(A).message))}})()})},Hd=e=>{const t=e.indexOf("?");return t===-1?{path:e,query:""}:{path:e.slice(0,t),query:e.slice(t+1)}},Kd=(e,t,r)=>{let o=es,n=null,a=0,s=!1;const i={get readyState(){return o},onopen:null,onmessage:null,onerror:null,onclose:null,send(d){if(o!==qo||!n||n.dead)throw new Error("relay tunnel socket is not open");if(typeof d=="string"){for(const u of Za(O.WsText,a,Nd.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 Za(O.WsBinary,a,l))n.send(u)},close(d=1e3,l=""){o===rs||o===ts||(o===qo&&n&&!n.dead&&(o=ts,n.send(Pe(O.WsClose,a,po({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=rs,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,hn(m).message,!0);return}if(s)return;n=d,a=d.nextStreamId(),d.streams.set(a,{handleFrame(m,g){if(m===O.WsOpened){if(o===es){o=qo;try{i.onopen?.()}catch{}}return}if(m===O.WsText){try{i.onmessage?.({data:Ld.decode(g)})}catch{}return}if(m===O.WsBinary){const h=new ArrayBuffer(g.byteLength);new Uint8Array(h).set(g);try{i.onmessage?.({data:h})}catch{}return}if(m===O.WsClose){let h=1e3,p="";try{const k=ho(g,Sd);h=k.code,p=k.reason}catch{}c(h,p);return}if(m===O.StreamAbort){let h="stream aborted";try{h=ho(g,mi).reason}catch{}c(1006,h,!0)}},fail(m){c(1012,m.message,!0)}});const{path:l,query:u}=Hd(t),f=r&&r.length>0?{path:l,query:u,protocols:r}:{path:l,query:u};d.send(Pe(O.WsOpen,a,po(f)))})(),i},Wo=new Uint8Array(0),Le=e=>e instanceof Error?e:new Error(String(e)),ns=()=>new DOMException("The operation was aborted.","AbortError"),as=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ia=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??fi,i=e.batch!==!1,c=e.reconnectBaseDelayMs??1e3,d=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(v=>wd(new WebSocket(v)));let f=!1,m={state:"idle"};const g=new Set;let h=null,p=null,k=null,A=null,C=0,w=0,B=null,P=[];const ee=v=>{if(!(m.state===v.state&&m.lastError===v.lastError)){m=v;for(const U of g)try{U(m)}catch{}}},Be=v=>{const U=P;P=[];for(const N of U)N.reject(v)},se=v=>{const U=P;P=[];for(const N of U)N.resolve(v)},We=(v,U)=>{v.dead=!0;const N=Array.from(v.streams.values());v.streams.clear();for(const $ of N)try{$.fail(U)}catch{}},Ce=()=>{B!==null&&(clearTimeout(B),B=null)},te=()=>{if(!(f||as())){if(B!==null){Ce(),Oe();return}m.state==="connecting"||m.state==="reconnecting"||h&&!h.dead&&A?.()}},Tt=()=>{typeof document<"u"&&document.addEventListener("visibilitychange",te),typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("pichamber:system-resume",te))},or=()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",te),typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("pichamber:system-resume",te))},qr=()=>{if(f||B!==null)return;const v=c*Math.pow(1.5,Math.min(w,8)),U=Math.random()*.3*v,N=Math.min(d,Math.round(v+U)),$=as()?Math.max(N,l):N;B=setTimeout(()=>{B=null,Oe()},$)},nr=()=>{const v=new URL(e.relayUrl);return v.searchParams.set("v",String(br)),v.searchParams.set("role","client"),v.searchParams.set("serverId",e.serverId),e.grant&&v.searchParams.set("grant",e.grant),v.toString()},Oe=async()=>{if(f)return;const v=++C;Ce(),k?.(),k=null,ee({state:w===0?"connecting":"reconnecting"});let U;try{U=await ld(e.hostEncPubJwk,{batch:i})}catch(I){ir(v,Le(I),!0);return}if(f||v!==C)return;let N;try{N=u(nr())}catch(I){ir(v,Le(I));return}p=N;let $=null,G=null,de=null,ae=null,dt=!1,Pt=null,Fe=!1,le=null,Ge=null,lt=Date.now(),ut=!1,E=Promise.resolve();const R=()=>{A===z&&(A=null),dt=!1,$!==null&&(clearInterval($),$=null),G!==null&&(clearTimeout(G),G=null),de!==null&&(clearInterval(de),de=null),ae!==null&&(clearTimeout(ae),ae=null),Pt?.dispose(),Pt=null};k=R;const T=(I,J={})=>{const{terminal:V=!1,asErrorState:q=!1}=J;if(!(Fe||v!==C)){Fe=!0,R(),k===R&&(k=null),le&&We(le,I),h===le&&(h=null);try{N.close()}catch{}if(p===N&&(p=null),V){f=!0,Be(I),ee({state:"error",lastError:I.message});return}ir(v,I,q)}},z=()=>{Fe||v!==C||!le||le.dead||dt||(dt=!0,lt=Date.now(),ae!==null&&(clearTimeout(ae),ae=null),le.send(Pe(O.Ping,0,Wo)),ae=setTimeout(()=>{ae=null,T(new Error("relay resume probe timeout"))},a))},ue=()=>{if(N.readyState===1)try{N.send(U.helloText)}catch(I){T(Le(I))}},ve=(I,J)=>{Ge=I,ut=J,$!==null&&(clearInterval($),$=null),G!==null&&(clearTimeout(G),G=null),w=0;const V=new Map,q=Ed(),ft=gd();let me=Promise.resolve();const Ne=dr=>{me=me.then(async()=>{if(cr.dead)return;const zc=await I.encryptor.encrypt(dr);N.send(zc)}).catch(()=>{})},mt=J?Ad({windowMs:s,sendBatch:Ne}):null;Pt=mt;const cr={streams:V,assembler:ft,nextStreamId:()=>q.next(),send:dr=>{if(lt=Date.now(),mt){mt.enqueue(dr);return}Ne(dr)},dead:!1};le=cr,h=cr,A=z,ee({state:"connected"}),se(cr),de=setInterval(()=>{Date.now()-lt<o||(cr.send(Pe(O.Ping,0,Wo)),ae===null&&(ae=setTimeout(()=>{ae=null,T(new Error("relay keepalive timeout"))},n)))},o)},sr=(I,J)=>{let V;try{V=ud(J)}catch(me){T(Le(me));return}if(ae!==null&&(clearTimeout(ae),ae=null),dt=!1,V.frameType===O.Ping){I.send(Pe(O.Pong,V.streamId,Wo));return}if(V.frameType===O.Pong)return;lt=Date.now();let q=V.payload;if(V.frameType===O.WsText||V.frameType===O.WsBinary){let me;try{me=I.assembler.push(V)}catch(Ne){T(Le(Ne));return}if(me===null)return;q=me}else if(V.hasMoreFragments){T(new Error("unexpected fragmented tunnel frame"));return}const ft=I.streams.get(V.streamId);ft&&ft.handleFrame(V.frameType,q)};N.onopen=()=>{Fe||v!==C||(ue(),$=setInterval(ue,t))},N.onmessage=I=>{if(Fe||v!==C)return;const J=I.data;if(typeof J=="string"){E=E.then(async()=>{if(Fe||v!==C)return;const q=await U.handleText(J);if(q.type==="established"){if(Ge)return;ve(q.channel,q.batch)}else q.type==="fail"&&T(new Error(`relay handshake failed: ${q.reason}`))}).catch(q=>{T(Le(q))});return}const V=J instanceof ArrayBuffer?new Uint8Array(J):J instanceof Uint8Array?J:null;V&&(E=E.then(async()=>{if(Fe||v!==C)return;const q=le,ft=Ge;if(!q||!ft){T(new Error("encrypted frame before handshake completed"));return}let me;try{me=await ft.decryptor.decrypt(V)}catch(Ne){T(Le(Ne));return}if(ut){let Ne;try{Ne=hd(me)}catch(mt){T(Le(mt));return}for(const mt of Ne){if(Fe||v!==C||q.dead)return;sr(q,mt)}return}sr(q,me)}).catch(q=>{T(Le(q))}))},N.onclose=I=>{const J=Cd.has(I.code);T(new Error(vd[I.code]??`relay socket closed (code ${I.code})`),{terminal:J,asErrorState:J})},N.onerror=()=>{},G=setTimeout(()=>{G=null,T(new Error("relay handshake timeout"),{asErrorState:!0})},r);function ir(I,J,V=!1){I!==C||f||(Be(J),w+=1,ee({state:V?"error":"reconnecting",lastError:J.message}),qr())}},ar=v=>f?Promise.reject(new Error("relay tunnel closed")):v?.aborted?Promise.reject(ns()):h&&!h.dead?Promise.resolve(h):new Promise((U,N)=>{let $=null;const G={resolve(de){$&&v&&v.removeEventListener("abort",$),U(de)},reject(de){$&&v&&v.removeEventListener("abort",$),N(de)}};v&&($=()=>{P=P.filter(de=>de!==G),N(ns())},v.addEventListener("abort",$,{once:!0})),P.push(G)}),$o=()=>{if(f)return;f=!0,C+=1,Ce(),or(),k?.(),k=null;const v=h;h=null;const U=new Error("relay tunnel closed");v&&We(v,U),Be(U);try{p?.close()}catch{}p=null,ee({state:"idle"})};return Tt(),Oe(),{fetch:(v,U)=>Ud(ar,v,U),openWebSocket:(v,U)=>Kd(()=>ar(),v,U),getStatus:()=>m,subscribeStatus(v){return g.add(v),()=>{g.delete(v)}},close:$o}};let pe=null,Er=null;const jd=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Nr=()=>pe,Qt=()=>pe!==null,Fn=new Set,Ky=e=>(Fn.add(e),()=>{Fn.delete(e)}),ca=e=>{if(e!==Qt())for(const t of[...Fn])t()},$d=e=>{if(pe&&Er&&jd(Er,e))return pe;const t=Qt();return pe?.close(),Er=e,pe=ia(e),ca(t),pe},jy=(e,t)=>{if(pe===t)return;const r=Qt();pe?.close(),Er=e,pe=t,ca(r)},zd=()=>{const e=Qt();pe?.close(),pe=null,Er=null,ca(e)};let pi=()=>null,hi="",Fo={},at="",Mr=0,Ft=null,Kt="",Tr=0,Ct="",yt=null,Qe="",no=0,ao=0;const da=1e4,qd=e=>e.toLowerCase()==="authorization",Fi=e=>{const t={};for(const[r,o]of Object.entries(e||{})){const n=r.trim(),a=o.trim();n&&a&&!qd(n)&&(t[n]=a)}return t},Wd=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([o,n])=>t[o]===n)},Lr=e=>typeof e!="string"?"":e.trim(),Gd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_CLIENT_TOKEN__;return Lr(e)},Vd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},yi=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():Vd();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},la=e=>{try{return new URL(e).origin}catch{return""}},bi=()=>{Kt="",Tr=0,Ct="",yt=null,Qe="",no+=1},Ur=e=>{e!==void 0&&Lr(e)!==at||(at="",Mr=0,bi())},Ai=()=>{ao+=1,Ft=null,Ur(),fa()},Ei=e=>{const t=Lr(e);hi=t,Ai(),pi=()=>t?{type:"bearer",token:t}:null},wi=e=>{const t=Fi(e);Wd(Fo,t)||(Fo=t,Ai())},ua=()=>{if(Object.keys(Fo).length>0)return Fo;if(typeof window>"u")return{};const e=window.__PICHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Fi(e):{}},Ro=()=>hi||Gd(),Jd=(e,t)=>{const r=Lr(e);if(!r||typeof t!="number"||!Number.isFinite(t)){Ur();return}const o=at;at=r,Mr=t,o&&o!==r&&tl()},Bi=()=>!at||Mr<=Date.now()+da?(Ur(),""):at,Yd=e=>{const t=la(e);return!t||Ct!==t?"":!Kt||Tr<=Date.now()+da?(Kt="",Tr=0,Ct="",""):Kt},Xd=()=>{const e=Bi();return!e&&(Ro()||typeof window<"u")&&Hr().catch(()=>{}),e},Ci=async()=>{const e=await pi(),t=e?.type==="bearer"?Lr(e.token):Ro();return t?{type:"bearer",token:t}:null},vi=e=>{if(Ft)return Ft;const t=ao,o=(async()=>{const n=await Ci(),a=new Headers;for(const[u,f]of Object.entries(ua()))a.set(u,f);n?.type==="bearer"&&a.set("Authorization",`Bearer ${n.token}`);const s=Nr(),i=s?await s.fetch("/auth/url-token",{method:"POST",headers:a}):await fetch(yi(e,"/auth/url-token"),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw t===ao&&Ur(),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!==ao)throw new Error("Runtime URL auth token response is stale");if(Jd(d,l),!at)throw new Error("Runtime URL auth token response was invalid");return at})().finally(()=>{Ft===o&&(Ft=null)});return Ft=o,Ft},Qd=e=>{const t=la(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(yt&&Qe===t)return yt;const r=no,n=(async()=>{const a=await fetch(yi(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!a.ok)throw r===no&&t===Qe&&(Kt="",Tr=0,Ct=""),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!==no||t!==Qe)throw new Error("Local runtime URL auth token response is stale");return Kt=i,Tr=c,Ct=t,i})().finally(()=>{yt===n&&(yt=null,Qe="")});return yt=n,Qe=t,yt},Hr=async e=>{const t=Bi();return t||vi(e)},Zd=async e=>{const t=la(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const r=Yd(t);return r||((Ct&&Ct!==t||Qe&&Qe!==t)&&bi(),Qd(t))};let Ot=0,wr=null,ki=null;const yn=new Set,el=5e3,tl=()=>{for(const e of yn)try{e()}catch{}},Di=()=>{wr!==null&&(clearTimeout(wr),wr=null)},fa=()=>{if(Di(),Ot<=0||typeof window>"u")return;const e=Mr-da-el,t=Mr>0?Math.max(0,e-Date.now()):0;wr=setTimeout(()=>{wr=null,!(Ot<=0)&&vi(ki).catch(()=>{}).finally(()=>{fa()})},t)},$y=e=>{typeof e=="string"&&e.trim()&&(ki=e.trim()),Ot+=1,fa();let t=!1;return()=>{t||(t=!0,Ot=Math.max(0,Ot-1),Ot===0&&Di())}},zy=e=>(yn.add(e),()=>{yn.delete(e)}),rl=async e=>{const t=new Headers(e);for(const[o,n]of Object.entries(ua()))t.has(o)||t.set(o,n);if(t.has("Authorization"))return t;const r=await Ci();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},bn="pichamber:auth-expired",qy=()=>{typeof window>"u"||window.dispatchEvent(new Event(bn))},Wy=e=>typeof window>"u"?()=>{}:(window.addEventListener(bn,e),()=>{window.removeEventListener(bn,e)}),Gy=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},ss=e=>{if(e instanceof Error)return e;if(typeof DOMException<"u")return new DOMException(typeof e=="string"?e:"The operation was aborted.","AbortError");const t=new Error(typeof e=="string"?e:"The operation was aborted.");return t.name="AbortError",t},Si=(e,t)=>t?t.aborted?Promise.reject(ss(t.reason)):new Promise((r,o)=>{let n=!1;const a=()=>{n||(n=!0,o(ss(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(),ol=["local","remote",null],nl=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Mi(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"||!ol.includes(o)))return{valid:!1};if(typeof n!="string"||!nl.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 al(){if(sl()!=="valid")return null;const t=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__,r=Mi(t);return r.valid?r.outcome:null}function sl(){if(typeof window>"u")return"not-injected";const e=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Mi(e).valid?"valid":"malformed"}const yo=/^[a-z][a-z\d+.-]*:\/\//i,il=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},An=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),cl=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return An(e)},dl=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},En=(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))},ll=(e,t)=>{if(!t)return e;const r=new URLSearchParams;En({searchParams:r},t);const o=r.toString();return o?e.includes("?")?`${e}&${o}`:`${e}?${o}`:e},is=(e,t,r)=>{if(yo.test(t)){const a=new URL(t);return En(a,r),a.toString()}const o=il(t);if(!e)return ll(o,r);const n=new URL(o,`${e}/`);return En(n,r),n.toString()},Go=(e,t)=>{const r=t===void 0?Xd():t;if(!r)return e;const o=yo.test(e)?new URL(e):new URL(e,"http://pichamber.local");return o.searchParams.set("oc_url_token",r),yo.test(e)?o.toString():`${o.pathname}${o.search}${o.hash}`},ul=(e,t)=>{const r=yo.test(e)?new URL(e):new URL(e,dl(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},ma=(e={})=>{const t=An(e.apiBaseUrl),r=An(e.realtimeBaseUrl),o=()=>t||cl(),n=()=>r||o(),a=(i,c)=>is(o(),i,c),s=(i,c)=>is(n(),i,c);return{api:a,authenticatedAsset:(i,c)=>Go(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)=>Go(s(i,c)),websocket:(i,c,d)=>ul(Go(s(i,c),d),e)}};let bo=ma();const Ie=()=>bo,fl=e=>{bo=e},ga=e=>(bo=ma(e),bo);let Vo=null,Jo=null,Yo=null;const cs=new Set;let ds=!1;const Ti=e=>{if(cs.add(e),ds||typeof window>"u")return;ds=!0;const t=()=>{for(const r of cs)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{}},ml=(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 Ti(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()}}},pa=e=>ml(()=>Ii(),e),gl=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 Ti(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}}},Pi=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},ha=()=>{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}}},Ri=e=>{const t=ha(),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}}},pl=()=>{const e=Pi("localStorage");return e?Ri(e):ha()},Ii=()=>(Vo||(Vo=pl()),Vo),Kr=()=>(Yo||(Yo=gl(Ii())),Yo),hl=()=>{const e=Pi("sessionStorage");return e?Ri(e):ha()},Vy=()=>(Jo||(Jo=hl()),Jo),wn="pichamber:runtime-endpoint-changed",Bn="pichamber:runtime-endpoint-will-change";let st="",vt="",_i=0;const Jy=()=>(Io(),_i),Cn="pichamber:lastRuntimeEndpoint.v1",Fl=()=>{try{const e=Kr().getItem(Cn);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}},yl=(e,t)=>{try{const r=Kr();if(t==="mobile-disconnected"||!e){r.removeItem(Cn);return}r.setItem(Cn,JSON.stringify({apiBaseUrl:e,runtimeKey:t}))}catch{}},Io=()=>{if(st||vt||typeof window>"u")return;const e=Fl();if(e){st=e.apiBaseUrl,vt=e.runtimeKey;try{window.__PICHAMBER_API_BASE_URL__=e.apiBaseUrl}catch{}ga({apiBaseUrl:e.apiBaseUrl,realtimeBaseUrl:e.apiBaseUrl})}},Xo=(e,t,r)=>{try{e[t]=r}catch{}},Fa=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"}`}},xi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Oi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Ni=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ze=()=>(Io(),st||xi());let Qo="",ls=null,us,fs;const ms=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(Io(),vt)return vt;const e=ms("__PICHAMBER_API_BASE_URL__"),t=ms("__PICHAMBER_LOCAL_ORIGIN__");if(ls===st&&us===e&&fs===t)return Qo;const r=ze();return Qo=Ni(r,Oi())?"local":Fa(r),ls=st,us=e,fs=t,Qo},bl=(e={})=>{if(Io(),st||vt)return;const t=e.apiBaseUrl?.trim()||xi();t&&(st=t,vt=e.runtimeKey?.trim()||(Ni(t,Oi())?"local":Fa(t)))},jt=e=>{const t=e.apiBaseUrl.trim(),r=ze(),o=D(),n=e.runtimeKey?.trim()||Fa(t);_i+=1,yl(t,n);const a={apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bn,{detail:a})),st=t,vt=n,typeof window<"u"){const s=window;Xo(s,"__PICHAMBER_API_BASE_URL__",t),Xo(s,"__PICHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Xo(s,"__PICHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}ga({apiBaseUrl:t,realtimeBaseUrl:t}),wi(e.requestHeaders||null),Ei(e.clientToken||null),e.relay?$d(e.relay):zd(),Hr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(wn,{detail:a}))},Al=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(Bn,t),()=>window.removeEventListener(Bn,t)},Li=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(wn,t),()=>window.removeEventListener(wn,t)};let vn=null;const El=e=>{vn=e},ya=()=>vn||(typeof window>"u"?null:window.__PICHAMBER_RUNTIME_APIS__??null),Yy=Object.freeze(Object.defineProperty({__proto__:null,getRegisteredRuntimeAPIs:ya,registerRuntimeAPIs:El},Symbol.toStringTag,{value:"Module"})),wl=()=>typeof window>"u"?null:window.__PICHAMBER_ELECTRON__??null,Zt=()=>typeof window>"u"?null:window.__PICHAMBER_DESKTOP__??null,_o=()=>wl()?.runtime==="electron",Xy=()=>{if(typeof window>"u")return null;const e=window.__PICHAMBER_PLATFORM__;return typeof e=="string"?e:null},Z=()=>typeof Zt()?.invoke=="function",xe=()=>_o()&&Z(),j=async(e,t)=>{const r=Zt();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},gs=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}}},Zo=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}}},Bl=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),lr=e=>{const t=Bl(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},we=()=>typeof window>"u"?!1:_o(),ce=()=>{if(typeof window>"u"||!we())return!1;if(D()==="local")return!0;const e=typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",t=Zo(e),r=Zo(ze());if(!r&&t&&al()?.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&&lr(t.hostname)&&lr(r.hostname)}const o=Zo(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&&lr(t.hostname)&&lr(o.hostname)}const n=gs(e),a=gs(window.location.origin)||window.location.origin;return n&&a&&n===a?!0:!!(o&&lr(o.hostname))},Qy=()=>{const t=ya()?.runtime?.platform;return t==="web"?!0:t!=="desktop"},Zy=(e,t=we())=>e==="web"&&!t,eb=async()=>{if(!xe())return null;try{const e=await j("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}},tb=async e=>{if(!xe())return null;try{const t=await j("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}},rb=async()=>{if(!xe())return null;try{const e=await j("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}},ob=async e=>{if(!xe())return null;try{const t=await j("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}},nb=async()=>{if(!xe())return null;try{const e=await j("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}},ab=async e=>{if(!xe())return null;try{const t=await j("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}},sb=async()=>{if(!xe())return null;try{const e=await j("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}},ib=async e=>{if(!xe())return null;try{const t=await j("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}},cb=async()=>{if(!xe())return null;try{const e=await j("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}},db=async e=>{if(!xe())return null;try{const t=await j("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}},Cl=()=>we()&&Z()&&ce(),vl=async()=>{if(typeof window<"u"){const e=window.__PICHAMBER_HOME__;if(e&&e.length>0)return e}return null},lb=async e=>{if(Cl())try{const t=await Zt()?.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"}},Ui=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ub=async e=>{if(Z()&&ce())try{const t=await Zt()?.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(!Ui(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"}},fb=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 Zt()?.grantFileAccess?.(t);if(!Ui(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)}}},mb=async e=>({success:!0}),gb=async e=>({success:!0}),pb=async()=>Z()&&await j("desktop_get_update_channel")==="rc"?"rc":"stable",hb=async e=>{if(!Z())throw new Error("Desktop update settings are unavailable.");const t=await j("desktop_set_update_channel",{channel:e});if(t!=="stable"&&t!=="rc")throw new Error("Unable to save the desktop update channel.");return t},Fb=async()=>Z()?await j("desktop_check_for_updates"):null,yb=async e=>{if(!Z())return!1;const t=Zt();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 j("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{}}},kl=async()=>{if(!Z())return!1;try{return await j("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},bb=async()=>Z()?kl():!1,Ab=async()=>{if(!Z()||!ce())return null;try{const e=await j("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}},Dl=async(e,t)=>{if(!Z()||!ce())return!1;const r=e?.trim();if(!r)return!1;try{return await j("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}},Eb=async e=>{if(!Z()||!ce())return!1;const t=e?.trim();if(!t)return!1;try{return await j("desktop_reveal_path",{path:t}),!0}catch{return Dl(t)}},wb=async(e,t)=>{if(!Z()||!ce())return null;const r=e?.trim();if(!r)return null;try{const o=await j("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}},Bb=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 j("desktop_open_in_app",{projectPath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},Cb=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 j("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}},vb=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 j("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}}},er=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location?.protocol==="capacitor:",kb=()=>{if(typeof window>"u"||!er()||Sl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Sl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return we()?"desktop":"web"},Db=()=>{if(typeof navigator>"u")return!1;const e=navigator.platform||"",t=navigator.userAgent||"";return/Win/i.test(e)&&/ARM|aarch64/i.test(t)},kt=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Ml=()=>typeof window>"u"?"":window.location.origin||"",ba=e=>{if(typeof window>"u")return!1;const t=Ml();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}},Aa=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Ea=(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))},so=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:kt(e.pathname)}catch{return!1}},en=e=>{if(kt(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ba(t)&&kt(t.pathname)}catch{return!1}},Tl=(e,t)=>{try{const r=new URL(e);if(!ba(r))return e;const o=Bt(`${r.pathname}${r.search}`,t);return!Aa(o)&&(r.protocol==="http:"||r.protocol==="https:")?(Ea(r,t),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return e}},Bt=(e,t)=>e==="/health"?Ie().health(t):e.startsWith("/auth/")||e==="/auth"?Ie().auth(e,t):kt(e)?Ie().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Tl(e,t):e,Pl=e=>{const t=e instanceof Request?e.url:e.toString();if(!Aa(t))return kt(t);try{return so(new URL(t))}catch{return!1}},Rl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Il=(e,t)=>!Rl(t),ps=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)Il(n,a)?(r.push([n,encodeURIComponent(a)]),o=!0):r.push([n,a]);return o?r:void 0},Ue=async(e,t,r=!0)=>{const o=new Headers(ps(e)??e);return t&&new Headers(ps(t)??t).forEach((n,a)=>o.set(a,n)),r?rl(o):o},_l=(e,t)=>{if(!t)return e;const r=new URL(e,sa);return Ea(r,t),`${r.pathname}${r.search}`},Hi=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!Aa(r))return kt(r)?_l(r,t):null;try{const o=new URL(r);return!ba(o)||!kt(o.pathname)?null:(Ea(o,t),`${o.pathname}${o.search}`)}catch{return null}},xl=async(e,t,r)=>{const o=Nr();if(!o)return null;const n=Hi(e,r);if(n===null)return null;const a=e instanceof Request?e.headers:void 0,s=await Ue(a,t.headers,!0);return e instanceof Request?o.fetch(e,{...t,headers:s}):o.fetch(n,{...t,headers:s})},Ol=(e,t)=>{if(typeof e=="string")return Bt(e,t);if(e instanceof URL)return Bt(e.toString(),t);const r=Bt(e.url,t);return r===e.url?e:new Request(r,e)},Nl=/\/api\/pi\/(health|projects|sessions|providers|resources|runtime|settings)(\b|\/|\?|$)/,Vr=new Map,Ll=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!Nl.test(t)?null:`GET ${t}`,b=async(e,t={})=>{const{query:r,...o}=t,n=Nr(),a=n?Hi(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,h=await Ue(g,o.headers,!0);i=e instanceof Request?()=>n.fetch(e,{...o,headers:h}):()=>n.fetch(a,{...o,headers:h}),c=a,d=String(o.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const g=Ol(e,r),h=g instanceof Request?g.headers:void 0,p=await Ue(h,o.headers,Pl(g));let k=g instanceof Request?()=>fetch(new Request(g,{...o,headers:p})):()=>fetch(g,{...o,headers:p});if(er()&&s){const A=k;k=()=>Si(A,s)}i=k,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=Ll(d,c,l);if(!u)return i();const f=Vr.get(u);if(f)return f.then(g=>g.clone());const m=i();return Vr.set(u,m),m.then(()=>Vr.delete(u),()=>Vr.delete(u)),m.then(g=>g.clone())};let hs=!1;const Ul=()=>{if(hs||typeof window>"u")return;hs=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const o=await xl(t,r??{});if(o)return o;if(typeof t=="string"){if(!en(t)){try{const a=new URL(t);if(so(a)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}}catch{}return e(t,r)}const n=await Ue(void 0,r?.headers);return e(Bt(t),{...r,headers:n})}if(t instanceof URL){const n=t.toString();if(!en(n)){if(so(t)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}return e(t,r)}const a=await Ue(void 0,r?.headers);return e(Bt(n),{...r,headers:a})}if(t instanceof Request){if(!en(t.url)){try{const i=new URL(t.url);if(so(i)){const c=await Ue(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const n=await Ue(t.headers,r?.headers),a=Bt(t.url),s=a===t.url?t:new Request(a,t);return e(new Request(s,{...r,headers:n}))}return e(t,r)}},$t=16384,Ao=globalThis,Hl=e=>{if(Ao.Buffer)return Ao.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,"")},Ki=e=>{try{if(Ao.Buffer)return Ao.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}},Kl=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}},jl=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}},Fs=e=>typeof e=="string"&&e.length>0,$l=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Fs(t.x)||!Fs(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},zl=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ql=e=>{if(!e||typeof e!="object")return null;const t=e,r=zl(t.priority);if(t.type==="lan"||t.type==="tunnel"||t.type==="tailscale"){const o=Kl(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=jl(t.relayUrl);if(!o)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const a=$l(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},wa=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(ql).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}),Mb=e=>{const t=wa(e);if(!t)throw new Error("Invalid pairing connection payload");const r=new URLSearchParams;return r.set("v","2"),r.set("p",Hl(JSON.stringify(t))),`pichamber://connect?${r.toString()}`},Wl=e=>{const t=e.trim();if(!t||t.length>$t)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>$t)return null;const n=Ki(o);return!n||n.length>$t?null:wa(JSON.parse(n))}catch{return null}},Tb=e=>{const t=e.trim();if(!t||t.length>$t)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>$t)return null;const a=Ki(n);if(!a||a.length>$t)return null;try{return wa(JSON.parse(a))}catch{return null}},Gt=e=>typeof e=="object"&&e!==null,Gl=e=>e.trim().toLowerCase()==="authorization",Vl=e=>{if(!Gt(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)||Gl(n)||(t[n]=a)}return Object.keys(t).length>0?t:void 0},ji=e=>`relay://${e}`,Jl=e=>{if(!Gt(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||!Gt(o)?null:{relayUrl:t,serverId:r,hostEncPubJwk:o}},Yl=()=>{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"},$i=5e3,Xl=async(e,t,r)=>{const o=Wl(e);if(!o)throw new Error("invalid-connect-link");const n=await Wi().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:Yl(),...n?{dedupeKey:`desktop:${n}`}:{}})},s=async w=>{if(!w.ok)return null;const B=await w.json().catch(()=>null);return(typeof B?.clientToken=="string"?B.clientToken.trim():"")||null};let i=null;const c=[...o.candidates].sort((w,B)=>(w.type==="relay"?1:0)-(B.type==="relay"?1:0));for(const w of c){if(w.type==="relay"){const P=ia({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const ee=await s(await P.fetch("/api/client-auth/pairing/redeem",a));if(ee){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:ee};break}}catch{}finally{P.close()}continue}const B=X(w.url);if(B)try{const P=await s(await fetch(`${B}/api/client-auth/pairing/redeem`,a));if(P){i={directUrl:B,token:P};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const d=o.candidates.find(w=>w.type==="relay"),l=i.relay||(d?{relayUrl:d.relayUrl,serverId:d.serverId,hostEncPubJwk:d.hostEncPubJwk}:void 0),u=o.candidates.filter(w=>w.type!=="relay").map(w=>X(w.url)).find(w=>!!w),f=i.directUrl||u,m=f||(l?ji(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");let g=null;if(i.directUrl){const w=r?.healthTimeoutMs??$i,B=new AbortController,P=setTimeout(()=>B.abort(),w);try{const ee=await fetch(`${i.directUrl}/health`,{headers:{Accept:"application/json"},signal:B.signal,credentials:"omit"});if(ee.ok){const Be=await ee.json().catch(()=>null),se=typeof Be?.serverId=="string"?Be.serverId.trim():"";se&&(g=se)}}catch{}finally{clearTimeout(P)}}const h=new Set;l?.serverId&&h.add(l.serverId),g&&h.add(g);const p=w=>{for(const B of h)if(w.serverId===B||w.relay?.serverId===B)return!0;return!1},k=t.find(w=>{if(l){if(w.relay?.serverId===l.serverId)return!0}else if(!w.relay&&X(w.apiUrl||w.url)===m)return!(w.serverId&&g&&w.serverId!==g);return p(w)}),A=k?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),C={...k||{},id:A,label:o.label||k?.label||Ba(m),url:m,apiUrl:f,clientToken:i.token,...l?{relay:l}:{}};return k?.serverId?C.serverId=k.serverId:g&&(C.serverId=g),{hostId:A,hosts:k?t.map(w=>w.id===A?C:w):[C,...t]}},Ql=/^(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}},Zl=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"}},Ba=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)Ql.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},ys=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},eu=e=>{if(!Gt(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=Vl(e.requestHeaders),i=Jl(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,tu=(e,t)=>{const r={...e,url:t,apiUrl:t};return X(_e(e))!==X(t)&&delete r.serverId,r},St=()=>Z()?(e,t)=>j(e,t):null,Ca=async()=>{const e=St();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Gt(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const r=t.hosts,o=Array.isArray(r)?r.map(eu).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}},zi=async e=>{const t=St();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})},qi=async()=>{const e=St();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Wi=async()=>{const e=St();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},ru=8e3,bs=async(e,t,r)=>{const o=new AbortController,n=window.setTimeout(()=>o.abort(),ru);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(n)}},ou=async(e,t)=>{const r=ia({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),o=Date.now();let n=!1;try{if(!(await bs(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 bs(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()}},va=async(e,t)=>{const r=St();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(!Gt(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=ys(o,"latencyMs")??ys(o,"latency_ms")??0,i=Y(o,"reportedServerId");return{status:a,latencyMs:s,...i?.trim()?{reportedServerId:i.trim()}:{}}},nu=async(e,t)=>{const r=St();r&&await r("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},au=async e=>{const t=St();t&&await t("desktop_new_window_for_host",{hostId:e})},Pb=Object.freeze(Object.defineProperty({__proto__:null,DESKTOP_HOST_HEALTH_PIN_TIMEOUT_MS:$i,desktopHostProbe:va,desktopHostsGet:Ca,desktopHostsSet:zi,desktopInstallIdGet:Wi,desktopLocalClientTokenGet:qi,desktopOpenNewWindowAtUrl:nu,desktopOpenNewWindowForHost:au,getDesktopHostApiUrl:_e,importDesktopHostPairing:Xl,locationMatchesHost:rt,normalizeHostUrl:X,probeRelayDesktopHost:ou,redactSensitiveUrl:Ba,relayHostDisplayUrl:ji,resolveDesktopHostUrl:Zl,withEditedDesktopHostUrl:tu},Symbol.toStringTag,{value:"Module"})),ot="local",su=e=>({id:ot,label:"Local",url:e||ka()}),ka=()=>typeof window>"u"?"":window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,Da=e=>e.id===ot?"local":`host:${e.id}`,As="host:",Gi=e=>{const t=e.runtimeKey.trim();if(t===ot)return{kind:"local"};if(t.startsWith(As)){const o=t.slice(As.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},iu=e=>{const t=typeof window>"u"?"":window.location.href,r=e.find(l=>l.id===ot)?.url||ka(),o=ze(),n=X(r)||r,a=X(t)||t,s=D(),i=e.find(l=>l.relay&&Da(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:Ba(a||"Instance"),url:a}},Rb=Object.freeze(Object.defineProperty({__proto__:null,LOCAL_HOST_ID:ot,buildLocalDesktopHost:su,getLocalDesktopOrigin:ka,resolveCurrentDesktopHost:iu,resolveDesktopHostIdentity:Gi,runtimeKeyForDesktopHost:Da},Symbol.toStringTag,{value:"Module"})),cu=5e3,du=1500;let tn=!1;const lu=async e=>{if(!_o()||tn)return;const t=`host:${e}`;if(D()===t){tn=!0;try{const r=await Ca().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 b("/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 h=X(g.url),p=g.type==="tailscale"?d:c;h&&!p.includes(h)&&p.push(h)}const l=c.length>0?c:d;if(l.length===0)return;const u=n&&l.includes(n)?n:l[0];u!==n&&await zi({hosts:r.hosts.map(m=>m.id===e?{...m,apiUrl:u}:m),defaultHostId:r.defaultHostId,initialHostChoiceCompleted:r.initialHostChoiceCompleted}).catch(()=>{});const f=await va(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;jt({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:t})}finally{tn=!1}}},uu=e=>{typeof window>"u"||window.setTimeout(()=>{lu(e).catch(()=>{})},cu)},fu=(e,t)=>{if(t){const o=e.hosts.find(n=>n.id===t);return o?{kind:"host",host:o}:null}const r=Gi({runtimeKey:D(),apiBaseUrl:ze(),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"}},mu=(e,t)=>{const r=e.clientToken||"";!r||Ro()===r||jt({apiBaseUrl:ze()||_e(e),clientToken:r,requestHeaders:e.requestHeaders||null,runtimeKey:t,relay:Qt()?e.relay:void 0})},gu=async e=>{if(!_o())return;const t=await Ca().catch(()=>null);if(!t)return;const r=fu(t,e);if(!r)return;if(r.kind==="local"){const u=await qi();if(!u)return;const f=t.localOrigin||ze();if(!f||D()==="local"&&Ro()===u)return;jt({apiBaseUrl:f,clientToken:u,runtimeKey:"local"});return}const o=r.host,n=Da(o),a=u=>{jt({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:n})},s=()=>{jt({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:o.clientToken||null,runtimeKey:n,relay:o.relay??void 0}),uu(o.id)};if(D()===n){const u=o.apiUrl?X(_e(o)):"";if(!!(u&&rt(ze(),u))||!o.relay){mu(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=va(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),du))]);if(l){if(c(l)){a(i);return}s();return}s(),d.then(u=>{c(u)&&D()===n&&a(i)})},pu=64*1024,hu=(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+pu,e.size),s=new Uint8Array(await e.slice(o,a).arrayBuffer());o=a,n.enqueue(s),r?.({loaded:o,total:e.size})}})},Fu=(e,t)=>!er()||e instanceof File?e:new File([e],t.filename,{type:t.mime||e.type}),yu=async(e,t,r)=>{const o=!!Nr();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?hu(t,r.signal,r.onProgress):Fu(t,r),signal:r.signal,...o?{duplex:"half"}:{}},a=await b(e,n);return!o&&a.ok&&r.onProgress?.({loaded:t.size,total:t.size}),a},_t=1,bu="events.streamEpoch",Au=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},Ib="pichamber.bash",_b=64*1024,Es=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0,Vi=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return!(t.snoozedUntil!==void 0&&(!Es(t.snoozedUntil)||!Es(t.snoozedAt)))},Eu=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(Vi)},wu=["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","session.moved","extension.entry","extension.message","extension.notify","extension.catalog","extension.editor","extension.title","extension.status","extension.control","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"],kn=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.protocolVersion===_t&&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))&&wu.includes(t.name)},Ji=(e,t)=>{const r=Nr();return r?r.openWebSocket(Md(e),t):Bd(new WebSocket(e))},Yi="pichamber.mobile.diagnostics.v1",Sa=300,Bu=240,Cu=1e3;let Vt=[],ws=!1,zt=null,rn=!1;const Nt=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,Bu)||void 0,vu=e=>{if(!e||typeof e!="object")return{detail:Nt(e)};const t=e;return{...typeof t.code=="string"?{code:Nt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.message!==void 0?{detail:Nt(t.message)}:typeof t.name=="string"?{detail:Nt(t.name)}:{}}},Xi=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},xo=()=>{if(ws)return;ws=!0;const e=Xi();if(e)try{const t=e.getItem(Yi);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)}Vt=[...o,...Vt].slice(-Sa)}catch{}},ku=()=>{zt!==null&&(clearTimeout(zt),zt=null)},Du=()=>{zt===null&&(zt=setTimeout(()=>{zt=null,io()},Cu))},io=()=>{ku();const e=Xi();if(e)try{xo(),e.setItem(Yi,JSON.stringify(Vt.slice(-Sa)))}catch{}},W=(e,t={})=>{if(!er())return;xo();const r={at:new Date().toISOString(),category:e.trim().slice(0,80)||"unknown",...t.code?{code:Nt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.detail!==void 0?{detail:Nt(t.detail)}:{}};Vt=[...Vt,r].slice(-Sa),Du()},Su=(e,t)=>{W(e,vu(t))},Mu=()=>(xo(),JSON.stringify({format:"pichamber-mobile-diagnostics-v1",generatedAt:new Date().toISOString(),platform:typeof navigator>"u"?"unknown":navigator.userAgent,entries:Vt},null,2)),xb=async()=>{const e=Mu(),{isShareCancelledError:t,saveOrShareFile:r}=await qc(async()=>{const{isShareCancelledError:n,saveOrShareFile:a}=await import("./nativeFileSave-D542OJlG.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")},Ob=()=>{if(!er()||typeof window>"u"||rn)return()=>{};rn=!0,xo(),W("app-launch",{code:"start"});const e=n=>{W("window-error",{code:n.error?.name,detail:n.message})},t=n=>{Su("unhandled-rejection",n.reason)},r=()=>{io()},o=()=>{document.visibilityState==="hidden"&&io()};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),io(),rn=!1}},Tu=3e4,Pu=250,Ru=5e3,Iu=6e4,_u=8,xu=2e3,Ou=1e4,Nu=5e3,Lu=3e4,Uu=5e3,xt=new Map,Hu=8,Ku=(e,t)=>{if(!(!e||!t||t.length>128))for(xt.delete(e),xt.set(e,t);xt.size>Hu;){const r=xt.keys().next();if(r.done)break;xt.delete(r.value)}};let Br=null;const Nb=e=>(Br=e,()=>{Br===e&&(Br=null)}),Ze=(e=D(),t)=>{if(t&&Br){const r=Br(e,t);if(r!==void 0)return r??void 0}return xt.get(e)},Qi=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),typeof e.cursor=="string"&&e.cursor.length>0&&(t.cursor=e.cursor),t.capabilities=bu,t},Bs=(e,t,r)=>{const o=Ie(),n=Qi(t);return e==="ws"?o.websocket("/api/pi/events",n,r):o.sse("/api/pi/events",n)},ju=()=>"/api/pi/runtime",co=()=>er()&&!Qt()&&typeof EventSource<"u",$u=3e3;let Dn=null,Fr=null;const Lb=()=>{Dn=null,Fr=null},zu=1e4,Jr=e=>({...e,capabilities:[...e.capabilities]}),Eo=async(e,t,r)=>{const o=t??D();if(!r?.fresh){const s=Dn;if(s&&s.runtimeKey===o&&s.runtimeKey===D()&&Date.now()<s.expiresAt)return Jr(s.result)}const n=!r?.fresh&&!e;if(n){const s=Fr;if(s&&s.runtimeKey===o&&s.runtimeKey===D())return s.promise.then(Jr)}const a=async()=>{const s=r?.timeoutMs??zu,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 b(ju(),{signal:i.signal});if(o!==D())return{state:"unavailable",protocolVersion:_t,capabilities:[],error:{code:"DAEMON_UNAVAILABLE",message:"Runtime changed during request"}};if(!l.ok)return W("runtime-health",{status:l.status,code:l.status===401||l.status===403?"auth":"http-error"}),{state:"unavailable",protocolVersion:_t,capabilities:[],error:{code:l.status===401||l.status===403?"DAEMON_AUTH_FAILED":"DAEMON_UNAVAILABLE"}};const f=await Si(()=>l.json(),i.signal).catch(p=>{if((p instanceof DOMException||p instanceof Error)&&p.name==="AbortError")throw p;return null});if(!f||typeof f!="object")return{state:"unavailable",protocolVersion:_t,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&&Ku(o,g);const h={state:f.state==="ready"?"ready":"unavailable",protocolVersion:typeof f.protocolVersion=="number"?f.protocolVersion:_t,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter(p=>typeof p=="string"):[],...g?{streamEpoch:g}:{},...m?{error:{code:m,...typeof f.error?.message=="string"?{message:f.error.message}:{}}}:{}};return!r?.fresh&&h.state==="ready"&&o===D()&&(Dn={runtimeKey:o,result:Jr(h),expiresAt:Date.now()+$u}),h}catch(l){const u=(l instanceof DOMException||l instanceof Error)&&l.name==="AbortError";return W("runtime-health",{code:u?"timeout":"unreachable"}),{state:"unavailable",protocolVersion:_t,capabilities:[],error:{code:u?"DAEMON_TIMEOUT":"DAEMON_UNAVAILABLE"}}}finally{clearTimeout(d),e&&e.removeEventListener("abort",c)}};if(n){const s=a().finally(()=>{Fr?.promise===s&&(Fr=null)});return Fr={runtimeKey:o,promise:s},s.then(Jr)}return a()},qu=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 Eo(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)}},Wu=(e,t,r,o,n,a,s)=>{if(co()){const f=new EventSource(Ie().sse("/api/pi/events",e)),m=new AbortController;let g=!1,h=!1,p=setTimeout(()=>{p=null,!(h||g)&&(W("stream-connect",{code:"setup-timeout"}),C(),a("sse-setup-timeout"))},s.setupTimeoutMs);const k=()=>{p&&clearTimeout(p),p=null},A=()=>{g||o()},C=()=>{k(),m.abort(),!g&&(g=!0,f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C))},w=B=>{try{const P=JSON.parse(B);kn(P)&&n(P)}catch{W("stream-frame",{code:"bad-sse-frame"})}};return f.onopen=()=>{g||(h=!0,k(),r())},f.onmessage=B=>{g||(o(),typeof B.data=="string"&&B.data.trim()&&w(B.data))},f.onerror=()=>{if(g)return;k(),f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C),g=!0,W("stream-disconnect",{code:"sse-error"});const B=s.classifySourceError;if(!B){a("sse-error");return}B(m.signal).then(P=>{m.signal.aborted||a(P==="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)&&(W("stream-connect",{code:"setup-timeout"}),a("sse-setup-timeout"),c())},s.setupTimeoutMs);const u=()=>{l&&clearTimeout(l),l=null};return b("/api/pi/events",{headers:{Accept:"text/event-stream"},query:e,signal:i.signal}).then(async f=>{if(!f.ok||!f.body){if(W("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 h="",p=[];const k=()=>{if(p.length===0)return;const A=p.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nativeFileSave-Bj-V_9ae.js","assets/vendor-boot-D-KEJjsM.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 xr,d as Or,p as aa}from"./vendor-zustand-CXhN0IMY.js";import{_ as qc}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Wc}from"./vendor-clsx-B-dksMZM.js";import{t as Gc}from"./vendor-tailwind-merge-BKkUfl9q.js";import{e as ri}from"./vendor-fuse.js-t_7AcMTv.js";import{R as Xa}from"./vendor-react-Bz1tRBxM.js";const br=1,Vc="pichamber-relay-v1",oi=1,ni=12,Ar=1+ni,Dr=64*1024,Sr=5,go=128,ai=0,si=1,Wt=4,Jc=1+Wt,gn=Dr-Sr-Jc,O={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Yc=new Set(Object.values(O)),Xc=e=>Yc.has(e),wt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},je=globalThis.crypto.subtle,ii={name:"ECDH",namedCurve:"P-256"},ci=16,zo=32,Qc=16,pn=4,di=8;class tt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Zc=()=>je.generateKey(ii,!0,["deriveBits"]),ed=async e=>{const t=await je.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},td=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 je.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},ii,!0,[])}catch{throw new tt("invalid ECDH public key JWK")}},rd=()=>{const e=new Uint8Array(ci);return globalThis.crypto.getRandomValues(e),e},od=async(e,t,r)=>{if(r.length!==ci)throw new tt("invalid handshake nonce length");const o=await je.deriveBits({name:"ECDH",public:t},e,256),n=await je.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=new Uint8Array(await je.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(Vc)},n,zo*2*8)),s=(i,c)=>je.importKey("raw",i,{name:"AES-GCM"},!1,c);return{clientToHost:await s(a.slice(0,zo),["encrypt","decrypt"]),hostToClient:await s(a.slice(zo),["encrypt","decrypt"])}},nd=(e,t,r)=>{for(let o=di-1;o>=0;o-=1)e[t+o]=Number(r&0xffn),r>>=8n},ad=(e,t)=>{let r=0n;for(let o=0;o<di;o+=1)r=r<<8n|BigInt(e[t+o]);return r},sd=e=>{const t=new Uint8Array(pn);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(o){if(o.length>Dr)throw new tt("plaintext frame exceeds maximum size");r+=1n;const n=new Uint8Array(ni);n.set(t,0),nd(n,pn,r);const a=new Uint8Array(await je.encrypt({name:"AES-GCM",iv:n},e,o)),s=new Uint8Array(Ar+a.length);return s[0]=oi,s.set(n,1),s.set(a,Ar),s}}},id=e=>{let t=0n;return{async decrypt(r){if(r.length<Ar+Qc)throw new tt("encrypted frame too short");if(r[0]!==oi)throw new tt("unsupported encrypted frame version");const o=r.slice(1,Ar),n=ad(o,pn);if(n<=t)throw new tt("frame counter regression");let a;try{a=await je.decrypt({name:"AES-GCM",iv:o},e,r.slice(Ar))}catch{throw new tt("frame decryption failed")}return t=n,new Uint8Array(a)}}},Wr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",cd=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+=Wr[o>>2],t+=Wr[(o&3)<<4|(n??0)>>4],n!==void 0&&(t+=Wr[(n&15)<<2|(a??0)>>6]),a!==void 0&&(t+=Wr[a&63])}return t},Qa=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!==br)return null;const o=r.batch===!0;return r.t==="ready"?{t:"ready",v:br,batch:o}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:br,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:o}:null},dd=e=>({type:"fail",closeCode:wt.ChannelFailure,reason:e}),ld=async(e,t={})=>{const r=t.batch!==!1,o=await td(e),n=await Zc(),a=rd(),s={t:"hello",v:br,clientPubJwk:await ed(n.publicKey),nonce:cd(a),...r?{batch:!0}:{}};let i=!1;return{helloText:JSON.stringify(s),get established(){return i},async handleText(c){if(i)return Qa(c)?.t==="ready"?{type:"ignore"}:dd("plaintext frame on established channel");const d=Qa(c);if(d?.t!=="ready")return{type:"ignore"};const l=await od(n.privateKey,o,a);return i=!0,{type:"established",batch:r&&d.batch===!0,channel:{encryptor:sd(l.clientToHost),decryptor:id(l.hostToClient)}}}}},li=4294967295;class ne extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Pe=(e,t,r,o=!1)=>{if(!Number.isInteger(t)||t<0||t>li)throw new ne("invalid stream id");if(r.length>gn)throw new ne("tunnel payload exceeds maximum size");const n=new Uint8Array(Sr+r.length);return n[0]=o?e|go:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(r,Sr),n},ud=e=>{if(e.length<Sr)throw new ne("tunnel frame too short");const t=e[0],r=(t&go)!==0,o=t&~go;if(!Xc(o))throw new ne(`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(Sr),hasMoreFragments:r}},fd=new TextEncoder,md=new TextDecoder,po=e=>fd.encode(JSON.stringify(e)),ho=(e,t)=>{let r;try{r=JSON.parse(md.decode(e))}catch{throw new ne("malformed JSON tunnel payload")}if(!t(r))throw new ne("unexpected JSON tunnel payload shape");return r},ui=(e,t=gn)=>{if(t<=0||t>gn)throw new ne("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},Za=(e,t,r)=>{const o=ui(r);return o.map((n,a)=>Pe(e,t,n,a<o.length-1))},gd=(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 ne("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)}}},pd=e=>{if(e.length===0)throw new ne("cannot encode an empty frame batch");if(e.length===1){const n=e[0],a=new Uint8Array(1+n.length);if(a[0]=ai,a.set(n,1),a.length>Dr)throw new ne("frame batch exceeds maximum plaintext size");return a}let t=1;for(const n of e)t+=Wt+n.length;if(t>Dr)throw new ne("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=si;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+=Wt,r.set(n,o),o+=n.length;return r},hd=e=>{if(e.length<1)throw new ne("empty batch plaintext");const t=e[0];if(t===ai)return[e.slice(1)];if(t!==si)throw new ne(`unknown batch container tag ${t}`);const r=[];let o=1;for(;o<e.length;){if(o+Wt>e.length)throw new ne("truncated batch frame length");const n=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;if(o+=Wt,o+n>e.length)throw new ne("truncated batch frame body");r.push(e.slice(o,o+n)),o+=n}if(r.length===0)throw new ne("empty frame batch");return r},Fd=new Set([O.HttpBody,O.WsText,O.WsBinary]),fi=150,yd=24*1024,bd=32,Ad=e=>{const t=e.windowMs??fi,r=e.maxBatchBytes??yd,o=e.maxBatchFrames??bd,n=e.now??(()=>Date.now()),a=e.setTimer??((h,p)=>setTimeout(h,p)),s=e.clearTimer??(h=>clearTimeout(h));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 h=i;i=[],c=0,l=n(),e.sendBatch(pd(h))};return{enqueue:h=>{if(u)return;const p=h[0]&~go;if(!Fd.has(p)){i.push(h),m();return}const k=n();if(i.length===0&&k-l>=t){i.push(h),m();return}const A=Wt+h.length;if(i.length>0&&1+c+A>Dr&&m(),i.push(h),c+=A,c>=r||i.length>=o){m();return}d===null&&(d=a(m,t))},flush:m,dispose(){u=!0,f(),i=[],c=0}}},Ed=()=>{let e=1;return{next(){if(e>li)throw new ne("stream id space exhausted");const t=e;return e+=2,t}}},wd=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},Bd=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},es=0,qo=1,ts=2,rs=3,Cd=new Set([wt.AuthFailed,wt.DuplicateClient,wt.LimitExceeded]),vd={[wt.AuthFailed]:"relay authentication failed",[wt.DuplicateClient]:"relay connection replaced by another client",[wt.LimitExceeded]:"relay connection limit reached"},Po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kd=e=>Po(e)&&Object.values(e).every(t=>typeof t=="string"),Dd=e=>Po(e)&&typeof e.status=="number"&&kd(e.headers),mi=e=>Po(e)&&typeof e.reason=="string",Sd=e=>Po(e)&&typeof e.code=="number"&&typeof e.reason=="string",gi=/^[a-z][a-z\d+.-]*:\/\//i,sa="http://tunnel.invalid",Md=e=>{try{const t=gi.test(e)?new URL(e):new URL(e,sa);return`${t.pathname}${t.search}`}catch{return e}},Gr=e=>({async*[Symbol.asyncIterator](){yield e}}),Td=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()}}}),Pd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Rd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Td(e)};if(typeof e=="string")return{body:Gr(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Gr(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Gr(Pd(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,o=new Uint8Array(await t.arrayBuffer());return{body:Gr(o),contentType:r}},Id=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=gi.test(r)?new URL(r):new URL(r,sa),{body:c,contentType:d}=await Rd(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}},_d="__pichamberAmbiguousTransport",xd=e=>(Object.defineProperty(e,_d,{value:!0,enumerable:!1,configurable:!0}),e),Od=new Uint8Array(0),Nd=new TextEncoder,Ld=new TextDecoder,hn=e=>e instanceof Error?e:new Error(String(e)),os=()=>new DOMException("The operation was aborted.","AbortError"),Ud=async(e,t,r)=>{const o=await Id(t,r),n=o.signal;if(n?.aborted)throw os();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{}}},h=A=>{a.dead||a.send(Pe(O.StreamAbort,s,po({reason:A})))},p=A=>xd(new Error(A));f=()=>{h("aborted"),g(os())},a.streams.set(s,{handleFrame(A,C){if(A===O.HttpResponse){if(d||l)return;let w;try{w=ho(C,Dd)}catch(ee){h("malformed response head"),g(p(hn(ee).message));return}const B=w.status===204||w.status===205||w.status===304;let P=null;B||(P=new ReadableStream({start(ee){u=ee},cancel(){l||(l=!0,m(),h("response body cancelled"))}})),d=!0,i(new Response(P,{status:w.status,headers:w.headers})),B&&(l=!0,m());return}if(A===O.HttpBody){if(!d||l)return;try{u?.enqueue(C)}catch{}return}if(A===O.StreamEnd){if(l)return;if(!d){g(p("tunnel stream ended before response head"));return}l=!0,m();try{u?.close()}catch{}return}if(A===O.StreamAbort){let w="stream aborted by host";try{w=ho(C,mi).reason}catch{}g(p(w))}},fail(A){g(p(A.message))}}),n&&n.addEventListener("abort",f,{once:!0});const k={method:o.method,path:o.path,query:o.query,headers:o.headers};a.send(Pe(O.HttpRequest,s,po(k))),(async()=>{try{if(o.body)for await(const A of o.body){if(l||a.dead)return;for(const C of ui(A))a.send(Pe(O.HttpBody,s,C))}!l&&!a.dead&&a.send(Pe(O.StreamEnd,s,Od))}catch(A){h("request body failed"),g(p(hn(A).message))}})()})},Hd=e=>{const t=e.indexOf("?");return t===-1?{path:e,query:""}:{path:e.slice(0,t),query:e.slice(t+1)}},Kd=(e,t,r)=>{let o=es,n=null,a=0,s=!1;const i={get readyState(){return o},onopen:null,onmessage:null,onerror:null,onclose:null,send(d){if(o!==qo||!n||n.dead)throw new Error("relay tunnel socket is not open");if(typeof d=="string"){for(const u of Za(O.WsText,a,Nd.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 Za(O.WsBinary,a,l))n.send(u)},close(d=1e3,l=""){o===rs||o===ts||(o===qo&&n&&!n.dead&&(o=ts,n.send(Pe(O.WsClose,a,po({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=rs,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,hn(m).message,!0);return}if(s)return;n=d,a=d.nextStreamId(),d.streams.set(a,{handleFrame(m,g){if(m===O.WsOpened){if(o===es){o=qo;try{i.onopen?.()}catch{}}return}if(m===O.WsText){try{i.onmessage?.({data:Ld.decode(g)})}catch{}return}if(m===O.WsBinary){const h=new ArrayBuffer(g.byteLength);new Uint8Array(h).set(g);try{i.onmessage?.({data:h})}catch{}return}if(m===O.WsClose){let h=1e3,p="";try{const k=ho(g,Sd);h=k.code,p=k.reason}catch{}c(h,p);return}if(m===O.StreamAbort){let h="stream aborted";try{h=ho(g,mi).reason}catch{}c(1006,h,!0)}},fail(m){c(1012,m.message,!0)}});const{path:l,query:u}=Hd(t),f=r&&r.length>0?{path:l,query:u,protocols:r}:{path:l,query:u};d.send(Pe(O.WsOpen,a,po(f)))})(),i},Wo=new Uint8Array(0),Le=e=>e instanceof Error?e:new Error(String(e)),ns=()=>new DOMException("The operation was aborted.","AbortError"),as=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ia=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??fi,i=e.batch!==!1,c=e.reconnectBaseDelayMs??1e3,d=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(v=>wd(new WebSocket(v)));let f=!1,m={state:"idle"};const g=new Set;let h=null,p=null,k=null,A=null,C=0,w=0,B=null,P=[];const ee=v=>{if(!(m.state===v.state&&m.lastError===v.lastError)){m=v;for(const U of g)try{U(m)}catch{}}},Be=v=>{const U=P;P=[];for(const N of U)N.reject(v)},se=v=>{const U=P;P=[];for(const N of U)N.resolve(v)},We=(v,U)=>{v.dead=!0;const N=Array.from(v.streams.values());v.streams.clear();for(const $ of N)try{$.fail(U)}catch{}},Ce=()=>{B!==null&&(clearTimeout(B),B=null)},te=()=>{if(!(f||as())){if(B!==null){Ce(),Oe();return}m.state==="connecting"||m.state==="reconnecting"||h&&!h.dead&&A?.()}},Tt=()=>{typeof document<"u"&&document.addEventListener("visibilitychange",te),typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("pichamber:system-resume",te))},or=()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",te),typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("pichamber:system-resume",te))},qr=()=>{if(f||B!==null)return;const v=c*Math.pow(1.5,Math.min(w,8)),U=Math.random()*.3*v,N=Math.min(d,Math.round(v+U)),$=as()?Math.max(N,l):N;B=setTimeout(()=>{B=null,Oe()},$)},nr=()=>{const v=new URL(e.relayUrl);return v.searchParams.set("v",String(br)),v.searchParams.set("role","client"),v.searchParams.set("serverId",e.serverId),e.grant&&v.searchParams.set("grant",e.grant),v.toString()},Oe=async()=>{if(f)return;const v=++C;Ce(),k?.(),k=null,ee({state:w===0?"connecting":"reconnecting"});let U;try{U=await ld(e.hostEncPubJwk,{batch:i})}catch(I){ir(v,Le(I),!0);return}if(f||v!==C)return;let N;try{N=u(nr())}catch(I){ir(v,Le(I));return}p=N;let $=null,G=null,de=null,ae=null,dt=!1,Pt=null,Fe=!1,le=null,Ge=null,lt=Date.now(),ut=!1,E=Promise.resolve();const R=()=>{A===z&&(A=null),dt=!1,$!==null&&(clearInterval($),$=null),G!==null&&(clearTimeout(G),G=null),de!==null&&(clearInterval(de),de=null),ae!==null&&(clearTimeout(ae),ae=null),Pt?.dispose(),Pt=null};k=R;const T=(I,J={})=>{const{terminal:V=!1,asErrorState:q=!1}=J;if(!(Fe||v!==C)){Fe=!0,R(),k===R&&(k=null),le&&We(le,I),h===le&&(h=null);try{N.close()}catch{}if(p===N&&(p=null),V){f=!0,Be(I),ee({state:"error",lastError:I.message});return}ir(v,I,q)}},z=()=>{Fe||v!==C||!le||le.dead||dt||(dt=!0,lt=Date.now(),ae!==null&&(clearTimeout(ae),ae=null),le.send(Pe(O.Ping,0,Wo)),ae=setTimeout(()=>{ae=null,T(new Error("relay resume probe timeout"))},a))},ue=()=>{if(N.readyState===1)try{N.send(U.helloText)}catch(I){T(Le(I))}},ve=(I,J)=>{Ge=I,ut=J,$!==null&&(clearInterval($),$=null),G!==null&&(clearTimeout(G),G=null),w=0;const V=new Map,q=Ed(),ft=gd();let me=Promise.resolve();const Ne=dr=>{me=me.then(async()=>{if(cr.dead)return;const zc=await I.encryptor.encrypt(dr);N.send(zc)}).catch(()=>{})},mt=J?Ad({windowMs:s,sendBatch:Ne}):null;Pt=mt;const cr={streams:V,assembler:ft,nextStreamId:()=>q.next(),send:dr=>{if(lt=Date.now(),mt){mt.enqueue(dr);return}Ne(dr)},dead:!1};le=cr,h=cr,A=z,ee({state:"connected"}),se(cr),de=setInterval(()=>{Date.now()-lt<o||(cr.send(Pe(O.Ping,0,Wo)),ae===null&&(ae=setTimeout(()=>{ae=null,T(new Error("relay keepalive timeout"))},n)))},o)},sr=(I,J)=>{let V;try{V=ud(J)}catch(me){T(Le(me));return}if(ae!==null&&(clearTimeout(ae),ae=null),dt=!1,V.frameType===O.Ping){I.send(Pe(O.Pong,V.streamId,Wo));return}if(V.frameType===O.Pong)return;lt=Date.now();let q=V.payload;if(V.frameType===O.WsText||V.frameType===O.WsBinary){let me;try{me=I.assembler.push(V)}catch(Ne){T(Le(Ne));return}if(me===null)return;q=me}else if(V.hasMoreFragments){T(new Error("unexpected fragmented tunnel frame"));return}const ft=I.streams.get(V.streamId);ft&&ft.handleFrame(V.frameType,q)};N.onopen=()=>{Fe||v!==C||(ue(),$=setInterval(ue,t))},N.onmessage=I=>{if(Fe||v!==C)return;const J=I.data;if(typeof J=="string"){E=E.then(async()=>{if(Fe||v!==C)return;const q=await U.handleText(J);if(q.type==="established"){if(Ge)return;ve(q.channel,q.batch)}else q.type==="fail"&&T(new Error(`relay handshake failed: ${q.reason}`))}).catch(q=>{T(Le(q))});return}const V=J instanceof ArrayBuffer?new Uint8Array(J):J instanceof Uint8Array?J:null;V&&(E=E.then(async()=>{if(Fe||v!==C)return;const q=le,ft=Ge;if(!q||!ft){T(new Error("encrypted frame before handshake completed"));return}let me;try{me=await ft.decryptor.decrypt(V)}catch(Ne){T(Le(Ne));return}if(ut){let Ne;try{Ne=hd(me)}catch(mt){T(Le(mt));return}for(const mt of Ne){if(Fe||v!==C||q.dead)return;sr(q,mt)}return}sr(q,me)}).catch(q=>{T(Le(q))}))},N.onclose=I=>{const J=Cd.has(I.code);T(new Error(vd[I.code]??`relay socket closed (code ${I.code})`),{terminal:J,asErrorState:J})},N.onerror=()=>{},G=setTimeout(()=>{G=null,T(new Error("relay handshake timeout"),{asErrorState:!0})},r);function ir(I,J,V=!1){I!==C||f||(Be(J),w+=1,ee({state:V?"error":"reconnecting",lastError:J.message}),qr())}},ar=v=>f?Promise.reject(new Error("relay tunnel closed")):v?.aborted?Promise.reject(ns()):h&&!h.dead?Promise.resolve(h):new Promise((U,N)=>{let $=null;const G={resolve(de){$&&v&&v.removeEventListener("abort",$),U(de)},reject(de){$&&v&&v.removeEventListener("abort",$),N(de)}};v&&($=()=>{P=P.filter(de=>de!==G),N(ns())},v.addEventListener("abort",$,{once:!0})),P.push(G)}),$o=()=>{if(f)return;f=!0,C+=1,Ce(),or(),k?.(),k=null;const v=h;h=null;const U=new Error("relay tunnel closed");v&&We(v,U),Be(U);try{p?.close()}catch{}p=null,ee({state:"idle"})};return Tt(),Oe(),{fetch:(v,U)=>Ud(ar,v,U),openWebSocket:(v,U)=>Kd(()=>ar(),v,U),getStatus:()=>m,subscribeStatus(v){return g.add(v),()=>{g.delete(v)}},close:$o}};let pe=null,Er=null;const jd=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Nr=()=>pe,Qt=()=>pe!==null,Fn=new Set,Ky=e=>(Fn.add(e),()=>{Fn.delete(e)}),ca=e=>{if(e!==Qt())for(const t of[...Fn])t()},$d=e=>{if(pe&&Er&&jd(Er,e))return pe;const t=Qt();return pe?.close(),Er=e,pe=ia(e),ca(t),pe},jy=(e,t)=>{if(pe===t)return;const r=Qt();pe?.close(),Er=e,pe=t,ca(r)},zd=()=>{const e=Qt();pe?.close(),pe=null,Er=null,ca(e)};let pi=()=>null,hi="",Fo={},at="",Mr=0,Ft=null,Kt="",Tr=0,Ct="",yt=null,Qe="",no=0,ao=0;const da=1e4,qd=e=>e.toLowerCase()==="authorization",Fi=e=>{const t={};for(const[r,o]of Object.entries(e||{})){const n=r.trim(),a=o.trim();n&&a&&!qd(n)&&(t[n]=a)}return t},Wd=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([o,n])=>t[o]===n)},Lr=e=>typeof e!="string"?"":e.trim(),Gd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_CLIENT_TOKEN__;return Lr(e)},Vd=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},yi=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():Vd();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},la=e=>{try{return new URL(e).origin}catch{return""}},bi=()=>{Kt="",Tr=0,Ct="",yt=null,Qe="",no+=1},Ur=e=>{e!==void 0&&Lr(e)!==at||(at="",Mr=0,bi())},Ai=()=>{ao+=1,Ft=null,Ur(),fa()},Ei=e=>{const t=Lr(e);hi=t,Ai(),pi=()=>t?{type:"bearer",token:t}:null},wi=e=>{const t=Fi(e);Wd(Fo,t)||(Fo=t,Ai())},ua=()=>{if(Object.keys(Fo).length>0)return Fo;if(typeof window>"u")return{};const e=window.__PICHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Fi(e):{}},Ro=()=>hi||Gd(),Jd=(e,t)=>{const r=Lr(e);if(!r||typeof t!="number"||!Number.isFinite(t)){Ur();return}const o=at;at=r,Mr=t,o&&o!==r&&tl()},Bi=()=>!at||Mr<=Date.now()+da?(Ur(),""):at,Yd=e=>{const t=la(e);return!t||Ct!==t?"":!Kt||Tr<=Date.now()+da?(Kt="",Tr=0,Ct="",""):Kt},Xd=()=>{const e=Bi();return!e&&(Ro()||typeof window<"u")&&Hr().catch(()=>{}),e},Ci=async()=>{const e=await pi(),t=e?.type==="bearer"?Lr(e.token):Ro();return t?{type:"bearer",token:t}:null},vi=e=>{if(Ft)return Ft;const t=ao,o=(async()=>{const n=await Ci(),a=new Headers;for(const[u,f]of Object.entries(ua()))a.set(u,f);n?.type==="bearer"&&a.set("Authorization",`Bearer ${n.token}`);const s=Nr(),i=s?await s.fetch("/auth/url-token",{method:"POST",headers:a}):await fetch(yi(e,"/auth/url-token"),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw t===ao&&Ur(),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!==ao)throw new Error("Runtime URL auth token response is stale");if(Jd(d,l),!at)throw new Error("Runtime URL auth token response was invalid");return at})().finally(()=>{Ft===o&&(Ft=null)});return Ft=o,Ft},Qd=e=>{const t=la(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(yt&&Qe===t)return yt;const r=no,n=(async()=>{const a=await fetch(yi(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!a.ok)throw r===no&&t===Qe&&(Kt="",Tr=0,Ct=""),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!==no||t!==Qe)throw new Error("Local runtime URL auth token response is stale");return Kt=i,Tr=c,Ct=t,i})().finally(()=>{yt===n&&(yt=null,Qe="")});return yt=n,Qe=t,yt},Hr=async e=>{const t=Bi();return t||vi(e)},Zd=async e=>{const t=la(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const r=Yd(t);return r||((Ct&&Ct!==t||Qe&&Qe!==t)&&bi(),Qd(t))};let Ot=0,wr=null,ki=null;const yn=new Set,el=5e3,tl=()=>{for(const e of yn)try{e()}catch{}},Di=()=>{wr!==null&&(clearTimeout(wr),wr=null)},fa=()=>{if(Di(),Ot<=0||typeof window>"u")return;const e=Mr-da-el,t=Mr>0?Math.max(0,e-Date.now()):0;wr=setTimeout(()=>{wr=null,!(Ot<=0)&&vi(ki).catch(()=>{}).finally(()=>{fa()})},t)},$y=e=>{typeof e=="string"&&e.trim()&&(ki=e.trim()),Ot+=1,fa();let t=!1;return()=>{t||(t=!0,Ot=Math.max(0,Ot-1),Ot===0&&Di())}},zy=e=>(yn.add(e),()=>{yn.delete(e)}),rl=async e=>{const t=new Headers(e);for(const[o,n]of Object.entries(ua()))t.has(o)||t.set(o,n);if(t.has("Authorization"))return t;const r=await Ci();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},bn="pichamber:auth-expired",qy=()=>{typeof window>"u"||window.dispatchEvent(new Event(bn))},Wy=e=>typeof window>"u"?()=>{}:(window.addEventListener(bn,e),()=>{window.removeEventListener(bn,e)}),Gy=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},ss=e=>{if(e instanceof Error)return e;if(typeof DOMException<"u")return new DOMException(typeof e=="string"?e:"The operation was aborted.","AbortError");const t=new Error(typeof e=="string"?e:"The operation was aborted.");return t.name="AbortError",t},Si=(e,t)=>t?t.aborted?Promise.reject(ss(t.reason)):new Promise((r,o)=>{let n=!1;const a=()=>{n||(n=!0,o(ss(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(),ol=["local","remote",null],nl=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Mi(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"||!ol.includes(o)))return{valid:!1};if(typeof n!="string"||!nl.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 al(){if(sl()!=="valid")return null;const t=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__,r=Mi(t);return r.valid?r.outcome:null}function sl(){if(typeof window>"u")return"not-injected";const e=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Mi(e).valid?"valid":"malformed"}const yo=/^[a-z][a-z\d+.-]*:\/\//i,il=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},An=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),cl=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return An(e)},dl=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},En=(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))},ll=(e,t)=>{if(!t)return e;const r=new URLSearchParams;En({searchParams:r},t);const o=r.toString();return o?e.includes("?")?`${e}&${o}`:`${e}?${o}`:e},is=(e,t,r)=>{if(yo.test(t)){const a=new URL(t);return En(a,r),a.toString()}const o=il(t);if(!e)return ll(o,r);const n=new URL(o,`${e}/`);return En(n,r),n.toString()},Go=(e,t)=>{const r=t===void 0?Xd():t;if(!r)return e;const o=yo.test(e)?new URL(e):new URL(e,"http://pichamber.local");return o.searchParams.set("oc_url_token",r),yo.test(e)?o.toString():`${o.pathname}${o.search}${o.hash}`},ul=(e,t)=>{const r=yo.test(e)?new URL(e):new URL(e,dl(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},ma=(e={})=>{const t=An(e.apiBaseUrl),r=An(e.realtimeBaseUrl),o=()=>t||cl(),n=()=>r||o(),a=(i,c)=>is(o(),i,c),s=(i,c)=>is(n(),i,c);return{api:a,authenticatedAsset:(i,c)=>Go(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)=>Go(s(i,c)),websocket:(i,c,d)=>ul(Go(s(i,c),d),e)}};let bo=ma();const Ie=()=>bo,fl=e=>{bo=e},ga=e=>(bo=ma(e),bo);let Vo=null,Jo=null,Yo=null;const cs=new Set;let ds=!1;const Ti=e=>{if(cs.add(e),ds||typeof window>"u")return;ds=!0;const t=()=>{for(const r of cs)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{}},ml=(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 Ti(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()}}},pa=e=>ml(()=>Ii(),e),gl=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 Ti(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}}},Pi=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},ha=()=>{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}}},Ri=e=>{const t=ha(),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}}},pl=()=>{const e=Pi("localStorage");return e?Ri(e):ha()},Ii=()=>(Vo||(Vo=pl()),Vo),Kr=()=>(Yo||(Yo=gl(Ii())),Yo),hl=()=>{const e=Pi("sessionStorage");return e?Ri(e):ha()},Vy=()=>(Jo||(Jo=hl()),Jo),wn="pichamber:runtime-endpoint-changed",Bn="pichamber:runtime-endpoint-will-change";let st="",vt="",_i=0;const Jy=()=>(Io(),_i),Cn="pichamber:lastRuntimeEndpoint.v1",Fl=()=>{try{const e=Kr().getItem(Cn);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}},yl=(e,t)=>{try{const r=Kr();if(t==="mobile-disconnected"||!e){r.removeItem(Cn);return}r.setItem(Cn,JSON.stringify({apiBaseUrl:e,runtimeKey:t}))}catch{}},Io=()=>{if(st||vt||typeof window>"u")return;const e=Fl();if(e){st=e.apiBaseUrl,vt=e.runtimeKey;try{window.__PICHAMBER_API_BASE_URL__=e.apiBaseUrl}catch{}ga({apiBaseUrl:e.apiBaseUrl,realtimeBaseUrl:e.apiBaseUrl})}},Xo=(e,t,r)=>{try{e[t]=r}catch{}},Fa=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"}`}},xi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Oi=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Ni=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ze=()=>(Io(),st||xi());let Qo="",ls=null,us,fs;const ms=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(Io(),vt)return vt;const e=ms("__PICHAMBER_API_BASE_URL__"),t=ms("__PICHAMBER_LOCAL_ORIGIN__");if(ls===st&&us===e&&fs===t)return Qo;const r=ze();return Qo=Ni(r,Oi())?"local":Fa(r),ls=st,us=e,fs=t,Qo},bl=(e={})=>{if(Io(),st||vt)return;const t=e.apiBaseUrl?.trim()||xi();t&&(st=t,vt=e.runtimeKey?.trim()||(Ni(t,Oi())?"local":Fa(t)))},jt=e=>{const t=e.apiBaseUrl.trim(),r=ze(),o=D(),n=e.runtimeKey?.trim()||Fa(t);_i+=1,yl(t,n);const a={apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bn,{detail:a})),st=t,vt=n,typeof window<"u"){const s=window;Xo(s,"__PICHAMBER_API_BASE_URL__",t),Xo(s,"__PICHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Xo(s,"__PICHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}ga({apiBaseUrl:t,realtimeBaseUrl:t}),wi(e.requestHeaders||null),Ei(e.clientToken||null),e.relay?$d(e.relay):zd(),Hr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(wn,{detail:a}))},Al=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(Bn,t),()=>window.removeEventListener(Bn,t)},Li=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(wn,t),()=>window.removeEventListener(wn,t)};let vn=null;const El=e=>{vn=e},ya=()=>vn||(typeof window>"u"?null:window.__PICHAMBER_RUNTIME_APIS__??null),Yy=Object.freeze(Object.defineProperty({__proto__:null,getRegisteredRuntimeAPIs:ya,registerRuntimeAPIs:El},Symbol.toStringTag,{value:"Module"})),wl=()=>typeof window>"u"?null:window.__PICHAMBER_ELECTRON__??null,Zt=()=>typeof window>"u"?null:window.__PICHAMBER_DESKTOP__??null,_o=()=>wl()?.runtime==="electron",Xy=()=>{if(typeof window>"u")return null;const e=window.__PICHAMBER_PLATFORM__;return typeof e=="string"?e:null},Z=()=>typeof Zt()?.invoke=="function",xe=()=>_o()&&Z(),j=async(e,t)=>{const r=Zt();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},gs=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}}},Zo=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}}},Bl=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),lr=e=>{const t=Bl(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},we=()=>typeof window>"u"?!1:_o(),ce=()=>{if(typeof window>"u"||!we())return!1;if(D()==="local")return!0;const e=typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",t=Zo(e),r=Zo(ze());if(!r&&t&&al()?.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&&lr(t.hostname)&&lr(r.hostname)}const o=Zo(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&&lr(t.hostname)&&lr(o.hostname)}const n=gs(e),a=gs(window.location.origin)||window.location.origin;return n&&a&&n===a?!0:!!(o&&lr(o.hostname))},Qy=()=>{const t=ya()?.runtime?.platform;return t==="web"?!0:t!=="desktop"},Zy=(e,t=we())=>e==="web"&&!t,eb=async()=>{if(!xe())return null;try{const e=await j("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}},tb=async e=>{if(!xe())return null;try{const t=await j("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}},rb=async()=>{if(!xe())return null;try{const e=await j("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}},ob=async e=>{if(!xe())return null;try{const t=await j("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}},nb=async()=>{if(!xe())return null;try{const e=await j("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}},ab=async e=>{if(!xe())return null;try{const t=await j("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}},sb=async()=>{if(!xe())return null;try{const e=await j("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}},ib=async e=>{if(!xe())return null;try{const t=await j("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}},cb=async()=>{if(!xe())return null;try{const e=await j("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}},db=async e=>{if(!xe())return null;try{const t=await j("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}},Cl=()=>we()&&Z()&&ce(),vl=async()=>{if(typeof window<"u"){const e=window.__PICHAMBER_HOME__;if(e&&e.length>0)return e}return null},lb=async e=>{if(Cl())try{const t=await Zt()?.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"}},Ui=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ub=async e=>{if(Z()&&ce())try{const t=await Zt()?.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(!Ui(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"}},fb=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 Zt()?.grantFileAccess?.(t);if(!Ui(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)}}},mb=async e=>({success:!0}),gb=async e=>({success:!0}),pb=async()=>Z()&&await j("desktop_get_update_channel")==="rc"?"rc":"stable",hb=async e=>{if(!Z())throw new Error("Desktop update settings are unavailable.");const t=await j("desktop_set_update_channel",{channel:e});if(t!=="stable"&&t!=="rc")throw new Error("Unable to save the desktop update channel.");return t},Fb=async()=>Z()?await j("desktop_check_for_updates"):null,yb=async e=>{if(!Z())return!1;const t=Zt();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 j("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{}}},kl=async()=>{if(!Z())return!1;try{return await j("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},bb=async()=>Z()?kl():!1,Ab=async()=>{if(!Z()||!ce())return null;try{const e=await j("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}},Dl=async(e,t)=>{if(!Z()||!ce())return!1;const r=e?.trim();if(!r)return!1;try{return await j("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}},Eb=async e=>{if(!Z()||!ce())return!1;const t=e?.trim();if(!t)return!1;try{return await j("desktop_reveal_path",{path:t}),!0}catch{return Dl(t)}},wb=async(e,t)=>{if(!Z()||!ce())return null;const r=e?.trim();if(!r)return null;try{const o=await j("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}},Bb=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 j("desktop_open_in_app",{projectPath:o,appId:n,appName:a}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},Cb=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 j("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}},vb=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 j("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}}},er=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location?.protocol==="capacitor:",kb=()=>{if(typeof window>"u"||!er()||Sl()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Sl=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return we()?"desktop":"web"},Db=()=>{if(typeof navigator>"u")return!1;const e=navigator.platform||"",t=navigator.userAgent||"";return/Win/i.test(e)&&/ARM|aarch64/i.test(t)},kt=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Ml=()=>typeof window>"u"?"":window.location.origin||"",ba=e=>{if(typeof window>"u")return!1;const t=Ml();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}},Aa=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Ea=(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))},so=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:kt(e.pathname)}catch{return!1}},en=e=>{if(kt(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ba(t)&&kt(t.pathname)}catch{return!1}},Tl=(e,t)=>{try{const r=new URL(e);if(!ba(r))return e;const o=Bt(`${r.pathname}${r.search}`,t);return!Aa(o)&&(r.protocol==="http:"||r.protocol==="https:")?(Ea(r,t),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return e}},Bt=(e,t)=>e==="/health"?Ie().health(t):e.startsWith("/auth/")||e==="/auth"?Ie().auth(e,t):kt(e)?Ie().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Tl(e,t):e,Pl=e=>{const t=e instanceof Request?e.url:e.toString();if(!Aa(t))return kt(t);try{return so(new URL(t))}catch{return!1}},Rl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Il=(e,t)=>!Rl(t),ps=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)Il(n,a)?(r.push([n,encodeURIComponent(a)]),o=!0):r.push([n,a]);return o?r:void 0},Ue=async(e,t,r=!0)=>{const o=new Headers(ps(e)??e);return t&&new Headers(ps(t)??t).forEach((n,a)=>o.set(a,n)),r?rl(o):o},_l=(e,t)=>{if(!t)return e;const r=new URL(e,sa);return Ea(r,t),`${r.pathname}${r.search}`},Hi=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!Aa(r))return kt(r)?_l(r,t):null;try{const o=new URL(r);return!ba(o)||!kt(o.pathname)?null:(Ea(o,t),`${o.pathname}${o.search}`)}catch{return null}},xl=async(e,t,r)=>{const o=Nr();if(!o)return null;const n=Hi(e,r);if(n===null)return null;const a=e instanceof Request?e.headers:void 0,s=await Ue(a,t.headers,!0);return e instanceof Request?o.fetch(e,{...t,headers:s}):o.fetch(n,{...t,headers:s})},Ol=(e,t)=>{if(typeof e=="string")return Bt(e,t);if(e instanceof URL)return Bt(e.toString(),t);const r=Bt(e.url,t);return r===e.url?e:new Request(r,e)},Nl=/\/api\/pi\/(health|projects|sessions|providers|resources|runtime|settings)(\b|\/|\?|$)/,Vr=new Map,Ll=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!Nl.test(t)?null:`GET ${t}`,b=async(e,t={})=>{const{query:r,...o}=t,n=Nr(),a=n?Hi(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,h=await Ue(g,o.headers,!0);i=e instanceof Request?()=>n.fetch(e,{...o,headers:h}):()=>n.fetch(a,{...o,headers:h}),c=a,d=String(o.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const g=Ol(e,r),h=g instanceof Request?g.headers:void 0,p=await Ue(h,o.headers,Pl(g));let k=g instanceof Request?()=>fetch(new Request(g,{...o,headers:p})):()=>fetch(g,{...o,headers:p});if(er()&&s){const A=k;k=()=>Si(A,s)}i=k,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=Ll(d,c,l);if(!u)return i();const f=Vr.get(u);if(f)return f.then(g=>g.clone());const m=i();return Vr.set(u,m),m.then(()=>Vr.delete(u),()=>Vr.delete(u)),m.then(g=>g.clone())};let hs=!1;const Ul=()=>{if(hs||typeof window>"u")return;hs=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const o=await xl(t,r??{});if(o)return o;if(typeof t=="string"){if(!en(t)){try{const a=new URL(t);if(so(a)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}}catch{}return e(t,r)}const n=await Ue(void 0,r?.headers);return e(Bt(t),{...r,headers:n})}if(t instanceof URL){const n=t.toString();if(!en(n)){if(so(t)){const s=await Ue(void 0,r?.headers);return e(t,{...r,headers:s})}return e(t,r)}const a=await Ue(void 0,r?.headers);return e(Bt(n),{...r,headers:a})}if(t instanceof Request){if(!en(t.url)){try{const i=new URL(t.url);if(so(i)){const c=await Ue(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const n=await Ue(t.headers,r?.headers),a=Bt(t.url),s=a===t.url?t:new Request(a,t);return e(new Request(s,{...r,headers:n}))}return e(t,r)}},$t=16384,Ao=globalThis,Hl=e=>{if(Ao.Buffer)return Ao.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,"")},Ki=e=>{try{if(Ao.Buffer)return Ao.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}},Kl=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}},jl=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}},Fs=e=>typeof e=="string"&&e.length>0,$l=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Fs(t.x)||!Fs(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},zl=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ql=e=>{if(!e||typeof e!="object")return null;const t=e,r=zl(t.priority);if(t.type==="lan"||t.type==="tunnel"||t.type==="tailscale"){const o=Kl(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=jl(t.relayUrl);if(!o)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const a=$l(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},wa=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(ql).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}),Mb=e=>{const t=wa(e);if(!t)throw new Error("Invalid pairing connection payload");const r=new URLSearchParams;return r.set("v","2"),r.set("p",Hl(JSON.stringify(t))),`pichamber://connect?${r.toString()}`},Wl=e=>{const t=e.trim();if(!t||t.length>$t)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>$t)return null;const n=Ki(o);return!n||n.length>$t?null:wa(JSON.parse(n))}catch{return null}},Tb=e=>{const t=e.trim();if(!t||t.length>$t)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>$t)return null;const a=Ki(n);if(!a||a.length>$t)return null;try{return wa(JSON.parse(a))}catch{return null}},Gt=e=>typeof e=="object"&&e!==null,Gl=e=>e.trim().toLowerCase()==="authorization",Vl=e=>{if(!Gt(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)||Gl(n)||(t[n]=a)}return Object.keys(t).length>0?t:void 0},ji=e=>`relay://${e}`,Jl=e=>{if(!Gt(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||!Gt(o)?null:{relayUrl:t,serverId:r,hostEncPubJwk:o}},Yl=()=>{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"},$i=5e3,Xl=async(e,t,r)=>{const o=Wl(e);if(!o)throw new Error("invalid-connect-link");const n=await Wi().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:Yl(),...n?{dedupeKey:`desktop:${n}`}:{}})},s=async w=>{if(!w.ok)return null;const B=await w.json().catch(()=>null);return(typeof B?.clientToken=="string"?B.clientToken.trim():"")||null};let i=null;const c=[...o.candidates].sort((w,B)=>(w.type==="relay"?1:0)-(B.type==="relay"?1:0));for(const w of c){if(w.type==="relay"){const P=ia({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const ee=await s(await P.fetch("/api/client-auth/pairing/redeem",a));if(ee){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:ee};break}}catch{}finally{P.close()}continue}const B=X(w.url);if(B)try{const P=await s(await fetch(`${B}/api/client-auth/pairing/redeem`,a));if(P){i={directUrl:B,token:P};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const d=o.candidates.find(w=>w.type==="relay"),l=i.relay||(d?{relayUrl:d.relayUrl,serverId:d.serverId,hostEncPubJwk:d.hostEncPubJwk}:void 0),u=o.candidates.filter(w=>w.type!=="relay").map(w=>X(w.url)).find(w=>!!w),f=i.directUrl||u,m=f||(l?ji(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");let g=null;if(i.directUrl){const w=r?.healthTimeoutMs??$i,B=new AbortController,P=setTimeout(()=>B.abort(),w);try{const ee=await fetch(`${i.directUrl}/health`,{headers:{Accept:"application/json"},signal:B.signal,credentials:"omit"});if(ee.ok){const Be=await ee.json().catch(()=>null),se=typeof Be?.serverId=="string"?Be.serverId.trim():"";se&&(g=se)}}catch{}finally{clearTimeout(P)}}const h=new Set;l?.serverId&&h.add(l.serverId),g&&h.add(g);const p=w=>{for(const B of h)if(w.serverId===B||w.relay?.serverId===B)return!0;return!1},k=t.find(w=>{if(l){if(w.relay?.serverId===l.serverId)return!0}else if(!w.relay&&X(w.apiUrl||w.url)===m)return!(w.serverId&&g&&w.serverId!==g);return p(w)}),A=k?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),C={...k||{},id:A,label:o.label||k?.label||Ba(m),url:m,apiUrl:f,clientToken:i.token,...l?{relay:l}:{}};return k?.serverId?C.serverId=k.serverId:g&&(C.serverId=g),{hostId:A,hosts:k?t.map(w=>w.id===A?C:w):[C,...t]}},Ql=/^(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}},Zl=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"}},Ba=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)Ql.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},ys=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},eu=e=>{if(!Gt(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=Vl(e.requestHeaders),i=Jl(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,tu=(e,t)=>{const r={...e,url:t,apiUrl:t};return X(_e(e))!==X(t)&&delete r.serverId,r},St=()=>Z()?(e,t)=>j(e,t):null,Ca=async()=>{const e=St();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Gt(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const r=t.hosts,o=Array.isArray(r)?r.map(eu).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}},zi=async e=>{const t=St();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})},qi=async()=>{const e=St();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Wi=async()=>{const e=St();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},ru=8e3,bs=async(e,t,r)=>{const o=new AbortController,n=window.setTimeout(()=>o.abort(),ru);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(n)}},ou=async(e,t)=>{const r=ia({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),o=Date.now();let n=!1;try{if(!(await bs(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 bs(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()}},va=async(e,t)=>{const r=St();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(!Gt(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=ys(o,"latencyMs")??ys(o,"latency_ms")??0,i=Y(o,"reportedServerId");return{status:a,latencyMs:s,...i?.trim()?{reportedServerId:i.trim()}:{}}},nu=async(e,t)=>{const r=St();r&&await r("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},au=async e=>{const t=St();t&&await t("desktop_new_window_for_host",{hostId:e})},Pb=Object.freeze(Object.defineProperty({__proto__:null,DESKTOP_HOST_HEALTH_PIN_TIMEOUT_MS:$i,desktopHostProbe:va,desktopHostsGet:Ca,desktopHostsSet:zi,desktopInstallIdGet:Wi,desktopLocalClientTokenGet:qi,desktopOpenNewWindowAtUrl:nu,desktopOpenNewWindowForHost:au,getDesktopHostApiUrl:_e,importDesktopHostPairing:Xl,locationMatchesHost:rt,normalizeHostUrl:X,probeRelayDesktopHost:ou,redactSensitiveUrl:Ba,relayHostDisplayUrl:ji,resolveDesktopHostUrl:Zl,withEditedDesktopHostUrl:tu},Symbol.toStringTag,{value:"Module"})),ot="local",su=e=>({id:ot,label:"Local",url:e||ka()}),ka=()=>typeof window>"u"?"":window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,Da=e=>e.id===ot?"local":`host:${e.id}`,As="host:",Gi=e=>{const t=e.runtimeKey.trim();if(t===ot)return{kind:"local"};if(t.startsWith(As)){const o=t.slice(As.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},iu=e=>{const t=typeof window>"u"?"":window.location.href,r=e.find(l=>l.id===ot)?.url||ka(),o=ze(),n=X(r)||r,a=X(t)||t,s=D(),i=e.find(l=>l.relay&&Da(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:Ba(a||"Instance"),url:a}},Rb=Object.freeze(Object.defineProperty({__proto__:null,LOCAL_HOST_ID:ot,buildLocalDesktopHost:su,getLocalDesktopOrigin:ka,resolveCurrentDesktopHost:iu,resolveDesktopHostIdentity:Gi,runtimeKeyForDesktopHost:Da},Symbol.toStringTag,{value:"Module"})),cu=5e3,du=1500;let tn=!1;const lu=async e=>{if(!_o()||tn)return;const t=`host:${e}`;if(D()===t){tn=!0;try{const r=await Ca().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 b("/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 h=X(g.url),p=g.type==="tailscale"?d:c;h&&!p.includes(h)&&p.push(h)}const l=c.length>0?c:d;if(l.length===0)return;const u=n&&l.includes(n)?n:l[0];u!==n&&await zi({hosts:r.hosts.map(m=>m.id===e?{...m,apiUrl:u}:m),defaultHostId:r.defaultHostId,initialHostChoiceCompleted:r.initialHostChoiceCompleted}).catch(()=>{});const f=await va(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;jt({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:t})}finally{tn=!1}}},uu=e=>{typeof window>"u"||window.setTimeout(()=>{lu(e).catch(()=>{})},cu)},fu=(e,t)=>{if(t){const o=e.hosts.find(n=>n.id===t);return o?{kind:"host",host:o}:null}const r=Gi({runtimeKey:D(),apiBaseUrl:ze(),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"}},mu=(e,t)=>{const r=e.clientToken||"";!r||Ro()===r||jt({apiBaseUrl:ze()||_e(e),clientToken:r,requestHeaders:e.requestHeaders||null,runtimeKey:t,relay:Qt()?e.relay:void 0})},gu=async e=>{if(!_o())return;const t=await Ca().catch(()=>null);if(!t)return;const r=fu(t,e);if(!r)return;if(r.kind==="local"){const u=await qi();if(!u)return;const f=t.localOrigin||ze();if(!f||D()==="local"&&Ro()===u)return;jt({apiBaseUrl:f,clientToken:u,runtimeKey:"local"});return}const o=r.host,n=Da(o),a=u=>{jt({apiBaseUrl:u,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:n})},s=()=>{jt({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:o.clientToken||null,runtimeKey:n,relay:o.relay??void 0}),uu(o.id)};if(D()===n){const u=o.apiUrl?X(_e(o)):"";if(!!(u&&rt(ze(),u))||!o.relay){mu(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=va(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),du))]);if(l){if(c(l)){a(i);return}s();return}s(),d.then(u=>{c(u)&&D()===n&&a(i)})},pu=64*1024,hu=(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+pu,e.size),s=new Uint8Array(await e.slice(o,a).arrayBuffer());o=a,n.enqueue(s),r?.({loaded:o,total:e.size})}})},Fu=(e,t)=>!er()||e instanceof File?e:new File([e],t.filename,{type:t.mime||e.type}),yu=async(e,t,r)=>{const o=!!Nr();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?hu(t,r.signal,r.onProgress):Fu(t,r),signal:r.signal,...o?{duplex:"half"}:{}},a=await b(e,n);return!o&&a.ok&&r.onProgress?.({loaded:t.size,total:t.size}),a},_t=1,bu="events.streamEpoch",Au=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},Ib="pichamber.bash",_b=64*1024,Es=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0,Vi=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return!(t.snoozedUntil!==void 0&&(!Es(t.snoozedUntil)||!Es(t.snoozedAt)))},Eu=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(Vi)},wu=["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","session.moved","extension.entry","extension.message","extension.notify","extension.catalog","extension.editor","extension.title","extension.status","extension.control","extension.widget","extension.dialog","extension.dialog.dismiss","extension.working","extension.editor.track","extension.custom","extension.custom.frame","extension.custom.dismiss","extension.error"],kn=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.protocolVersion===_t&&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))&&wu.includes(t.name)},Ji=(e,t)=>{const r=Nr();return r?r.openWebSocket(Md(e),t):Bd(new WebSocket(e))},Yi="pichamber.mobile.diagnostics.v1",Sa=300,Bu=240,Cu=1e3;let Vt=[],ws=!1,zt=null,rn=!1;const Nt=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,Bu)||void 0,vu=e=>{if(!e||typeof e!="object")return{detail:Nt(e)};const t=e;return{...typeof t.code=="string"?{code:Nt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.message!==void 0?{detail:Nt(t.message)}:typeof t.name=="string"?{detail:Nt(t.name)}:{}}},Xi=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},xo=()=>{if(ws)return;ws=!0;const e=Xi();if(e)try{const t=e.getItem(Yi);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)}Vt=[...o,...Vt].slice(-Sa)}catch{}},ku=()=>{zt!==null&&(clearTimeout(zt),zt=null)},Du=()=>{zt===null&&(zt=setTimeout(()=>{zt=null,io()},Cu))},io=()=>{ku();const e=Xi();if(e)try{xo(),e.setItem(Yi,JSON.stringify(Vt.slice(-Sa)))}catch{}},W=(e,t={})=>{if(!er())return;xo();const r={at:new Date().toISOString(),category:e.trim().slice(0,80)||"unknown",...t.code?{code:Nt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.detail!==void 0?{detail:Nt(t.detail)}:{}};Vt=[...Vt,r].slice(-Sa),Du()},Su=(e,t)=>{W(e,vu(t))},Mu=()=>(xo(),JSON.stringify({format:"pichamber-mobile-diagnostics-v1",generatedAt:new Date().toISOString(),platform:typeof navigator>"u"?"unknown":navigator.userAgent,entries:Vt},null,2)),xb=async()=>{const e=Mu(),{isShareCancelledError:t,saveOrShareFile:r}=await qc(async()=>{const{isShareCancelledError:n,saveOrShareFile:a}=await import("./nativeFileSave-Bj-V_9ae.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")},Ob=()=>{if(!er()||typeof window>"u"||rn)return()=>{};rn=!0,xo(),W("app-launch",{code:"start"});const e=n=>{W("window-error",{code:n.error?.name,detail:n.message})},t=n=>{Su("unhandled-rejection",n.reason)},r=()=>{io()},o=()=>{document.visibilityState==="hidden"&&io()};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),io(),rn=!1}},Tu=3e4,Pu=250,Ru=5e3,Iu=6e4,_u=8,xu=2e3,Ou=1e4,Nu=5e3,Lu=3e4,Uu=5e3,xt=new Map,Hu=8,Ku=(e,t)=>{if(!(!e||!t||t.length>128))for(xt.delete(e),xt.set(e,t);xt.size>Hu;){const r=xt.keys().next();if(r.done)break;xt.delete(r.value)}};let Br=null;const Nb=e=>(Br=e,()=>{Br===e&&(Br=null)}),Ze=(e=D(),t)=>{if(t&&Br){const r=Br(e,t);if(r!==void 0)return r??void 0}return xt.get(e)},Qi=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),typeof e.cursor=="string"&&e.cursor.length>0&&(t.cursor=e.cursor),t.capabilities=bu,t},Bs=(e,t,r)=>{const o=Ie(),n=Qi(t);return e==="ws"?o.websocket("/api/pi/events",n,r):o.sse("/api/pi/events",n)},ju=()=>"/api/pi/runtime",co=()=>er()&&!Qt()&&typeof EventSource<"u",$u=3e3;let Dn=null,Fr=null;const Lb=()=>{Dn=null,Fr=null},zu=1e4,Jr=e=>({...e,capabilities:[...e.capabilities]}),Eo=async(e,t,r)=>{const o=t??D();if(!r?.fresh){const s=Dn;if(s&&s.runtimeKey===o&&s.runtimeKey===D()&&Date.now()<s.expiresAt)return Jr(s.result)}const n=!r?.fresh&&!e;if(n){const s=Fr;if(s&&s.runtimeKey===o&&s.runtimeKey===D())return s.promise.then(Jr)}const a=async()=>{const s=r?.timeoutMs??zu,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 b(ju(),{signal:i.signal});if(o!==D())return{state:"unavailable",protocolVersion:_t,capabilities:[],error:{code:"DAEMON_UNAVAILABLE",message:"Runtime changed during request"}};if(!l.ok)return W("runtime-health",{status:l.status,code:l.status===401||l.status===403?"auth":"http-error"}),{state:"unavailable",protocolVersion:_t,capabilities:[],error:{code:l.status===401||l.status===403?"DAEMON_AUTH_FAILED":"DAEMON_UNAVAILABLE"}};const f=await Si(()=>l.json(),i.signal).catch(p=>{if((p instanceof DOMException||p instanceof Error)&&p.name==="AbortError")throw p;return null});if(!f||typeof f!="object")return{state:"unavailable",protocolVersion:_t,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&&Ku(o,g);const h={state:f.state==="ready"?"ready":"unavailable",protocolVersion:typeof f.protocolVersion=="number"?f.protocolVersion:_t,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter(p=>typeof p=="string"):[],...g?{streamEpoch:g}:{},...m?{error:{code:m,...typeof f.error?.message=="string"?{message:f.error.message}:{}}}:{}};return!r?.fresh&&h.state==="ready"&&o===D()&&(Dn={runtimeKey:o,result:Jr(h),expiresAt:Date.now()+$u}),h}catch(l){const u=(l instanceof DOMException||l instanceof Error)&&l.name==="AbortError";return W("runtime-health",{code:u?"timeout":"unreachable"}),{state:"unavailable",protocolVersion:_t,capabilities:[],error:{code:u?"DAEMON_TIMEOUT":"DAEMON_UNAVAILABLE"}}}finally{clearTimeout(d),e&&e.removeEventListener("abort",c)}};if(n){const s=a().finally(()=>{Fr?.promise===s&&(Fr=null)});return Fr={runtimeKey:o,promise:s},s.then(Jr)}return a()},qu=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 Eo(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)}},Wu=(e,t,r,o,n,a,s)=>{if(co()){const f=new EventSource(Ie().sse("/api/pi/events",e)),m=new AbortController;let g=!1,h=!1,p=setTimeout(()=>{p=null,!(h||g)&&(W("stream-connect",{code:"setup-timeout"}),C(),a("sse-setup-timeout"))},s.setupTimeoutMs);const k=()=>{p&&clearTimeout(p),p=null},A=()=>{g||o()},C=()=>{k(),m.abort(),!g&&(g=!0,f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C))},w=B=>{try{const P=JSON.parse(B);kn(P)&&n(P)}catch{W("stream-frame",{code:"bad-sse-frame"})}};return f.onopen=()=>{g||(h=!0,k(),r())},f.onmessage=B=>{g||(o(),typeof B.data=="string"&&B.data.trim()&&w(B.data))},f.onerror=()=>{if(g)return;k(),f.removeEventListener("heartbeat",A),f.close(),t.removeEventListener("abort",C),g=!0,W("stream-disconnect",{code:"sse-error"});const B=s.classifySourceError;if(!B){a("sse-error");return}B(m.signal).then(P=>{m.signal.aborted||a(P==="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)&&(W("stream-connect",{code:"setup-timeout"}),a("sse-setup-timeout"),c())},s.setupTimeoutMs);const u=()=>{l&&clearTimeout(l),l=null};return b("/api/pi/events",{headers:{Accept:"text/event-stream"},query:e,signal:i.signal}).then(async f=>{if(!f.ok||!f.body){if(W("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 h="",p=[];const k=()=>{if(p.length===0)return;const A=p.join(`
3
3
  `).trim();if(p=[],!!A)try{const C=JSON.parse(A);kn(C)&&n(C)}catch{}};for(;;){const{value:A,done:C}=await m.read();if(C){k(),u(),a("sse-eof");return}o(),h+=g.decode(A,{stream:!0});let w=h.indexOf(`
4
4
  `);for(;w!==-1;){const B=h.slice(0,w).replace(/\r$/,"");h=h.slice(w+1),B.length===0?k():B.startsWith("data:")&&p.push(B.slice(5).replace(/^ /,"")),w=h.indexOf(`
5
5
  `)}}}).catch(f=>{if(i.signal.aborted)return;const m=f instanceof Error?f.message.slice(0,80):"fetch-failed";W("stream-connect",{code:"fetch-failed",detail:m}),a(`sse-error:${m}`)}).finally(()=>{u(),t.removeEventListener("abort",c)}),c},Gu=(e,t,r,o,n,a)=>{const s=Ji(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);kn(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},Cs=()=>typeof document>"u"||document.visibilityState==="visible",vs=()=>typeof navigator>"u"||navigator.onLine!==!1,Ub=(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=typeof t.cursor=="string"&&t.cursor.length>0?t.cursor:void 0,m=t.transport==="ws"?"ws":"sse",g=null,h=null,p=null,k=null,A=0,C=!1,w=!1;const B=t.setupTimeoutMs??Ou,P=t.authTokenTimeoutMs??Nu,ee=t.healthResetMs??Lu,Be=t.epochProbeTimeoutMs??Uu;let se=null;const We=new Set;let Ce=!1,te=null,Tt=null,or=null,qr=!1;const nr=()=>{g&&clearTimeout(g),h&&clearTimeout(h),p&&clearTimeout(p),g=null,h=null,p=null},Oe=()=>{A+=1,k?.(),k=null,h&&clearTimeout(h),h=null,p&&clearTimeout(p),p=null},ar=E=>{h&&clearTimeout(h),h=setTimeout(()=>{E===A&&G("heartbeat-timeout",E)},t.heartbeatTimeoutMs??Tu)},$o=E=>{c||a.aborted||E!==A||(ar(E),qr&&dt(E),qr=!0)},v=E=>{if(c||a.aborted||E!==A)return;const R=!C;C=!0,w=!1,R&&(p&&clearTimeout(p),p=setTimeout(()=>{p=null,E===A&&C&&(d=0)},ee),W("stream-ready",{code:m}),e.onReconnect?.()),ar(E)},U=()=>{const E=Cs()&&vs()?Ru:Iu,R=Math.min(_u,d),T=Math.min(E,Pu*2**R);return d===0&&t.reconnectDelayMs!==void 0?Math.max(0,t.reconnectDelayMs):T+Math.floor(Math.random()*100)},N=(E,R=!0)=>{c||a.aborted||g||(W("stream-reconnect",{code:E}),R&&e.onDisconnect?.(E),g=setTimeout(()=>{g=null,d+=1,le()},U()))},$=()=>{c||a.aborted||!g||(clearTimeout(g),g=null,d+=1,le())},G=(E,R)=>{if(!(c||a.aborted||R!==A)){if(Oe(),!C&&m==="ws"&&t.transport!=="ws"&&(m="sse",e.onTransportSwitch?.()),C=!1,E==="runtime-change"){e.onDisconnect?.(E);return}if(E==="sse-auth-401"||E==="sse-auth-403"||E==="sse-auth-probe"){W("stream-auth",{code:E}),e.onDisconnect?.(E),e.onAuthRequired?.();return}N(E)}},de=(E,R)=>{if(c||a.aborted||R!==A)return;if(!i()){G("runtime-change",R);return}if(typeof E.stream=="string"||E.name==="session.moved"){typeof E.cursor=="string"&&E.cursor.length>0&&(f=E.cursor),v(R),e.onEvent(E);return}const T=typeof E.streamEpoch=="string"&&E.streamEpoch.length>0?E.streamEpoch:null;if(T&&T!==se){if(We.has(T)){W("stream-epoch",{code:"retired-frame"});return}const z=se??l;if(z!==null&&z!==T){if(Ce){Tt??={event:E,epoch:T,connectionId:R};return}ae(E,T,z,R);return}se=T,u=Math.max(u??0,E.sequence),z===null&&e.onEpochChange?.(T)}(u===void 0||E.sequence>u)&&(u=E.sequence),v(R),e.onEvent(E)},ae=async(E,R,T,z)=>{Ce=!0,te=new AbortController;const ue=setTimeout(()=>te?.abort(),Be);try{const ve=await Eo(te.signal,s,{fresh:!0});if(c||a.aborted||z!==A)return;if(ve.state==="ready"&&ve.streamEpoch===R){We.add(T),se=R,u=E.sequence,W("stream-epoch",{code:"verified"}),e.onEpochChange?.(R),v(z),e.onEvent(E);return}if(ve.state==="unavailable"&&ve.error?.code==="DAEMON_AUTH_FAILED"){G("sse-auth-probe",z);return}if(ve.state==="ready"){We.add(R),W("stream-epoch",{code:"rejected"});return}W("stream-epoch",{code:"unverified"}),G("epoch-unverified",z)}finally{clearTimeout(ue),Ce=!1,te=null,Tt=null,Pt()}},dt=async E=>{const R=se??l;if(!R)return;if(Ce){or=E;return}Ce=!0,te=new AbortController;const T=setTimeout(()=>te?.abort(),Be);try{const z=await Eo(te.signal,s,{fresh:!0});if(c||a.aborted||E!==A)return;const ue=z.state==="ready"?z.streamEpoch:void 0;if(!ue||ue===R||We.has(ue)||(se??l)!==R)return;We.add(R),se=ue,u=void 0,W("stream-epoch",{code:"verified-on-resubscribe"}),e.onEpochChange?.(ue)}catch{}finally{clearTimeout(T),Ce=!1,te=null;const z=Tt;Tt=null,z&&de(z.event,z.connectionId),Pt()}},Pt=()=>{const E=or;or=null,!(E===null||c||a.aborted||E!==A)&&dt(E)},Fe=async()=>{let E=null;try{return await Promise.race([Hr(),new Promise((R,T)=>{E=setTimeout(()=>T(new Error("url-token-timeout")),P)})])}finally{E&&clearTimeout(E)}},le=async()=>{if(c||a.aborted)return;if(!i()){e.onDisconnect?.("runtime-change");return}const E=A+1;A=E;let R;if(m==="ws")try{R=await Fe()}catch{if(E!==A||c||a.aborted)return;if(t.transport!=="ws"){m="sse",e.onTransportSwitch?.(),Oe(),le();return}W("stream-auth",{code:"url-token-unavailable"}),G("ws-auth-token-unavailable",E);return}if(E!==A||c||a.aborted)return;if(!i()){G("runtime-change",E);return}if(m==="sse"&&co()){try{await Fe()}catch{if(E!==A||c||a.aborted)return;W("stream-auth",{code:"url-token-unavailable"}),G("sse-auth-token-unavailable",E);return}if(E!==A||c||a.aborted||!i())return}const T=se??l??void 0,z=Bs(m,{...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...T?{streamEpoch:T}:{},...f?{cursor:f}:{}},R),ue=()=>$o(E),ve=I=>de(I,E),sr=I=>G(I,E),ir=Qi({...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...T?{streamEpoch:T}:{},...f?{cursor:f}:{}});k=m==="ws"?Gu(z,a,ue,ve,sr,xu):Wu(ir,a,ue,()=>v(E),ve,sr,{setupTimeoutMs:B,...co()?{classifySourceError:I=>qu(s,Be,I)}:{}})},Ge=()=>{!Cs()||!vs()||$()},lt=()=>{if(!(!co()||c||a.aborted)){if(w){$();return}w=!0,nr(),Oe(),C=!1,N("system-resume",!1)}};typeof window<"u"&&(window.addEventListener("pichamber:system-resume",lt),window.addEventListener("online",Ge)),typeof document<"u"&&document.addEventListener("visibilitychange",Ge);const ut=()=>{c||(c=!0,typeof window<"u"&&(window.removeEventListener("pichamber:system-resume",lt),window.removeEventListener("online",Ge)),typeof document<"u"&&document.removeEventListener("visibilitychange",Ge),o?.removeEventListener("abort",n),a.removeEventListener("abort",ut),nr(),Oe(),te?.abort(),te=null,a.aborted||r.abort())};return a.aborted?ut():a.addEventListener("abort",ut,{once:!0}),le(),{dispose:ut,reconnect:(E="manual")=>{c||a.aborted||(nr(),Oe(),N(E))},get eventsUrl(){const E=se??l??void 0;return Bs(m,{...u!==void 0?{fromSequence:u}:{},...t.sessionId?{sessionId:t.sessionId}:{},...E?{streamEpoch:E}:{},...f?{cursor:f}:{}})}}},Vu=3e4,Rt=6e4,Ju=1,Yu=300,Xu=e=>new Promise(t=>setTimeout(t,e)),ks=660*1e3,y=async(e,t)=>{const r=t.runtimeKey;if(r&&r!==D())throw new L("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?Ju: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 L("DAEMON_UNAVAILABLE","Runtime changed during request");if(await Xu(Yu),t.signal?.aborted)break;if(r&&r!==D())throw new L("DAEMON_UNAVAILABLE","Runtime changed during request")}const d=new AbortController,l=setTimeout(()=>d.abort(),t.timeoutMs??Vu),u=t.signal,f=()=>d.abort();u&&(u.aborted?d.abort():u.addEventListener("abort",f,{once:!0}));try{const m=await b(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 p=(await m.json().catch(()=>null))?.error??{code:"DAEMON_REQUEST_FAILED"};if(m.status===503&&(p.code==="DAEMON_UNAVAILABLE"||p.code==="DAEMON_TIMEOUT")&&c<s&&!u?.aborted){i=new L(p.code,p.message,m.status);continue}throw new L(p.code,p.message,m.status,p.reason,p.messages)}if(m.status===204){if(r&&r!==D())throw new L("DAEMON_UNAVAILABLE","Runtime changed during request");return}const g=await m.json();if(r&&r!==D())throw new L("DAEMON_UNAVAILABLE","Runtime changed during request");return g}catch(m){if(i=m,m instanceof L||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 L extends Error{code;status;reason;messages;constructor(t,r,o,n,a){super(r??`Pi request failed: ${t}`),this.name="PiRequestError",this.code=t,o!==void 0&&(this.status=o),typeof n=="string"&&(this.reason=n),Array.isArray(a)&&(this.messages=a.filter(s=>typeof s=="string"))}}class ur extends Error{code;status;reason;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),typeof o?.reason=="string"&&(this.reason=o.reason),o?.cause!==void 0&&this.cause===void 0&&(this.cause=o.cause)}}const Qu=e=>{if(!e||typeof e!="object")return!1;const t=e;if(!Array.isArray(t.sessions))return!1;if(t.sequence===void 0){if(t.incomplete!==!0)return!1}else if(!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||!Au(o.pending))return!1}return!0},on=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)},Zu=e=>{if(!(e instanceof L))return!1;const t=e.status;return typeof t!="number"||!Number.isInteger(t)?!1:t===503&&e.code==="SANDBOX_UNAVAILABLE"?!0:!(t<400||t>499||t===408||e.code==="OPERATION_EXPIRED"||e.code==="STALE_STREAM_EPOCH")},nn=e=>e instanceof ur?e:e instanceof L?new ur(e.code,e.message,{status:e.status,cause:e,reason:e.reason}):e instanceof DOMException&&e.name==="AbortError"?new ur("DAEMON_TIMEOUT",e.message||"Send timed out",{cause:e}):e instanceof Error?new ur("DAEMON_REQUEST_FAILED",e.message,{cause:e}):new ur("DAEMON_REQUEST_FAILED",void 0,{cause:e}),F=e=>{if(e?.runtimeKey&&e.runtimeKey!==D())throw new L("DAEMON_UNAVAILABLE","Runtime changed during request")},Yr=(e,t,r)=>{const o=Ze(e,t);if(!r||!o||r!==o)throw new L("STALE_STREAM_EPOCH","The Pi runtime restarted before this send could be verified.",409);return r},Zi=5e3,Ds=32,be=new Map,Xr=new Map,ec=new Map,ef=(e,t)=>`${e}
6
6
  ${t?.trim()??""}`,lo=e=>ec.get(e)??0,Qr=e=>{ec.set(e,lo(e)+1);const t=`${e}
7
- `;for(const r of[...be.keys()])r.startsWith(t)&&be.delete(r)},tf=(e,t,r)=>{if(be.size>=Ds){const o=Date.now();for(const[n,a]of be)o-a.settledAt>=Zi&&be.delete(n);for(;be.size>=Ds;){const n=be.keys().next().value;if(typeof n!="string")break;be.delete(n)}}be.set(e,{response:t,settledAt:r})};class rf{currentDirectory;setDirectory(t){this.currentDirectory=t}getDirectory(){return this.currentDirectory}async health(t){F(t);const r=await Eo(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 F(t),y("/api/pi/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async selectProject(t,r){return F(r),y("/api/pi/projects/select",{method:"POST",body:{directory:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSessions(t){F(t);const r=t?.directory??this.currentDirectory;return y("/api/pi/sessions",{method:"GET",...r?{query:{directory:r}}:{},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listPendingInput(t){F(t);const r=await y("/api/pi/sessions/pending-input",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!Qu(r))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed pending-input list");return r}async createSession(t,r){return F(r),y("/api/pi/sessions",{method:"POST",body:t,timeoutMs:Rt,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSession(t,r){F(r);const o=r?.directory??this.currentDirectory;return y(`/api/pi/sessions/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:Rt,...o?{query:{directory:o}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSessionMessages(t,r,o){F(o);const n=o?.directory??this.currentDirectory;return y(`/api/pi/sessions/${encodeURIComponent(t)}/messages`,{method:"GET",timeoutMs:Rt,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){F(r),await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"PATCH",body:{sessionId:t.sessionId,title:t.title},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async discardDraftSession(t,r){return F(r),(await y(`/api/pi/sessions/${encodeURIComponent(t)}/discard-draft`,{method:"POST",...r?.directory?{query:{directory:r.directory}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.discarded===!0}async deleteSession(t,r){F(r);try{return await y(`/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 L&&o.status===404)return!0;throw o}}async archiveSession(t,r){F(r),await y(`/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){F(t);const r=await y("/api/pi/session-shelf",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!Eu(r))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf");return r}async setSessionShelf(t,r){F(r);const{sessionId:o,...n}=t,s=(await y(`/api/pi/sessions/${encodeURIComponent(o)}/shelf`,{method:"POST",body:{...n,...r?.directory?{directory:r.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.entry;if(s!==null&&!Vi(s))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf entry");return s}async getSessionTree(t,r){return F(r),y(`/api/pi/sessions/${encodeURIComponent(t)}/tree`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async navigateSession(t,r,o){return F(o),y(`/api/pi/sessions/${encodeURIComponent(t)}/navigate`,{method:"POST",body:{messageId:r},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async forkSession(t,r){return F(r),y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/fork`,{method:"POST",timeoutMs:Rt,body:{sessionId:t.sessionId,...t.messageId?{messageId:t.messageId}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async cloneSession(t,r){return F(r),y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/clone`,{method:"POST",body:t,timeoutMs:Rt,...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();F({...r,runtimeKey:o});const n=Yr(o,t.sessionId,t.streamEpoch??r?.streamEpoch??Ze(o,t.sessionId)),a=r?.directory??this.currentDirectory,s=await y(`/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(F({...r,runtimeKey:o}),Yr(o,t.sessionId,n),!s||typeof s!="object")throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");const i=s.status;if(i==="accepted"){const c=s.receipt;if(!on(c))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");return{status:"accepted",receipt:c}}if(i==="pending"||i==="expired"||i==="unknown")return{status:i};throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt")}async sendWithReceipt(t,r,o,n){const a=n?.runtimeKey??D();let s;try{F({...n,runtimeKey:a}),s=Yr(a,r.sessionId,n?.streamEpoch??Ze(a,r.sessionId))}catch(c){throw nn(c)}const i=n?.directory??this.currentDirectory;try{const c=await y(o,{method:"POST",body:{...r,streamEpoch:s},...i?{query:{directory:i}}:{},runtimeKey:a,retry:!1,timeoutMs:Rt});if(!on(c))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send response");return F({...n,runtimeKey:a}),Yr(a,r.sessionId,s),c}catch(c){if(c instanceof L&&c.code==="STALE_STREAM_EPOCH")throw nn(c);if(Zu(c))throw c;const d=r.operationId;if(typeof d=="string"&&d.length>0)try{F({...n,runtimeKey:a});const l=this.getSendReceipt;if(!l)throw new L("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(F({...n,runtimeKey:a}),typeof u=="object"&&u!==null&&u.status==="accepted"&&on(u.receipt))return u.receipt}catch{}throw nn(c)}}async abortSession(t,r){F(r),await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setSessionModel(t,r){F(r),await y(`/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){F(r),await y(`/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(F(r),(await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).accepted!==!0)throw new L("DAEMON_PROTOCOL_MISMATCH")}async runBash(t,r){F(r);const o=await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash`,{method:"POST",body:{command:t.command,...t.excludeFromContext?{excludeFromContext:!0}:{},...t.clientId?{clientId:t.clientId}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});if(o?.accepted!==!0||typeof o.id!="string")throw new L("DAEMON_PROTOCOL_MISMATCH");return{id:o.id}}async abortBash(t,r){F(r),await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listProviders(t){return F(t),y("/api/pi/providers",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listEngines(t){return F(t),y("/api/pi/engines",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async refreshProviders(t){return F(t),y("/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 F(r),y(`/api/pi/providers/${encodeURIComponent(t)}/status`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async loginProvider(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/login`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderLogin(t,r,o){return F(o),y(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async respondProviderLogin(t,r,o,n){return F(n),y(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}/respond`,{method:"POST",body:{value:o},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async logoutProvider(t,r){F(r),await y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/logout`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderConfig(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t)}/config`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setProviderModels(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async addProviderModel(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"POST",body:t.model,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSandboxStatus(t){return F(t),y("/api/pi/sandbox",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async recheckSandbox(t){return F(t),y("/api/pi/sandbox/recheck",{method:"POST",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listProjectSandboxes(t){return F(t),y("/api/pi/sandbox/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getSandboxDefaults(t){return F(t),(await y("/api/pi/sandbox/defaults",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})).defaults}async setSandboxDefaults(t,r){return F(r),y("/api/pi/sandbox/defaults",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setProjectSandbox(t,r,o){return F(o),(await y(`/api/pi/sandbox/projects/${encodeURIComponent(t)}`,{method:"PUT",body:r,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})).project}async getSandboxProfile(t){return F(t),(await y("/api/pi/sandbox/profile",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})).profile}async saveSandboxProfile(t,r){return F(r),(await y("/api/pi/sandbox/profile",{method:"PUT",body:{content:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).profile}async resetSandboxProfile(t){return F(t),(await y("/api/pi/sandbox/profile",{method:"DELETE",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})).profile}async getSettings(t){return F(t),y("/api/pi/settings",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async setPiSettings(t,r){return F(r),y("/api/pi/settings/pi",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPiChamberDefaults(t,r){return F(r),y("/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;F(o);const a=o?.runtimeKey??D(),s=ef(a,n),i=lo(a);if(o?.reload!==!0){const m=be.get(s);if(m&&Date.now()-m.settledAt<Zi)return structuredClone(m.response)}const c=Xr.get(s);if(c&&c.revision===i)return structuredClone(await c.promise);const d=Date.now(),l=lo(a),u={},f=(async()=>{try{const m=await y("/api/pi/resources",{method:"GET",...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});if(D()===a&&lo(a)===l){const g=be.get(s);(!g||g.settledAt<=d)&&tf(s,m,Date.now())}return m}finally{Xr.get(s)?.promise===u.promise&&Xr.delete(s)}})();return u.promise=f,Xr.set(s,{revision:l,promise:f}),structuredClone(await f)}async listCommands(t,r){return F(r),y("/api/pi/commands",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSnippets(t,r){return F(r),y("/api/pi/snippets",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async createSnippet(t,r){return F(r),y("/api/pi/snippets",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateSnippet(t,r,o,n){return F(n),y(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"PUT",body:r,...o?{query:{directory:o}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deleteSnippet(t,r,o){return F(o),y(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"DELETE",...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateResource(t,r){F(r);const o=r?.runtimeKey??D(),n=t.directory??r?.directory,a=await y(`/api/pi/resources/${encodeURIComponent(t.resourceId)}`,{method:"PUT",body:t,...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});return Qr(o),a}async createPromptTemplate(t,r,o){const n=r??t.directory??o?.directory;F(o);const a=o?.runtimeKey??D(),s=await y("/api/pi/resources/prompts",{method:"POST",body:t,...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Qr(a),s}async updatePromptTemplate(t,r,o,n){F(n);const a=n?.runtimeKey??D(),s=o??r.directory??n?.directory,i=await y(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"PUT",body:r,...s?{query:{directory:s}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}});return Qr(a),i}async deletePromptTemplate(t,r,o){F(o);const n=o?.runtimeKey??D(),a=r??o?.directory,s=await y(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"DELETE",...a?{query:{directory:a}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Qr(n),s}async createAttachment(t,r){return F(r),(await y("/api/pi/attachments",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).attachment}async uploadAttachment(t,r,o){F(o);const n=await yu("/api/pi/attachments",t,r);if(!n.ok){const i=(await n.json().catch(()=>null))?.error??{code:"ATTACHMENT_FAILED"};throw new L(i.code,i.message,n.status)}const a=await n.json();return F(o),a.attachment}async deleteAttachment(t,r){F(r),await y(`/api/pi/attachments/${encodeURIComponent(t)}`,{method:"DELETE",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listPlugins(t,r){return F(r),y("/api/pi/plugins",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPluginEnabled(t,r,o){return F(o),y(`/api/pi/plugins/${encodeURIComponent(t)}`,{method:"PUT",body:{enabled:r},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setPluginState(t,r,o){return F(o),y(`/api/pi/plugins/${encodeURIComponent(t)}/state`,{method:"PUT",body:r,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getPluginSessionState(t,r){return F(r),y(`/api/pi/plugins/sessions/${encodeURIComponent(t)}`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPluginSessionState(t,r,o,n){return F(n),y(`/api/pi/plugins/${encodeURIComponent(t)}/sessions/${encodeURIComponent(r)}`,{method:"PUT",body:o,...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async listExtensions(t,r){return F(r),y("/api/pi/extensions",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getExtensionConfig(t,r){return F(r),y("/api/pi/extensions/config",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setExtensionConfig(t,r,o){return F(o),y(`/api/pi/extensions/config/${encodeURIComponent(t)}`,{method:"PUT",body:r,retry:!1,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async removeExtensionPackage(t,r,o){return F(o),y(`/api/pi/extensions/packages/${encodeURIComponent(t)}`,{method:"DELETE",retry:!1,...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async installExtensionPackage(t,r){return F(r),y("/api/pi/extensions/packages",{method:"POST",body:t,retry:!1,timeoutMs:ks,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateExtensionPackage(t,r,o){return F(o),y(`/api/pi/extensions/packages/${encodeURIComponent(t)}/update`,{method:"POST",retry:!1,timeoutMs:ks,...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async searchMarketplace(t,r){F(r);const o={};return t.query&&(o.q=t.query),t.from&&(o.from=String(t.from)),t.pichamberOnly&&(o.pichamber="1"),y("/api/pi/marketplace/search",{method:"GET",query:o,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getMarketplaceFeatured(t){return F(t),y("/api/pi/marketplace/featured",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getMarketplacePackage(t,r){return F(r),y("/api/pi/marketplace/package",{method:"GET",query:{name:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getMarketplaceVersions(t,r){return F(r),y("/api/pi/marketplace/versions",{method:"GET",query:{names:t.join(",")},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getExtensionPalette(t,r){return F(r),y("/api/pi/extensions/palette",{method:"POST",body:{terminal:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async respondToExtensionDialog(t,r){F(r),await y("/api/pi/extensions/respond",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async runExtensionControl(t,r){F(r);const o={...t,...r?.directory?{directory:r.directory}:{}};return{ran:(await y("/api/pi/extensions/control",{method:"POST",body:o,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.ran===!0}}async sendExtensionSurface(t,r,o){F(o);const{sessionId:n,...a}=r;await y(`/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){F(r),await y(`/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 At=new rf;async function of(e){return(await af(e)).home}let Sn=null,yr=null;const Hb=()=>{Sn=null,yr=null},nf=async()=>{let e=null,t=null;try{const r=await b("/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}},af=async e=>{const t=D();if(!e?.fresh){const o=Sn;if(o&&o.key===t)return o.state;const n=yr;if(n&&n.key===t)return n.promise}const r=(async()=>{const o=await nf();return!e?.fresh&&o.home&&D()===t&&(Sn={key:t,state:o}),o})();e?.fresh||(yr={key:t,promise:r});try{return await r}finally{yr?.promise===r&&(yr=null)}};async function Kb(e,t){if(!e||e.trim().length===0)return[];const r={path:e},o=Ie().api("/api/fs/list",r),n=await b(o);if(!n.ok)return[];const a=await n.json();return Array.isArray(a.entries)?a.entries:[]}async function sf(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 b(n);if(!a.ok)return[];const s=await a.json();return Array.isArray(s.files)?s.files:[]}async function jb(e=""){try{const t=await b("/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 $b={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."}},cf=e=>typeof e=="string"&&(e==="explore"||e==="plan"||e==="review"||e==="find-bugs"||e==="write-tests"),zb=[{type:"text",key:"explore"},{type:"text",key:"plan"},{type:"text",key:"review"},{type:"text",key:"find-bugs"},{type:"text",key:"write-tests"}],qb="book-open",df=/^[^\s/]+$/,Ss=e=>e.type==="prompt"?`prompt:${e.name}`:`text:${e.key}`,Wb=(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,Gb=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Ma=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(!cf(n.key))continue;const d={type:"text",key:n.key},l=Ss(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||!df.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=Ss(i);r.has(c)||(r.add(c),t.push(i))}return t},lf=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=lf(n);a&&r.set(o,a)}return r},Jb=(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}},uf={markdown:"0.875rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.8125rem",micro:"0.75rem",settingsPageTitle:"1.125rem"};function Ms(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Zr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},an={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Zr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:an.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Zr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:an.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Zr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:an.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Zr.tool.inline})},ff=[{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'}],mf=[{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'}],tc=e=>Object.fromEntries(e.map(t=>[t.id,t])),gf=tc(ff),pf=tc(mf),hf="system",Ff="system-mono",rc=e=>typeof e=="string"&&e in gf,oc=e=>typeof e=="string"&&e in pf,sn="pichamber.pwaName",Mn="pichamber.mobileKeyboardMode",Yb="pichamber.pwaRecentSessions",yf=["native","resize-content"];function bf(e,t="resize-content"){return typeof e=="string"&&yf.includes(e)?e:t}const Af=64;function nc(e,t){if(typeof e!="string")return t;const r=e.trim().replace(/\s+/g," ");return r?r.slice(0,Af):t}const Xb=()=>!0;function Ta(e,t="resize-content"){return bf(e,t)??void 0}const Ef=()=>{if(typeof window>"u")return"resize-content";try{return Ta(localStorage.getItem(Mn))}catch{return"resize-content"}},wf=e=>{const t=Ta(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Mn):localStorage.setItem(Mn,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("/")?"/":"")},Bf=["workspace","folder","timeline","threads"],Cf="workspace",ac=e=>typeof e=="string"&&Bf.includes(e),vf=["none","dither","ascii","halftone","strands","grain"],kf="none",Pa=e=>typeof e=="string"&&vf.includes(e),Qb=e=>e!=="none"&&e!=="grain",Zb=e=>e==="dither"||e==="ascii"||e==="halftone",sc=e=>typeof e=="string"&&/^[0-9a-f]{16}$/.test(e),eA=3,tA={width:7,height:13},Ts=" .:-=+*#%@",Df=[0,32,8,40,2,34,10,42,48,16,56,24,50,18,58,26,12,44,4,36,14,46,6,38,60,28,52,20,62,30,54,22,3,35,11,43,1,33,9,41,51,19,59,27,49,17,57,25,15,47,7,39,13,45,5,37,63,31,55,23,61,29,53,21].map(e=>(e+.5)/64),rA=(e,t)=>Df[(t&7)*8+(e&7)],bt=(e,t)=>{let r=Math.imul(e,374761393)^Math.imul(t,668265263);return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967295},Tn=e=>e*e*(3-2*e),Sf=(e,t)=>{const r=Math.floor(e),o=Math.floor(t),n=Tn(e-r),a=Tn(t-o),s=bt(r,o)+(bt(r+1,o)-bt(r,o))*n,i=bt(r,o+1)+(bt(r+1,o+1)-bt(r,o+1))*n;return s+(i-s)*a},Oo=2*Math.PI/60,Mf={bottom:[.45,.78],session:[.12,.55]};function Ps(e,t,r){if(r==="none"||r==="full")return 1;const[o,n]=Mf[r],a=(e/Math.max(1,t)-o)/(n-o);return a<=0?1:a>=1?0:1-a}function Tf(e,t,r,o){const n=e/Math.max(1,r*.5),a=t/Math.max(1,o*.5),s=Math.min(1,Math.sqrt(n*n+a*a));return Tn(Math.min(1,Math.max(0,(s-.45)/.55)))}function Pf(e,t,r,o){const n=e/260,a=t/260;let s=0,i=.5,c=1;for(let l=0;l<4;l+=1)s+=i*Sf(n*c+l*17.3,a*c-l*9.1),i*=.5,c*=2;const d=Tf(e,t,r,o);return{noise:s,phase:(e*.6+t)/140+s*5,reveal:d}}function oA(e,t,r,o,n="none"){const a=Math.max(0,Math.ceil(e/r)),s=Math.max(0,Math.ceil(t/o)),i=e/2,c=t/2,d=[],l=[],u=[],f=[];for(let m=0;m<s;m+=1){const g=m*o+o/2-c;for(let h=0;h<a;h+=1){const p=Pf(h*r+r/2-i,g,e,t);n==="full"?p.reveal=1:n==="session"?p.reveal=Ps(g+c,t,n):n!=="none"&&(p.reveal*=Ps(g+c,t,n)),!(p.reveal<=0)&&(d.push(m*a+h),l.push(p.noise),u.push(p.phase),f.push(p.reveal))}}return{cols:a,rows:s,cells:Uint32Array.from(d),noise:Float32Array.from(l),phase:Float32Array.from(u),reveal:Float32Array.from(f)}}const Cr=4096,ic=Cr/(2*Math.PI),Rf=Float32Array.from({length:Cr},(e,t)=>.5+.5*Math.sin(t/ic)),No=e=>{const t=Math.floor(e*ic);return Rf[(t%Cr+Cr)%Cr]};function nA(e,t,r){const o=t*Oo,{noise:n,phase:a,reveal:s}=e;for(let i=0;i<e.cells.length;i+=1){const c=(n[i]*.55+No(a[i]-o)*.45-.35)*1.5;r[i]=c<=0?0:c>=1?s[i]:c*s[i]}}function aA(e,t,r){const o=t*Oo,{noise:n,phase:a}=e;for(let s=0;s<e.cells.length;s+=1)r[s]=n[s]*.55+No(a[s]-o)*.45}function sA(e,t,r){const o=t*Oo,{noise:n,phase:a}=e;for(let s=0;s<e.cells.length;s+=1)r[s]=n[s]*4*Math.PI+(No(a[s]-o)-.5)*1.2}const iA=(e,t)=>bt(e,t),cA=(e,t,r,o,n)=>{const a=(.2126*e+.7152*t+.0722*r)/255,s=n?a:1-a;return Math.min(1,Math.max(0,(s-.08)/.84))*(o/255)},If=.4;function dA(e,t,r,o){const n=r*Oo,{phase:a,reveal:s}=e;for(let i=0;i<e.cells.length;i+=1){const c=t[i]+(No(a[i]-n)-.5)*If;o[i]=c<=0?0:c>=1?s[i]:c*s[i]}}const lA=e=>Math.min(Ts.length-1,Math.floor(e*Ts.length)),_f=365,Jt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=_f,uA=e=>e===1?"1 session":`${e} sessions`,Se=20,xf=8,Rs=4096,Of=2160*60*6e4,H=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=H(t),o=H(e);if(!r||!o)return!1;const n=Xe(r),a=Xe(o);return a===n||a.startsWith(`${n}/`)},fr=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=H(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=>H(m)).filter(m=>m.length<=Rs&&et(m,a)))).slice(-50):[],c=Array.isArray(s.expandedPaths)?Array.from(new Set(s.expandedPaths.filter(m=>typeof m=="string").map(m=>H(m)).filter(m=>m.length<=Rs&&et(m,a)))).slice(-500):[],d=typeof s.selectedPath=="string"?H(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>Of)continue;const f=r[a];if(f){const m=Array.from(new Set([...f.openPaths,...i])),g=Array.from(new Set([...f.expandedPaths,...c])),h=f.selectedPath??l??m[0]??null;r[a]={openPaths:m,selectedPath:h,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},It=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},Nf=xr()(Or(aa((e,t)=>({byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{},resetForRuntimeSwitch:r=>{e(o=>{const n={...o.runtimeSnapshots,[o.activeRuntimeKey]:{byRoot:fr(o.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:r,runtimeSnapshots:n,byRoot:fr(n[r]?.byRoot)}})},addOpenPath:(r,o,n)=>{const a=H((r||"").trim()),s=H((o||"").trim());!a||!s||!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=It(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=H((r||"").trim()),a=H((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=H((r||"").trim()),a=H((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 h=Xe(g);return h===c||h.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=H((r||"").trim()),a=H((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=H((r||"").trim()),s=o?H(o.trim()):null;!a||s&&!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=It(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=H((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=H((r||"").trim()),a=H((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=It(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=H((r||"").trim());o&&e(n=>{const a=n.byRoot[o];if(!a||a.expandedPaths.length===0)return n;const s={...n.byRoot,[o]:{...It(a),expandedPaths:[]}};return{byRoot:Me(s,Se)}})},expandPath:(r,o)=>{const n=H((r||"").trim()),a=H((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=It(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=H((r||"").trim());if(!n||!o||o.length===0)return;const a=o.map(s=>H((s||"").trim())).filter(s=>s&&et(s,n));a.length!==0&&e(s=>{const i=s.byRoot[n],c=It(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:pa(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:fr(e.byRoot),updatedAt:Date.now()}},r=Object.fromEntries(Object.entries(t).sort(([,o],[,n])=>n.updatedAt-o.updatedAt).slice(0,xf).map(([o,n])=>[o,{byRoot:fr(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:fr(o[n]?.byRoot)}}}),{name:"files-view-tabs-store"})),Ra=12,Lf=4096,Uf=200,Hf=/^[A-Za-z0-9_.:-]{1,120}$/,Lo=()=>`page-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36).slice(-4)}`,Pr=e=>{if(typeof e!="string")return null;const t=e.trim();return!t||t==="about:blank"?null:t.slice(0,Lf)},cc=e=>{if(typeof e!="string")return null;const t=e.replace(/\s+/g," ").trim();return t?t.slice(0,Uf):null},Rr=e=>e==="server"||e==="device"?e:null,dc=(e,t)=>t&&e.some(r=>r.id===t)?t:e[0]?.id??null,Kf=(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(!(!Hf.test(c)||n.has(c))&&(n.add(c),o.push({id:c,url:Pr(i.url),route:Rr(i.route),title:cc(i.title)}),o.length>=Ra))break}o.length===0&&o.push({id:t.tabId,url:Pr(t.url),route:t.route,title:null});const a=typeof r?.activePageId=="string"?r.activePageId:null;return{pages:o,activePageId:dc(o,a)}},jf=(e,t=Lo)=>{const r=t();return{pages:[{id:r,url:Pr(e.url),route:Rr(e.route),title:null}],activePageId:r}},$f=(e,t,r=Lo)=>{const o=Pr(t.url),n=Rr(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>=Ra);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}},zf=(e,t,r=Lo)=>{if(e.pages.length>=Ra)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}},qf=(e,t,r=Lo)=>{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:dc(n,e.activePageId)};const a=n[Math.min(o,n.length-1)];return{pages:n,activePageId:a.id}},Wf=(e,t)=>e.activePageId!==t&&e.pages.some(r=>r.id===t)?{...e,activePageId:t}:e,Gf=(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=Pr(r.url);i&&i!==a.url&&(s.url=i)}return r.title!==void 0&&(s.title=cc(r.title)),r.route!==void 0&&(s.route=Rr(r.route)??a.route),r.defaultRoute!==void 0&&s.route===null&&(s.route=Rr(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},fA=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}},Vf=380,Jf=380,Yf=1400,lc=12,Is=120,Xf=["git","file","diff","context","terminal","browser","preview","pull-requests","issues","extensions","agents"],Qf=K,uo=e=>Number.isFinite(e)?Math.min(Yf,Math.max(Jf,Math.round(e))):Vf,Zf=e=>{if(typeof e.width=="number"&&Number.isFinite(e.width))return uo(e.width);if(!e.widthByMode||typeof e.widthByMode!="object")return;const t=e.widthByMode;for(const r of Xf){const o=t[r];if(typeof o=="number"&&Number.isFinite(o))return uo(o)}for(const r of Object.values(t))if(typeof r=="number"&&Number.isFinite(r))return uo(r)},wo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Bo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>Is?t.slice(0,Is):t:null},Ia=e=>e==="server"||e==="device"?e:null,_a=e=>e==="all"||e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,em=(e,t)=>(e==="file"||e==="preview")&&t||e,uc=(e,t,r)=>{if(e==="diff")return e;if(e==="browser")return xa;if(typeof r=="string"){const o=r.trim();if(o)return o}return em(e,t)},Pn=(e,t)=>t===e?e:`${e}:${t}`,xa="desktop-browser",fc=`browser:${xa}`,tm=(e,t)=>{let r=!1;const o=e.tabs.map(n=>{if(n.id!==fc||!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},Oa=e=>{const t=wo(e.targetPath),r=uc(e.mode,t,e.dedupeKey),o=Pn(e.mode,r),n=e.mode==="browser";return{id:o,mode:e.mode,targetPath:n?null:t,dedupeKey:r,label:Bo(e.label),sessionTitleFallback:Bo(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:_a(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),browser:n?jf({url:t,route:Ia(e.browserRoute)}):null,touchedAt:Date.now()}},mc=(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))},gc=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"&&n.mode!=="agents")continue;const a=wo(typeof n.targetPath=="string"?n.targetPath:null),s=uc(n.mode,a,typeof n.dedupeKey=="string"?n.dedupeKey:null),i=Pn(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:Bo(typeof n.label=="string"?n.label:null),sessionTitleFallback:Bo(typeof n.sessionTitleFallback=="string"?n.sessionTitleFallback:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,diffScope:_a(n.diffScope)??(n.stagedDiff===!0?"staged":"working"),browser:c?Kf(n.browser,{tabId:Pn("browser",d),url:a,route:Ia(n.browserRoute)}):null,touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()})}return t},Yt=(e,t)=>t&&e.some(r=>r.id===t)?t:e.length===0?null:e[e.length-1].id,gt=e=>{if(e){const t=gc(e.tabs),r=Yt(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()}},rm=(e,t)=>{const r=Oa(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=mc(a,lc,s);return{...e,isOpen:!0,tabs:i,activeTabId:Yt(i,s),touchedAt:Date.now()}},om=(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:Yt(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??Yt(o,null),isOpen:a?e.isOpen:!1,touchedAt:Date.now()}},nm=(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},am=(e,t,r)=>({...e,tabs:e.tabs.map(o=>o.id===t?{...o,targetPath:r}:o)}),sm=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:Oa({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=sm(gc(s.tabs)),c=typeof s.activeTabId=="string"?s.activeTabId:null;i.length===0&&(s.mode==="diff"||s.mode==="file"||s.mode==="context")&&(i=[Oa({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=Yt(i,c),l=mc(i,lc,d),u=Zf(s);r[a]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:l,activeTabId:Yt(l,d),...u!==void 0?{width:u}:{},touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},pt=(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},_s=50,im=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}`},cm=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=K(o),s=im(n);!a||!s||(r[a]=s)}return r},xs=(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 Os(e){return e==="vim"?"vim":"default"}const mr=280,cn=new Map,dn=e=>(e??D()).trim()||"default",gr=(e,t,r,o)=>{const n=t(),a=n.contextPanelByDirectory[r];if(!a)return;const s=tm(a,o);s!==a&&e({contextPanelByDirectory:{...n.contextPanelByDirectory,[r]:s}})},ie=xr()(Or(aa((e,t)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:mr,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:hf,monoFont:Ff,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Ef(),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:Cf,sessionAutoArchiveAfterDays:0,sessionAutoDeleteAfterDays:0,expandedEditorToolbar:!1,draftStartersVisible:!0,draftWallpaper:kf,draftWallpaperMotion:!0,draftWallpaperPicture:!1,draftWallpaperInSessions:!1,draftWallpaperImageVersion:null,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:mr}:{isSidebarOpen:o}})},setSidebarOpen:r=>{e(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==mr?{isSidebarOpen:r,sidebarWidth:mr}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:mr}:{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:xs({...a.githubSelectedRepoByDirectory,[n]:s},_s)}})},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=gt(s),c={...a.contextPanelByDirectory,[n]:rm(i,o)};return{contextPanelByDirectory:pt(c,20)}})},openContextDiff:(r,o,n=!1,a=null)=>{const s=K((r||"").trim()),i=(o||"").trim();if(!s||!i)return;const c=_a(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=wo(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=wo(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===fc);if(t().openContextPanelTab(a,{mode:"browser",targetPath:i?null:s,dedupeKey:xa,label:"Browser",browserRoute:i?null:n?.route??null}),!i)return;const c=n?.target??(s?"new":null);c&&gr(e,t,a,d=>$f(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 gr(e,t,a,i=>{const c=zf(i,{openerPageId:o,popupId:n});return s=c!==null,c??i}),s},closeBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&gr(e,t,n,a=>qf(a,o))},activateBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&gr(e,t,n,a=>Wf(a,o))},updateBrowserPage:(r,o,n)=>{const a=K((r||"").trim());a&&gr(e,t,a,s=>Gf(s,o,n))},setBrowserRoutePreference:r=>{e({browserRoutePreference:Ia(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]:am(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=gt(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:pt(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=gt(d);if(!l.tabs.some(m=>m.id===s)||!l.tabs.some(m=>m.id===i))return c;const u=nm(l,s,i);if(u.tabs===l.tabs)return c;const f={...c.contextPanelByDirectory,[a]:u};return{contextPanelByDirectory:pt(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=gt(c);if(!d.tabs.some(u=>u.id===a))return i;const l={...i.contextPanelByDirectory,[n]:om(d,a)};return{contextPanelByDirectory:pt(l,20)}}),s?.mode==="file"&&s.targetPath&&Nf.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]:{...gt(a),isOpen:!1}};return{contextPanelByDirectory:pt(s,20)}})},toggleContextPanelExpanded:r=>{const o=K((r||"").trim());o&&e(n=>{const a=n.contextPanelByDirectory[o],s=gt(a),i={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:pt(i,20)}})},setContextPanelWidth:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{const s=a.contextPanelByDirectory[n],i=gt(s),c={...a.contextPanelByDirectory,[n]:{...i,width:uo(o)}};return{contextPanelByDirectory:pt(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)||(cn.set(dn(),r),e({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{cn.set(dn(r),t().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=cn.get(dn(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})},setDraftWallpaper:r=>{Pa(r)&&e({draftWallpaper:r})},setDraftWallpaperMotion:r=>{e({draftWallpaperMotion:r})},setDraftWallpaperPicture:r=>{e({draftWallpaperPicture:r===!0})},setDraftWallpaperInSessions:r=>{e({draftWallpaperInSessions:r===!0})},setDraftWallpaperImageVersion:r=>{e({draftWallpaperImageVersion: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(uf);if(n===1){for(const[s]of a)o.style.removeProperty(Ms(s));return}for(const[s,i]of a){const c=parseFloat(i);Number.isFinite(c)&&o.style.setProperty(Ms(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=>{Jt(r)&&e({sessionAutoArchiveAfterDays:r})},setSessionAutoDeleteAfterDays:r=>{Jt(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:Os(r)})},toggleExpandedInput:()=>{e(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{e({isExpandedInput:r})}}),{name:"ui-store",storage:pa(),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=Os(r.fileEditorKeymap),r.githubSelectedRepoByDirectory=xs(cm(r.githubSelectedRepoByDirectory),_s),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,draftWallpaper:e.draftWallpaper,draftWallpaperMotion:e.draftWallpaperMotion,draftWallpaperPicture:e.draftWallpaperPicture,draftWallpaperInSessions:e.draftWallpaperInSessions,draftWallpaperImageVersion:e.draftWallpaperImageVersion,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),mA=Object.freeze(Object.defineProperty({__proto__:null,normalizeContextPanelDirectoryKey:Qf,useUIStore:ie},Symbol.toStringTag,{value:"Module"}));let Ns="idle";const dm=new Set;let eo=null;const ye=e=>{eo&&(clearTimeout(eo),eo=null);const t=e==="saved"?"idle":e;t!==Ns&&(Ns=t,dm.forEach(r=>r())),t==="error"&&(eo=setTimeout(()=>ye("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("pichamber:settings-save-state",{detail:e}))},gA=e=>{ye(e)},lm=e=>{if(!(typeof window>"u")&&!(typeof window.__PICHAMBER_HOME__=="string"&&window.__PICHAMBER_HOME__.length>0))try{window.__PICHAMBER_HOME__=e}catch{}},Ls="pichamber.settingsMirror.v2.index",um="pichamber.settingsMirror.v2:",fm=5,Us=e=>`${um}${encodeURIComponent(e)}`,ht=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},mm=(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(Us(t),JSON.stringify(r));let o=[];try{const a=JSON.parse(localStorage.getItem(Ls)??"[]");Array.isArray(a)&&(o=a.filter(s=>typeof s=="string"))}catch{o=[]}const n=[t,...o.filter(a=>a!==t)].slice(0,fm);for(const a of o)n.includes(a)||localStorage.removeItem(Us(a));localStorage.setItem(Ls,JSON.stringify(n))},gm=e=>{if(!(typeof window>"u")){if(mm(e,D()),ht("selectedThemeId",e.themeId||null),ht("selectedThemeVariant",e.themeVariant||null),ht("lightThemeId",e.lightThemeId||null),ht("darkThemeId",e.darkThemeId||null),ht("useSystemTheme",typeof e.useSystemTheme=="boolean"?String(e.useSystemTheme):null),ht("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),lm(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"),ht("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=nc(e.pwaAppName,"");t.length>0?localStorage.setItem(sn,t):localStorage.removeItem(sn)}else localStorage.removeItem(sn);wf(e.mobileKeyboardMode)}},Rn=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("pichamber:settings-synced",{detail:e}))},pm=()=>{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)}`},hm=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},Na="queue",La=e=>e==="steer"||e==="queue",Ua=(e,t)=>e==="immediate"?"steer":La(e)?e:t===!1?"steer":t===!0?"queue":Na,Hs=50,Ks=20,ln=(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))At.deleteAttachment(o,{runtimeKey:e.runtimeKey}).catch(()=>{})},Fm=(e,t,r=D())=>{const o=hm(t);return!r||!o||!e?null:{runtimeKey:r,directory:o,sessionId:e}},re=e=>`${e.runtimeKey}
7
+ `;for(const r of[...be.keys()])r.startsWith(t)&&be.delete(r)},tf=(e,t,r)=>{if(be.size>=Ds){const o=Date.now();for(const[n,a]of be)o-a.settledAt>=Zi&&be.delete(n);for(;be.size>=Ds;){const n=be.keys().next().value;if(typeof n!="string")break;be.delete(n)}}be.set(e,{response:t,settledAt:r})};class rf{currentDirectory;setDirectory(t){this.currentDirectory=t}getDirectory(){return this.currentDirectory}async health(t){F(t);const r=await Eo(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 F(t),y("/api/pi/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async selectProject(t,r){return F(r),y("/api/pi/projects/select",{method:"POST",body:{directory:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSessions(t){F(t);const r=t?.directory??this.currentDirectory;return y("/api/pi/sessions",{method:"GET",...r?{query:{directory:r}}:{},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listPendingInput(t){F(t);const r=await y("/api/pi/sessions/pending-input",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!Qu(r))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed pending-input list");return r}async createSession(t,r){return F(r),y("/api/pi/sessions",{method:"POST",body:t,timeoutMs:Rt,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSession(t,r){F(r);const o=r?.directory??this.currentDirectory;return y(`/api/pi/sessions/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:Rt,...o?{query:{directory:o}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSessionMessages(t,r,o){F(o);const n=o?.directory??this.currentDirectory;return y(`/api/pi/sessions/${encodeURIComponent(t)}/messages`,{method:"GET",timeoutMs:Rt,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){F(r),await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"PATCH",body:{sessionId:t.sessionId,title:t.title},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async discardDraftSession(t,r){return F(r),(await y(`/api/pi/sessions/${encodeURIComponent(t)}/discard-draft`,{method:"POST",...r?.directory?{query:{directory:r.directory}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.discarded===!0}async deleteSession(t,r){F(r);try{return await y(`/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 L&&o.status===404)return!0;throw o}}async archiveSession(t,r){F(r),await y(`/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){F(t);const r=await y("/api/pi/session-shelf",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}});if(!Eu(r))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf");return r}async setSessionShelf(t,r){F(r);const{sessionId:o,...n}=t,s=(await y(`/api/pi/sessions/${encodeURIComponent(o)}/shelf`,{method:"POST",body:{...n,...r?.directory?{directory:r.directory}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.entry;if(s!==null&&!Vi(s))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed session shelf entry");return s}async getSessionTree(t,r){return F(r),y(`/api/pi/sessions/${encodeURIComponent(t)}/tree`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async navigateSession(t,r,o){return F(o),y(`/api/pi/sessions/${encodeURIComponent(t)}/navigate`,{method:"POST",body:{messageId:r},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async forkSession(t,r){return F(r),y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/fork`,{method:"POST",timeoutMs:Rt,body:{sessionId:t.sessionId,...t.messageId?{messageId:t.messageId}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async cloneSession(t,r){return F(r),y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/clone`,{method:"POST",body:t,timeoutMs:Rt,...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();F({...r,runtimeKey:o});const n=Yr(o,t.sessionId,t.streamEpoch??r?.streamEpoch??Ze(o,t.sessionId)),a=r?.directory??this.currentDirectory,s=await y(`/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(F({...r,runtimeKey:o}),Yr(o,t.sessionId,n),!s||typeof s!="object")throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");const i=s.status;if(i==="accepted"){const c=s.receipt;if(!on(c))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt");return{status:"accepted",receipt:c}}if(i==="pending"||i==="expired"||i==="unknown")return{status:i};throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send receipt")}async sendWithReceipt(t,r,o,n){const a=n?.runtimeKey??D();let s;try{F({...n,runtimeKey:a}),s=Yr(a,r.sessionId,n?.streamEpoch??Ze(a,r.sessionId))}catch(c){throw nn(c)}const i=n?.directory??this.currentDirectory;try{const c=await y(o,{method:"POST",body:{...r,streamEpoch:s},...i?{query:{directory:i}}:{},runtimeKey:a,retry:!1,timeoutMs:Rt});if(!on(c))throw new L("DAEMON_PROTOCOL_MISMATCH","Malformed send response");return F({...n,runtimeKey:a}),Yr(a,r.sessionId,s),c}catch(c){if(c instanceof L&&c.code==="STALE_STREAM_EPOCH")throw nn(c);if(Zu(c))throw c;const d=r.operationId;if(typeof d=="string"&&d.length>0)try{F({...n,runtimeKey:a});const l=this.getSendReceipt;if(!l)throw new L("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(F({...n,runtimeKey:a}),typeof u=="object"&&u!==null&&u.status==="accepted"&&on(u.receipt))return u.receipt}catch{}throw nn(c)}}async abortSession(t,r){F(r),await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setSessionModel(t,r){F(r),await y(`/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){F(r),await y(`/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(F(r),(await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).accepted!==!0)throw new L("DAEMON_PROTOCOL_MISMATCH")}async runBash(t,r){F(r);const o=await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash`,{method:"POST",body:{command:t.command,...t.excludeFromContext?{excludeFromContext:!0}:{},...t.clientId?{clientId:t.clientId}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});if(o?.accepted!==!0||typeof o.id!="string")throw new L("DAEMON_PROTOCOL_MISMATCH");return{id:o.id}}async abortBash(t,r){F(r),await y(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/bash/abort`,{method:"POST",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listProviders(t){return F(t),y("/api/pi/providers",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listEngines(t){return F(t),y("/api/pi/engines",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async refreshProviders(t){return F(t),y("/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 F(r),y(`/api/pi/providers/${encodeURIComponent(t)}/status`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async loginProvider(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/login`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderLogin(t,r,o){return F(o),y(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async respondProviderLogin(t,r,o,n){return F(n),y(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(r)}/respond`,{method:"POST",body:{value:o},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async logoutProvider(t,r){F(r),await y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/logout`,{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getProviderConfig(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t)}/config`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setProviderModels(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async addProviderModel(t,r){return F(r),y(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"POST",body:t.model,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getSandboxStatus(t){return F(t),y("/api/pi/sandbox",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async recheckSandbox(t){return F(t),y("/api/pi/sandbox/recheck",{method:"POST",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async listProjectSandboxes(t){return F(t),y("/api/pi/sandbox/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getSandboxDefaults(t){return F(t),(await y("/api/pi/sandbox/defaults",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})).defaults}async setSandboxDefaults(t,r){return F(r),y("/api/pi/sandbox/defaults",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setProjectSandbox(t,r,o){return F(o),(await y(`/api/pi/sandbox/projects/${encodeURIComponent(t)}`,{method:"PUT",body:r,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})).project}async getSandboxProfile(t){return F(t),(await y("/api/pi/sandbox/profile",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})).profile}async saveSandboxProfile(t,r){return F(r),(await y("/api/pi/sandbox/profile",{method:"PUT",body:{content:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).profile}async resetSandboxProfile(t){return F(t),(await y("/api/pi/sandbox/profile",{method:"DELETE",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})).profile}async getSettings(t){return F(t),y("/api/pi/settings",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async setPiSettings(t,r){return F(r),y("/api/pi/settings/pi",{method:"PUT",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPiChamberDefaults(t,r){return F(r),y("/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;F(o);const a=o?.runtimeKey??D(),s=ef(a,n),i=lo(a);if(o?.reload!==!0){const m=be.get(s);if(m&&Date.now()-m.settledAt<Zi)return structuredClone(m.response)}const c=Xr.get(s);if(c&&c.revision===i)return structuredClone(await c.promise);const d=Date.now(),l=lo(a),u={},f=(async()=>{try{const m=await y("/api/pi/resources",{method:"GET",...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});if(D()===a&&lo(a)===l){const g=be.get(s);(!g||g.settledAt<=d)&&tf(s,m,Date.now())}return m}finally{Xr.get(s)?.promise===u.promise&&Xr.delete(s)}})();return u.promise=f,Xr.set(s,{revision:l,promise:f}),structuredClone(await f)}async listCommands(t,r){return F(r),y("/api/pi/commands",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listSnippets(t,r){return F(r),y("/api/pi/snippets",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async createSnippet(t,r){return F(r),y("/api/pi/snippets",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateSnippet(t,r,o,n){return F(n),y(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"PUT",body:r,...o?{query:{directory:o}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deleteSnippet(t,r,o){return F(o),y(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"DELETE",...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateResource(t,r){F(r);const o=r?.runtimeKey??D(),n=t.directory??r?.directory,a=await y(`/api/pi/resources/${encodeURIComponent(t.resourceId)}`,{method:"PUT",body:t,...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}});return Qr(o),a}async createPromptTemplate(t,r,o){const n=r??t.directory??o?.directory;F(o);const a=o?.runtimeKey??D(),s=await y("/api/pi/resources/prompts",{method:"POST",body:t,...n?{query:{directory:n}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Qr(a),s}async updatePromptTemplate(t,r,o,n){F(n);const a=n?.runtimeKey??D(),s=o??r.directory??n?.directory,i=await y(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"PUT",body:r,...s?{query:{directory:s}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}});return Qr(a),i}async deletePromptTemplate(t,r,o){F(o);const n=o?.runtimeKey??D(),a=r??o?.directory,s=await y(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"DELETE",...a?{query:{directory:a}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}});return Qr(n),s}async createAttachment(t,r){return F(r),(await y("/api/pi/attachments",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})).attachment}async uploadAttachment(t,r,o){F(o);const n=await yu("/api/pi/attachments",t,r);if(!n.ok){const i=(await n.json().catch(()=>null))?.error??{code:"ATTACHMENT_FAILED"};throw new L(i.code,i.message,n.status)}const a=await n.json();return F(o),a.attachment}async deleteAttachment(t,r){F(r),await y(`/api/pi/attachments/${encodeURIComponent(t)}`,{method:"DELETE",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listPlugins(t,r){return F(r),y("/api/pi/plugins",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPluginEnabled(t,r,o){return F(o),y(`/api/pi/plugins/${encodeURIComponent(t)}`,{method:"PUT",body:{enabled:r},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setPluginState(t,r,o){return F(o),y(`/api/pi/plugins/${encodeURIComponent(t)}/state`,{method:"PUT",body:r,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getPluginSessionState(t,r){return F(r),y(`/api/pi/plugins/sessions/${encodeURIComponent(t)}`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setPluginSessionState(t,r,o,n){return F(n),y(`/api/pi/plugins/${encodeURIComponent(t)}/sessions/${encodeURIComponent(r)}`,{method:"PUT",body:o,...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async listExtensions(t,r){return F(r),y("/api/pi/extensions",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getExtensionConfig(t,r){return F(r),y("/api/pi/extensions/config",{method:"GET",...t?{query:{directory:t}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async setExtensionConfig(t,r,o){return F(o),y(`/api/pi/extensions/config/${encodeURIComponent(t)}`,{method:"PUT",body:r,retry:!1,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async removeExtensionPackage(t,r,o){return F(o),y(`/api/pi/extensions/packages/${encodeURIComponent(t)}`,{method:"DELETE",retry:!1,...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async installExtensionPackage(t,r){return F(r),y("/api/pi/extensions/packages",{method:"POST",body:t,retry:!1,timeoutMs:ks,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateExtensionPackage(t,r,o){return F(o),y(`/api/pi/extensions/packages/${encodeURIComponent(t)}/update`,{method:"POST",retry:!1,timeoutMs:ks,...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async searchMarketplace(t,r){F(r);const o={};return t.query&&(o.q=t.query),t.from&&(o.from=String(t.from)),t.pichamberOnly&&(o.pichamber="1"),y("/api/pi/marketplace/search",{method:"GET",query:o,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getMarketplaceFeatured(t){return F(t),y("/api/pi/marketplace/featured",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getMarketplacePackage(t,r){return F(r),y("/api/pi/marketplace/package",{method:"GET",query:{name:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getMarketplaceVersions(t,r){return F(r),y("/api/pi/marketplace/versions",{method:"GET",query:{names:t.join(",")},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async getExtensionPalette(t,r){return F(r),y("/api/pi/extensions/palette",{method:"POST",body:{terminal:t},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async respondToExtensionDialog(t,r){F(r),await y("/api/pi/extensions/respond",{method:"POST",body:t,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async runExtensionControl(t,r){F(r);const o={...t,...r?.directory?{directory:r.directory}:{}};return{ran:(await y("/api/pi/extensions/control",{method:"POST",body:o,retry:!1,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.ran===!0}}async runExtensionCommand(t,r){F(r);const o={...t,...r?.directory?{directory:r.directory}:{}};return{ran:(await y("/api/pi/extensions/command",{method:"POST",body:o,retry:!1,...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}}))?.ran===!0}}async sendExtensionSurface(t,r,o){F(o);const{sessionId:n,...a}=r;await y(`/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){F(r),await y(`/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 At=new rf;async function of(e){return(await af(e)).home}let Sn=null,yr=null;const Hb=()=>{Sn=null,yr=null},nf=async()=>{let e=null,t=null;try{const r=await b("/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}},af=async e=>{const t=D();if(!e?.fresh){const o=Sn;if(o&&o.key===t)return o.state;const n=yr;if(n&&n.key===t)return n.promise}const r=(async()=>{const o=await nf();return!e?.fresh&&o.home&&D()===t&&(Sn={key:t,state:o}),o})();e?.fresh||(yr={key:t,promise:r});try{return await r}finally{yr?.promise===r&&(yr=null)}};async function Kb(e,t){if(!e||e.trim().length===0)return[];const r={path:e},o=Ie().api("/api/fs/list",r),n=await b(o);if(!n.ok)return[];const a=await n.json();return Array.isArray(a.entries)?a.entries:[]}async function sf(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 b(n);if(!a.ok)return[];const s=await a.json();return Array.isArray(s.files)?s.files:[]}async function jb(e=""){try{const t=await b("/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 $b={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."}},cf=e=>typeof e=="string"&&(e==="explore"||e==="plan"||e==="review"||e==="find-bugs"||e==="write-tests"),zb=[{type:"text",key:"explore"},{type:"text",key:"plan"},{type:"text",key:"review"},{type:"text",key:"find-bugs"},{type:"text",key:"write-tests"}],qb="book-open",df=/^[^\s/]+$/,Ss=e=>e.type==="prompt"?`prompt:${e.name}`:`text:${e.key}`,Wb=(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,Gb=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Ma=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(!cf(n.key))continue;const d={type:"text",key:n.key},l=Ss(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||!df.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=Ss(i);r.has(c)||(r.add(c),t.push(i))}return t},lf=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=lf(n);a&&r.set(o,a)}return r},Jb=(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}},uf={markdown:"0.875rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.8125rem",micro:"0.75rem",settingsPageTitle:"1.125rem"};function Ms(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Zr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},an={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Zr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:an.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Zr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:an.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Zr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:an.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Zr.tool.inline})},ff=[{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'}],mf=[{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'}],tc=e=>Object.fromEntries(e.map(t=>[t.id,t])),gf=tc(ff),pf=tc(mf),hf="system",Ff="system-mono",rc=e=>typeof e=="string"&&e in gf,oc=e=>typeof e=="string"&&e in pf,sn="pichamber.pwaName",Mn="pichamber.mobileKeyboardMode",Yb="pichamber.pwaRecentSessions",yf=["native","resize-content"];function bf(e,t="resize-content"){return typeof e=="string"&&yf.includes(e)?e:t}const Af=64;function nc(e,t){if(typeof e!="string")return t;const r=e.trim().replace(/\s+/g," ");return r?r.slice(0,Af):t}const Xb=()=>!0;function Ta(e,t="resize-content"){return bf(e,t)??void 0}const Ef=()=>{if(typeof window>"u")return"resize-content";try{return Ta(localStorage.getItem(Mn))}catch{return"resize-content"}},wf=e=>{const t=Ta(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Mn):localStorage.setItem(Mn,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("/")?"/":"")},Bf=["workspace","folder","timeline","threads"],Cf="workspace",ac=e=>typeof e=="string"&&Bf.includes(e),vf=["none","dither","ascii","halftone","strands","grain"],kf="none",Pa=e=>typeof e=="string"&&vf.includes(e),Qb=e=>e!=="none"&&e!=="grain",Zb=e=>e==="dither"||e==="ascii"||e==="halftone",sc=e=>typeof e=="string"&&/^[0-9a-f]{16}$/.test(e),eA=3,tA={width:7,height:13},Ts=" .:-=+*#%@",Df=[0,32,8,40,2,34,10,42,48,16,56,24,50,18,58,26,12,44,4,36,14,46,6,38,60,28,52,20,62,30,54,22,3,35,11,43,1,33,9,41,51,19,59,27,49,17,57,25,15,47,7,39,13,45,5,37,63,31,55,23,61,29,53,21].map(e=>(e+.5)/64),rA=(e,t)=>Df[(t&7)*8+(e&7)],bt=(e,t)=>{let r=Math.imul(e,374761393)^Math.imul(t,668265263);return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967295},Tn=e=>e*e*(3-2*e),Sf=(e,t)=>{const r=Math.floor(e),o=Math.floor(t),n=Tn(e-r),a=Tn(t-o),s=bt(r,o)+(bt(r+1,o)-bt(r,o))*n,i=bt(r,o+1)+(bt(r+1,o+1)-bt(r,o+1))*n;return s+(i-s)*a},Oo=2*Math.PI/60,Mf={bottom:[.45,.78],session:[.12,.55]};function Ps(e,t,r){if(r==="none"||r==="full")return 1;const[o,n]=Mf[r],a=(e/Math.max(1,t)-o)/(n-o);return a<=0?1:a>=1?0:1-a}function Tf(e,t,r,o){const n=e/Math.max(1,r*.5),a=t/Math.max(1,o*.5),s=Math.min(1,Math.sqrt(n*n+a*a));return Tn(Math.min(1,Math.max(0,(s-.45)/.55)))}function Pf(e,t,r,o){const n=e/260,a=t/260;let s=0,i=.5,c=1;for(let l=0;l<4;l+=1)s+=i*Sf(n*c+l*17.3,a*c-l*9.1),i*=.5,c*=2;const d=Tf(e,t,r,o);return{noise:s,phase:(e*.6+t)/140+s*5,reveal:d}}function oA(e,t,r,o,n="none"){const a=Math.max(0,Math.ceil(e/r)),s=Math.max(0,Math.ceil(t/o)),i=e/2,c=t/2,d=[],l=[],u=[],f=[];for(let m=0;m<s;m+=1){const g=m*o+o/2-c;for(let h=0;h<a;h+=1){const p=Pf(h*r+r/2-i,g,e,t);n==="full"?p.reveal=1:n==="session"?p.reveal=Ps(g+c,t,n):n!=="none"&&(p.reveal*=Ps(g+c,t,n)),!(p.reveal<=0)&&(d.push(m*a+h),l.push(p.noise),u.push(p.phase),f.push(p.reveal))}}return{cols:a,rows:s,cells:Uint32Array.from(d),noise:Float32Array.from(l),phase:Float32Array.from(u),reveal:Float32Array.from(f)}}const Cr=4096,ic=Cr/(2*Math.PI),Rf=Float32Array.from({length:Cr},(e,t)=>.5+.5*Math.sin(t/ic)),No=e=>{const t=Math.floor(e*ic);return Rf[(t%Cr+Cr)%Cr]};function nA(e,t,r){const o=t*Oo,{noise:n,phase:a,reveal:s}=e;for(let i=0;i<e.cells.length;i+=1){const c=(n[i]*.55+No(a[i]-o)*.45-.35)*1.5;r[i]=c<=0?0:c>=1?s[i]:c*s[i]}}function aA(e,t,r){const o=t*Oo,{noise:n,phase:a}=e;for(let s=0;s<e.cells.length;s+=1)r[s]=n[s]*.55+No(a[s]-o)*.45}function sA(e,t,r){const o=t*Oo,{noise:n,phase:a}=e;for(let s=0;s<e.cells.length;s+=1)r[s]=n[s]*4*Math.PI+(No(a[s]-o)-.5)*1.2}const iA=(e,t)=>bt(e,t),cA=(e,t,r,o,n)=>{const a=(.2126*e+.7152*t+.0722*r)/255,s=n?a:1-a;return Math.min(1,Math.max(0,(s-.08)/.84))*(o/255)},If=.4;function dA(e,t,r,o){const n=r*Oo,{phase:a,reveal:s}=e;for(let i=0;i<e.cells.length;i+=1){const c=t[i]+(No(a[i]-n)-.5)*If;o[i]=c<=0?0:c>=1?s[i]:c*s[i]}}const lA=e=>Math.min(Ts.length-1,Math.floor(e*Ts.length)),_f=365,Jt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=_f,uA=e=>e===1?"1 session":`${e} sessions`,Se=20,xf=8,Rs=4096,Of=2160*60*6e4,H=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=H(t),o=H(e);if(!r||!o)return!1;const n=Xe(r),a=Xe(o);return a===n||a.startsWith(`${n}/`)},fr=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=H(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=>H(m)).filter(m=>m.length<=Rs&&et(m,a)))).slice(-50):[],c=Array.isArray(s.expandedPaths)?Array.from(new Set(s.expandedPaths.filter(m=>typeof m=="string").map(m=>H(m)).filter(m=>m.length<=Rs&&et(m,a)))).slice(-500):[],d=typeof s.selectedPath=="string"?H(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>Of)continue;const f=r[a];if(f){const m=Array.from(new Set([...f.openPaths,...i])),g=Array.from(new Set([...f.expandedPaths,...c])),h=f.selectedPath??l??m[0]??null;r[a]={openPaths:m,selectedPath:h,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},It=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},Nf=xr()(Or(aa((e,t)=>({byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{},resetForRuntimeSwitch:r=>{e(o=>{const n={...o.runtimeSnapshots,[o.activeRuntimeKey]:{byRoot:fr(o.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:r,runtimeSnapshots:n,byRoot:fr(n[r]?.byRoot)}})},addOpenPath:(r,o,n)=>{const a=H((r||"").trim()),s=H((o||"").trim());!a||!s||!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=It(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=H((r||"").trim()),a=H((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=H((r||"").trim()),a=H((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 h=Xe(g);return h===c||h.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=H((r||"").trim()),a=H((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=H((r||"").trim()),s=o?H(o.trim()):null;!a||s&&!n?.allowOutsideRoot&&!et(s,a)||e(i=>{const c=i.byRoot[a],d=It(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=H((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=H((r||"").trim()),a=H((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=It(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=H((r||"").trim());o&&e(n=>{const a=n.byRoot[o];if(!a||a.expandedPaths.length===0)return n;const s={...n.byRoot,[o]:{...It(a),expandedPaths:[]}};return{byRoot:Me(s,Se)}})},expandPath:(r,o)=>{const n=H((r||"").trim()),a=H((o||"").trim());!n||!a||!et(a,n)||e(s=>{const i=s.byRoot[n],c=It(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=H((r||"").trim());if(!n||!o||o.length===0)return;const a=o.map(s=>H((s||"").trim())).filter(s=>s&&et(s,n));a.length!==0&&e(s=>{const i=s.byRoot[n],c=It(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:pa(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:D(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:fr(e.byRoot),updatedAt:Date.now()}},r=Object.fromEntries(Object.entries(t).sort(([,o],[,n])=>n.updatedAt-o.updatedAt).slice(0,xf).map(([o,n])=>[o,{byRoot:fr(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:fr(o[n]?.byRoot)}}}),{name:"files-view-tabs-store"})),Ra=12,Lf=4096,Uf=200,Hf=/^[A-Za-z0-9_.:-]{1,120}$/,Lo=()=>`page-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36).slice(-4)}`,Pr=e=>{if(typeof e!="string")return null;const t=e.trim();return!t||t==="about:blank"?null:t.slice(0,Lf)},cc=e=>{if(typeof e!="string")return null;const t=e.replace(/\s+/g," ").trim();return t?t.slice(0,Uf):null},Rr=e=>e==="server"||e==="device"?e:null,dc=(e,t)=>t&&e.some(r=>r.id===t)?t:e[0]?.id??null,Kf=(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(!(!Hf.test(c)||n.has(c))&&(n.add(c),o.push({id:c,url:Pr(i.url),route:Rr(i.route),title:cc(i.title)}),o.length>=Ra))break}o.length===0&&o.push({id:t.tabId,url:Pr(t.url),route:t.route,title:null});const a=typeof r?.activePageId=="string"?r.activePageId:null;return{pages:o,activePageId:dc(o,a)}},jf=(e,t=Lo)=>{const r=t();return{pages:[{id:r,url:Pr(e.url),route:Rr(e.route),title:null}],activePageId:r}},$f=(e,t,r=Lo)=>{const o=Pr(t.url),n=Rr(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>=Ra);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}},zf=(e,t,r=Lo)=>{if(e.pages.length>=Ra)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}},qf=(e,t,r=Lo)=>{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:dc(n,e.activePageId)};const a=n[Math.min(o,n.length-1)];return{pages:n,activePageId:a.id}},Wf=(e,t)=>e.activePageId!==t&&e.pages.some(r=>r.id===t)?{...e,activePageId:t}:e,Gf=(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=Pr(r.url);i&&i!==a.url&&(s.url=i)}return r.title!==void 0&&(s.title=cc(r.title)),r.route!==void 0&&(s.route=Rr(r.route)??a.route),r.defaultRoute!==void 0&&s.route===null&&(s.route=Rr(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},fA=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}},Vf=380,Jf=380,Yf=1400,lc=12,Is=120,Xf=["git","file","diff","context","terminal","browser","preview","pull-requests","issues","extensions","agents"],Qf=K,uo=e=>Number.isFinite(e)?Math.min(Yf,Math.max(Jf,Math.round(e))):Vf,Zf=e=>{if(typeof e.width=="number"&&Number.isFinite(e.width))return uo(e.width);if(!e.widthByMode||typeof e.widthByMode!="object")return;const t=e.widthByMode;for(const r of Xf){const o=t[r];if(typeof o=="number"&&Number.isFinite(o))return uo(o)}for(const r of Object.values(t))if(typeof r=="number"&&Number.isFinite(r))return uo(r)},wo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Bo=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>Is?t.slice(0,Is):t:null},Ia=e=>e==="server"||e==="device"?e:null,_a=e=>e==="all"||e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,em=(e,t)=>(e==="file"||e==="preview")&&t||e,uc=(e,t,r)=>{if(e==="diff")return e;if(e==="browser")return xa;if(typeof r=="string"){const o=r.trim();if(o)return o}return em(e,t)},Pn=(e,t)=>t===e?e:`${e}:${t}`,xa="desktop-browser",fc=`browser:${xa}`,tm=(e,t)=>{let r=!1;const o=e.tabs.map(n=>{if(n.id!==fc||!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},Oa=e=>{const t=wo(e.targetPath),r=uc(e.mode,t,e.dedupeKey),o=Pn(e.mode,r),n=e.mode==="browser";return{id:o,mode:e.mode,targetPath:n?null:t,dedupeKey:r,label:Bo(e.label),sessionTitleFallback:Bo(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:_a(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),browser:n?jf({url:t,route:Ia(e.browserRoute)}):null,touchedAt:Date.now()}},mc=(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))},gc=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"&&n.mode!=="agents")continue;const a=wo(typeof n.targetPath=="string"?n.targetPath:null),s=uc(n.mode,a,typeof n.dedupeKey=="string"?n.dedupeKey:null),i=Pn(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:Bo(typeof n.label=="string"?n.label:null),sessionTitleFallback:Bo(typeof n.sessionTitleFallback=="string"?n.sessionTitleFallback:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,diffScope:_a(n.diffScope)??(n.stagedDiff===!0?"staged":"working"),browser:c?Kf(n.browser,{tabId:Pn("browser",d),url:a,route:Ia(n.browserRoute)}):null,touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()})}return t},Yt=(e,t)=>t&&e.some(r=>r.id===t)?t:e.length===0?null:e[e.length-1].id,gt=e=>{if(e){const t=gc(e.tabs),r=Yt(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()}},rm=(e,t)=>{const r=Oa(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=mc(a,lc,s);return{...e,isOpen:!0,tabs:i,activeTabId:Yt(i,s),touchedAt:Date.now()}},om=(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:Yt(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??Yt(o,null),isOpen:a?e.isOpen:!1,touchedAt:Date.now()}},nm=(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},am=(e,t,r)=>({...e,tabs:e.tabs.map(o=>o.id===t?{...o,targetPath:r}:o)}),sm=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:Oa({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=sm(gc(s.tabs)),c=typeof s.activeTabId=="string"?s.activeTabId:null;i.length===0&&(s.mode==="diff"||s.mode==="file"||s.mode==="context")&&(i=[Oa({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=Yt(i,c),l=mc(i,lc,d),u=Zf(s);r[a]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:l,activeTabId:Yt(l,d),...u!==void 0?{width:u}:{},touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},pt=(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},_s=50,im=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}`},cm=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[o,n]of Object.entries(t)){const a=K(o),s=im(n);!a||!s||(r[a]=s)}return r},xs=(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 Os(e){return e==="vim"?"vim":"default"}const mr=280,cn=new Map,dn=e=>(e??D()).trim()||"default",gr=(e,t,r,o)=>{const n=t(),a=n.contextPanelByDirectory[r];if(!a)return;const s=tm(a,o);s!==a&&e({contextPanelByDirectory:{...n.contextPanelByDirectory,[r]:s}})},ie=xr()(Or(aa((e,t)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:mr,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:hf,monoFont:Ff,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Ef(),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:Cf,sessionAutoArchiveAfterDays:0,sessionAutoDeleteAfterDays:0,expandedEditorToolbar:!1,draftStartersVisible:!0,draftWallpaper:kf,draftWallpaperMotion:!0,draftWallpaperPicture:!1,draftWallpaperInSessions:!1,draftWallpaperImageVersion:null,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:mr}:{isSidebarOpen:o}})},setSidebarOpen:r=>{e(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==mr?{isSidebarOpen:r,sidebarWidth:mr}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:mr}:{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:xs({...a.githubSelectedRepoByDirectory,[n]:s},_s)}})},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=gt(s),c={...a.contextPanelByDirectory,[n]:rm(i,o)};return{contextPanelByDirectory:pt(c,20)}})},openContextDiff:(r,o,n=!1,a=null)=>{const s=K((r||"").trim()),i=(o||"").trim();if(!s||!i)return;const c=_a(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=wo(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=wo(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===fc);if(t().openContextPanelTab(a,{mode:"browser",targetPath:i?null:s,dedupeKey:xa,label:"Browser",browserRoute:i?null:n?.route??null}),!i)return;const c=n?.target??(s?"new":null);c&&gr(e,t,a,d=>$f(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 gr(e,t,a,i=>{const c=zf(i,{openerPageId:o,popupId:n});return s=c!==null,c??i}),s},closeBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&gr(e,t,n,a=>qf(a,o))},activateBrowserPage:(r,o)=>{const n=K((r||"").trim());n&&gr(e,t,n,a=>Wf(a,o))},updateBrowserPage:(r,o,n)=>{const a=K((r||"").trim());a&&gr(e,t,a,s=>Gf(s,o,n))},setBrowserRoutePreference:r=>{e({browserRoutePreference:Ia(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]:am(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=gt(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:pt(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=gt(d);if(!l.tabs.some(m=>m.id===s)||!l.tabs.some(m=>m.id===i))return c;const u=nm(l,s,i);if(u.tabs===l.tabs)return c;const f={...c.contextPanelByDirectory,[a]:u};return{contextPanelByDirectory:pt(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=gt(c);if(!d.tabs.some(u=>u.id===a))return i;const l={...i.contextPanelByDirectory,[n]:om(d,a)};return{contextPanelByDirectory:pt(l,20)}}),s?.mode==="file"&&s.targetPath&&Nf.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]:{...gt(a),isOpen:!1}};return{contextPanelByDirectory:pt(s,20)}})},toggleContextPanelExpanded:r=>{const o=K((r||"").trim());o&&e(n=>{const a=n.contextPanelByDirectory[o],s=gt(a),i={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:pt(i,20)}})},setContextPanelWidth:(r,o)=>{const n=K((r||"").trim());n&&e(a=>{const s=a.contextPanelByDirectory[n],i=gt(s),c={...a.contextPanelByDirectory,[n]:{...i,width:uo(o)}};return{contextPanelByDirectory:pt(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)||(cn.set(dn(),r),e({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{cn.set(dn(r),t().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=cn.get(dn(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})},setDraftWallpaper:r=>{Pa(r)&&e({draftWallpaper:r})},setDraftWallpaperMotion:r=>{e({draftWallpaperMotion:r})},setDraftWallpaperPicture:r=>{e({draftWallpaperPicture:r===!0})},setDraftWallpaperInSessions:r=>{e({draftWallpaperInSessions:r===!0})},setDraftWallpaperImageVersion:r=>{e({draftWallpaperImageVersion: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(uf);if(n===1){for(const[s]of a)o.style.removeProperty(Ms(s));return}for(const[s,i]of a){const c=parseFloat(i);Number.isFinite(c)&&o.style.setProperty(Ms(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=>{Jt(r)&&e({sessionAutoArchiveAfterDays:r})},setSessionAutoDeleteAfterDays:r=>{Jt(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:Os(r)})},toggleExpandedInput:()=>{e(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{e({isExpandedInput:r})}}),{name:"ui-store",storage:pa(),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=Os(r.fileEditorKeymap),r.githubSelectedRepoByDirectory=xs(cm(r.githubSelectedRepoByDirectory),_s),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,draftWallpaper:e.draftWallpaper,draftWallpaperMotion:e.draftWallpaperMotion,draftWallpaperPicture:e.draftWallpaperPicture,draftWallpaperInSessions:e.draftWallpaperInSessions,draftWallpaperImageVersion:e.draftWallpaperImageVersion,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),mA=Object.freeze(Object.defineProperty({__proto__:null,normalizeContextPanelDirectoryKey:Qf,useUIStore:ie},Symbol.toStringTag,{value:"Module"}));let Ns="idle";const dm=new Set;let eo=null;const ye=e=>{eo&&(clearTimeout(eo),eo=null);const t=e==="saved"?"idle":e;t!==Ns&&(Ns=t,dm.forEach(r=>r())),t==="error"&&(eo=setTimeout(()=>ye("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("pichamber:settings-save-state",{detail:e}))},gA=e=>{ye(e)},lm=e=>{if(!(typeof window>"u")&&!(typeof window.__PICHAMBER_HOME__=="string"&&window.__PICHAMBER_HOME__.length>0))try{window.__PICHAMBER_HOME__=e}catch{}},Ls="pichamber.settingsMirror.v2.index",um="pichamber.settingsMirror.v2:",fm=5,Us=e=>`${um}${encodeURIComponent(e)}`,ht=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},mm=(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(Us(t),JSON.stringify(r));let o=[];try{const a=JSON.parse(localStorage.getItem(Ls)??"[]");Array.isArray(a)&&(o=a.filter(s=>typeof s=="string"))}catch{o=[]}const n=[t,...o.filter(a=>a!==t)].slice(0,fm);for(const a of o)n.includes(a)||localStorage.removeItem(Us(a));localStorage.setItem(Ls,JSON.stringify(n))},gm=e=>{if(!(typeof window>"u")){if(mm(e,D()),ht("selectedThemeId",e.themeId||null),ht("selectedThemeVariant",e.themeVariant||null),ht("lightThemeId",e.lightThemeId||null),ht("darkThemeId",e.darkThemeId||null),ht("useSystemTheme",typeof e.useSystemTheme=="boolean"?String(e.useSystemTheme):null),ht("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),lm(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"),ht("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=nc(e.pwaAppName,"");t.length>0?localStorage.setItem(sn,t):localStorage.removeItem(sn)}else localStorage.removeItem(sn);wf(e.mobileKeyboardMode)}},Rn=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("pichamber:settings-synced",{detail:e}))},pm=()=>{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)}`},hm=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},Na="queue",La=e=>e==="steer"||e==="queue",Ua=(e,t)=>e==="immediate"?"steer":La(e)?e:t===!1?"steer":t===!0?"queue":Na,Hs=50,Ks=20,ln=(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))At.deleteAttachment(o,{runtimeKey:e.runtimeKey}).catch(()=>{})},Fm=(e,t,r=D())=>{const o=hm(t);return!r||!o||!e?null:{runtimeKey:r,directory:o,sessionId:e}},re=e=>`${e.runtimeKey}
8
8
  ${e.directory}
9
9
  ${e.sessionId}`,ym=e=>{const[t,r,...o]=e.split(`
10
10
  `);return Fm(o.join(`