@pi-chamber/web 0.9.1 → 0.9.3

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 (55) hide show
  1. package/README.md +2 -2
  2. package/bin/lib/cli-paths.js +22 -6
  3. package/dist/assets/{DiagramEditor-DoEOH0hY.js → DiagramEditor-DuGmiPZ5.js} +1 -1
  4. package/dist/assets/{DiagramView-y9Ystuhv.js → DiagramView-CV-iReyY.js} +1 -1
  5. package/dist/assets/{DiffView-ScM4XoqZ.js → DiffView-DVd1MLPB.js} +1 -1
  6. package/dist/assets/{FilesView-CjkhMFqJ.js → FilesView-CPnW4I90.js} +1 -1
  7. package/dist/assets/{GitView-Bqi6H8I-.js → GitView-Dj_7hgX_.js} +3 -3
  8. package/dist/assets/{JsonTreeView-DWhlH6NK.js → JsonTreeView-Cyy0lEZR.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-CEOKZ1qH.js → MarkdownRendererImpl-BXN78Wu_.js} +1 -1
  10. package/dist/assets/{PatchDiff-ClnfJJ2J.js → PatchDiff-C7dA3U29.js} +1 -1
  11. package/dist/assets/{SessionSwitcherContent-e6JzUXD_.js → SessionSwitcherContent-dr3g9DR7.js} +1 -1
  12. package/dist/assets/{SessionSwitcherDropdown-C4etG8dv.js → SessionSwitcherDropdown-C3zdd82V.js} +2 -2
  13. package/dist/assets/{SessionUnreadDot-BVTSwRiG.js → SessionUnreadDot-qeik5qtT.js} +1 -1
  14. package/dist/assets/{SettingsView-C0S0Sx-S.js → SettingsView-C57uV1YS.js} +2 -2
  15. package/dist/assets/{SettingsWindow-Cy9tmnMg.js → SettingsWindow-Bbay2W76.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-Csrc0Uk2.js → ToolOutputDialog-CRTiN1CH.js} +1 -1
  17. package/dist/assets/{ToolPartDiffPreview-6oH6KD44.js → ToolPartDiffPreview-CqnNcLPk.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-DJNcTQNp.js → VirtualizedFileDiff-iqwryMNU.js} +1 -1
  19. package/dist/assets/{collapsible-DxgVLhi9.js → collapsible-szfZ0Syc.js} +1 -1
  20. package/dist/assets/{computeVirtualFileMetrics-B-WoeBMW.js → computeVirtualFileMetrics-Bbugxxtp.js} +1 -1
  21. package/dist/assets/{contextFileOpenGuard-DQ4U9xRH.js → contextFileOpenGuard-BC3ie230.js} +1 -1
  22. package/dist/assets/{gitStatusPredicates-CIFSGjJs.js → gitStatusPredicates-DbThKVSf.js} +1 -1
  23. package/dist/assets/{index-D2C3q2xD.js → index-KIdiBFJs.js} +1 -1
  24. package/dist/assets/{index-DmNPBaSo.js → index-v6K3L94m.js} +1 -1
  25. package/dist/assets/{isDiffPlainText-CrvpUauF.js → isDiffPlainText-Dl0RBjPZ.js} +1 -1
  26. package/dist/assets/{isFilePlainText-CKvhS32g.js → isFilePlainText-CbrmvrM6.js} +1 -1
  27. package/dist/assets/{main-CjM7g4Gq.js → main-4PkIvzf4.js} +3 -3
  28. package/dist/assets/{main-BFv8slLp.js → main-DMyWi0qs.js} +2 -2
  29. package/dist/assets/{markdownCore-DKrraAqT.js → markdownCore-BD5WkOKU.js} +1 -1
  30. package/dist/assets/{miniChat-hQnLS5mt.js → miniChat-CLMNhna4.js} +2 -2
  31. package/dist/assets/{mobile-DuXOBGs_.js → mobile-rWMDwhtQ.js} +2 -2
  32. package/dist/assets/{renderElectronMiniChatApp-ClJBZVGy.js → renderElectronMiniChatApp-BRhGNRJ8.js} +2 -2
  33. package/dist/assets/{renderMobileApp-DofX2wjB.js → renderMobileApp-DLy2YoQg.js} +3 -3
  34. package/dist/assets/{runtimeEndpointReset-BZeYg6eN.js → runtimeEndpointReset-Z9YtcHxZ.js} +15 -15
  35. package/dist/assets/{runtimeSurface-C7CBxDbh.js → runtimeSurface-CySRuLbN.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-Cs0f1dKn.js → useAppFontEffects-DfuJVB15.js} +85 -85
  37. package/dist/assets/{useFilesViewSearch-D1hcbBEc.js → useFilesViewSearch-BZBHrZ90.js} +1 -1
  38. package/dist/assets/{usePushVisibilityBeacon-DqHkuVS5.js → usePushVisibilityBeacon-BxTkEajM.js} +1 -1
  39. package/dist/assets/{useSwitcherItems-BEoW7LlC.js → useSwitcherItems-jITqE8PV.js} +1 -1
  40. package/dist/assets/{vendor-codemirror-language-data-B8Ac62S_.js → vendor-codemirror-language-data-CDdfwzlS.js} +2 -2
  41. package/dist/assets/{web-components-Dy-Tz_LJ.js → web-components-C9wXMuCp.js} +1 -1
  42. package/dist/index.html +3 -3
  43. package/dist/mini-chat.html +2 -2
  44. package/dist/mobile.html +2 -2
  45. package/package.json +1 -1
  46. package/server/lib/pi/routes.js +35 -1
  47. package/server/lib/pi/routes.test.js +53 -0
  48. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -4
  49. package/server/lib/pi/session-daemon/ipc-client.js +20 -9
  50. package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
  51. package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
  52. package/server/lib/pi/session-daemon/session-daemon.js +127 -26
  53. package/server/lib/pi/session-daemon/session-daemon.test.js +141 -0
  54. package/server/lib/pi/ui-settings-store.js +130 -25
  55. package/server/lib/pi/ui-settings-store.test.js +58 -7
@@ -1,7 +1,7 @@
1
1
  import{c as Wt,d as Vt,p as qr}from"./vendor-zustand-GVb4H8HE.js";import{c as ss}from"./vendor-clsx-B-dksMZM.js";import{t as cs}from"./vendor-tailwind-merge-CPcsbTWB.js";import{F as Sa}from"./vendor-fuse.js-Dw8P0qyA.js";import{R as Eo}from"./vendor-react-B5Z1Mdn3.js";const xt=1,ds="pichamber-relay-v1",Ma=1,Ta=12,_t=1+Ta,Ht=64*1024,jt=5,wo=128,Ra=0,Pa=1,bt=4,ls=1+bt,mr=Ht-jt-ls,M={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},us=new Set(Object.values(M)),fs=e=>us.has(e),tt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},Ee=globalThis.crypto.subtle,Ia={name:"ECDH",namedCurve:"P-256"},xa=16,Wo=32,ms=16,gr=4,_a=8;class xe extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const gs=()=>Ee.generateKey(Ia,!0,["deriveBits"]),ps=async e=>{const t=await Ee.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},hs=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new xe("invalid ECDH public key JWK");try{return await Ee.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Ia,!0,[])}catch{throw new xe("invalid ECDH public key JWK")}},Fs=()=>{const e=new Uint8Array(xa);return globalThis.crypto.getRandomValues(e),e},ys=async(e,t,o)=>{if(o.length!==xa)throw new xe("invalid handshake nonce length");const r=await Ee.deriveBits({name:"ECDH",public:t},e,256),n=await Ee.importKey("raw",r,"HKDF",!1,["deriveBits"]),a=new Uint8Array(await Ee.deriveBits({name:"HKDF",hash:"SHA-256",salt:o,info:new TextEncoder().encode(ds)},n,Wo*2*8)),i=(s,c)=>Ee.importKey("raw",s,{name:"AES-GCM"},!1,c);return{clientToHost:await i(a.slice(0,Wo),["encrypt","decrypt"]),hostToClient:await i(a.slice(Wo),["encrypt","decrypt"])}},bs=(e,t,o)=>{for(let r=_a-1;r>=0;r-=1)e[t+r]=Number(o&0xffn),o>>=8n},As=(e,t)=>{let o=0n;for(let r=0;r<_a;r+=1)o=o<<8n|BigInt(e[t+r]);return o},Es=e=>{const t=new Uint8Array(gr);globalThis.crypto.getRandomValues(t);let o=0n;return{async encrypt(r){if(r.length>Ht)throw new xe("plaintext frame exceeds maximum size");o+=1n;const n=new Uint8Array(Ta);n.set(t,0),bs(n,gr,o);const a=new Uint8Array(await Ee.encrypt({name:"AES-GCM",iv:n},e,r)),i=new Uint8Array(_t+a.length);return i[0]=Ma,i.set(n,1),i.set(a,_t),i}}},ws=e=>{let t=0n;return{async decrypt(o){if(o.length<_t+ms)throw new xe("encrypted frame too short");if(o[0]!==Ma)throw new xe("unsupported encrypted frame version");const r=o.slice(1,_t),n=As(r,gr);if(n<=t)throw new xe("frame counter regression");let a;try{a=await Ee.decrypt({name:"AES-GCM",iv:r},e,o.slice(_t))}catch{throw new xe("frame decryption failed")}return t=n,new Uint8Array(a)}}},no="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Bs=e=>{let t="";for(let o=0;o<e.length;o+=3){const r=e[o],n=o+1<e.length?e[o+1]:void 0,a=o+2<e.length?e[o+2]:void 0;t+=no[r>>2],t+=no[(r&3)<<4|(n??0)>>4],n!==void 0&&(t+=no[(n&15)<<2|(a??0)>>6]),a!==void 0&&(t+=no[a&63])}return t},xn=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const o=t;if(o.v!==xt)return null;const r=o.batch===!0;return o.t==="ready"?{t:"ready",v:xt,batch:r}:o.t==="hello"&&typeof o.nonce=="string"&&typeof o.clientPubJwk=="object"&&o.clientPubJwk!==null?{t:"hello",v:xt,clientPubJwk:o.clientPubJwk,nonce:o.nonce,batch:r}:null},Cs=e=>({type:"fail",closeCode:tt.ChannelFailure,reason:e}),ks=async(e,t={})=>{const o=t.batch!==!1,r=await hs(e),n=await gs(),a=Fs(),i={t:"hello",v:xt,clientPubJwk:await ps(n.publicKey),nonce:Bs(a),...o?{batch:!0}:{}};let s=!1;return{helloText:JSON.stringify(i),get established(){return s},async handleText(c){if(s)return xn(c)?.t==="ready"?{type:"ignore"}:Cs("plaintext frame on established channel");const d=xn(c);if(d?.t!=="ready")return{type:"ignore"};const l=await ys(n.privateKey,r,a);return s=!0,{type:"established",batch:o&&d.batch===!0,channel:{encryptor:Es(l.clientToHost),decryptor:ws(l.hostToClient)}}}}},Oa=4294967295;class G extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const we=(e,t,o,r=!1)=>{if(!Number.isInteger(t)||t<0||t>Oa)throw new G("invalid stream id");if(o.length>mr)throw new G("tunnel payload exceeds maximum size");const n=new Uint8Array(jt+o.length);return n[0]=r?e|wo:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(o,jt),n},vs=e=>{if(e.length<jt)throw new G("tunnel frame too short");const t=e[0],o=(t&wo)!==0,r=t&~wo;if(!fs(r))throw new G(`unknown tunnel frame type ${r}`);const n=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:n,payload:e.slice(jt),hasMoreFragments:o}},Ds=new TextEncoder,Ss=new TextDecoder,Bo=e=>Ds.encode(JSON.stringify(e)),Co=(e,t)=>{let o;try{o=JSON.parse(Ss.decode(e))}catch{throw new G("malformed JSON tunnel payload")}if(!t(o))throw new G("unexpected JSON tunnel payload shape");return o},Na=(e,t=mr)=>{if(t<=0||t>mr)throw new G("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const o=[];for(let r=0;r<e.length;r+=t)o.push(e.slice(r,r+t));return o},_n=(e,t,o)=>{const r=Na(o);return r.map((n,a)=>we(e,t,n,a<r.length-1))},Ms=(e=16*1024*1024)=>{const t=new Map;return{push(o){const r=`${o.streamId}:${o.frameType}`,n=t.get(r);if(!o.hasMoreFragments&&!n)return o.payload;const a=n?.chunks??[],i=(n?.totalBytes??0)+o.payload.length;if(i>e)throw t.delete(r),new G("fragmented message exceeds maximum size");if(a.push(o.payload),o.hasMoreFragments)return t.set(r,{chunks:a,totalBytes:i}),null;t.delete(r);const s=new Uint8Array(i);let c=0;for(const d of a)s.set(d,c),c+=d.length;return s},dropStream(o){for(const r of t.keys())r.startsWith(`${o}:`)&&t.delete(r)}}},Ts=e=>{if(e.length===0)throw new G("cannot encode an empty frame batch");if(e.length===1){const n=e[0],a=new Uint8Array(1+n.length);if(a[0]=Ra,a.set(n,1),a.length>Ht)throw new G("frame batch exceeds maximum plaintext size");return a}let t=1;for(const n of e)t+=bt+n.length;if(t>Ht)throw new G("frame batch exceeds maximum plaintext size");const o=new Uint8Array(t);o[0]=Pa;let r=1;for(const n of e)o[r]=n.length>>>24&255,o[r+1]=n.length>>>16&255,o[r+2]=n.length>>>8&255,o[r+3]=n.length&255,r+=bt,o.set(n,r),r+=n.length;return o},Rs=e=>{if(e.length<1)throw new G("empty batch plaintext");const t=e[0];if(t===Ra)return[e.slice(1)];if(t!==Pa)throw new G(`unknown batch container tag ${t}`);const o=[];let r=1;for(;r<e.length;){if(r+bt>e.length)throw new G("truncated batch frame length");const n=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=bt,r+n>e.length)throw new G("truncated batch frame body");o.push(e.slice(r,r+n)),r+=n}if(o.length===0)throw new G("empty frame batch");return o},Ps=new Set([M.HttpBody,M.WsText,M.WsBinary]),La=150,Is=24*1024,xs=32,_s=e=>{const t=e.windowMs??La,o=e.maxBatchBytes??Is,r=e.maxBatchFrames??xs,n=e.now??(()=>Date.now()),a=e.setTimer??((g,F)=>setTimeout(g,F)),i=e.clearTimer??(g=>clearTimeout(g));let s=[],c=0,d=null,l=0,u=!1;const f=()=>{d!==null&&(i(d),d=null)},m=()=>{if(f(),s.length===0)return;const g=s;s=[],c=0,l=n(),e.sendBatch(Ts(g))};return{enqueue:g=>{if(u)return;const F=g[0]&~wo;if(!Ps.has(F)){s.push(g),m();return}const y=n();if(s.length===0&&y-l>=t){s.push(g),m();return}const b=bt+g.length;if(s.length>0&&1+c+b>Ht&&m(),s.push(g),c+=b,c>=o||s.length>=r){m();return}d===null&&(d=a(m,t))},flush:m,dispose(){u=!0,f(),s=[],c=0}}},Os=()=>{let e=1;return{next(){if(e>Oa)throw new G("stream id space exhausted");const t=e;return e+=2,t}}},Ns=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(o){e.send(o)},close(o,r){e.close(o,r)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=o=>t.onmessage?.({data:o.data}),e.onclose=o=>t.onclose?.({code:o.code,reason:o.reason}),e.onerror=()=>t.onerror?.(),t},Ls=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(o){o&&(e.binaryType=o)},onopen:null,onmessage:null,onerror:null,onclose:null,send(o){e.send(o)},close(o,r){e.close(o,r)}};return e.onopen=()=>t.onopen?.(),e.onmessage=o=>{const r=o.data;(typeof r=="string"||r instanceof ArrayBuffer)&&t.onmessage?.({data:r})},e.onerror=()=>t.onerror?.(),e.onclose=o=>t.onclose?.({code:o.code,reason:o.reason}),t},On=0,Vo=1,Nn=2,Ln=3,Us=new Set([tt.AuthFailed,tt.DuplicateClient,tt.LimitExceeded]),Hs={[tt.AuthFailed]:"relay authentication failed",[tt.DuplicateClient]:"relay connection replaced by another client",[tt.LimitExceeded]:"relay connection limit reached"},Oo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),js=e=>Oo(e)&&Object.values(e).every(t=>typeof t=="string"),zs=e=>Oo(e)&&typeof e.status=="number"&&js(e.headers),Ua=e=>Oo(e)&&typeof e.reason=="string",$s=e=>Oo(e)&&typeof e.code=="number"&&typeof e.reason=="string",Ha=/^[a-z][a-z\d+.-]*:\/\//i,Gr="http://tunnel.invalid",Ks=e=>{try{const t=Ha.test(e)?new URL(e):new URL(e,Gr);return`${t.pathname}${t.search}`}catch{return e}},ao=e=>({async*[Symbol.asyncIterator](){yield e}}),qs=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:o,value:r}=await t.read();if(o)return;r&&(yield r)}}finally{t.releaseLock()}}}),Gs=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Ws=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:qs(e)};if(typeof e=="string")return{body:ao(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:ao(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:ao(Gs(e))};const t=new Response(e),o=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:ao(r),contentType:o}},Vs=async(e,t)=>{let o;const r=new Headers;let n="GET",a=null,i;e instanceof Request?(o=e.url,n=e.method,e.headers.forEach((u,f)=>r.set(f,u)),i=e.signal,a=e.body):o=e.toString(),t&&(t.method&&(n=t.method),t.headers&&new Headers(t.headers).forEach((u,f)=>r.set(f,u)),t.body!==void 0&&(a=t.body),t.signal&&(i=t.signal));const s=Ha.test(o)?new URL(o):new URL(o,Gr),{body:c,contentType:d}=await Ws(a);d&&!r.has("content-type")&&r.set("content-type",d);const l={};return r.forEach((u,f)=>{l[f]=u}),{method:n.toUpperCase(),path:s.pathname,query:s.search.startsWith("?")?s.search.slice(1):s.search,headers:l,body:c,signal:i}},Js="__pichamberAmbiguousTransport",Ys=e=>(Object.defineProperty(e,Js,{value:!0,enumerable:!1,configurable:!0}),e),Qs=new Uint8Array(0),Xs=new TextEncoder,Zs=new TextDecoder,pr=e=>e instanceof Error?e:new Error(String(e)),Un=()=>new DOMException("The operation was aborted.","AbortError"),ec=async(e,t,o)=>{const r=await Vs(t,o),n=r.signal;if(n?.aborted)throw Un();const a=await e(n),i=a.nextStreamId();return await new Promise((s,c)=>{let d=!1,l=!1,u=null,f=null;const m=()=>{a.streams.delete(i),a.assembler.dropStream(i),f&&n&&n.removeEventListener("abort",f)},p=b=>{if(!l){if(l=!0,m(),!d){c(b);return}try{u?.error(b)}catch{}}},g=b=>{a.dead||a.send(we(M.StreamAbort,i,Bo({reason:b})))},F=b=>Ys(new Error(b));f=()=>{g("aborted"),p(Un())},a.streams.set(i,{handleFrame(b,D){if(b===M.HttpResponse){if(d||l)return;let C;try{C=Co(D,zs)}catch(L){g("malformed response head"),p(F(pr(L).message));return}const I=C.status===204||C.status===205||C.status===304;let V=null;I||(V=new ReadableStream({start(L){u=L},cancel(){l||(l=!0,m(),g("response body cancelled"))}})),d=!0,s(new Response(V,{status:C.status,headers:C.headers})),I&&(l=!0,m());return}if(b===M.HttpBody){if(!d||l)return;try{u?.enqueue(D)}catch{}return}if(b===M.StreamEnd){if(l)return;if(!d){p(F("tunnel stream ended before response head"));return}l=!0,m();try{u?.close()}catch{}return}if(b===M.StreamAbort){let C="stream aborted by host";try{C=Co(D,Ua).reason}catch{}p(F(C))}},fail(b){p(F(b.message))}}),n&&n.addEventListener("abort",f,{once:!0});const y={method:r.method,path:r.path,query:r.query,headers:r.headers};a.send(we(M.HttpRequest,i,Bo(y))),(async()=>{try{if(r.body)for await(const b of r.body){if(l||a.dead)return;for(const D of Na(b))a.send(we(M.HttpBody,i,D))}!l&&!a.dead&&a.send(we(M.StreamEnd,i,Qs))}catch(b){g("request body failed"),p(F(pr(b).message))}})()})},tc=e=>{const t=e.indexOf("?");return t===-1?{path:e,query:""}:{path:e.slice(0,t),query:e.slice(t+1)}},oc=(e,t,o)=>{let r=On,n=null,a=0,i=!1;const s={get readyState(){return r},onopen:null,onmessage:null,onerror:null,onclose:null,send(d){if(r!==Vo||!n||n.dead)throw new Error("relay tunnel socket is not open");if(typeof d=="string"){for(const u of _n(M.WsText,a,Xs.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 _n(M.WsBinary,a,l))n.send(u)},close(d=1e3,l=""){r===Ln||r===Nn||(r===Vo&&n&&!n.dead&&(r=Nn,n.send(we(M.WsClose,a,Bo({code:d,reason:l})))),c(d,l))}},c=(d,l,u=!1)=>{if(!i){if(i=!0,n&&(n.streams.delete(a),n.assembler.dropStream(a)),r=Ln,u)try{s.onerror?.()}catch{}try{s.onclose?.({code:d,reason:l})}catch{}}};return(async()=>{let d;try{d=await e()}catch(m){c(1006,pr(m).message,!0);return}if(i)return;n=d,a=d.nextStreamId(),d.streams.set(a,{handleFrame(m,p){if(m===M.WsOpened){if(r===On){r=Vo;try{s.onopen?.()}catch{}}return}if(m===M.WsText){try{s.onmessage?.({data:Zs.decode(p)})}catch{}return}if(m===M.WsBinary){const g=new ArrayBuffer(p.byteLength);new Uint8Array(g).set(p);try{s.onmessage?.({data:g})}catch{}return}if(m===M.WsClose){let g=1e3,F="";try{const y=Co(p,$s);g=y.code,F=y.reason}catch{}c(g,F);return}if(m===M.StreamAbort){let g="stream aborted";try{g=Co(p,Ua).reason}catch{}c(1006,g,!0)}},fail(m){c(1012,m.message,!0)}});const{path:l,query:u}=tc(t),f=o&&o.length>0?{path:l,query:u,protocols:o}:{path:l,query:u};d.send(we(M.WsOpen,a,Bo(f)))})(),s},Hn=new Uint8Array(0),Fe=e=>e instanceof Error?e:new Error(String(e)),jn=()=>new DOMException("The operation was aborted.","AbortError"),zn=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Wr=e=>{const t=e.helloRetryMs??1e3,o=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,n=e.pingTimeoutMs??15e3,a=e.batchWindowMs??La,i=e.batch!==!1,s=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,d=e.hiddenOrOfflineMaxDelayMs??6e4,l=e.createWireSocket??(w=>Ns(new WebSocket(w)));let u=!1,f={state:"idle"};const m=new Set;let p=null,g=null,F=null,y=0,b=0,D=null,C=[],I=!1;const V=w=>{if(!(f.state===w.state&&f.lastError===w.lastError)){f=w;for(const x of m)try{x(f)}catch{}}},L=w=>{const x=C;C=[];for(const P of x)P.reject(w)},Ct=w=>{const x=C;C=[];for(const P of x)P.resolve(w)},ve=(w,x)=>{w.dead=!0;const P=Array.from(w.streams.values());w.streams.clear();for(const j of P)try{j.fail(x)}catch{}},lt=()=>{D!==null&&(clearTimeout(D),D=null)},v=()=>{u||D===null||zn()||(lt(),ze(),$e())},z=()=>{typeof document>"u"||document.visibilityState==="visible"&&v()},kt=()=>{I||(I=!0,typeof window<"u"&&window.addEventListener("online",v),typeof document<"u"&&document.addEventListener("visibilitychange",z))},ze=()=>{I&&(I=!1,typeof window<"u"&&window.removeEventListener("online",v),typeof document<"u"&&document.removeEventListener("visibilitychange",z))},to=()=>{if(u||D!==null)return;const w=s*Math.pow(1.5,Math.min(b,8)),x=Math.random()*.3*w,P=Math.min(c,Math.round(w+x)),j=zn()?Math.max(P,d):P;kt(),D=setTimeout(()=>{D=null,ze(),$e()},j)},oo=()=>{const w=new URL(e.relayUrl);return w.searchParams.set("v",String(xt)),w.searchParams.set("role","client"),w.searchParams.set("serverId",e.serverId),e.grant&&w.searchParams.set("grant",e.grant),w.toString()},$e=async()=>{if(u)return;const w=++y;lt(),ze(),F?.(),F=null,V({state:b===0?"connecting":"reconnecting"});let x;try{x=await ks(e.hostEncPubJwk,{batch:i})}catch(T){Go(w,Fe(T),!0);return}if(u||w!==y)return;let P;try{P=l(oo())}catch(T){Go(w,Fe(T));return}g=P;let j=null,ae=null,ce=null,pe=null,zo=null,Ke=!1,vt=null,$o=null,Ko=Date.now(),Rn=!1,ro=Promise.resolve();const qo=()=>{j!==null&&(clearInterval(j),j=null),ae!==null&&(clearTimeout(ae),ae=null),ce!==null&&(clearInterval(ce),ce=null),pe!==null&&(clearTimeout(pe),pe=null),zo?.dispose(),zo=null};F=qo;const X=(T,U={})=>{const{terminal:N=!1,asErrorState:O=!1}=U;if(!(Ke||w!==y)){Ke=!0,qo(),F===qo&&(F=null),vt&&ve(vt,T),p===vt&&(p=null);try{P.close()}catch{}if(g===P&&(g=null),N){u=!0,L(T),V({state:"error",lastError:T.message});return}Go(w,T,O)}},Pn=()=>{if(P.readyState===1)try{P.send(x.helloText)}catch(T){X(Fe(T))}},as=(T,U)=>{$o=T,Rn=U,j!==null&&(clearInterval(j),j=null),ae!==null&&(clearTimeout(ae),ae=null),b=0;const N=new Map,O=Os(),qe=Ms();let ee=Promise.resolve();const he=St=>{ee=ee.then(async()=>{if(Dt.dead)return;const is=await T.encryptor.encrypt(St);P.send(is)}).catch(()=>{})},Ge=U?_s({windowMs:a,sendBatch:he}):null;zo=Ge;const Dt={streams:N,assembler:qe,nextStreamId:()=>O.next(),send:St=>{if(Ko=Date.now(),Ge){Ge.enqueue(St);return}he(St)},dead:!1};vt=Dt,p=Dt,V({state:"connected"}),Ct(Dt),ce=setInterval(()=>{Date.now()-Ko<r||(Dt.send(we(M.Ping,0,Hn)),pe===null&&(pe=setTimeout(()=>{pe=null,X(new Error("relay keepalive timeout"))},n)))},r)},In=(T,U)=>{let N;try{N=vs(U)}catch(ee){X(Fe(ee));return}if(pe!==null&&(clearTimeout(pe),pe=null),N.frameType===M.Ping){T.send(we(M.Pong,N.streamId,Hn));return}if(N.frameType===M.Pong)return;Ko=Date.now();let O=N.payload;if(N.frameType===M.WsText||N.frameType===M.WsBinary){let ee;try{ee=T.assembler.push(N)}catch(he){X(Fe(he));return}if(ee===null)return;O=ee}else if(N.hasMoreFragments){X(new Error("unexpected fragmented tunnel frame"));return}const qe=T.streams.get(N.streamId);qe&&qe.handleFrame(N.frameType,O)};P.onopen=()=>{Ke||w!==y||(Pn(),j=setInterval(Pn,t))},P.onmessage=T=>{if(Ke||w!==y)return;const U=T.data;if(typeof U=="string"){ro=ro.then(async()=>{if(Ke||w!==y)return;const O=await x.handleText(U);if(O.type==="established"){if($o)return;as(O.channel,O.batch)}else O.type==="fail"&&X(new Error(`relay handshake failed: ${O.reason}`))}).catch(O=>{X(Fe(O))});return}const N=U instanceof ArrayBuffer?new Uint8Array(U):U instanceof Uint8Array?U:null;N&&(ro=ro.then(async()=>{if(Ke||w!==y)return;const O=vt,qe=$o;if(!O||!qe){X(new Error("encrypted frame before handshake completed"));return}let ee;try{ee=await qe.decryptor.decrypt(N)}catch(he){X(Fe(he));return}if(Rn){let he;try{he=Rs(ee)}catch(Ge){X(Fe(Ge));return}for(const Ge of he){if(Ke||w!==y||O.dead)return;In(O,Ge)}return}In(O,ee)}).catch(O=>{X(Fe(O))}))},P.onclose=T=>{const U=Us.has(T.code);X(new Error(Hs[T.code]??`relay socket closed (code ${T.code})`),{terminal:U,asErrorState:U})},P.onerror=()=>{},ae=setTimeout(()=>{ae=null,X(new Error("relay handshake timeout"),{asErrorState:!0})},o);function Go(T,U,N=!1){T!==y||u||(L(U),b+=1,V({state:N?"error":"reconnecting",lastError:U.message}),to())}},Tn=w=>u?Promise.reject(new Error("relay tunnel closed")):w?.aborted?Promise.reject(jn()):p&&!p.dead?Promise.resolve(p):new Promise((x,P)=>{let j=null;const ae={resolve(ce){j&&w&&w.removeEventListener("abort",j),x(ce)},reject(ce){j&&w&&w.removeEventListener("abort",j),P(ce)}};w&&(j=()=>{C=C.filter(ce=>ce!==ae),P(jn())},w.addEventListener("abort",j,{once:!0})),C.push(ae)}),ns=()=>{if(u)return;u=!0,y+=1,lt(),ze(),F?.(),F=null;const w=p;p=null;const x=new Error("relay tunnel closed");w&&ve(w,x),L(x);try{g?.close()}catch{}g=null,V({state:"idle"})};return $e(),{fetch:(w,x)=>ec(Tn,w,x),openWebSocket:(w,x)=>oc(()=>Tn(),w,x),getStatus:()=>f,subscribeStatus(w){return m.add(w),()=>{m.delete(w)}},close:ns}};let re=null,Ot=null;const rc=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Jt=()=>re,ja=()=>re!==null,nc=e=>(re&&Ot&&rc(Ot,e)||(re?.close(),Ot=e,re=Wr(e)),re),oF=(e,t)=>{re!==t&&(re?.close(),Ot=e,re=t)},ac=()=>{re?.close(),re=null,Ot=null};let za=()=>null,$a="",ko={},Ne="",zt=0,Ye=null,ht="",$t=0,rt="",Qe=null,Re="",po=0,ho=0;const Vr=1e4,ic=e=>e.toLowerCase()==="authorization",Ka=e=>{const t={};for(const[o,r]of Object.entries(e||{})){const n=o.trim(),a=r.trim();n&&a&&!ic(n)&&(t[n]=a)}return t},sc=(e,t)=>{const o=Object.entries(e);return o.length!==Object.keys(t).length?!1:o.every(([r,n])=>t[r]===n)},Yt=e=>typeof e!="string"?"":e.trim(),cc=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_CLIENT_TOKEN__;return Yt(e)},dc=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},qa=(e,t)=>{const o=typeof e=="string"&&e.trim()?e.trim():dc();if(!o)return t;try{return new URL(t,`${o.replace(/\/+$/,"")}/`).toString()}catch{return t}},Jr=e=>{try{return new URL(e).origin}catch{return""}},Ga=()=>{ht="",$t=0,rt="",Qe=null,Re="",po+=1},Qt=e=>{e!==void 0&&Yt(e)!==Ne||(Ne="",zt=0,Ga())},Wa=()=>{ho+=1,Ye=null,Qt(),Qr()},Va=e=>{const t=Yt(e);$a=t,Wa(),za=()=>t?{type:"bearer",token:t}:null},Ja=e=>{const t=Ka(e);sc(ko,t)||(ko=t,Wa())},Yr=()=>{if(Object.keys(ko).length>0)return ko;if(typeof window>"u")return{};const e=window.__PICHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Ka(e):{}},No=()=>$a||cc(),lc=(e,t)=>{const o=Yt(e);if(!o||typeof t!="number"||!Number.isFinite(t)){Qt();return}const r=Ne;Ne=o,zt=t,r&&r!==o&&hc()},Ya=()=>!Ne||zt<=Date.now()+Vr?(Qt(),""):Ne,uc=e=>{const t=Jr(e);return!t||rt!==t?"":!ht||$t<=Date.now()+Vr?(ht="",$t=0,rt="",""):ht},fc=()=>{const e=Ya();return!e&&(No()||typeof window<"u")&&At().catch(()=>{}),e},Qa=async()=>{const e=await za(),t=e?.type==="bearer"?Yt(e.token):No();return t?{type:"bearer",token:t}:null},Xa=e=>{if(Ye)return Ye;const t=ho,r=(async()=>{const n=await Qa(),a=new Headers;for(const[u,f]of Object.entries(Yr()))a.set(u,f);n?.type==="bearer"&&a.set("Authorization",`Bearer ${n.token}`);const i=Jt(),s=i?await i.fetch("/auth/url-token",{method:"POST",headers:a}):await fetch(qa(e,"/auth/url-token"),{method:"POST",headers:a,credentials:"include"});if(!s.ok)throw t===ho&&Qt(),new Error(`Failed to mint runtime URL auth token (${s.status})`);const c=await s.json().catch(()=>null),d=typeof c?.token=="string"?c.token.trim():"",l=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==ho)throw new Error("Runtime URL auth token response is stale");if(lc(d,l),!Ne)throw new Error("Runtime URL auth token response was invalid");return Ne})().finally(()=>{Ye===r&&(Ye=null)});return Ye=r,Ye},mc=e=>{const t=Jr(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Qe&&Re===t)return Qe;const o=po,n=(async()=>{const a=await fetch(qa(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!a.ok)throw o===po&&t===Re&&(ht="",$t=0,rt=""),new Error(`Failed to mint local runtime URL auth token (${a.status})`);const i=await a.json().catch(()=>null),s=typeof i?.token=="string"?i.token.trim():"",c=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!s||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(o!==po||t!==Re)throw new Error("Local runtime URL auth token response is stale");return ht=s,$t=c,rt=t,s})().finally(()=>{Qe===n&&(Qe=null,Re="")});return Qe=n,Re=t,Qe},At=async e=>{const t=Ya();return t||Xa(e)},gc=async e=>{const t=Jr(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const o=uc(t);return o||((rt&&rt!==t||Re&&Re!==t)&&Ga(),mc(t))};let gt=0,Nt=null,Za=null;const hr=new Set,pc=5e3,hc=()=>{for(const e of hr)try{e()}catch{}},ei=()=>{Nt!==null&&(clearTimeout(Nt),Nt=null)},Qr=()=>{if(ei(),gt<=0||typeof window>"u")return;const e=zt-Vr-pc,t=zt>0?Math.max(0,e-Date.now()):0;Nt=setTimeout(()=>{Nt=null,!(gt<=0)&&Xa(Za).catch(()=>{}).finally(()=>{Qr()})},t)},rF=e=>{typeof e=="string"&&e.trim()&&(Za=e.trim()),gt+=1,Qr();let t=!1;return()=>{t||(t=!0,gt=Math.max(0,gt-1),gt===0&&ei())}},nF=e=>(hr.add(e),()=>{hr.delete(e)}),Fc=async e=>{const t=new Headers(e);for(const[r,n]of Object.entries(Yr()))t.has(r)||t.set(r,n);if(t.has("Authorization"))return t;const o=await Qa();return o?.type==="bearer"&&t.set("Authorization",`Bearer ${o.token}`),t},vo=/^[a-z][a-z\d+.-]*:\/\//i,yc=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Fr=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),bc=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return Fr(e)},Ac=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},yr=(e,t)=>{if(!t)return;const o=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,n]of o)n!=null&&e.searchParams.set(r,String(n))},Ec=(e,t)=>{if(!t)return e;const o=new URLSearchParams;yr({searchParams:o},t);const r=o.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},$n=(e,t,o)=>{if(vo.test(t)){const a=new URL(t);return yr(a,o),a.toString()}const r=yc(t);if(!e)return Ec(r,o);const n=new URL(r,`${e}/`);return yr(n,o),n.toString()},Jo=(e,t)=>{const o=t===void 0?fc():t;if(!o)return e;const r=vo.test(e)?new URL(e):new URL(e,"http://pichamber.local");return r.searchParams.set("oc_url_token",o),vo.test(e)?r.toString():`${r.pathname}${r.search}${r.hash}`},wc=(e,t)=>{const o=vo.test(e)?new URL(e):new URL(e,Ac(t));return o.protocol==="ws:"||o.protocol==="wss:"||(o.protocol=o.protocol==="https:"?"wss:":"ws:"),o.toString()},Xr=(e={})=>{const t=Fr(e.apiBaseUrl),o=Fr(e.realtimeBaseUrl),r=()=>t||bc(),n=()=>o||r(),a=(s,c)=>$n(r(),s,c),i=(s,c)=>$n(n(),s,c);return{api:a,authenticatedAsset:(s,c)=>Jo(a(s,c)),auth:a,health:s=>a("/health",s),rawFile:(s,c)=>a("/api/fs/raw",{path:s,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(s,c)=>Jo(i(s,c)),websocket:(s,c,d)=>wc(Jo(i(s,c),d),e)}};let Do=Xr();const ge=()=>Do,Bc=e=>{Do=e},Zr=e=>(Do=Xr(e),Do),nt=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Cc=()=>typeof window>"u"?"":window.location.origin||"",en=e=>{if(typeof window>"u")return!1;const t=Cc();if(t&&e.origin===t)return!0;try{const o=new URL(window.location.href||t);return e.protocol===o.protocol&&e.host===o.host}catch{return!1}},tn=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),on=(e,t)=>{if(!t)return;const o=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,n]of o)n!=null&&e.searchParams.set(r,String(n))},Fo=e=>{try{const t=ge().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const o=new URL(t);return e.origin!==o.origin?!1:nt(e.pathname)}catch{return!1}},Yo=e=>{if(nt(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return en(t)&&nt(t.pathname)}catch{return!1}},kc=(e,t)=>{try{const o=new URL(e);if(!en(o))return e;const r=ot(`${o.pathname}${o.search}`,t);return!tn(r)&&(o.protocol==="http:"||o.protocol==="https:")?(on(o,t),o.toString()):o.hash?`${r}${o.hash}`:r}catch{return e}},ot=(e,t)=>e==="/health"?ge().health(t):e.startsWith("/auth/")||e==="/auth"?ge().auth(e,t):nt(e)?ge().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?kc(e,t):e,vc=e=>{const t=e instanceof Request?e.url:e.toString();if(!tn(t))return nt(t);try{return Fo(new URL(t))}catch{return!1}},Dc=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Sc=(e,t)=>!Dc(t),Kn=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 o=[];let r=!1;for(const[n,a]of t)Sc(n,a)?(o.push([n,encodeURIComponent(a)]),r=!0):o.push([n,a]);return r?o:void 0},be=async(e,t,o=!0)=>{const r=new Headers(Kn(e)??e);return t&&new Headers(Kn(t)??t).forEach((n,a)=>r.set(a,n)),o?Fc(r):r},Mc=(e,t)=>{if(!t)return e;const o=new URL(e,Gr);return on(o,t),`${o.pathname}${o.search}`},ti=(e,t)=>{const o=e instanceof Request?e.url:e.toString();if(!tn(o))return nt(o)?Mc(o,t):null;try{const r=new URL(o);return!en(r)||!nt(r.pathname)?null:(on(r,t),`${r.pathname}${r.search}`)}catch{return null}},Tc=async(e,t,o)=>{const r=Jt();if(!r)return null;const n=ti(e,o);if(n===null)return null;const a=e instanceof Request?e.headers:void 0,i=await be(a,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(n,{...t,headers:i})},Rc=(e,t)=>{if(typeof e=="string")return ot(e,t);if(e instanceof URL)return ot(e.toString(),t);const o=ot(e.url,t);return o===e.url?e:new Request(o,e)},Pc=/\/api\/pi\/(health|projects|sessions|providers|resources|settings)(\b|\/|\?|$)/,io=new Map,Ic=(e,t,o)=>o||e!=="GET"||t.includes("/event")||!Pc.test(t)?null:`GET ${t}`,h=async(e,t={})=>{const{query:o,...r}=t,n=Jt(),a=n?ti(e,o):null;let i,s,c;if(n&&a!==null){const m=e instanceof Request?e.headers:void 0,p=await be(m,r.headers,!0);i=e instanceof Request?()=>n.fetch(e,{...r,headers:p}):()=>n.fetch(a,{...r,headers:p}),s=a,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const m=Rc(e,o),p=m instanceof Request?m.headers:void 0,g=await be(p,r.headers,vc(m));i=m instanceof Request?()=>fetch(new Request(m,{...r,headers:g})):()=>fetch(m,{...r,headers:g}),s=m instanceof Request?m.url:m instanceof URL?m.toString():String(m),c=String(r.method??(m instanceof Request?m.method:"GET")).toUpperCase()}const d=r.signal!=null||e instanceof Request,l=Ic(c,s,d);if(!l)return i();const u=io.get(l);if(u)return u.then(m=>m.clone());const f=i();return io.set(l,f),f.then(()=>io.delete(l),()=>io.delete(l)),f.then(m=>m.clone())};let qn=!1;const xc=()=>{if(qn||typeof window>"u")return;qn=!0;const e=window.fetch.bind(window);window.fetch=async(t,o)=>{const r=await Tc(t,o??{});if(r)return r;if(typeof t=="string"){if(!Yo(t)){try{const a=new URL(t);if(Fo(a)){const i=await be(void 0,o?.headers);return e(t,{...o,headers:i})}}catch{}return e(t,o)}const n=await be(void 0,o?.headers);return e(ot(t),{...o,headers:n})}if(t instanceof URL){const n=t.toString();if(!Yo(n)){if(Fo(t)){const i=await be(void 0,o?.headers);return e(t,{...o,headers:i})}return e(t,o)}const a=await be(void 0,o?.headers);return e(ot(n),{...o,headers:a})}if(t instanceof Request){if(!Yo(t.url)){try{const s=new URL(t.url);if(Fo(s)){const c=await be(t.headers,o?.headers);return e(new Request(t,{...o,headers:c}))}}catch{}return e(t,o)}const n=await be(t.headers,o?.headers),a=ot(t.url),i=a===t.url?t:new Request(a,t);return e(new Request(i,{...o,headers:n}))}return e(t,o)}};let Qo=null,Xo=null,Zo=null;const Gn=new Set;let Wn=!1;const oi=e=>{if(Gn.add(e),Wn||typeof window>"u")return;Wn=!0;const t=()=>{for(const o of Gn)o()};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{}},_c=(e,t)=>{let o;try{o=e()}catch{return}const r=new Map,n=new Set;let a;const i=()=>{if(a=void 0,r.size===0&&n.size===0)return;const c=Array.from(r.entries()),d=Array.from(n);r.clear(),n.clear();for(const[l,u]of c)try{o.setItem(l,JSON.stringify(u,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!r.has(l)&&!n.has(l)&&r.set(l,u)}for(const l of d)try{o.removeItem(l)}catch(u){console.error("Failed to remove deferred storage value",u),r.has(l)||n.add(l)}},s=()=>{a===void 0&&(a=setTimeout(i,0))};return oi(i),{getItem:c=>{if(r.has(c))return r.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{o.removeItem(c)}catch{}return null}},l=o.getItem(c);return l instanceof Promise?l.then(d):d(l)},setItem:(c,d)=>{r.set(c,d),n.delete(c),s()},removeItem:c=>{r.delete(c),n.add(c),s()}}},rn=e=>_c(()=>ai(),e),Oc=e=>{const t=new Map,o=new Set;let r;const n=()=>{if(r=void 0,t.size===0&&o.size===0)return;const i=Array.from(t.entries()),s=Array.from(o);t.clear(),o.clear();for(const[c,d]of i)try{e.setItem(c,d)}catch(l){console.error("Failed to persist deferred storage value",l),!t.has(c)&&!o.has(c)&&t.set(c,d)}for(const c of s)try{e.removeItem(c)}catch(d){console.error("Failed to remove deferred storage value",d),t.has(c)||o.add(c)}},a=()=>{r===void 0&&(r=setTimeout(n,0))};return oi(n),{getItem:i=>t.has(i)?t.get(i)??null:o.has(i)?null:e.getItem(i),setItem:(i,s)=>{t.set(i,s),o.delete(i),a()},removeItem:i=>{t.delete(i),o.add(i),a()},clear:()=>{t.clear(),o.clear(),r!==void 0&&(clearTimeout(r),r=void 0),e.clear()},key:i=>e.key(i),get length(){return e.length}}},ri=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},nn=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,o)=>{e.set(t,o)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},ni=e=>{const t=nn(),o=new Set,r=new Set,n=d=>{if(r.has(d))return null;if(o.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),o.delete(d),r.delete(d);return}catch{try{e.removeItem(d)}catch{}}t.setItem(d,l),o.add(d),r.delete(d)},i=d=>{try{e.removeItem(d),r.delete(d)}catch{r.add(d)}t.removeItem(d),o.delete(d)},s=()=>{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(),r.clear()}catch{for(const l of d)r.add(l)}t.clear(),o.clear()},c=()=>{const d=new Set;try{for(let l=0;l<e.length;l+=1){const u=e.key(l);u&&!r.has(u)&&!o.has(u)&&d.add(u)}}catch{}for(const l of o)d.add(l);return[...d]};return{getItem:n,setItem:a,removeItem:i,clear:s,key:d=>c()[d]??null,get length(){return c().length}}},Nc=()=>{const e=ri("localStorage");return e?ni(e):nn()},ai=()=>(Qo||(Qo=Nc()),Qo),st=()=>(Zo||(Zo=Oc(ai())),Zo),Lc=()=>{const e=ri("sessionStorage");return e?ni(e):nn()},aF=()=>(Xo||(Xo=Lc()),Xo),br="pichamber:runtime-endpoint-changed",Ar="pichamber:runtime-endpoint-will-change";let Le="",at="";const Er="pichamber:lastRuntimeEndpoint.v1",Uc=()=>{try{const e=st().getItem(Er);if(!e)return null;const t=JSON.parse(e),o=typeof t.apiBaseUrl=="string"?t.apiBaseUrl.trim():"",r=typeof t.runtimeKey=="string"?t.runtimeKey.trim():"";return!o||!r||r==="mobile-disconnected"?null:{apiBaseUrl:o,runtimeKey:r}}catch{return null}},Hc=(e,t)=>{try{const o=st();if(t==="mobile-disconnected"||!e){o.removeItem(Er);return}o.setItem(Er,JSON.stringify({apiBaseUrl:e,runtimeKey:t}))}catch{}},an=()=>{if(Le||at||typeof window>"u")return;const e=Uc();if(e){Le=e.apiBaseUrl,at=e.runtimeKey;try{window.__PICHAMBER_API_BASE_URL__=e.apiBaseUrl}catch{}Zr({apiBaseUrl:e.apiBaseUrl,realtimeBaseUrl:e.apiBaseUrl})}},er=(e,t,o)=>{try{e[t]=o}catch{}},sn=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"}`}},ii=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},si=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},ci=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ue=()=>(an(),Le||ii());let tr="",Vn=null,Jn,Yn;const Qn=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},S=()=>{if(an(),at)return at;const e=Qn("__PICHAMBER_API_BASE_URL__"),t=Qn("__PICHAMBER_LOCAL_ORIGIN__");if(Vn===Le&&Jn===e&&Yn===t)return tr;const o=Ue();return tr=ci(o,si())?"local":sn(o),Vn=Le,Jn=e,Yn=t,tr},jc=(e={})=>{if(an(),Le||at)return;const t=e.apiBaseUrl?.trim()||ii();t&&(Le=t,at=e.runtimeKey?.trim()||(ci(t,si())?"local":sn(t)))},Ft=e=>{const t=e.apiBaseUrl.trim(),o=Ue(),r=S(),n=e.runtimeKey?.trim()||sn(t);Hc(t,n);const a={apiBaseUrl:t,previousApiBaseUrl:o,runtimeKey:n,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ar,{detail:a})),Le=t,at=n,typeof window<"u"){const i=window;er(i,"__PICHAMBER_API_BASE_URL__",t),er(i,"__PICHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),er(i,"__PICHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Zr({apiBaseUrl:t,realtimeBaseUrl:t}),Ja(e.requestHeaders||null),Va(e.clientToken||null),e.relay?nc(e.relay):ac(),At(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(br,{detail:a}))},zc=e=>{if(typeof window>"u")return()=>{};const t=o=>{e(o.detail)};return window.addEventListener(Ar,t),()=>window.removeEventListener(Ar,t)},di=e=>{if(typeof window>"u")return()=>{};const t=o=>{e(o.detail)};return window.addEventListener(br,t),()=>window.removeEventListener(br,t)},$c=["local","remote",null],Kc=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function li(e){if(!e||typeof e!="object")return{valid:!1};const t=e,o=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,n=t.status;if(r!==null&&(typeof r!="string"||!$c.includes(r)))return{valid:!1};if(typeof n!="string"||!Kc.includes(n))return{valid:!1};if(r==="remote"||r==="local"){if(n==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok",...o}};if(n==="ok"&&r==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...o}};if(n==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...o}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...o}};if(n==="incompatible"||n==="wrong-service")return r!=="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,...o}};if(n==="missing")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...o}}}if(r===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...o}};if(n==="missing")return{valid:!1}}return{valid:!1}}function qc(){if(Gc()!=="valid")return null;const t=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__,o=li(t);return o.valid?o.outcome:null}function Gc(){if(typeof window>"u")return"not-injected";const e=window.__PICHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":li(e).valid?"valid":"malformed"}let wr=null;const iF=e=>{wr=e},ui=()=>wr||(typeof window>"u"?null:window.__PICHAMBER_RUNTIME_APIS__??null),Wc=()=>typeof window>"u"?null:window.__PICHAMBER_ELECTRON__??null,Bt=()=>typeof window>"u"?null:window.__PICHAMBER_DESKTOP__??null,Lo=()=>Wc()?.runtime==="electron",sF=()=>{if(typeof window>"u")return null;const e=window.__PICHAMBER_PLATFORM__;return typeof e=="string"?e:null},Y=()=>typeof Bt()?.invoke=="function",He=()=>Lo()&&Y(),H=async(e,t)=>{const o=Bt();return typeof o?.invoke!="function"?null:o.invoke(e,t??{})},Xn=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}}},or=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}}},Vc=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Mt=e=>{const t=Vc(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},se=()=>typeof window>"u"?!1:Lo(),_=()=>{if(typeof window>"u"||!se())return!1;if(S()==="local")return!0;const e=typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",t=or(e),o=or(Ue());if(!o&&t&&qc()?.target==="local")return!0;if(t&&o){if(t.origin===o.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),s=o.port||(o.protocol==="https:"?"443":"80");return t.protocol===o.protocol&&i===s&&Mt(t.hostname)&&Mt(o.hostname)}const r=or(window.location.origin);if(t&&r){if(t.origin===r.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),s=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&i===s&&Mt(t.hostname)&&Mt(r.hostname)}const n=Xn(e),a=Xn(window.location.origin)||window.location.origin;return n&&a&&n===a?!0:!!(r&&Mt(r.hostname))},cF=()=>{const t=ui()?.runtime?.platform;return t==="web"?!0:t!=="desktop"},dF=(e,t=se())=>e==="web"&&!t,lF=async()=>{if(!He()||!_())return null;try{const e=await H("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}},uF=async e=>{if(!He()||!_())return null;try{const t=await H("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}},fF=async()=>{if(!He()||!_())return null;try{const e=await H("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}},mF=async e=>{if(!He()||!_())return null;try{const t=await H("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}},gF=async()=>{if(!He()||!_())return null;try{const e=await H("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}},pF=async e=>{if(!He()||!_())return null;try{const t=await H("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}},hF=async()=>{if(!He()||!_())return null;try{const e=await H("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}},FF=async e=>{if(!He()||!_())return null;try{const t=await H("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}},Jc=()=>se()&&Y()&&_(),Yc=async()=>{if(typeof window<"u"){const e=window.__PICHAMBER_HOME__;if(e&&e.length>0)return e}return null},yF=async e=>{if(Jc())try{const t=await Bt()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},fi=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),bF=async e=>{if(Y()&&_())try{const t=await Bt()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!fi(t))return{success:!1,error:"File selection cancelled"};const o=typeof t.path=="string"?t.path:"";return o?{success:!0,path:o,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"}},AF=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!Y()||!_())return{success:!1,error:"Native file access not available"};try{const o=await Bt()?.grantFileAccess?.(t);if(!fi(o))return{success:!1,error:"File access was not granted"};const r=typeof o.path=="string"?o.path:"",n=typeof o.outsideFileGrant=="string"?o.outsideFileGrant:"";return!r||!n?{success:!1,error:"File access was not granted"}:{success:!0,path:r,outsideFileGrant:n}}catch(o){return console.warn("Failed to request existing file access",o),{success:!1,error:o instanceof Error?o.message:String(o)}}},EF=async e=>({success:!0}),wF=async e=>({success:!0}),BF=async()=>Y()?await H("desktop_check_for_updates"):null,CF=async e=>{if(!Y())return!1;const t=Bt();let o=null,r=0,n;try{return typeof e=="function"&&t?.listen&&(o=await t.listen("pichamber:update-progress",a=>{const i=a?.payload;if(!i||typeof i!="object")return;const s=i,c=typeof s.event=="string"?s.event:null,d=s.data&&typeof s.data=="object"?s.data:null;if(c==="Started"){r=0,n=typeof d?.contentLength=="number"?d.contentLength:void 0,e({downloaded:r,total:n});return}if(c==="Progress"){const l=d?.downloaded,u=d?.total;typeof l=="number"&&(r=l),typeof u=="number"&&(n=u),e({downloaded:r,total:n});return}c==="Finished"&&e({downloaded:r,total:n})})),await H("desktop_download_and_install_update"),!0}catch(a){throw a instanceof Error?a:new Error(String(a))}finally{if(o)try{const a=o();a instanceof Promise&&await a}catch{}}},Qc=async()=>{if(!Y())return!1;try{return await H("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},kF=async()=>Y()?Qc():!1,vF=async()=>{if(!Y()||!_())return null;try{const e=await H("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}},Xc=async(e,t)=>{if(!Y()||!_())return!1;const o=e?.trim();if(!o)return!1;try{return await H("desktop_open_path",{path:o,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},DF=async e=>{if(!Y()||!_())return!1;const t=e?.trim();if(!t)return!1;try{return await H("desktop_reveal_path",{path:t}),!0}catch{return Xc(t)}},SF=async(e,t)=>{if(!Y()||!_())return null;const o=e?.trim();if(!o)return null;try{const r=await H("desktop_save_markdown_file",{defaultFileName:o,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},MF=async(e,t,o)=>{if(!Y()||!_())return!1;const r=e?.trim(),n=t?.trim(),a=o?.trim();if(!r||!n||!a)return!1;try{return await H("desktop_open_in_app",{projectPath:r,appId:n,appName:a}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},TF=async(e,t,o)=>{if(!Y()||!_())return!1;const r=e?.trim(),n=t?.trim(),a=o?.trim();if(!r||!n||!a)return!1;try{return await H("desktop_open_file_in_app",{filePath:r,appId:n,appName:a}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},RF=async(e,t)=>{if(!Y()||!_())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const o=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];if(o.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const r=await H("desktop_get_installed_apps",{apps:o,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=r;return n.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(n.apps)?{apps:n.apps.filter(i=>i&&typeof i=="object").map(i=>{const s=i;return{name:typeof s.name=="string"?s.name:"",iconDataUrl:typeof s.iconDataUrl=="string"?s.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},yt=16384,So=globalThis,Zc=e=>{if(So.Buffer)return So.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let o="";for(let r=0;r<t.length;r+=32768)o+=String.fromCharCode(...t.slice(r,r+32768));return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},mi=e=>{try{if(So.Buffer)return So.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),o=atob(t),r=new Uint8Array(o.length);for(let n=0;n<o.length;n+=1)r[n]=o.charCodeAt(n);return new TextDecoder().decode(r)}catch{return null}},ed=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const o=new URL(t);return o.protocol!=="http:"&&o.protocol!=="https:"?null:(o.hash="",o.toString().replace(/\/+$/g,""))}catch{return null}},td=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const o=new URL(t);return o.protocol!=="ws:"&&o.protocol!=="wss:"?null:(o.hash="",o.toString())}catch{return null}},Zn=e=>typeof e=="string"&&e.length>0,od=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Zn(t.x)||!Zn(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},rd=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,nd=e=>{if(!e||typeof e!="object")return null;const t=e,o=rd(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=ed(t.url);return r?o===void 0?{type:t.type,url:r}:{type:t.type,url:r,priority:o}:null}if(t.type==="relay"){const r=td(t.relayUrl);if(!r)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const a=od(t.hostEncPubJwk);if(!a)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:r,serverId:n,hostEncPubJwk:a,...i?{grant:i}:{},...o===void 0?{}:{priority:o}}}return null},cn=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const o=typeof t.pairingId=="string"?t.pairingId.trim():"",r=typeof t.secret=="string"?t.secret.trim():"";if(!o||!r)return null;const n=Array.isArray(t.candidates)?t.candidates.map(nd).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 i=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,s=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:o,secret:r,...i?{label:i}:{},...s?{fingerprint:s}:{},...a?{expiresAt:a}:{},candidates:n}},PF=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}),IF=e=>{const t=cn(e);if(!t)throw new Error("Invalid pairing connection payload");const o=new URLSearchParams;return o.set("v","2"),o.set("p",Zc(JSON.stringify(t))),`pichamber://connect?${o.toString()}`},ad=e=>{const t=e.trim();if(!t||t.length>yt)return null;try{const o=new URL(t);if(o.protocol!=="pichamber:"||o.hostname!=="connect"||o.searchParams.get("v")!=="2")return null;const r=o.searchParams.get("p")||"";if(!r||r.length>yt)return null;const n=mi(r);return!n||n.length>yt?null:cn(JSON.parse(n))}catch{return null}},xF=e=>{const t=e.trim();if(!t||t.length>yt)return null;const o=t.indexOf("?");if(o===-1||!/^pichamber:\/\/connect\/?$/i.test(t.slice(0,o)))return null;let r=null,n=null;for(const i of t.slice(o+1).split("&")){const s=i.indexOf("=");if(s===-1)continue;const c=i.slice(0,s),d=i.slice(s+1);c==="v"?r=d:c==="p"&&(n=d)}if(r!=="2"||!n||n.length>yt)return null;const a=mi(n);if(!a||a.length>yt)return null;try{return cn(JSON.parse(a))}catch{return null}},Et=e=>typeof e=="object"&&e!==null,id=e=>e.trim().toLowerCase()==="authorization",sd=e=>{if(!Et(e))return;const t={};for(const[o,r]of Object.entries(e)){const n=o.trim(),a=typeof r=="string"?r.trim():"";!n||!a||/[\r\n:]/.test(n)||/[\r\n]/.test(a)||id(n)||(t[n]=a)}return Object.keys(t).length>0?t:void 0},gi=e=>`relay://${e}`,cd=e=>{if(!Et(e))return null;const t=J(e,"relayUrl")||J(e,"relay_url"),o=J(e,"serverId")||J(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!o||!Et(r)?null:{relayUrl:t,serverId:o,hostEncPubJwk:r}},dd=()=>{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"},ld=async(e,t)=>{const o=ad(e);if(!o)throw new Error("invalid-connect-link");const r=await Fi().catch(()=>""),n={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:dd(),...r?{dedupeKey:`desktop:${r}`}:{}})},a=async F=>{if(!F.ok)return null;const y=await F.json().catch(()=>null);return(typeof y?.clientToken=="string"?y.clientToken.trim():"")||null};let i=null;const s=[...o.candidates].sort((F,y)=>(F.type==="relay"?1:0)-(y.type==="relay"?1:0));for(const F of s){if(F.type==="relay"){const b=Wr({relayUrl:F.relayUrl,serverId:F.serverId,hostEncPubJwk:F.hostEncPubJwk,...F.grant?{grant:F.grant}:{}});try{const D=await a(await b.fetch("/api/client-auth/pairing/redeem",n));if(D){i={relay:{relayUrl:F.relayUrl,serverId:F.serverId,hostEncPubJwk:F.hostEncPubJwk},token:D};break}}catch{}finally{b.close()}continue}const y=W(F.url);if(y)try{const b=await a(await fetch(`${y}/api/client-auth/pairing/redeem`,n));if(b){i={directUrl:y,token:b};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=o.candidates.find(F=>F.type==="relay"),d=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),l=o.candidates.filter(F=>F.type!=="relay").map(F=>W(F.url)).find(F=>!!F),u=i.directUrl||l,f=u||(d?gi(d.serverId):null);if(!f)throw new Error("pairing-missing-transport");const m=t.find(F=>d?F.relay?.serverId===d.serverId:!F.relay&&W(F.apiUrl||F.url)===f),p=m?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),g={...m||{},id:p,label:o.label||m?.label||dn(f),url:f,apiUrl:u,clientToken:i.token,...d?{relay:d}:{}};return{hostId:p,hosts:m?t.map(F=>F.id===p?g:F):[g,...t]}},ud=/^(t|.*(?:token|auth|secret|api).*)$/i,W=e=>{const t=e.trim();if(!t)return null;try{const o=new URL(t);return o.protocol!=="http:"&&o.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},fd=e=>{const t=W(e);if(!t)return null;try{const o=new URL(t);if((o.pathname.replace(/\/+$/,"")||"/")==="/connect"&&o.searchParams.has("t"))return{persistedUrl:o.origin,redeemUrl:o.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},dn=e=>{const t=W(e);if(!t)return e;try{const o=new URL(t);(o.username||o.password)&&(o.username="",o.password="");const r=Array.from(new Set(Array.from(o.searchParams.keys())));for(const n of r)ud.test(n)&&o.searchParams.set(n,"[REDACTED]");return o.toString()}catch{return t}},_e=(e,t)=>{const o=W(e),r=W(t);if(!o||!r)return!1;try{const n=new URL(o),a=new URL(r);if(n.origin!==a.origin||a.search&&n.search!==a.search)return!1;const i=a.pathname.length>1?a.pathname.replace(/\/+$/,""):a.pathname,s=n.pathname.length>1?n.pathname.replace(/\/+$/,""):n.pathname;return i==="/"?!0:s===i||s.startsWith(`${i}/`)}catch{return!1}},J=(e,t)=>{const o=e[t];return typeof o=="string"?o:null},ea=(e,t)=>{const o=e[t];return typeof o=="number"&&Number.isFinite(o)?o:null},md=e=>{if(!Et(e))return null;const t=J(e,"id"),o=J(e,"label"),r=J(e,"url"),n=J(e,"apiUrl")||J(e,"api_url"),a=J(e,"clientToken")||J(e,"client_token"),i=sd(e.requestHeaders),s=cd(e.relay);return!t||!o||!r?null:{id:t,label:o,url:r,...n?{apiUrl:n}:{},...a?{clientToken:a}:{},...i?{requestHeaders:i}:{},...s?{relay:s}:{}}},Be=e=>W(e.apiUrl||e.url)||e.apiUrl||e.url,ct=()=>Y()?(e,t)=>H(e,t):null,ln=async()=>{const e=ct();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Et(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const o=t.hosts,r=Array.isArray(o)?o.map(md).filter(s=>!!s):[],n=J(t,"defaultHostId")||J(t,"default_host_id")||J(t,"defaultHostID"),a=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=J(t,"localOrigin")||J(t,"local_origin");return{hosts:r,defaultHostId:n,initialHostChoiceCompleted:a,localOrigin:i}},pi=async e=>{const t=ct();if(!t)return;const o={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(o.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:o})},hi=async()=>{const e=ct();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Fi=async()=>{const e=ct();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},gd=8e3,ta=async(e,t,o)=>{const r=new AbortController,n=window.setTimeout(()=>r.abort(),gd);try{return await e.fetch(t,{...o,signal:r.signal})}finally{window.clearTimeout(n)}},pd=async(e,t)=>{const o=Wr({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now();let n=!1;try{if(!(await ta(o,"/health")).ok)return{status:"unreachable",latencyMs:0};const i=new Headers({Accept:"application/json"});for(const[d,l]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&i.set(d,l);const s=t?.clientToken?.trim();s&&i.set("Authorization",`Bearer ${s}`);const c=await ta(o,"/auth/session",{headers:i});return c.status===401||c.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:c.ok?(n=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...n?{tunnel:o}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{n||o.close()}},un=async(e,t)=>{const o=ct();if(!o)return{status:"unreachable",latencyMs:0};const r=await o("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!Et(r))return{status:"unreachable",latencyMs:0};const n=r.status,a=n==="ok"||n==="auth"||n==="update-recommended"||n==="incompatible"||n==="wrong-service"||n==="unreachable"?n:"unreachable",i=ea(r,"latencyMs")??ea(r,"latency_ms")??0;return{status:a,latencyMs:i}},hd=async(e,t)=>{const o=ct();o&&await o("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Fd=async e=>{const t=ct();t&&await t("desktop_new_window_for_host",{hostId:e})},_F=Object.freeze(Object.defineProperty({__proto__:null,desktopHostProbe:un,desktopHostsGet:ln,desktopHostsSet:pi,desktopInstallIdGet:Fi,desktopLocalClientTokenGet:hi,desktopOpenNewWindowAtUrl:hd,desktopOpenNewWindowForHost:Fd,getDesktopHostApiUrl:Be,importDesktopHostPairing:ld,locationMatchesHost:_e,normalizeHostUrl:W,probeRelayDesktopHost:pd,redactSensitiveUrl:dn,relayHostDisplayUrl:gi,resolveDesktopHostUrl:fd},Symbol.toStringTag,{value:"Module"})),Oe="local",yd=e=>({id:Oe,label:"Local",url:e||fn()}),fn=()=>typeof window>"u"?"":window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,mn=e=>e.id===Oe?"local":`host:${e.id}`,oa="host:",yi=e=>{const t=e.runtimeKey.trim();if(t===Oe)return{kind:"local"};if(t.startsWith(oa)){const r=t.slice(oa.length),n=e.hosts.find(a=>a.id===r);if(n)return{kind:"host",host:n}}const o=e.hosts.find(r=>e.apiBaseUrl?_e(e.apiBaseUrl,Be(r)):!1);return o?{kind:"host",host:o}:e.localOrigin&&e.apiBaseUrl&&_e(e.apiBaseUrl,e.localOrigin)?{kind:"local"}:null},bd=e=>{const t=typeof window>"u"?"":window.location.href,o=e.find(l=>l.id===Oe)?.url||fn(),r=Ue(),n=W(o)||o,a=W(t)||t,i=S(),s=e.find(l=>l.relay&&mn(l)===i);if(s)return{id:s.id,label:s.label,url:s.url};if(r&&_e(r,o))return{id:Oe,label:"Local",url:n};const c=e.find(l=>r?_e(r,Be(l)):!1);if(c)return{id:c.id,label:c.label,url:W(Be(c))||Be(c)};if(t&&_e(t,o))return{id:Oe,label:"Local",url:n};const d=e.find(l=>t?_e(t,l.url):!1);return d?{id:d.id,label:d.label,url:W(d.url)||d.url}:t.startsWith("pichamber-ui://")?{id:Oe,label:"Local",url:n}:{id:"custom",label:dn(a||"Instance"),url:a}},OF=Object.freeze(Object.defineProperty({__proto__:null,LOCAL_HOST_ID:Oe,buildLocalDesktopHost:yd,getLocalDesktopOrigin:fn,resolveCurrentDesktopHost:bd,resolveDesktopHostIdentity:yi,runtimeKeyForDesktopHost:mn},Symbol.toStringTag,{value:"Module"})),Ad=5e3,Ed=1500;let rr=!1;const wd=async e=>{if(!Lo()||rr)return;const t=`host:${e}`;if(S()===t){rr=!0;try{const o=await ln().catch(()=>null),r=o?.hosts.find(u=>u.id===e);if(!o||!r?.relay)return;const n=r.apiUrl?W(r.apiUrl):null;if(n&&n.startsWith("https://"))return;const a=await h("/api/client-auth/connection/candidates").catch(()=>null);if(!a?.ok)return;const i=await a.json().catch(()=>null);if(!i||i.serverId!==r.relay.serverId)return;const s=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const u of s){if(!u||typeof u!="object")continue;const f=u;if(f.type!=="lan"||typeof f.url!="string")continue;const m=W(f.url);m&&!c.includes(m)&&c.push(m)}if(c.length===0)return;const d=n&&c.includes(n)?n:c[0];d!==n&&await pi({hosts:o.hosts.map(u=>u.id===e?{...u,apiUrl:d}:u),defaultHostId:o.defaultHostId,initialHostChoiceCompleted:o.initialHostChoiceCompleted}).catch(()=>{});const l=await un(d,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(l.status==="unreachable"||l.status==="wrong-service"||l.status==="incompatible"||S()!==t)return;Ft({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{rr=!1}}},Bd=e=>{typeof window>"u"||window.setTimeout(()=>{wd(e).catch(()=>{})},Ad)},Cd=(e,t)=>{if(t){const r=e.hosts.find(n=>n.id===t);return r?{kind:"host",host:r}:null}const o=yi({runtimeKey:S(),apiBaseUrl:Ue(),hosts:e.hosts,localOrigin:e.localOrigin});if(o)return o;if(e.defaultHostId&&e.defaultHostId!=="local"){const r=e.hosts.find(n=>n.id===e.defaultHostId);if(r)return{kind:"host",host:r}}return{kind:"local"}},kd=(e,t)=>{const o=e.clientToken||"";!o||No()===o||Ft({apiBaseUrl:Ue()||Be(e),clientToken:o,requestHeaders:e.requestHeaders||null,runtimeKey:t,relay:ja()?e.relay:void 0})},vd=async e=>{if(!Lo())return;const t=await ln().catch(()=>null);if(!t)return;const o=Cd(t,e);if(!o)return;if(o.kind==="local"){const u=await hi();if(!u)return;const f=t.localOrigin||Ue();if(!f||S()==="local"&&No()===u)return;Ft({apiBaseUrl:f,clientToken:u,runtimeKey:"local"});return}const r=o.host,n=mn(r),a=u=>{Ft({apiBaseUrl:u,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:n})},i=()=>{Ft({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:n,relay:r.relay??void 0}),Bd(r.id)};if(S()===n){const u=r.apiUrl?W(Be(r)):"";if(!!(u&&_e(Ue(),u))||!r.relay){kd(r,n);return}i();return}if(!r.relay){const u=Be(r);if(!u)return;a(u);return}const s=r.apiUrl?W(Be(r)):null;if(!s){i();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",d=un(s,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),l=await Promise.race([d,new Promise(u=>setTimeout(()=>u(null),Ed))]);if(l){if(c(l)){a(s);return}i();return}i(),d.then(u=>{c(u)&&S()===n&&a(s)})},Dd=64*1024,Sd=(e,t,o)=>{let r=0;return new ReadableStream({async pull(n){if(t?.aborted){n.error(new DOMException("The operation was aborted.","AbortError"));return}if(r>=e.size){n.close();return}const a=Math.min(r+Dd,e.size),i=new Uint8Array(await e.slice(r,a).arrayBuffer());r=a,n.enqueue(i),o?.({loaded:r,total:e.size})}})},Md=async(e,t,o)=>{const r=!!Jt();r||o.onProgress?.({loaded:0,total:t.size});const n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/octet-stream","X-PiChamber-Filename":encodeURIComponent(o.filename),"X-PiChamber-Mime":o.mime},body:r?Sd(t,o.signal,o.onProgress):t,signal:o.signal,...r?{duplex:"half"}:{}},a=await h(e,n);return!r&&a.ok&&o.onProgress?.({loaded:t.size,total:t.size}),a},mt=1,Td=["session.snapshot","session.lifecycle","session.updated","session.tree.updated","assistant.message.start","assistant.message.delta","assistant.message.end","assistant.thinking.delta","session.tool.start","session.tool.update","session.tool.end","session.queue","session.model","session.thinking","session.compaction","session.error","session.interrupted","extension.entry","extension.message","extension.notify","extension.catalog","extension.editor","extension.title","extension.status","extension.widget","extension.dialog","extension.dialog.dismiss","extension.ui","extension.app","extension.error"],Br=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.protocolVersion===mt&&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))&&Td.includes(t.name)},bi=(e,t)=>{const o=Jt();return o?o.openWebSocket(Ks(e),t):Ls(new WebSocket(e))},Uo=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",NF=()=>{if(typeof window>"u"||!Uo()||Rd()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Rd=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return se()?"desktop":"web"},LF=()=>{if(typeof navigator>"u")return!1;const e=navigator.platform||"",t=navigator.userAgent||"";return/Win/i.test(e)&&/ARM|aarch64/i.test(t)},Pd=240;let Cr=[],nr=!1;const pt=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,Pd)||void 0,Id=e=>{if(!e||typeof e!="object")return{detail:pt(e)};const t=e;return{...typeof t.code=="string"?{code:pt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.message!==void 0?{detail:pt(t.message)}:typeof t.name=="string"?{detail:pt(t.name)}:{}}},ne=(e,t={})=>{if(!Uo())return;const o={at:new Date().toISOString(),category:e.trim().slice(0,80)||"unknown",...t.code?{code:pt(t.code)}:{},...typeof t.status=="number"&&Number.isFinite(t.status)?{status:t.status}:{},...t.detail!==void 0?{detail:pt(t.detail)}:{}};Cr=[...Cr,o].slice(-300)},xd=(e,t)=>{ne(e,Id(t))},_d=()=>JSON.stringify({format:"pichamber-mobile-diagnostics-v1",generatedAt:new Date().toISOString(),platform:typeof navigator>"u"?"unknown":navigator.userAgent,entries:Cr},null,2),UF=async()=>{const e=_d();if(typeof navigator<"u"&&typeof navigator.share=="function")return await navigator.share({title:"PiChamber mobile diagnostics",text:e}),"shared";if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),"copied";if(typeof document<"u"){const t=new Blob([e],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");return r.href=o,r.download="pichamber-mobile-diagnostics.json",r.click(),window.setTimeout(()=>URL.revokeObjectURL(o),0),"downloaded"}throw new Error("No mobile export method is available")},HF=()=>{if(!Uo()||typeof window>"u"||nr)return()=>{};nr=!0;const e=o=>{ne("window-error",{code:o.error?.name,detail:o.message})},t=o=>{xd("unhandled-rejection",o.reason)};return window.addEventListener("error",e),window.addEventListener("unhandledrejection",t),()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",t),nr=!1}},Od=3e4,Nd=250,Ld=5e3,Ud=6e4,Hd=8,jd=2e3,Ai=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),t},ra=(e,t,o)=>{const r=ge(),n=Ai(t);return e==="ws"?r.websocket("/api/pi/events",n,o):r.sse("/api/pi/events",n)},zd=()=>"/api/pi/runtime",kr=()=>Uo()&&!ja()&&typeof EventSource<"u",$d=async(e,t)=>{let o;try{o=await h(zd(),e?{signal:e}:{})}catch(a){return ne("runtime-health",{code:a instanceof DOMException&&a.name==="AbortError"?"timeout":"unreachable"}),{state:"unavailable",protocolVersion:mt,capabilities:[],error:{code:a instanceof DOMException&&a.name==="AbortError"?"DAEMON_TIMEOUT":"DAEMON_UNAVAILABLE"}}}if(t&&t!==S())return{state:"unavailable",protocolVersion:mt,capabilities:[],error:{code:"DAEMON_UNAVAILABLE",message:"Runtime changed during request"}};if(!o.ok)return ne("runtime-health",{status:o.status,code:o.status===401||o.status===403?"auth":"http-error"}),{state:"unavailable",protocolVersion:mt,capabilities:[],error:{code:o.status===401||o.status===403?"DAEMON_AUTH_FAILED":"DAEMON_UNAVAILABLE"}};const r=await o.json().catch(()=>null);if(!r||typeof r!="object")return{state:"unavailable",protocolVersion:mt,capabilities:[],error:{code:"DAEMON_PROTOCOL_MISMATCH"}};const n=typeof r.error?.code=="string"?r.error.code:void 0;return{state:r.state==="ready"?"ready":"unavailable",protocolVersion:typeof r.protocolVersion=="number"?r.protocolVersion:mt,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter(a=>typeof a=="string"):[],...n?{error:{code:n,...typeof r.error?.message=="string"?{message:r.error.message}:{}}}:{}}},Kd=(e,t,o,r,n,a)=>{if(kr()){const c=new EventSource(ge().sse("/api/pi/events",e));let d=!1;const l=()=>{d||r()},u=()=>{d||(d=!0,c.removeEventListener("heartbeat",l),c.close(),t.removeEventListener("abort",u))},f=m=>{try{const p=JSON.parse(m);Br(p)&&n(p)}catch{ne("stream-frame",{code:"bad-sse-frame"})}};return c.onopen=()=>{d||o()},c.onmessage=m=>{d||(r(),typeof m.data=="string"&&m.data.trim()&&f(m.data))},c.onerror=()=>{d||(u(),ne("stream-disconnect",{code:"sse-error"}),a("sse-error"))},c.addEventListener("heartbeat",l),t.aborted?u():t.addEventListener("abort",u,{once:!0}),u}const i=new AbortController,s=()=>i.abort();return t.aborted?i.abort():t.addEventListener("abort",s,{once:!0}),h("/api/pi/events",{headers:{Accept:"text/event-stream"},query:e,signal:i.signal}).then(async c=>{if(!c.ok||!c.body){ne("stream-connect",{status:c.status,code:c.body?"http-error":"missing-stream-body"}),a(`sse-status-${c.status}`);return}o();const d=c.body.getReader(),l=new TextDecoder;let u="",f=[];const m=()=>{if(f.length===0)return;const p=f.join(`
2
2
  `).trim();if(f=[],!!p)try{const g=JSON.parse(p);Br(g)&&n(g)}catch{}};for(;;){const{value:p,done:g}=await d.read();if(g){m(),a("sse-eof");return}r(),u+=l.decode(p,{stream:!0});let F=u.indexOf(`
3
3
  `);for(;F!==-1;){const y=u.slice(0,F).replace(/\r$/,"");u=u.slice(F+1),y.length===0?m():y.startsWith("data:")&&f.push(y.slice(5).replace(/^ /,"")),F=u.indexOf(`
4
- `)}}}).catch(c=>{if(i.signal.aborted)return;const d=c instanceof Error?c.message.slice(0,80):"fetch-failed";ne("stream-connect",{code:"fetch-failed",detail:d}),a(`sse-error:${d}`)}).finally(()=>t.removeEventListener("abort",s)),s},qd=(e,t,o,r,n,a)=>{const i=bi(e);let s=!1,c=!1,d=null;const l=()=>{if(!s){s=!0,d&&clearTimeout(d),d=null;try{i.close()}catch{}}};d=setTimeout(()=>{c||s||(n("ws-ready-timeout"),l())},a);const u=()=>l();return t.aborted?l():t.addEventListener("abort",u,{once:!0}),i.onopen=()=>{c=!0,d&&clearTimeout(d),d=null,o()},i.onmessage=f=>{const m=typeof f.data=="string"?f.data:void 0;if(m)try{const p=JSON.parse(m);Br(p)&&r(p)}catch{}},i.onerror=()=>{s||n("ws-error")},i.onclose=f=>{t.removeEventListener("abort",u),s||n(`ws-close-${f?.code??0}`)},l},Gd=()=>typeof document>"u"||document.visibilityState==="visible",Wd=()=>typeof navigator>"u"||navigator.onLine!==!1,jF=(e,t={})=>{const o=new AbortController,r=t.signal;r&&(r.aborted?o.abort():r.addEventListener("abort",()=>o.abort(),{once:!0}));const n=o.signal,a=t.runtimeKey,i=()=>!a||a===S();let s=!1,c=0,d=typeof t.fromSequence=="number"&&Number.isFinite(t.fromSequence)?Math.max(0,Math.floor(t.fromSequence)):0,l=t.transport==="ws"?"ws":"sse",u=null,f=null,m=null,p=0,g=!1;const F=()=>{u&&clearTimeout(u),f&&clearTimeout(f),u=null,f=null},y=()=>{p+=1,m?.(),m=null,f&&clearTimeout(f),f=null},b=v=>{f&&clearTimeout(f),f=setTimeout(()=>{v===p&&L("heartbeat-timeout",v)},t.heartbeatTimeoutMs??Od)},D=v=>{s||n.aborted||v!==p||b(v)},C=v=>{if(s||n.aborted||v!==p)return;const z=!g;c=0,g=!0,b(v),z&&(ne("stream-ready",{code:l}),e.onReconnect?.())},I=()=>{const v=Gd()&&Wd()?Ld:Ud,z=Math.min(Hd,c),kt=Math.min(v,Nd*2**z);return c===0&&t.reconnectDelayMs!==void 0?Math.max(0,t.reconnectDelayMs):kt+Math.floor(Math.random()*100)},V=(v,z=!0)=>{s||n.aborted||u||(ne("stream-reconnect",{code:v}),z&&e.onDisconnect?.(v),u=setTimeout(()=>{u=null,c+=1,ve()},I()))},L=(v,z)=>{if(!(s||n.aborted||z!==p)){if(y(),!g&&l==="ws"&&t.transport!=="ws"&&(l="sse",e.onTransportSwitch?.()),g=!1,v==="runtime-change"){e.onDisconnect?.(v);return}V(v)}},Ct=(v,z)=>{if(!(s||n.aborted||z!==p)){if(!i()){L("runtime-change",z);return}v.sequence>d&&(d=v.sequence),C(z),e.onEvent(v)}},ve=async()=>{if(s||n.aborted)return;if(!i()){e.onDisconnect?.("runtime-change");return}const v=p+1;p=v;let z;if(l==="ws")try{z=await At()}catch{if(v!==p||s||n.aborted)return;if(t.transport!=="ws"){l="sse",e.onTransportSwitch?.(),y(),ve();return}ne("stream-auth",{code:"url-token-unavailable"}),L("ws-auth-token-unavailable",v);return}if(v!==p||s||n.aborted)return;if(!i()){L("runtime-change",v);return}if(l==="sse"&&kr()){try{await At()}catch{if(v!==p||s||n.aborted)return;ne("stream-auth",{code:"url-token-unavailable"}),L("sse-auth-token-unavailable",v);return}if(v!==p||s||n.aborted||!i())return}const kt=ra(l,{fromSequence:d,...t.sessionId?{sessionId:t.sessionId}:{}},z),ze=()=>D(v),to=$e=>Ct($e,v),oo=$e=>L($e,v);m=l==="ws"?qd(kt,n,ze,to,oo,jd):Kd(Ai({fromSequence:d,...t.sessionId?{sessionId:t.sessionId}:{}}),n,ze,()=>C(v),to,oo)},lt=()=>{!kr()||s||n.aborted||(F(),y(),g=!1,V("system-resume",!1))};return typeof window<"u"&&window.addEventListener("pichamber:system-resume",lt),ve(),{dispose:()=>{s||(s=!0,typeof window<"u"&&window.removeEventListener("pichamber:system-resume",lt),F(),y(),o.abort())},reconnect:(v="manual")=>{s||n.aborted||(F(),y(),V(v))},get eventsUrl(){return ra(l,{fromSequence:d,...t.sessionId?{sessionId:t.sessionId}:{}})}}},Vd=3e4,ar=1,Jd=300,Yd=e=>new Promise(t=>setTimeout(t,e)),k=async(e,t)=>{const o=t.runtimeKey;if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");const r=t.query?`?${new URLSearchParams(Object.entries(t.query).map(([i,s])=>[i,String(s)])).toString()}`:"",n={Accept:"application/json"};t.body!==void 0&&(n["Content-Type"]="application/json");let a;for(let i=0;i<=ar;i+=1){if(i>0){if(t.signal?.aborted)break;if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");if(await Yd(Jd),t.signal?.aborted)break;if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request")}const s=new AbortController,c=setTimeout(()=>s.abort(),Vd),d=t.signal,l=()=>s.abort();d&&(d.aborted?s.abort():d.addEventListener("abort",l,{once:!0}));try{const u=await h(e+r,{method:t.method,headers:n,body:t.body===void 0?void 0:JSON.stringify(t.body),signal:s.signal});if(!u.ok){const p=(await u.json().catch(()=>null))?.error??{code:"DAEMON_REQUEST_FAILED"};if(u.status===503&&(p.code==="DAEMON_UNAVAILABLE"||p.code==="DAEMON_TIMEOUT")&&i<ar&&!d?.aborted){a=new te(p.code,p.message,u.status);continue}throw new te(p.code,p.message,u.status)}if(u.status===204){if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");return}const f=await u.json();if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");return f}catch(u){if(a=u,u instanceof te||d?.aborted||u instanceof DOMException&&u.name==="AbortError")throw u;if(i<ar&&!d?.aborted)continue;throw u}finally{clearTimeout(c),d&&d.removeEventListener("abort",l)}}throw a};class te extends Error{code;status;constructor(t,o,r){super(o??`Pi request failed: ${t}`),this.name="PiRequestError",this.code=t,r!==void 0&&(this.status=r)}}const B=e=>{if(e?.runtimeKey&&e.runtimeKey!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request")};class Qd{currentDirectory;setDirectory(t){this.currentDirectory=t}getDirectory(){return this.currentDirectory}async health(t){B(t);const o=await $d(void 0,t?.runtimeKey);return o.state==="ready"?{protocolVersion:o.protocolVersion,state:"ready",capabilities:o.capabilities}:{protocolVersion:o.protocolVersion,state:"unavailable",capabilities:o.capabilities,...o.error?{error:o.error}:{}}}async listProjects(t){return B(t),k("/api/pi/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async selectProject(t,o){return B(o),k("/api/pi/projects/select",{method:"POST",body:{directory:t},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listSessions(t){B(t);const o=t?.directory??this.currentDirectory;return k("/api/pi/sessions",{method:"GET",...o?{query:{directory:o}}:{},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async createSession(t,o){return B(o),k("/api/pi/sessions",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getSession(t,o){B(o);const r=o?.directory??this.currentDirectory;return k(`/api/pi/sessions/${encodeURIComponent(t)}`,{method:"GET",...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async renameSession(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"PATCH",body:{sessionId:t.sessionId,title:t.title},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async deleteSession(t,o){B(o);try{return await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"DELETE",...o?.directory?{query:{directory:o.directory}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}}),!0}catch(r){if(r instanceof te&&r.status===404)return!0;throw r}}async archiveSession(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/archive`,{method:"POST",body:{sessionId:t.sessionId,archived:t.archived,...o?.directory?{directory:o.directory}:{}},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getSessionTree(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t)}/tree`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async navigateSession(t,o,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t)}/navigate`,{method:"POST",body:{messageId:o},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async forkSession(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/fork`,{method:"POST",body:{sessionId:t.sessionId,...t.messageId?{messageId:t.messageId}:{}},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async cloneSession(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/clone`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async sendPrompt(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/prompt`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async sendSteer(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/steer`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async sendFollowUp(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/follow-up`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async abortSession(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/abort`,{method:"POST",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setSessionModel(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/model`,{method:"POST",body:{sessionId:t.sessionId,model:t.model},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setSessionThinking(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/thinking`,{method:"POST",body:{sessionId:t.sessionId,thinking:t.thinking},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async compactSession(t,o){if(B(o),(await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})).accepted!==!0)throw new te("DAEMON_PROTOCOL_MISMATCH")}async listProviders(t){return B(t),k("/api/pi/providers",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async refreshProviders(t){return B(t),k("/api/pi/providers/refresh",{method:"POST",...t?.directory?{body:{directory:t.directory}}:{body:void 0},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getProviderStatus(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t)}/status`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async loginProvider(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/login`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getProviderLogin(t,o,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(o)}`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async respondProviderLogin(t,o,r,n){return B(n),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(o)}/respond`,{method:"POST",body:{value:r},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async logoutProvider(t,o){B(o),await k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/logout`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getProviderConfig(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t)}/config`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setProviderModels(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"PUT",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getSettings(t){return B(t),k("/api/pi/settings",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async setPiSettings(t,o){return B(o),k("/api/pi/settings/pi",{method:"PUT",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setPiChamberDefaults(t,o){return B(o),k("/api/pi/settings/defaults",{method:"PUT",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listResources(t,o){const r=typeof t=="string"?o:t,n=typeof t=="string"?t:void 0;return B(r),k("/api/pi/resources",{method:"GET",...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listCommands(t,o){return B(o),k("/api/pi/commands",{method:"GET",...t?{query:{directory:t}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listSnippets(t,o){return B(o),k("/api/pi/snippets",{method:"GET",...t?{query:{directory:t}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async createSnippet(t,o){return B(o),k("/api/pi/snippets",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateSnippet(t,o,r,n){return B(n),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"PUT",body:o,...r?{query:{directory:r}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deleteSnippet(t,o,r){return B(r),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"DELETE",...o?{query:{directory:o}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateResource(t,o){B(o);const r=t.directory??o?.directory;return k(`/api/pi/resources/${encodeURIComponent(t.resourceId)}`,{method:"PUT",body:t,...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async createPromptTemplate(t,o,r){const n=o??t.directory??r?.directory;return B(r),k("/api/pi/resources/prompts",{method:"POST",body:t,...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updatePromptTemplate(t,o,r,n){B(n);const a=r??o.directory??n?.directory;return k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"PUT",body:o,...a?{query:{directory:a}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deletePromptTemplate(t,o,r){B(r);const n=o??r?.directory;return k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"DELETE",...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async createAttachment(t,o){return B(o),(await k("/api/pi/attachments",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})).attachment}async uploadAttachment(t,o,r){B(r);const n=await Md("/api/pi/attachments",t,o);if(!n.ok){const s=(await n.json().catch(()=>null))?.error??{code:"ATTACHMENT_FAILED"};throw new te(s.code,s.message,n.status)}const a=await n.json();return B(r),a.attachment}async deleteAttachment(t,o){B(o),await k(`/api/pi/attachments/${encodeURIComponent(t)}`,{method:"DELETE",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listExtensions(t,o){return B(o),k("/api/pi/extensions",{method:"GET",...t?{query:{directory:t}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async respondToExtensionDialog(t,o){B(o),await k("/api/pi/extensions/respond",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}}const Ze=new Qd;async function Xd(){try{const e=await h("/api/fs/home",{method:"GET",headers:{Accept:"application/json"}});if(e.ok){const t=await e.json();if(typeof t.home=="string"&&t.home.trim().length>0)return t.home.trim()}}catch{}return null}async function zF(e,t){if(!e||e.trim().length===0)return[];const o={path:e},r=ge().api("/api/fs/list",o),n=await h(r);if(!n.ok)return[];const a=await n.json();return Array.isArray(a.entries)?a.entries:[]}async function Zd(e,t){const o=t?.directory||"";if(!o)return[];const r={directory:o,query:e};t?.limit&&(r.limit=t.limit),t?.includeHidden&&(r.includeHidden=!0),t?.respectGitignore!==void 0&&(r.respectGitignore=t.respectGitignore),t?.type&&(r.type=t.type);const n=ge().api("/api/fs/find",r),a=await h(n);if(!a.ok)return[];const i=await a.json();return Array.isArray(i.files)?i.files:[]}async function $F(e=""){try{const t=await h("/api/fs/pick-directory",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({path:e||void 0})}),o=await t.json().catch(()=>null);return o?.cancelled===!0?{status:"cancelled"}:t.status===501?{status:"unavailable",error:typeof o?.error=="string"?o.error:"Folder picker is not available."}:t.ok?typeof o?.path=="string"&&o.path.trim()?{status:"picked",path:o.path.trim()}:{status:"failed",error:"Failed to select directory."}:{status:"failed",error:typeof o?.error=="string"?o.error:"Failed to select directory."}}catch(t){return{status:"failed",error:t instanceof Error?t.message:"Failed to select directory."}}}const KF={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."}},el=e=>typeof e=="string"&&(e==="explore"||e==="plan"||e==="review"||e==="find-bugs"||e==="write-tests"),qF=[{type:"text",key:"explore"},{type:"text",key:"plan"},{type:"text",key:"review"},{type:"text",key:"find-bugs"},{type:"text",key:"write-tests"}],GF="book-open",tl=/^[^\s/]+$/,na=e=>e.type==="prompt"?`prompt:${e.name}`:`text:${e.key}`,WF=(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,VF=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Mo=e=>{if(!Array.isArray(e))return[];const t=[],o=new Set;for(const r of e){if(!r||typeof r!="object")continue;const n=r;if(n.type==="text"){if(!el(n.key))continue;const d={type:"text",key:n.key},l=na(d);if(o.has(l))continue;o.add(l),t.push(d);continue}if(n.type!=="prompt")continue;const a=typeof n.name=="string"?n.name.trim():"";if(!a||!tl.test(a))continue;const i=n.scope==="global"||n.scope==="project"?n.scope:void 0,s=i?{type:"prompt",name:a,scope:i}:{type:"prompt",name:a},c=na(s);o.has(c)||(o.add(c),t.push(s))}return t},ol=e=>{let t,o=-1;for(const r of e){const a=(r.location==="project"?2:r.location==="global"?1:0)+(r.editable?.5:0);a>o&&(t=r,o=a)}return t},JF=e=>{const t=new Map;for(const r of e){const n=t.get(r.name)??[];n.push(r),t.set(r.name,n)}const o=new Map;for(const[r,n]of t){const a=ol(n);a&&o.set(r,a)}return o},YF=(e,t)=>{const o=new Set,r=i=>i.filter(s=>{const c=s.insertText.trim();return o.has(c)?!1:(o.add(c),!0)}),n=r(e),a=r(t);return{project:n,global:a}},rl={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem",settingsPageTitle:"1.125rem"};function aa(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const so={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)"}}},ir={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...so.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:ir.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...so.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ir.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...so.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ir.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...so.tool.inline})},nl=[{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'}],al=[{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'}],Ei=e=>Object.fromEntries(e.map(t=>[t.id,t])),il=Ei(nl),sl=Ei(al),cl="system",dl="system-mono",wi=e=>typeof e=="string"&&e in il,Bi=e=>typeof e=="string"&&e in sl,sr="pichamber.pwaName",vr="pichamber.mobileKeyboardMode",QF="pichamber.pwaRecentSessions",ll=["native","resize-content"];function ul(e,t="resize-content"){return typeof e=="string"&&ll.includes(e)?e:t}const fl=64;function Ci(e,t){if(typeof e!="string")return t;const o=e.trim().replace(/\s+/g," ");return o?o.slice(0,fl):t}const XF=()=>!0;function gn(e,t="resize-content"){return ul(e,t)??void 0}const ml=()=>{if(typeof window>"u")return"resize-content";try{return gn(localStorage.getItem(vr))}catch{return"resize-content"}},gl=e=>{const t=gn(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(vr):localStorage.setItem(vr,t)}catch{}return t},$=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),o=t.startsWith("//");let r=t.replace(/\/+$/g,"").replace(/\/+/g,"/");return o&&!r.startsWith("//")&&(r=`/${r}`),r||(t.startsWith("/")?"/":"")},le=20,pl=8,ia=4096,hl=2160*60*6e4,R=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),o=t.startsWith("//");let r=t.replace(/\/+/g,"/");o&&!r.startsWith("//")&&(r=`/${r}`);const n=r==="/",a=/^[A-Za-z]:\/$/.test(r);return!n&&!a&&(r=r.replace(/\/+$/,"")),r},Te=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Pe=(e,t)=>{const o=R(t),r=R(e);if(!o||!r)return!1;const n=Te(o),a=Te(r);return a===n||a.startsWith(`${n}/`)},Tt=e=>{if(!e||typeof e!="object")return{};const t=e,o={};for(const[r,n]of Object.entries(t)){const a=R(r);if(!a||!n||typeof n!="object")continue;const i=n,s=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(m=>typeof m=="string").map(m=>R(m)).filter(m=>m.length<=ia&&Pe(m,a)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(m=>typeof m=="string").map(m=>R(m)).filter(m=>m.length<=ia&&Pe(m,a)))).slice(-500):[],d=typeof i.selectedPath=="string"?R(i.selectedPath):null,l=d&&Pe(d,a)?d:s[0]??null,u=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-u>hl)continue;const f=o[a];if(f){const m=Array.from(new Set([...f.openPaths,...s])),p=Array.from(new Set([...f.expandedPaths,...c])),g=f.selectedPath??l??m[0]??null;o[a]={openPaths:m,selectedPath:g,expandedPaths:p,touchedAt:Math.max(f.touchedAt,u)};continue}o[a]={openPaths:s,selectedPath:l,expandedPaths:c,touchedAt:u}}return ue(o,le)},ue=(e,t)=>{const o=Object.entries(e);if(o.length<=t)return e;o.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const r={};for(const[n,a]of o.slice(0,t))r[n]=a;return r},ut=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},Fl=Wt()(Vt(qr((e,t)=>({byRoot:{},activeRuntimeKey:S(),runtimeSnapshots:{},resetForRuntimeSwitch:o=>{e(r=>{const n={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Tt(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:o,runtimeSnapshots:n,byRoot:Tt(n[o]?.byRoot)}})},addOpenPath:(o,r,n)=>{const a=R((o||"").trim()),i=R((r||"").trim());!a||!i||!n?.allowOutsideRoot&&!Pe(i,a)||e(s=>{const c=s.byRoot[a],d=ut(c),l=d.openPaths.includes(i),u=l?d.openPaths:[...d.openPaths,i],f=d.selectedPath??i;if(c&&l&&c.selectedPath===f)return s;const m={...s.byRoot,[a]:{...d,openPaths:u,selectedPath:f}};return{byRoot:ue(m,le)}})},removeOpenPath:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||e(i=>{const s=i.byRoot[n];if(!s)return i;const c=Te(a),d=p=>Te(p)===c,l=s.selectedPath?d(s.selectedPath):!1;if(!s.openPaths.some(d)&&!l)return i;const u=s.openPaths.filter(p=>!d(p)),f=l?u[0]??null:s.selectedPath,m={...i.byRoot,[n]:{...s,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:ue(m,le)}})},removeOpenPathsByPrefix:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||e(i=>{const s=i.byRoot[n];if(!s)return i;const c=Te(a),d=c.endsWith("/")?c:`${c}/`,l=p=>{const g=Te(p);return g===c||g.startsWith(d)},u=s.openPaths.filter(p=>!l(p));if(u.length===s.openPaths.length)return i;const f=s.selectedPath&&l(s.selectedPath)?u[0]??null:s.selectedPath,m={...i.byRoot,[n]:{...s,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:ue(m,le)}})},removeExpandedPathsByPrefix:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||e(i=>{const s=i.byRoot[n];if(!s)return i;const c=Te(a),d=c.endsWith("/")?c:`${c}/`,l=s.expandedPaths.filter(f=>{const m=Te(f);return m!==c&&!m.startsWith(d)});if(l.length===s.expandedPaths.length)return i;const u={...i.byRoot,[n]:{...s,expandedPaths:l,touchedAt:Date.now()}};return{byRoot:ue(u,le)}})},setSelectedPath:(o,r,n)=>{const a=R((o||"").trim()),i=r?R(r.trim()):null;!a||i&&!n?.allowOutsideRoot&&!Pe(i,a)||e(s=>{const c=s.byRoot[a],d=ut(c),l=i&&!d.openPaths.includes(i)?[...d.openPaths,i]:d.openPaths;if(c&&c.selectedPath===i&&l===c.openPaths)return s;const u={...s.byRoot,[a]:{...d,openPaths:l,selectedPath:i}};return{byRoot:ue(u,le)}})},ensureSelectedPath:o=>{const r=R((o||"").trim());if(!r)return;const n=t().byRoot[r];if(!n||n.selectedPath)return;const a=n.openPaths[0]??null;a&&t().setSelectedPath(r,a)},toggleExpandedPath:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||!Pe(a,n)||e(i=>{const s=i.byRoot[n],c=ut(s),l=c.expandedPaths.includes(a)?c.expandedPaths.filter(f=>f!==a):[...c.expandedPaths,a];if(s&&s.expandedPaths===l&&s.selectedPath===c.selectedPath&&s.openPaths===c.openPaths)return i;const u={...i.byRoot,[n]:{...c,expandedPaths:l}};return{byRoot:ue(u,le)}})},collapseAllExpandedPaths:o=>{const r=R((o||"").trim());r&&e(n=>{const a=n.byRoot[r];if(!a||a.expandedPaths.length===0)return n;const i={...n.byRoot,[r]:{...ut(a),expandedPaths:[]}};return{byRoot:ue(i,le)}})},expandPath:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||!Pe(a,n)||e(i=>{const s=i.byRoot[n],c=ut(s);if(c.expandedPaths.includes(a)&&s)return i;const l={...i.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,a]}};return{byRoot:ue(l,le)}})},expandPaths:(o,r)=>{const n=R((o||"").trim());if(!n||!r||r.length===0)return;const a=r.map(i=>R((i||"").trim())).filter(i=>i&&Pe(i,n));a.length!==0&&e(i=>{const s=i.byRoot[n],c=ut(s),d=new Set(c.expandedPaths),l=a.filter(f=>!d.has(f));if(l.length===0)return i;const u={...i.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,...l]}};return{byRoot:ue(u,le)}})}}),{name:"files-view-tabs-store",version:3,storage:rn(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:S(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Tt(e.byRoot),updatedAt:Date.now()}},o=Object.fromEntries(Object.entries(t).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,pl).map(([r,n])=>[r,{byRoot:Tt(n.byRoot),updatedAt:n.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:o}},merge:(e,t)=>{const o=e&&typeof e=="object"?e:{},r=o.runtimeSnapshots&&typeof o.runtimeSnapshots=="object"?o.runtimeSnapshots:{},n=S();return{...t,activeRuntimeKey:n,runtimeSnapshots:r,byRoot:Tt(r[n]?.byRoot)}}}),{name:"files-view-tabs-store"})),yl=380,bl=380,Al=1400,ki=12,sa=120,El=["git","file","diff","context","terminal","browser","preview"],ZF=$,yo=e=>Number.isFinite(e)?Math.min(Al,Math.max(bl,Math.round(e))):yl,wl=e=>{if(typeof e.width=="number"&&Number.isFinite(e.width))return yo(e.width);if(!e.widthByMode||typeof e.widthByMode!="object")return;const t=e.widthByMode;for(const o of El){const r=t[o];if(typeof r=="number"&&Number.isFinite(r))return yo(r)}for(const o of Object.values(t))if(typeof o=="number"&&Number.isFinite(o))return yo(o)},To=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Ro=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>sa?t.slice(0,sa):t:null},pn=e=>e==="all"||e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,Bl=(e,t)=>(e==="file"||e==="preview")&&t||e,vi=(e,t,o)=>{if(e==="diff")return e;if(typeof o=="string"){const r=o.trim();if(r)return r}return Bl(e,t)},Di=(e,t)=>t===e?e:`${e}:${t}`,hn=e=>{const t=To(e.targetPath),o=vi(e.mode,t,e.dedupeKey);return{id:Di(e.mode,o),mode:e.mode,targetPath:t,dedupeKey:o,label:Ro(e.label),sessionTitleFallback:Ro(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:pn(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Si=(e,t,o)=>{if(e.length<=t)return e;const n=[...e].sort((s,c)=>s.touchedAt-c.touchedAt).filter(s=>s.id!==o),a=e.length-t;if(a<=0||n.length===0)return e.slice(-t);const i=new Set(n.slice(0,a).map(s=>s.id));return e.filter(s=>!i.has(s.id))},Mi=e=>{if(!Array.isArray(e))return[];const t=[],o=new Set;for(const r of e){if(!r||typeof r!="object")continue;const n=r;if(n.mode!=="diff"&&n.mode!=="file"&&n.mode!=="context"&&n.mode!=="preview"&&n.mode!=="browser"&&n.mode!=="git"&&n.mode!=="terminal")continue;const a=To(typeof n.targetPath=="string"?n.targetPath:null),i=vi(n.mode,a,typeof n.dedupeKey=="string"?n.dedupeKey:null),s=Di(n.mode,i);!s||o.has(s)||(o.add(s),t.push({id:s,mode:n.mode,targetPath:a,dedupeKey:i,label:Ro(typeof n.label=="string"?n.label:null),sessionTitleFallback:Ro(typeof n.sessionTitleFallback=="string"?n.sessionTitleFallback:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,diffScope:pn(n.diffScope)??(n.stagedDiff===!0?"staged":"working"),touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()}))}return t},wt=(e,t)=>t&&e.some(o=>o.id===t)?t:e.length===0?null:e[e.length-1].id,We=e=>{if(e){const t=Mi(e.tabs),o=wt(t,e.activeTabId);return{...e,tabs:t,activeTabId:o,width:e.width,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,touchedAt:Date.now()}},Cl=(e,t)=>{const o=hn(t),r=o.mode==="file"&&o.targetPath?e.tabs.filter(c=>!(c.mode==="file"&&!c.targetPath)):e.tabs,n=r.findIndex(c=>c.id===o.id),a=n===-1?[...r,o]:r.map((c,d)=>d===n?{...c,mode:o.mode,targetPath:o.targetPath||c.targetPath,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||c.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:c),i=o.id,s=Si(a,ki,i);return{...e,isOpen:!0,tabs:s,activeTabId:wt(s,i),touchedAt:Date.now()}},kl=(e,t)=>{const o=e.tabs.find(i=>i.id===t)??null,r=e.tabs.filter(i=>i.id!==t);if(e.activeTabId!==t)return{...e,tabs:r,activeTabId:wt(r,e.activeTabId),isOpen:r.length>0?e.isOpen:!1,touchedAt:Date.now()};const n=o?r.filter(i=>i.mode===o.mode):[],a=n.length>0?n.reduce((i,s)=>s.touchedAt>=i.touchedAt?s:i):null;return{...e,tabs:r,activeTabId:a?.id??wt(r,null),isOpen:a?e.isOpen:!1,touchedAt:Date.now()}},vl=(e,t,o)=>{if(t===o)return e;const r=e.tabs.findIndex(s=>s.id===t),n=e.tabs.findIndex(s=>s.id===o);if(r===-1||n===-1)return e;const a=[...e.tabs],[i]=a.splice(r,1);return i?(a.splice(n,0,i),{...e,tabs:a,touchedAt:Date.now()}):e},Dl=(e,t,o)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:o}:r)}),Sl=e=>{const t=[];let o=!1;for(const r of e){if(r.mode!=="diff"&&r.mode!=="git"){t.push(r);continue}o||(o=!0,t.push(r.mode==="git"?r:hn({mode:"git"})))}return t},De=e=>{if(!e||typeof e!="object")return{};const t=e,o={};for(const[r,n]of Object.entries(t)){const a=$(r);if(!a||!n||typeof n!="object")continue;const i=n;let s=Sl(Mi(i.tabs)),c=typeof i.activeTabId=="string"?i.activeTabId:null;s.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context")&&(s=[hn({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=s[0]?.id??null);const d=wt(s,c),l=Si(s,ki,d),u=wl(i);o[a]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:l,activeTabId:wt(l,d),...u!==void 0?{width:u}:{},touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return o},Ve=(e,t)=>{const o=Object.entries(e);if(o.length<=t)return e;o.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const r={};for(const[n,a]of o.slice(0,t))r[n]=a;return r};function ca(e){return e==="vim"?"vim":"default"}const co={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},Se={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},lo=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,Ml=e=>{if(!e||typeof e!="object")return!1;const t=e;return lo(t.completion,co.completion)&&lo(t.error,co.error)&&lo(t.question,co.question)&&lo(t.subtask,co.subtask)},Rt=280,cr=new Map,dr=e=>(e??S()).trim()||"default",Q=Wt()(Vt(qr((e,t)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:Rt,hasManuallyResizedLeftSidebar:!1,contextPanelByDirectory:{},contextRailOrder:[],contextEditorTreeVisible:!0,contextEditorTreeWidth:240,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,showReasoningTraces:!0,collapsibleThinkingBlocks:!0,collapseThinkingByDefault:!0,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:cl,monoFont:dl,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:ml(),favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,inputSpellcheckEnabled:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,expandedEditorToolbar:!1,showSplitAssistantMessageActions:!1,draftStartersVisible:!0,isExpandedInput:!1,shortcutOverrides:{},commandTriggers:[],fileEditorKeymap:"default",setTheme:o=>{e({theme:o}),t().applyTheme()},toggleSidebar:()=>{e(o=>{const r=!o.isSidebarOpen;return r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:Rt}:{isSidebarOpen:r}})},setSidebarOpen:o=>{e(r=>r.isSidebarOpen===o?o&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==Rt?{isSidebarOpen:o,sidebarWidth:Rt}:r:o&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:o,sidebarWidth:Rt}:{isSidebarOpen:o})},setSidebarWidth:o=>{e({sidebarWidth:o,hasManuallyResizedLeftSidebar:!0})},setContextRailOrder:o=>{const r=Array.isArray(o)?o.filter((n,a)=>typeof n=="string"&&n.trim()!==""&&o.indexOf(n)===a):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(o=>({contextEditorTreeVisible:!o.contextEditorTreeVisible}))},setContextEditorTreeWidth:o=>{Number.isFinite(o)&&e({contextEditorTreeWidth:Math.min(480,Math.max(200,Math.round(o)))})},openContextSurface:(o,r)=>{const n=r==="diff"?"git":r,a=$((o||"").trim());if(!a)return;const i=t(),s=i.contextPanelByDirectory[a],c=s?.tabs??[],d=c.find(u=>u.id===s?.activeTabId)??null;if(s?.isOpen&&d?.mode===n){i.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);i.setActiveContextPanelTab(a,u.id);return}n!=="preview"&&i.openContextPanelTab(a,{mode:n})},openContextPanelTab:(o,r)=>{const n=$((o||"").trim());n&&e(a=>{const i=a.contextPanelByDirectory[n],s=We(i),c={...a.contextPanelByDirectory,[n]:Cl(s,r)};return{contextPanelByDirectory:Ve(c,20)}})},openContextDiff:(o,r,n=!1,a=null)=>{const i=$((o||"").trim()),s=(r||"").trim();if(!i||!s)return;const c=pn(a)??(n?"staged":"working");t().setPendingDiffFile(s,n,c),t().openContextPanelTab(i,{mode:"git"})},openContextFile:(o,r)=>{const n=$((o||"").trim()),a=To(r);!n||!a||(t().openContextPanelTab(n,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(a),t().setPendingFileNavigation(null))},openContextFileAtLine:(o,r,n,a)=>{const i=$((o||"").trim()),s=To(r),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,d=Number.isFinite(a)?Math.max(1,Math.trunc(a)):1;!i||!s||(t().openContextPanelTab(i,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:s,line:c,column:d}))},openContextOverview:o=>{const r=$((o||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(o,r)=>{const n=$((o||"").trim()),a=(r||"").trim();if(!n||!a)return;let i=null;try{const s=new URL(a);(s.protocol==="http:"||s.protocol==="https:")&&(i=s.host||s.hostname||"Preview")}catch{}t().openContextPanelTab(n,{mode:"preview",targetPath:a,dedupeKey:a,label:i})},openContextBrowser:(o,r="")=>{const n=$((o||"").trim());if(!n)return;const a=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(n,{mode:"browser",targetPath:a,dedupeKey:"desktop-browser",label:"Browser"})},setContextPanelTabTargetPath:(o,r,n)=>{const a=$((o||"").trim()),i=(r||"").trim();!a||!i||e(s=>{const c=s.contextPanelByDirectory[a];return c?{contextPanelByDirectory:{...s.contextPanelByDirectory,[a]:Dl(c,i,n)}}:s})},setActiveContextPanelTab:(o,r)=>{const n=$((o||"").trim()),a=(r||"").trim();!n||!a||e(i=>{const s=i.contextPanelByDirectory[n],c=We(s);if(!c.tabs.some(l=>l.id===a)||c.activeTabId===a&&c.isOpen)return i;const d={...i.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:Ve(d,20)}})},reorderContextPanelTabs:(o,r,n)=>{const a=$((o||"").trim()),i=(r||"").trim(),s=(n||"").trim();!a||!i||!s||e(c=>{const d=c.contextPanelByDirectory[a],l=We(d);if(!l.tabs.some(m=>m.id===i)||!l.tabs.some(m=>m.id===s))return c;const u=vl(l,i,s);if(u.tabs===l.tabs)return c;const f={...c.contextPanelByDirectory,[a]:u};return{contextPanelByDirectory:Ve(f,20)}})},closeContextPanelTab:(o,r)=>{const n=$((o||"").trim()),a=(r||"").trim();if(!n||!a)return;const i=t().contextPanelByDirectory[n]?.tabs.find(s=>s.id===a);e(s=>{const c=s.contextPanelByDirectory[n],d=We(c);if(!d.tabs.some(u=>u.id===a))return s;const l={...s.contextPanelByDirectory,[n]:kl(d,a)};return{contextPanelByDirectory:Ve(l,20)}}),i?.mode==="file"&&i.targetPath&&Fl.getState().removeOpenPath(n,i.targetPath)},closeContextPanel:o=>{const r=$((o||"").trim());r&&e(n=>{const a=n.contextPanelByDirectory[r];if(!a||!a.isOpen)return n;const i={...n.contextPanelByDirectory,[r]:{...We(a),isOpen:!1}};return{contextPanelByDirectory:Ve(i,20)}})},toggleContextPanelExpanded:o=>{const r=$((o||"").trim());r&&e(n=>{const a=n.contextPanelByDirectory[r],i=We(a),s={...n.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Ve(s,20)}})},setContextPanelWidth:(o,r)=>{const n=$((o||"").trim());n&&e(a=>{const i=a.contextPanelByDirectory[n],s=We(i),c={...a.contextPanelByDirectory,[n]:{...s,width:yo(r)}};return{contextPanelByDirectory:Ve(c,20)}})},setSessionSwitcherOpen:o=>{t().isSessionSwitcherOpen!==o&&e({isSessionSwitcherOpen:o})},setSessionDropdownOpen:o=>{t().isSessionDropdownOpen!==o&&e({isSessionDropdownOpen:o})},setMainTabGuard:o=>{t().mainTabGuard!==o&&e({mainTabGuard:o})},setActiveMainTab:o=>{const r=t().mainTabGuard;r&&!r(o)||(cr.set(dr(),o),e({activeMainTab:o}))},prepareForRuntimeSwitch:o=>{cr.set(dr(o),t().activeMainTab)},restoreForRuntimeSwitch:o=>{const r=cr.get(dr(o))??"chat";e({activeMainTab:r})},setPendingDiffFile:(o,r=!1,n=null)=>{e({pendingDiffFile:o,pendingDiffStaged:o?r:!1,pendingDiffScope:o?n:null})},setPendingDiagramFile:o=>{e({pendingDiagramFile:o})},setPendingFileNavigation:o=>{e({pendingFileNavigation:o})},setPendingFileFocusPath:o=>{e({pendingFileFocusPath:o})},navigateToDiff:(o,r=!1,n=null)=>{const a=t().mainTabGuard;a&&!a("diff")||e({pendingDiffFile:o,pendingDiffStaged:r,pendingDiffScope:n,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:o}=t();return o&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),o},navigateToDiagram:o=>{const r=t().mainTabGuard;r&&!r("diagram")||e({pendingDiagramFile:o,activeMainTab:"diagram"})},consumePendingDiagramFile:()=>{const{pendingDiagramFile:o}=t();return o&&e({pendingDiagramFile:null}),o},setIsMobile:o=>{e({isMobile:o})},toggleCommandPalette:()=>{e(o=>({isCommandPaletteOpen:!o.isCommandPaletteOpen}))},setCommandPaletteOpen:o=>{e({isCommandPaletteOpen:o})},toggleHelpDialog:()=>{e(o=>({isHelpDialogOpen:!o.isHelpDialogOpen}))},setHelpDialogOpen:o=>{e({isHelpDialogOpen:o})},setSessionCreateDialogOpen:o=>{e({isSessionCreateDialogOpen:o})},setArchivePageOpen:o=>{e({isArchivePageOpen:o})},closeMainSurfaces:()=>{t().isArchivePageOpen&&e({isArchivePageOpen:!1})},setSettingsDialogOpen:o=>{e(r=>o?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setModelSelectorOpen:o=>{e({isModelSelectorOpen:o})},setSidebarSection:o=>{e({sidebarSection:o})},setSettingsPage:o=>{e({settingsPage:o})},setSettingsProjectsSelectedId:o=>{e({settingsProjectsSelectedId:o})},setSettingsRemoteInstancesSelectedId:o=>{e({settingsRemoteInstancesSelectedId:o})},setEventStreamStatus:(o,r)=>{e({eventStreamStatus:o,eventStreamHint:r??null})},setShowReasoningTraces:o=>{e({showReasoningTraces:o})},setCollapsibleThinkingBlocks:o=>{e({collapsibleThinkingBlocks:o})},setCollapseThinkingByDefault:o=>{e({collapseThinkingByDefault:o})},setShowDeletionDialog:o=>{e({showDeletionDialog:o})},setAutoDeleteEnabled:o=>{e({autoDeleteEnabled:o})},setAutoSaveEnabled:o=>{e({autoSaveEnabled:o})},setAutoDeleteAfterDays:o=>{const r=Math.max(1,Math.min(365,o));e({autoDeleteAfterDays:r})},setSessionRetentionAction:o=>{e({sessionRetentionAction:o})},setAutoDeleteLastRunAt:o=>{e({autoDeleteLastRunAt:o})},setMessageLimit:o=>{const r=Math.max(10,Math.min(500,Math.round(o)));e({messageLimit:r})},setFontSize:o=>{const r=Math.max(50,Math.min(200,o));e({fontSize:r}),t().applyTypography()},setGlobalDraftStarters:o=>{e({globalDraftStarters:o})},setDraftStartersVisible:o=>{e({draftStartersVisible:o})},setTerminalFontSize:o=>{const r=Math.round(o),n=Math.max(9,Math.min(52,r));e({terminalFontSize:n})},setTerminalShell:o=>{e({terminalShell:o})},setTerminalLoginShells:o=>{e({terminalLoginShells:[...new Set(o)]})},setEditorFontSize:o=>{const r=Math.round(o),n=Math.max(9,Math.min(32,r));e({editorFontSize:n})},setUiFont:o=>{e({uiFont:o})},setMonoFont:o=>{e({monoFont:o})},setPadding:o=>{const r=Math.max(50,Math.min(200,o));e({padding:r}),t().applyPadding()},setCornerRadius:o=>{e({cornerRadius:o})},applyTypography:()=>{const{fontSize:o}=t(),r=document.documentElement,n=o/100,a=Object.entries(rl);if(n===1){for(const[i]of a)r.style.removeProperty(aa(i));return}for(const[i,s]of a){const c=parseFloat(s);Number.isFinite(c)&&r.style.setProperty(aa(i),`${c*n}rem`)}},applyPadding:()=>{const{padding:o}=t(),r=document.documentElement,n=o/100;if(n===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(n);r.style.setProperty("--padding-scale",a.toString());const i=1+(n-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:o=>{e({diffLayoutPreference:o})},setDiffFileLayout:(o,r)=>{e(n=>({diffFileLayout:{...n.diffFileLayout,[o]:r}}))},setDiffWrapLines:o=>{e({diffWrapLines:o})},setWalkthroughTocWidth:o=>{e({walkthroughTocWidth:Math.round(o)})},setGitChangesViewMode:o=>{e({gitChangesViewMode:o})},setInputBarOffset:o=>{e({inputBarOffset:o})},setMobileKeyboardMode:o=>{e(r=>r.mobileKeyboardMode===o?r:{mobileKeyboardMode:o})},toggleFavoriteModel:(o,r)=>{e(n=>n.favoriteModels.some(i=>i.providerID===o&&i.modelID===r)?{favoriteModels:n.favoriteModels.filter(i=>!(i.providerID===o&&i.modelID===r))}:{favoriteModels:[{providerID:o,modelID:r},...n.favoriteModels]})},reorderFavoriteModel:(o,r,n,a)=>{e(i=>{const s=i.favoriteModels.findIndex(u=>u.providerID===o&&u.modelID===r),c=i.favoriteModels.findIndex(u=>u.providerID===n&&u.modelID===a);if(s===-1||c===-1||s===c)return i;const d=i.favoriteModels.slice(),[l]=d.splice(s,1);return l?(d.splice(c,0,l),{favoriteModels:d}):i})},toggleHiddenModel:(o,r)=>{e(n=>n.hiddenModels.some(i=>i.providerID===o&&i.modelID===r)?{hiddenModels:n.hiddenModels.filter(i=>!(i.providerID===o&&i.modelID===r))}:{hiddenModels:[{providerID:o,modelID:r},...n.hiddenModels]})},isHiddenModel:(o,r)=>{const{hiddenModels:n}=t();return n.some(a=>a.providerID===o&&a.modelID===r)},hideAllModels:(o,r)=>{e(n=>{const a=n.hiddenModels.filter(s=>s.providerID!==o);return{hiddenModels:[...[...new Set(r.filter(s=>typeof s=="string"&&s.length>0))].map(s=>({providerID:o,modelID:s})),...a]}})},showAllModels:o=>{e(r=>({hiddenModels:r.hiddenModels.filter(n=>n.providerID!==o)}))},toggleModelProviderCollapsed:o=>{const r=typeof o=="string"?o.trim():"";r&&e(n=>n.collapsedModelProviders.includes(r)?{collapsedModelProviders:n.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...n.collapsedModelProviders,r]})},setModelProvidersCollapsed:(o,r)=>{const n=Array.from(new Set(o.filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean)));n.length!==0&&e(a=>{const i=new Set(n),s=a.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...s,...n]:s}})},isFavoriteModel:(o,r)=>{const{favoriteModels:n}=t();return n.some(a=>a.providerID===o&&a.modelID===r)},addRecentModel:(o,r)=>{e(n=>{const a=n.recentModels.filter(i=>!(i.providerID===o&&i.modelID===r));return{recentModels:[{providerID:o,modelID:r},...a].slice(0,5)}})},addRecentAgent:o=>{const r=typeof o=="string"?o.trim():"";r&&e(n=>{if(n.recentAgents.includes(r))return n;const a=n.recentAgents;return{recentAgents:[r,...a].slice(0,5)}})},addRecentEffort:(o,r,n)=>{const a=typeof o=="string"?o.trim():"",i=typeof r=="string"?r.trim():"";if(!a||!i)return;const s=`${a}/${i}`,c=typeof n=="string"&&n.trim().length>0?n.trim():"default";e(d=>{const l=d.recentEfforts[s]??[];if(l.includes(c))return d;const u=l;return{recentEfforts:{...d.recentEfforts,[s]:[c,...u].slice(0,5)}}})},applyTheme:()=>{const{theme:o}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),o==="system"){const n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(n)}else r.classList.add(o)},setTimelineDialogOpen:o=>{e({isTimelineDialogOpen:o})},setPromptNavigatorPanelOpen:o=>{e({isPromptNavigatorPanelOpen:o})},togglePromptNavigatorPanel:()=>{e(o=>({isPromptNavigatorPanelOpen:!o.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:o=>{e({isImagePreviewOpen:o})},setNativeNotificationsEnabled:o=>{e({nativeNotificationsEnabled:o})},setNotificationMode:o=>{e({notificationMode:o})},setShowTerminalQuickKeysOnDesktop:o=>{e({showTerminalQuickKeysOnDesktop:o})},setNotifyOnSubtasks:o=>{e({notifyOnSubtasks:o})},setDockBadgeEnabled:o=>{e({dockBadgeEnabled:o})},setNotifyOnCompletion:o=>{e({notifyOnCompletion:o})},setNotifyOnError:o=>{e({notifyOnError:o})},setNotifyOnQuestion:o=>{e({notifyOnQuestion:o})},setNotificationTemplates:o=>{e(r=>({notificationTemplates:typeof o=="function"?o(r.notificationTemplates):o}))},setSummarizeLastMessage:o=>{e({summarizeLastMessage:o})},setSummaryThreshold:o=>{e({summaryThreshold:o})},setSummaryLength:o=>{e({summaryLength:o})},setMaxLastMessageLength:o=>{e({maxLastMessageLength:o})},setPersistChatDraft:o=>{e({persistChatDraft:o})},setInputSpellcheckEnabled:o=>{e({inputSpellcheckEnabled:o})},setWideChatLayoutEnabled:o=>{e({wideChatLayoutEnabled:o})},setCodeBlockLineWrap:o=>{e({codeBlockLineWrap:o})},setShowToolFileIcons:o=>{e({showToolFileIcons:o})},setShowTurnChangedFiles:o=>{e({showTurnChangedFiles:o})},setShowExpandedBashTools:o=>{e({showExpandedBashTools:o})},setShowExpandedEditTools:o=>{e({showExpandedEditTools:o})},setTimeFormatPreference:o=>{e({timeFormatPreference:o})},setWeekStartPreference:o=>{e({weekStartPreference:o})},setDesktopWindowControlsPosition:o=>{e({desktopWindowControlsPosition:o==="left"?"left":"right"})},setDesktopWindowControlsStyle:o=>{e({desktopWindowControlsStyle:o==="traffic-lights"?"traffic-lights":"classic"})},setMermaidRenderingMode:o=>{e({mermaidRenderingMode:o})},setUserMessageRenderingMode:o=>{e({userMessageRenderingMode:o})},setCollapsibleUserMessages:o=>{e({collapsibleUserMessages:o})},setStickyUserHeader:o=>{e({stickyUserHeader:o})},setPromptNavigatorEnabled:o=>{e({promptNavigatorEnabled:o})},setExpandedEditorToolbar:o=>{e({expandedEditorToolbar:o})},setShowSplitAssistantMessageActions:o=>{e({showSplitAssistantMessageActions:o})},viewPagerPage:"center",setViewPagerPage:o=>{e({viewPagerPage:o}),e({isSessionSwitcherOpen:o==="left"})},setShortcutOverride:(o,r)=>{e(n=>({shortcutOverrides:{...n.shortcutOverrides,[o]:r}}))},clearShortcutOverride:o=>{e(r=>{const n={...r.shortcutOverrides};return delete n[o],{shortcutOverrides:n}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:o=>{e({fileEditorKeymap:ca(o)})},toggleExpandedInput:()=>{e(o=>({isExpandedInput:!o.isExpandedInput}))},setExpandedInput:o=>{e({isExpandedInput:o})}}),{name:"ui-store",storage:rn(),version:18,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const o=e;if(t<18&&(delete o.notesPanelHeight,delete o.todoPanelHeight,o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="notes"))),t<17&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="chat"))),t<16&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="chat"))),t<15&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="pr"))),t<14&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="diff"))),t<13&&typeof o.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const n=localStorage.getItem("pichamber:files:auto-save-enabled");n!==null&&(r=n!=="false",localStorage.removeItem("pichamber:files:auto-save-enabled"))}}catch{r=!0}o.autoSaveEnabled=r}if(t<12&&(o.desktopWindowControlsPosition==="auto"||o.desktopWindowControlsPosition==null)&&(o.desktopWindowControlsPosition="right"),t<11&&o.terminalFontSize===13&&(o.terminalFontSize=14),t<10&&delete o.diffViewMode,t<9&&((typeof o.notesPanelHeight!="number"||!Number.isFinite(o.notesPanelHeight))&&(o.notesPanelHeight=112),(typeof o.todoPanelHeight!="number"||!Number.isFinite(o.todoPanelHeight))&&(o.todoPanelHeight=259)),t<1&&Ml(o.notificationTemplates)&&(o.notificationTemplates={completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}}),t<3){const r=new Set([90,120,180,220]),n=o.memoryLimitHistorical,a=o.memoryLimitActiveSession;typeof n=="number"&&!r.has(n)?o.messageLimit=n:typeof a=="number"&&!r.has(a)&&(o.messageLimit=a),delete o.memoryLimitHistorical,delete o.memoryLimitViewport,delete o.memoryLimitActiveSession}if(delete o.isRightSidebarOpen,delete o.rightSidebarWidth,delete o.rightSidebarTab,delete o.workStatusExpandedSections,delete o.workStatusScrollTop,delete o.workStatusPanelEnabled,delete o.workStatusHiddenSections,o.contextPanelByDirectory=De(o.contextPanelByDirectory),t<5)if(!o.shortcutOverrides||typeof o.shortcutOverrides!="object")o.shortcutOverrides={};else{const r=o.shortcutOverrides,n={};for(const[a,i]of Object.entries(r))typeof a=="string"&&typeof i=="string"&&(n[a]=i);o.shortcutOverrides=n}return t<6&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory)),t<7&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory)),t<8&&o.gitChangesViewMode!=="flat"&&o.gitChangesViewMode!=="tree"&&(o.gitChangesViewMode="flat"),o.fileEditorKeymap=ca(o.fileEditorKeymap),typeof o.autoSaveEnabled!="boolean"&&(o.autoSaveEnabled=!0),o.contextRailOrder=Array.isArray(o.contextRailOrder)?o.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""&&r!=="pr"&&r!=="diff"&&r!=="chat"&&r!=="notes"):[],o},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,isSessionSwitcherOpen:e.isSessionSwitcherOpen,activeMainTab:e.activeMainTab,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,collapseThinkingByDefault:e.collapseThinkingByDefault,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,diffWrapLines:e.diffWrapLines,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,inputSpellcheckEnabled:e.inputSpellcheckEnabled,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,expandedEditorToolbar:e.expandedEditorToolbar,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Tl=e=>{if(!e||typeof e!="object")return null;const t={};return typeof e.showReasoningTraces=="boolean"&&(t.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&(t.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),typeof e.collapseThinkingByDefault=="boolean"&&(t.collapseThinkingByDefault=e.collapseThinkingByDefault),Object.keys(t).length>0?t:null},Rl=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,collapseThinkingByDefault:t.collapseThinkingByDefault}},Pl=e=>{const t=Q.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.collapseThinkingByDefault=="boolean"&&t.setCollapseThinkingByDefault(e.collapseThinkingByDefault)},Il=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),o=Rl(t);return Tl(o)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}};let da="idle";const xl=new Set;let uo=null;const fe=e=>{uo&&(clearTimeout(uo),uo=null);const t=e==="saved"?"idle":e;t!==da&&(da=t,xl.forEach(o=>o())),t==="error"&&(uo=setTimeout(()=>fe("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("pichamber:settings-save-state",{detail:e}))},e0=e=>{fe(e)},_l=e=>{if(!(typeof window>"u")&&!(typeof window.__PICHAMBER_HOME__=="string"&&window.__PICHAMBER_HOME__.length>0))try{window.__PICHAMBER_HOME__=e}catch{}},la="pichamber.settingsMirror.v2.index",Ol="pichamber.settingsMirror.v2:",Nl=5,ua=e=>`${Ol}${encodeURIComponent(e)}`,Je=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},Ll=(e,t)=>{const o={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,gitmojiEnabled:e.gitmojiEnabled,directoryShowHidden:e.directoryShowHidden,filesViewShowGitignored:e.filesViewShowGitignored,openInAppId:e.openInAppId,pwaAppName:e.pwaAppName,mobileKeyboardMode:e.mobileKeyboardMode};localStorage.setItem(ua(t),JSON.stringify(o));let r=[];try{const a=JSON.parse(localStorage.getItem(la)??"[]");Array.isArray(a)&&(r=a.filter(i=>typeof i=="string"))}catch{r=[]}const n=[t,...r.filter(a=>a!==t)].slice(0,Nl);for(const a of r)n.includes(a)||localStorage.removeItem(ua(a));localStorage.setItem(la,JSON.stringify(n))},Ul=e=>{if(!(typeof window>"u")){if(Ll(e,S()),Je("selectedThemeId",e.themeId||null),Je("selectedThemeVariant",e.themeVariant||null),Je("lightThemeId",e.lightThemeId||null),Je("darkThemeId",e.darkThemeId||null),Je("useSystemTheme",typeof e.useSystemTheme=="boolean"?String(e.useSystemTheme):null),Je("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),_l(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(o=>o.sidebarCollapsed===!0).map(o=>o.id).filter(o=>typeof o=="string"&&o.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(e.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof e.directoryShowHidden=="boolean"?localStorage.setItem("directoryTreeShowHidden",e.directoryShowHidden?"true":"false"):localStorage.removeItem("directoryTreeShowHidden"),typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),Je("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=Ci(e.pwaAppName,"");t.length>0?localStorage.setItem(sr,t):localStorage.removeItem(sr)}else localStorage.removeItem(sr);gl(e.mobileKeyboardMode)}},Dr=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("pichamber:settings-synced",{detail:e}))},Hl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const o=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,a)=>a.toUpperCase()+":");return o==="/"?"/":(o.length>1?o.replace(/\/+$/,""):o)||null},Fn="queue",yn=e=>e==="steer"||e==="queue",bn=(e,t)=>e==="immediate"?"steer":yn(e)?e:t===!1?"steer":t===!0?"queue":Fn,fa=50,lr=20,fo=(e,t)=>{if(e.runtimeKey!==S())return;const o=t.flatMap(r=>(r.attachments??[]).flatMap(n=>n.uploadState?.status==="ready"?[n.uploadState.attachmentId]:[]));for(const r of new Set(o))Ze.deleteAttachment(r,{runtimeKey:e.runtimeKey}).catch(()=>{})},jl=(e,t,o=S())=>{const r=Hl(t);return!o||!r||!e?null:{runtimeKey:o,directory:r,sessionId:e}},ye=e=>`${e.runtimeKey}
4
+ `)}}}).catch(c=>{if(i.signal.aborted)return;const d=c instanceof Error?c.message.slice(0,80):"fetch-failed";ne("stream-connect",{code:"fetch-failed",detail:d}),a(`sse-error:${d}`)}).finally(()=>t.removeEventListener("abort",s)),s},qd=(e,t,o,r,n,a)=>{const i=bi(e);let s=!1,c=!1,d=null;const l=()=>{if(!s){s=!0,d&&clearTimeout(d),d=null;try{i.close()}catch{}}};d=setTimeout(()=>{c||s||(n("ws-ready-timeout"),l())},a);const u=()=>l();return t.aborted?l():t.addEventListener("abort",u,{once:!0}),i.onopen=()=>{c=!0,d&&clearTimeout(d),d=null,o()},i.onmessage=f=>{const m=typeof f.data=="string"?f.data:void 0;if(m)try{const p=JSON.parse(m);Br(p)&&r(p)}catch{}},i.onerror=()=>{s||n("ws-error")},i.onclose=f=>{t.removeEventListener("abort",u),s||n(`ws-close-${f?.code??0}`)},l},Gd=()=>typeof document>"u"||document.visibilityState==="visible",Wd=()=>typeof navigator>"u"||navigator.onLine!==!1,jF=(e,t={})=>{const o=new AbortController,r=t.signal;r&&(r.aborted?o.abort():r.addEventListener("abort",()=>o.abort(),{once:!0}));const n=o.signal,a=t.runtimeKey,i=()=>!a||a===S();let s=!1,c=0,d=typeof t.fromSequence=="number"&&Number.isFinite(t.fromSequence)?Math.max(0,Math.floor(t.fromSequence)):0,l=t.transport==="ws"?"ws":"sse",u=null,f=null,m=null,p=0,g=!1;const F=()=>{u&&clearTimeout(u),f&&clearTimeout(f),u=null,f=null},y=()=>{p+=1,m?.(),m=null,f&&clearTimeout(f),f=null},b=v=>{f&&clearTimeout(f),f=setTimeout(()=>{v===p&&L("heartbeat-timeout",v)},t.heartbeatTimeoutMs??Od)},D=v=>{s||n.aborted||v!==p||b(v)},C=v=>{if(s||n.aborted||v!==p)return;const z=!g;c=0,g=!0,b(v),z&&(ne("stream-ready",{code:l}),e.onReconnect?.())},I=()=>{const v=Gd()&&Wd()?Ld:Ud,z=Math.min(Hd,c),kt=Math.min(v,Nd*2**z);return c===0&&t.reconnectDelayMs!==void 0?Math.max(0,t.reconnectDelayMs):kt+Math.floor(Math.random()*100)},V=(v,z=!0)=>{s||n.aborted||u||(ne("stream-reconnect",{code:v}),z&&e.onDisconnect?.(v),u=setTimeout(()=>{u=null,c+=1,ve()},I()))},L=(v,z)=>{if(!(s||n.aborted||z!==p)){if(y(),!g&&l==="ws"&&t.transport!=="ws"&&(l="sse",e.onTransportSwitch?.()),g=!1,v==="runtime-change"){e.onDisconnect?.(v);return}V(v)}},Ct=(v,z)=>{if(!(s||n.aborted||z!==p)){if(!i()){L("runtime-change",z);return}v.sequence>d&&(d=v.sequence),C(z),e.onEvent(v)}},ve=async()=>{if(s||n.aborted)return;if(!i()){e.onDisconnect?.("runtime-change");return}const v=p+1;p=v;let z;if(l==="ws")try{z=await At()}catch{if(v!==p||s||n.aborted)return;if(t.transport!=="ws"){l="sse",e.onTransportSwitch?.(),y(),ve();return}ne("stream-auth",{code:"url-token-unavailable"}),L("ws-auth-token-unavailable",v);return}if(v!==p||s||n.aborted)return;if(!i()){L("runtime-change",v);return}if(l==="sse"&&kr()){try{await At()}catch{if(v!==p||s||n.aborted)return;ne("stream-auth",{code:"url-token-unavailable"}),L("sse-auth-token-unavailable",v);return}if(v!==p||s||n.aborted||!i())return}const kt=ra(l,{fromSequence:d,...t.sessionId?{sessionId:t.sessionId}:{}},z),ze=()=>D(v),to=$e=>Ct($e,v),oo=$e=>L($e,v);m=l==="ws"?qd(kt,n,ze,to,oo,jd):Kd(Ai({fromSequence:d,...t.sessionId?{sessionId:t.sessionId}:{}}),n,ze,()=>C(v),to,oo)},lt=()=>{!kr()||s||n.aborted||(F(),y(),g=!1,V("system-resume",!1))};return typeof window<"u"&&window.addEventListener("pichamber:system-resume",lt),ve(),{dispose:()=>{s||(s=!0,typeof window<"u"&&window.removeEventListener("pichamber:system-resume",lt),F(),y(),o.abort())},reconnect:(v="manual")=>{s||n.aborted||(F(),y(),V(v))},get eventsUrl(){return ra(l,{fromSequence:d,...t.sessionId?{sessionId:t.sessionId}:{}})}}},Vd=3e4,ar=1,Jd=300,Yd=e=>new Promise(t=>setTimeout(t,e)),k=async(e,t)=>{const o=t.runtimeKey;if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");const r=t.query?`?${new URLSearchParams(Object.entries(t.query).map(([i,s])=>[i,String(s)])).toString()}`:"",n={Accept:"application/json"};t.body!==void 0&&(n["Content-Type"]="application/json");let a;for(let i=0;i<=ar;i+=1){if(i>0){if(t.signal?.aborted)break;if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");if(await Yd(Jd),t.signal?.aborted)break;if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request")}const s=new AbortController,c=setTimeout(()=>s.abort(),Vd),d=t.signal,l=()=>s.abort();d&&(d.aborted?s.abort():d.addEventListener("abort",l,{once:!0}));try{const u=await h(e+r,{method:t.method,headers:n,body:t.body===void 0?void 0:JSON.stringify(t.body),signal:s.signal});if(!u.ok){const p=(await u.json().catch(()=>null))?.error??{code:"DAEMON_REQUEST_FAILED"};if(u.status===503&&(p.code==="DAEMON_UNAVAILABLE"||p.code==="DAEMON_TIMEOUT")&&i<ar&&!d?.aborted){a=new te(p.code,p.message,u.status);continue}throw new te(p.code,p.message,u.status)}if(u.status===204){if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");return}const f=await u.json();if(o&&o!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request");return f}catch(u){if(a=u,u instanceof te||d?.aborted||u instanceof DOMException&&u.name==="AbortError")throw u;if(i<ar&&!d?.aborted)continue;throw u}finally{clearTimeout(c),d&&d.removeEventListener("abort",l)}}throw a};class te extends Error{code;status;constructor(t,o,r){super(o??`Pi request failed: ${t}`),this.name="PiRequestError",this.code=t,r!==void 0&&(this.status=r)}}const B=e=>{if(e?.runtimeKey&&e.runtimeKey!==S())throw new te("DAEMON_UNAVAILABLE","Runtime changed during request")};class Qd{currentDirectory;setDirectory(t){this.currentDirectory=t}getDirectory(){return this.currentDirectory}async health(t){B(t);const o=await $d(void 0,t?.runtimeKey);return o.state==="ready"?{protocolVersion:o.protocolVersion,state:"ready",capabilities:o.capabilities}:{protocolVersion:o.protocolVersion,state:"unavailable",capabilities:o.capabilities,...o.error?{error:o.error}:{}}}async listProjects(t){return B(t),k("/api/pi/projects",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async selectProject(t,o){return B(o),k("/api/pi/projects/select",{method:"POST",body:{directory:t},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listSessions(t){B(t);const o=t?.directory??this.currentDirectory;return k("/api/pi/sessions",{method:"GET",...o?{query:{directory:o}}:{},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async createSession(t,o){return B(o),k("/api/pi/sessions",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getSession(t,o){B(o);const r=o?.directory??this.currentDirectory;return k(`/api/pi/sessions/${encodeURIComponent(t)}`,{method:"GET",...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getSessionMessages(t,o,r){B(r);const n=r?.directory??this.currentDirectory;return k(`/api/pi/sessions/${encodeURIComponent(t)}/messages`,{method:"GET",query:{...n?{directory:n}:{},...o.before?{before:o.before}:{},...o.limit!==void 0?{limit:o.limit}:{}},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async renameSession(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"PATCH",body:{sessionId:t.sessionId,title:t.title},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async deleteSession(t,o){B(o);try{return await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}`,{method:"DELETE",...o?.directory?{query:{directory:o.directory}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}}),!0}catch(r){if(r instanceof te&&r.status===404)return!0;throw r}}async archiveSession(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/archive`,{method:"POST",body:{sessionId:t.sessionId,archived:t.archived,...o?.directory?{directory:o.directory}:{}},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getSessionTree(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t)}/tree`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async navigateSession(t,o,r){return B(r),k(`/api/pi/sessions/${encodeURIComponent(t)}/navigate`,{method:"POST",body:{messageId:o},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async forkSession(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/fork`,{method:"POST",body:{sessionId:t.sessionId,...t.messageId?{messageId:t.messageId}:{}},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async cloneSession(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/clone`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async sendPrompt(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/prompt`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async sendSteer(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/steer`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async sendFollowUp(t,o){return B(o),k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/follow-up`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async abortSession(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/abort`,{method:"POST",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setSessionModel(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/model`,{method:"POST",body:{sessionId:t.sessionId,model:t.model},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setSessionThinking(t,o){B(o),await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/thinking`,{method:"POST",body:{sessionId:t.sessionId,thinking:t.thinking},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async compactSession(t,o){if(B(o),(await k(`/api/pi/sessions/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})).accepted!==!0)throw new te("DAEMON_PROTOCOL_MISMATCH")}async listProviders(t){return B(t),k("/api/pi/providers",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async refreshProviders(t){return B(t),k("/api/pi/providers/refresh",{method:"POST",...t?.directory?{body:{directory:t.directory}}:{body:void 0},...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async getProviderStatus(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t)}/status`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async loginProvider(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/login`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getProviderLogin(t,o,r){return B(r),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(o)}`,{method:"GET",...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async respondProviderLogin(t,o,r,n){return B(n),k(`/api/pi/providers/${encodeURIComponent(t)}/login/${encodeURIComponent(o)}/respond`,{method:"POST",body:{value:r},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async logoutProvider(t,o){B(o),await k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/logout`,{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getProviderConfig(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t)}/config`,{method:"GET",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setProviderModels(t,o){return B(o),k(`/api/pi/providers/${encodeURIComponent(t.providerId)}/models`,{method:"PUT",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async getSettings(t){return B(t),k("/api/pi/settings",{method:"GET",...t?.runtimeKey?{runtimeKey:t.runtimeKey}:{}})}async setPiSettings(t,o){return B(o),k("/api/pi/settings/pi",{method:"PUT",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async setPiChamberDefaults(t,o){return B(o),k("/api/pi/settings/defaults",{method:"PUT",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listResources(t,o){const r=typeof t=="string"?o:t,n=typeof t=="string"?t:void 0;return B(r),k("/api/pi/resources",{method:"GET",...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async listCommands(t,o){return B(o),k("/api/pi/commands",{method:"GET",...t?{query:{directory:t}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listSnippets(t,o){return B(o),k("/api/pi/snippets",{method:"GET",...t?{query:{directory:t}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async createSnippet(t,o){return B(o),k("/api/pi/snippets",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async updateSnippet(t,o,r,n){return B(n),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"PUT",body:o,...r?{query:{directory:r}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deleteSnippet(t,o,r){return B(r),k(`/api/pi/snippets/${encodeURIComponent(t)}`,{method:"DELETE",...o?{query:{directory:o}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updateResource(t,o){B(o);const r=t.directory??o?.directory;return k(`/api/pi/resources/${encodeURIComponent(t.resourceId)}`,{method:"PUT",body:t,...r?{query:{directory:r}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async createPromptTemplate(t,o,r){const n=o??t.directory??r?.directory;return B(r),k("/api/pi/resources/prompts",{method:"POST",body:t,...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async updatePromptTemplate(t,o,r,n){B(n);const a=r??o.directory??n?.directory;return k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"PUT",body:o,...a?{query:{directory:a}}:{},...n?.runtimeKey?{runtimeKey:n.runtimeKey}:{}})}async deletePromptTemplate(t,o,r){B(r);const n=o??r?.directory;return k(`/api/pi/resources/prompts/${encodeURIComponent(t)}`,{method:"DELETE",...n?{query:{directory:n}}:{},...r?.runtimeKey?{runtimeKey:r.runtimeKey}:{}})}async createAttachment(t,o){return B(o),(await k("/api/pi/attachments",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})).attachment}async uploadAttachment(t,o,r){B(r);const n=await Md("/api/pi/attachments",t,o);if(!n.ok){const s=(await n.json().catch(()=>null))?.error??{code:"ATTACHMENT_FAILED"};throw new te(s.code,s.message,n.status)}const a=await n.json();return B(r),a.attachment}async deleteAttachment(t,o){B(o),await k(`/api/pi/attachments/${encodeURIComponent(t)}`,{method:"DELETE",...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async listExtensions(t,o){return B(o),k("/api/pi/extensions",{method:"GET",...t?{query:{directory:t}}:{},...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}async respondToExtensionDialog(t,o){B(o),await k("/api/pi/extensions/respond",{method:"POST",body:t,...o?.runtimeKey?{runtimeKey:o.runtimeKey}:{}})}}const Ze=new Qd;async function Xd(){try{const e=await h("/api/fs/home",{method:"GET",headers:{Accept:"application/json"}});if(e.ok){const t=await e.json();if(typeof t.home=="string"&&t.home.trim().length>0)return t.home.trim()}}catch{}return null}async function zF(e,t){if(!e||e.trim().length===0)return[];const o={path:e},r=ge().api("/api/fs/list",o),n=await h(r);if(!n.ok)return[];const a=await n.json();return Array.isArray(a.entries)?a.entries:[]}async function Zd(e,t){const o=t?.directory||"";if(!o)return[];const r={directory:o,query:e};t?.limit&&(r.limit=t.limit),t?.includeHidden&&(r.includeHidden=!0),t?.respectGitignore!==void 0&&(r.respectGitignore=t.respectGitignore),t?.type&&(r.type=t.type);const n=ge().api("/api/fs/find",r),a=await h(n);if(!a.ok)return[];const i=await a.json();return Array.isArray(i.files)?i.files:[]}async function $F(e=""){try{const t=await h("/api/fs/pick-directory",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({path:e||void 0})}),o=await t.json().catch(()=>null);return o?.cancelled===!0?{status:"cancelled"}:t.status===501?{status:"unavailable",error:typeof o?.error=="string"?o.error:"Folder picker is not available."}:t.ok?typeof o?.path=="string"&&o.path.trim()?{status:"picked",path:o.path.trim()}:{status:"failed",error:"Failed to select directory."}:{status:"failed",error:typeof o?.error=="string"?o.error:"Failed to select directory."}}catch(t){return{status:"failed",error:t instanceof Error?t.message:"Failed to select directory."}}}const KF={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."}},el=e=>typeof e=="string"&&(e==="explore"||e==="plan"||e==="review"||e==="find-bugs"||e==="write-tests"),qF=[{type:"text",key:"explore"},{type:"text",key:"plan"},{type:"text",key:"review"},{type:"text",key:"find-bugs"},{type:"text",key:"write-tests"}],GF="book-open",tl=/^[^\s/]+$/,na=e=>e.type==="prompt"?`prompt:${e.name}`:`text:${e.key}`,WF=(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,VF=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Mo=e=>{if(!Array.isArray(e))return[];const t=[],o=new Set;for(const r of e){if(!r||typeof r!="object")continue;const n=r;if(n.type==="text"){if(!el(n.key))continue;const d={type:"text",key:n.key},l=na(d);if(o.has(l))continue;o.add(l),t.push(d);continue}if(n.type!=="prompt")continue;const a=typeof n.name=="string"?n.name.trim():"";if(!a||!tl.test(a))continue;const i=n.scope==="global"||n.scope==="project"?n.scope:void 0,s=i?{type:"prompt",name:a,scope:i}:{type:"prompt",name:a},c=na(s);o.has(c)||(o.add(c),t.push(s))}return t},ol=e=>{let t,o=-1;for(const r of e){const a=(r.location==="project"?2:r.location==="global"?1:0)+(r.editable?.5:0);a>o&&(t=r,o=a)}return t},JF=e=>{const t=new Map;for(const r of e){const n=t.get(r.name)??[];n.push(r),t.set(r.name,n)}const o=new Map;for(const[r,n]of t){const a=ol(n);a&&o.set(r,a)}return o},YF=(e,t)=>{const o=new Set,r=i=>i.filter(s=>{const c=s.insertText.trim();return o.has(c)?!1:(o.add(c),!0)}),n=r(e),a=r(t);return{project:n,global:a}},rl={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem",settingsPageTitle:"1.125rem"};function aa(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const so={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)"}}},ir={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...so.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:ir.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...so.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ir.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...so.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ir.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...so.tool.inline})},nl=[{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'}],al=[{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'}],Ei=e=>Object.fromEntries(e.map(t=>[t.id,t])),il=Ei(nl),sl=Ei(al),cl="system",dl="system-mono",wi=e=>typeof e=="string"&&e in il,Bi=e=>typeof e=="string"&&e in sl,sr="pichamber.pwaName",vr="pichamber.mobileKeyboardMode",QF="pichamber.pwaRecentSessions",ll=["native","resize-content"];function ul(e,t="resize-content"){return typeof e=="string"&&ll.includes(e)?e:t}const fl=64;function Ci(e,t){if(typeof e!="string")return t;const o=e.trim().replace(/\s+/g," ");return o?o.slice(0,fl):t}const XF=()=>!0;function gn(e,t="resize-content"){return ul(e,t)??void 0}const ml=()=>{if(typeof window>"u")return"resize-content";try{return gn(localStorage.getItem(vr))}catch{return"resize-content"}},gl=e=>{const t=gn(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(vr):localStorage.setItem(vr,t)}catch{}return t},$=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),o=t.startsWith("//");let r=t.replace(/\/+$/g,"").replace(/\/+/g,"/");return o&&!r.startsWith("//")&&(r=`/${r}`),r||(t.startsWith("/")?"/":"")},le=20,pl=8,ia=4096,hl=2160*60*6e4,R=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),o=t.startsWith("//");let r=t.replace(/\/+/g,"/");o&&!r.startsWith("//")&&(r=`/${r}`);const n=r==="/",a=/^[A-Za-z]:\/$/.test(r);return!n&&!a&&(r=r.replace(/\/+$/,"")),r},Te=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Pe=(e,t)=>{const o=R(t),r=R(e);if(!o||!r)return!1;const n=Te(o),a=Te(r);return a===n||a.startsWith(`${n}/`)},Tt=e=>{if(!e||typeof e!="object")return{};const t=e,o={};for(const[r,n]of Object.entries(t)){const a=R(r);if(!a||!n||typeof n!="object")continue;const i=n,s=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(m=>typeof m=="string").map(m=>R(m)).filter(m=>m.length<=ia&&Pe(m,a)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(m=>typeof m=="string").map(m=>R(m)).filter(m=>m.length<=ia&&Pe(m,a)))).slice(-500):[],d=typeof i.selectedPath=="string"?R(i.selectedPath):null,l=d&&Pe(d,a)?d:s[0]??null,u=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-u>hl)continue;const f=o[a];if(f){const m=Array.from(new Set([...f.openPaths,...s])),p=Array.from(new Set([...f.expandedPaths,...c])),g=f.selectedPath??l??m[0]??null;o[a]={openPaths:m,selectedPath:g,expandedPaths:p,touchedAt:Math.max(f.touchedAt,u)};continue}o[a]={openPaths:s,selectedPath:l,expandedPaths:c,touchedAt:u}}return ue(o,le)},ue=(e,t)=>{const o=Object.entries(e);if(o.length<=t)return e;o.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const r={};for(const[n,a]of o.slice(0,t))r[n]=a;return r},ut=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},Fl=Wt()(Vt(qr((e,t)=>({byRoot:{},activeRuntimeKey:S(),runtimeSnapshots:{},resetForRuntimeSwitch:o=>{e(r=>{const n={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Tt(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:o,runtimeSnapshots:n,byRoot:Tt(n[o]?.byRoot)}})},addOpenPath:(o,r,n)=>{const a=R((o||"").trim()),i=R((r||"").trim());!a||!i||!n?.allowOutsideRoot&&!Pe(i,a)||e(s=>{const c=s.byRoot[a],d=ut(c),l=d.openPaths.includes(i),u=l?d.openPaths:[...d.openPaths,i],f=d.selectedPath??i;if(c&&l&&c.selectedPath===f)return s;const m={...s.byRoot,[a]:{...d,openPaths:u,selectedPath:f}};return{byRoot:ue(m,le)}})},removeOpenPath:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||e(i=>{const s=i.byRoot[n];if(!s)return i;const c=Te(a),d=p=>Te(p)===c,l=s.selectedPath?d(s.selectedPath):!1;if(!s.openPaths.some(d)&&!l)return i;const u=s.openPaths.filter(p=>!d(p)),f=l?u[0]??null:s.selectedPath,m={...i.byRoot,[n]:{...s,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:ue(m,le)}})},removeOpenPathsByPrefix:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||e(i=>{const s=i.byRoot[n];if(!s)return i;const c=Te(a),d=c.endsWith("/")?c:`${c}/`,l=p=>{const g=Te(p);return g===c||g.startsWith(d)},u=s.openPaths.filter(p=>!l(p));if(u.length===s.openPaths.length)return i;const f=s.selectedPath&&l(s.selectedPath)?u[0]??null:s.selectedPath,m={...i.byRoot,[n]:{...s,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:ue(m,le)}})},removeExpandedPathsByPrefix:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||e(i=>{const s=i.byRoot[n];if(!s)return i;const c=Te(a),d=c.endsWith("/")?c:`${c}/`,l=s.expandedPaths.filter(f=>{const m=Te(f);return m!==c&&!m.startsWith(d)});if(l.length===s.expandedPaths.length)return i;const u={...i.byRoot,[n]:{...s,expandedPaths:l,touchedAt:Date.now()}};return{byRoot:ue(u,le)}})},setSelectedPath:(o,r,n)=>{const a=R((o||"").trim()),i=r?R(r.trim()):null;!a||i&&!n?.allowOutsideRoot&&!Pe(i,a)||e(s=>{const c=s.byRoot[a],d=ut(c),l=i&&!d.openPaths.includes(i)?[...d.openPaths,i]:d.openPaths;if(c&&c.selectedPath===i&&l===c.openPaths)return s;const u={...s.byRoot,[a]:{...d,openPaths:l,selectedPath:i}};return{byRoot:ue(u,le)}})},ensureSelectedPath:o=>{const r=R((o||"").trim());if(!r)return;const n=t().byRoot[r];if(!n||n.selectedPath)return;const a=n.openPaths[0]??null;a&&t().setSelectedPath(r,a)},toggleExpandedPath:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||!Pe(a,n)||e(i=>{const s=i.byRoot[n],c=ut(s),l=c.expandedPaths.includes(a)?c.expandedPaths.filter(f=>f!==a):[...c.expandedPaths,a];if(s&&s.expandedPaths===l&&s.selectedPath===c.selectedPath&&s.openPaths===c.openPaths)return i;const u={...i.byRoot,[n]:{...c,expandedPaths:l}};return{byRoot:ue(u,le)}})},collapseAllExpandedPaths:o=>{const r=R((o||"").trim());r&&e(n=>{const a=n.byRoot[r];if(!a||a.expandedPaths.length===0)return n;const i={...n.byRoot,[r]:{...ut(a),expandedPaths:[]}};return{byRoot:ue(i,le)}})},expandPath:(o,r)=>{const n=R((o||"").trim()),a=R((r||"").trim());!n||!a||!Pe(a,n)||e(i=>{const s=i.byRoot[n],c=ut(s);if(c.expandedPaths.includes(a)&&s)return i;const l={...i.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,a]}};return{byRoot:ue(l,le)}})},expandPaths:(o,r)=>{const n=R((o||"").trim());if(!n||!r||r.length===0)return;const a=r.map(i=>R((i||"").trim())).filter(i=>i&&Pe(i,n));a.length!==0&&e(i=>{const s=i.byRoot[n],c=ut(s),d=new Set(c.expandedPaths),l=a.filter(f=>!d.has(f));if(l.length===0)return i;const u={...i.byRoot,[n]:{...c,expandedPaths:[...c.expandedPaths,...l]}};return{byRoot:ue(u,le)}})}}),{name:"files-view-tabs-store",version:3,storage:rn(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:S(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Tt(e.byRoot),updatedAt:Date.now()}},o=Object.fromEntries(Object.entries(t).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,pl).map(([r,n])=>[r,{byRoot:Tt(n.byRoot),updatedAt:n.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:o}},merge:(e,t)=>{const o=e&&typeof e=="object"?e:{},r=o.runtimeSnapshots&&typeof o.runtimeSnapshots=="object"?o.runtimeSnapshots:{},n=S();return{...t,activeRuntimeKey:n,runtimeSnapshots:r,byRoot:Tt(r[n]?.byRoot)}}}),{name:"files-view-tabs-store"})),yl=380,bl=380,Al=1400,ki=12,sa=120,El=["git","file","diff","context","terminal","browser","preview"],ZF=$,yo=e=>Number.isFinite(e)?Math.min(Al,Math.max(bl,Math.round(e))):yl,wl=e=>{if(typeof e.width=="number"&&Number.isFinite(e.width))return yo(e.width);if(!e.widthByMode||typeof e.widthByMode!="object")return;const t=e.widthByMode;for(const o of El){const r=t[o];if(typeof r=="number"&&Number.isFinite(r))return yo(r)}for(const o of Object.values(t))if(typeof o=="number"&&Number.isFinite(o))return yo(o)},To=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Ro=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>sa?t.slice(0,sa):t:null},pn=e=>e==="all"||e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,Bl=(e,t)=>(e==="file"||e==="preview")&&t||e,vi=(e,t,o)=>{if(e==="diff")return e;if(typeof o=="string"){const r=o.trim();if(r)return r}return Bl(e,t)},Di=(e,t)=>t===e?e:`${e}:${t}`,hn=e=>{const t=To(e.targetPath),o=vi(e.mode,t,e.dedupeKey);return{id:Di(e.mode,o),mode:e.mode,targetPath:t,dedupeKey:o,label:Ro(e.label),sessionTitleFallback:Ro(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:pn(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Si=(e,t,o)=>{if(e.length<=t)return e;const n=[...e].sort((s,c)=>s.touchedAt-c.touchedAt).filter(s=>s.id!==o),a=e.length-t;if(a<=0||n.length===0)return e.slice(-t);const i=new Set(n.slice(0,a).map(s=>s.id));return e.filter(s=>!i.has(s.id))},Mi=e=>{if(!Array.isArray(e))return[];const t=[],o=new Set;for(const r of e){if(!r||typeof r!="object")continue;const n=r;if(n.mode!=="diff"&&n.mode!=="file"&&n.mode!=="context"&&n.mode!=="preview"&&n.mode!=="browser"&&n.mode!=="git"&&n.mode!=="terminal")continue;const a=To(typeof n.targetPath=="string"?n.targetPath:null),i=vi(n.mode,a,typeof n.dedupeKey=="string"?n.dedupeKey:null),s=Di(n.mode,i);!s||o.has(s)||(o.add(s),t.push({id:s,mode:n.mode,targetPath:a,dedupeKey:i,label:Ro(typeof n.label=="string"?n.label:null),sessionTitleFallback:Ro(typeof n.sessionTitleFallback=="string"?n.sessionTitleFallback:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,diffScope:pn(n.diffScope)??(n.stagedDiff===!0?"staged":"working"),touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()}))}return t},wt=(e,t)=>t&&e.some(o=>o.id===t)?t:e.length===0?null:e[e.length-1].id,We=e=>{if(e){const t=Mi(e.tabs),o=wt(t,e.activeTabId);return{...e,tabs:t,activeTabId:o,width:e.width,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,touchedAt:Date.now()}},Cl=(e,t)=>{const o=hn(t),r=o.mode==="file"&&o.targetPath?e.tabs.filter(c=>!(c.mode==="file"&&!c.targetPath)):e.tabs,n=r.findIndex(c=>c.id===o.id),a=n===-1?[...r,o]:r.map((c,d)=>d===n?{...c,mode:o.mode,targetPath:o.targetPath||c.targetPath,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||c.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:c),i=o.id,s=Si(a,ki,i);return{...e,isOpen:!0,tabs:s,activeTabId:wt(s,i),touchedAt:Date.now()}},kl=(e,t)=>{const o=e.tabs.find(i=>i.id===t)??null,r=e.tabs.filter(i=>i.id!==t);if(e.activeTabId!==t)return{...e,tabs:r,activeTabId:wt(r,e.activeTabId),isOpen:r.length>0?e.isOpen:!1,touchedAt:Date.now()};const n=o?r.filter(i=>i.mode===o.mode):[],a=n.length>0?n.reduce((i,s)=>s.touchedAt>=i.touchedAt?s:i):null;return{...e,tabs:r,activeTabId:a?.id??wt(r,null),isOpen:a?e.isOpen:!1,touchedAt:Date.now()}},vl=(e,t,o)=>{if(t===o)return e;const r=e.tabs.findIndex(s=>s.id===t),n=e.tabs.findIndex(s=>s.id===o);if(r===-1||n===-1)return e;const a=[...e.tabs],[i]=a.splice(r,1);return i?(a.splice(n,0,i),{...e,tabs:a,touchedAt:Date.now()}):e},Dl=(e,t,o)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:o}:r)}),Sl=e=>{const t=[];let o=!1;for(const r of e){if(r.mode!=="diff"&&r.mode!=="git"){t.push(r);continue}o||(o=!0,t.push(r.mode==="git"?r:hn({mode:"git"})))}return t},De=e=>{if(!e||typeof e!="object")return{};const t=e,o={};for(const[r,n]of Object.entries(t)){const a=$(r);if(!a||!n||typeof n!="object")continue;const i=n;let s=Sl(Mi(i.tabs)),c=typeof i.activeTabId=="string"?i.activeTabId:null;s.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context")&&(s=[hn({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=s[0]?.id??null);const d=wt(s,c),l=Si(s,ki,d),u=wl(i);o[a]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:l,activeTabId:wt(l,d),...u!==void 0?{width:u}:{},touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return o},Ve=(e,t)=>{const o=Object.entries(e);if(o.length<=t)return e;o.sort((n,a)=>(a[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const r={};for(const[n,a]of o.slice(0,t))r[n]=a;return r};function ca(e){return e==="vim"?"vim":"default"}const co={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},Se={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},lo=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,Ml=e=>{if(!e||typeof e!="object")return!1;const t=e;return lo(t.completion,co.completion)&&lo(t.error,co.error)&&lo(t.question,co.question)&&lo(t.subtask,co.subtask)},Rt=280,cr=new Map,dr=e=>(e??S()).trim()||"default",Q=Wt()(Vt(qr((e,t)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:Rt,hasManuallyResizedLeftSidebar:!1,contextPanelByDirectory:{},contextRailOrder:[],contextEditorTreeVisible:!0,contextEditorTreeWidth:240,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,showReasoningTraces:!0,collapsibleThinkingBlocks:!0,collapseThinkingByDefault:!1,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:cl,monoFont:dl,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:ml(),favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,inputSpellcheckEnabled:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,expandedEditorToolbar:!1,showSplitAssistantMessageActions:!1,draftStartersVisible:!0,isExpandedInput:!1,shortcutOverrides:{},commandTriggers:[],fileEditorKeymap:"default",setTheme:o=>{e({theme:o}),t().applyTheme()},toggleSidebar:()=>{e(o=>{const r=!o.isSidebarOpen;return r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:Rt}:{isSidebarOpen:r}})},setSidebarOpen:o=>{e(r=>r.isSidebarOpen===o?o&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==Rt?{isSidebarOpen:o,sidebarWidth:Rt}:r:o&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:o,sidebarWidth:Rt}:{isSidebarOpen:o})},setSidebarWidth:o=>{e({sidebarWidth:o,hasManuallyResizedLeftSidebar:!0})},setContextRailOrder:o=>{const r=Array.isArray(o)?o.filter((n,a)=>typeof n=="string"&&n.trim()!==""&&o.indexOf(n)===a):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(o=>({contextEditorTreeVisible:!o.contextEditorTreeVisible}))},setContextEditorTreeWidth:o=>{Number.isFinite(o)&&e({contextEditorTreeWidth:Math.min(480,Math.max(200,Math.round(o)))})},openContextSurface:(o,r)=>{const n=r==="diff"?"git":r,a=$((o||"").trim());if(!a)return;const i=t(),s=i.contextPanelByDirectory[a],c=s?.tabs??[],d=c.find(u=>u.id===s?.activeTabId)??null;if(s?.isOpen&&d?.mode===n){i.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);i.setActiveContextPanelTab(a,u.id);return}n!=="preview"&&i.openContextPanelTab(a,{mode:n})},openContextPanelTab:(o,r)=>{const n=$((o||"").trim());n&&e(a=>{const i=a.contextPanelByDirectory[n],s=We(i),c={...a.contextPanelByDirectory,[n]:Cl(s,r)};return{contextPanelByDirectory:Ve(c,20)}})},openContextDiff:(o,r,n=!1,a=null)=>{const i=$((o||"").trim()),s=(r||"").trim();if(!i||!s)return;const c=pn(a)??(n?"staged":"working");t().setPendingDiffFile(s,n,c),t().openContextPanelTab(i,{mode:"git"})},openContextFile:(o,r)=>{const n=$((o||"").trim()),a=To(r);!n||!a||(t().openContextPanelTab(n,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(a),t().setPendingFileNavigation(null))},openContextFileAtLine:(o,r,n,a)=>{const i=$((o||"").trim()),s=To(r),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,d=Number.isFinite(a)?Math.max(1,Math.trunc(a)):1;!i||!s||(t().openContextPanelTab(i,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:s,line:c,column:d}))},openContextOverview:o=>{const r=$((o||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(o,r)=>{const n=$((o||"").trim()),a=(r||"").trim();if(!n||!a)return;let i=null;try{const s=new URL(a);(s.protocol==="http:"||s.protocol==="https:")&&(i=s.host||s.hostname||"Preview")}catch{}t().openContextPanelTab(n,{mode:"preview",targetPath:a,dedupeKey:a,label:i})},openContextBrowser:(o,r="")=>{const n=$((o||"").trim());if(!n)return;const a=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(n,{mode:"browser",targetPath:a,dedupeKey:"desktop-browser",label:"Browser"})},setContextPanelTabTargetPath:(o,r,n)=>{const a=$((o||"").trim()),i=(r||"").trim();!a||!i||e(s=>{const c=s.contextPanelByDirectory[a];return c?{contextPanelByDirectory:{...s.contextPanelByDirectory,[a]:Dl(c,i,n)}}:s})},setActiveContextPanelTab:(o,r)=>{const n=$((o||"").trim()),a=(r||"").trim();!n||!a||e(i=>{const s=i.contextPanelByDirectory[n],c=We(s);if(!c.tabs.some(l=>l.id===a)||c.activeTabId===a&&c.isOpen)return i;const d={...i.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:Ve(d,20)}})},reorderContextPanelTabs:(o,r,n)=>{const a=$((o||"").trim()),i=(r||"").trim(),s=(n||"").trim();!a||!i||!s||e(c=>{const d=c.contextPanelByDirectory[a],l=We(d);if(!l.tabs.some(m=>m.id===i)||!l.tabs.some(m=>m.id===s))return c;const u=vl(l,i,s);if(u.tabs===l.tabs)return c;const f={...c.contextPanelByDirectory,[a]:u};return{contextPanelByDirectory:Ve(f,20)}})},closeContextPanelTab:(o,r)=>{const n=$((o||"").trim()),a=(r||"").trim();if(!n||!a)return;const i=t().contextPanelByDirectory[n]?.tabs.find(s=>s.id===a);e(s=>{const c=s.contextPanelByDirectory[n],d=We(c);if(!d.tabs.some(u=>u.id===a))return s;const l={...s.contextPanelByDirectory,[n]:kl(d,a)};return{contextPanelByDirectory:Ve(l,20)}}),i?.mode==="file"&&i.targetPath&&Fl.getState().removeOpenPath(n,i.targetPath)},closeContextPanel:o=>{const r=$((o||"").trim());r&&e(n=>{const a=n.contextPanelByDirectory[r];if(!a||!a.isOpen)return n;const i={...n.contextPanelByDirectory,[r]:{...We(a),isOpen:!1}};return{contextPanelByDirectory:Ve(i,20)}})},toggleContextPanelExpanded:o=>{const r=$((o||"").trim());r&&e(n=>{const a=n.contextPanelByDirectory[r],i=We(a),s={...n.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Ve(s,20)}})},setContextPanelWidth:(o,r)=>{const n=$((o||"").trim());n&&e(a=>{const i=a.contextPanelByDirectory[n],s=We(i),c={...a.contextPanelByDirectory,[n]:{...s,width:yo(r)}};return{contextPanelByDirectory:Ve(c,20)}})},setSessionSwitcherOpen:o=>{t().isSessionSwitcherOpen!==o&&e({isSessionSwitcherOpen:o})},setSessionDropdownOpen:o=>{t().isSessionDropdownOpen!==o&&e({isSessionDropdownOpen:o})},setMainTabGuard:o=>{t().mainTabGuard!==o&&e({mainTabGuard:o})},setActiveMainTab:o=>{const r=t().mainTabGuard;r&&!r(o)||(cr.set(dr(),o),e({activeMainTab:o}))},prepareForRuntimeSwitch:o=>{cr.set(dr(o),t().activeMainTab)},restoreForRuntimeSwitch:o=>{const r=cr.get(dr(o))??"chat";e({activeMainTab:r})},setPendingDiffFile:(o,r=!1,n=null)=>{e({pendingDiffFile:o,pendingDiffStaged:o?r:!1,pendingDiffScope:o?n:null})},setPendingDiagramFile:o=>{e({pendingDiagramFile:o})},setPendingFileNavigation:o=>{e({pendingFileNavigation:o})},setPendingFileFocusPath:o=>{e({pendingFileFocusPath:o})},navigateToDiff:(o,r=!1,n=null)=>{const a=t().mainTabGuard;a&&!a("diff")||e({pendingDiffFile:o,pendingDiffStaged:r,pendingDiffScope:n,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:o}=t();return o&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),o},navigateToDiagram:o=>{const r=t().mainTabGuard;r&&!r("diagram")||e({pendingDiagramFile:o,activeMainTab:"diagram"})},consumePendingDiagramFile:()=>{const{pendingDiagramFile:o}=t();return o&&e({pendingDiagramFile:null}),o},setIsMobile:o=>{e({isMobile:o})},toggleCommandPalette:()=>{e(o=>({isCommandPaletteOpen:!o.isCommandPaletteOpen}))},setCommandPaletteOpen:o=>{e({isCommandPaletteOpen:o})},toggleHelpDialog:()=>{e(o=>({isHelpDialogOpen:!o.isHelpDialogOpen}))},setHelpDialogOpen:o=>{e({isHelpDialogOpen:o})},setSessionCreateDialogOpen:o=>{e({isSessionCreateDialogOpen:o})},setArchivePageOpen:o=>{e({isArchivePageOpen:o})},closeMainSurfaces:()=>{t().isArchivePageOpen&&e({isArchivePageOpen:!1})},setSettingsDialogOpen:o=>{e(r=>o?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setModelSelectorOpen:o=>{e({isModelSelectorOpen:o})},setSidebarSection:o=>{e({sidebarSection:o})},setSettingsPage:o=>{e({settingsPage:o})},setSettingsProjectsSelectedId:o=>{e({settingsProjectsSelectedId:o})},setSettingsRemoteInstancesSelectedId:o=>{e({settingsRemoteInstancesSelectedId:o})},setEventStreamStatus:(o,r)=>{e({eventStreamStatus:o,eventStreamHint:r??null})},setShowReasoningTraces:o=>{e({showReasoningTraces:o})},setCollapsibleThinkingBlocks:o=>{e({collapsibleThinkingBlocks:o})},setCollapseThinkingByDefault:o=>{e({collapseThinkingByDefault:o})},setShowDeletionDialog:o=>{e({showDeletionDialog:o})},setAutoDeleteEnabled:o=>{e({autoDeleteEnabled:o})},setAutoSaveEnabled:o=>{e({autoSaveEnabled:o})},setAutoDeleteAfterDays:o=>{const r=Math.max(1,Math.min(365,o));e({autoDeleteAfterDays:r})},setSessionRetentionAction:o=>{e({sessionRetentionAction:o})},setAutoDeleteLastRunAt:o=>{e({autoDeleteLastRunAt:o})},setMessageLimit:o=>{const r=Math.max(10,Math.min(500,Math.round(o)));e({messageLimit:r})},setFontSize:o=>{const r=Math.max(50,Math.min(200,o));e({fontSize:r}),t().applyTypography()},setGlobalDraftStarters:o=>{e({globalDraftStarters:o})},setDraftStartersVisible:o=>{e({draftStartersVisible:o})},setTerminalFontSize:o=>{const r=Math.round(o),n=Math.max(9,Math.min(52,r));e({terminalFontSize:n})},setTerminalShell:o=>{e({terminalShell:o})},setTerminalLoginShells:o=>{e({terminalLoginShells:[...new Set(o)]})},setEditorFontSize:o=>{const r=Math.round(o),n=Math.max(9,Math.min(32,r));e({editorFontSize:n})},setUiFont:o=>{e({uiFont:o})},setMonoFont:o=>{e({monoFont:o})},setPadding:o=>{const r=Math.max(50,Math.min(200,o));e({padding:r}),t().applyPadding()},setCornerRadius:o=>{e({cornerRadius:o})},applyTypography:()=>{const{fontSize:o}=t(),r=document.documentElement,n=o/100,a=Object.entries(rl);if(n===1){for(const[i]of a)r.style.removeProperty(aa(i));return}for(const[i,s]of a){const c=parseFloat(s);Number.isFinite(c)&&r.style.setProperty(aa(i),`${c*n}rem`)}},applyPadding:()=>{const{padding:o}=t(),r=document.documentElement,n=o/100;if(n===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(n);r.style.setProperty("--padding-scale",a.toString());const i=1+(n-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:o=>{e({diffLayoutPreference:o})},setDiffFileLayout:(o,r)=>{e(n=>({diffFileLayout:{...n.diffFileLayout,[o]:r}}))},setDiffWrapLines:o=>{e({diffWrapLines:o})},setWalkthroughTocWidth:o=>{e({walkthroughTocWidth:Math.round(o)})},setGitChangesViewMode:o=>{e({gitChangesViewMode:o})},setInputBarOffset:o=>{e({inputBarOffset:o})},setMobileKeyboardMode:o=>{e(r=>r.mobileKeyboardMode===o?r:{mobileKeyboardMode:o})},toggleFavoriteModel:(o,r)=>{e(n=>n.favoriteModels.some(i=>i.providerID===o&&i.modelID===r)?{favoriteModels:n.favoriteModels.filter(i=>!(i.providerID===o&&i.modelID===r))}:{favoriteModels:[{providerID:o,modelID:r},...n.favoriteModels]})},reorderFavoriteModel:(o,r,n,a)=>{e(i=>{const s=i.favoriteModels.findIndex(u=>u.providerID===o&&u.modelID===r),c=i.favoriteModels.findIndex(u=>u.providerID===n&&u.modelID===a);if(s===-1||c===-1||s===c)return i;const d=i.favoriteModels.slice(),[l]=d.splice(s,1);return l?(d.splice(c,0,l),{favoriteModels:d}):i})},toggleHiddenModel:(o,r)=>{e(n=>n.hiddenModels.some(i=>i.providerID===o&&i.modelID===r)?{hiddenModels:n.hiddenModels.filter(i=>!(i.providerID===o&&i.modelID===r))}:{hiddenModels:[{providerID:o,modelID:r},...n.hiddenModels]})},isHiddenModel:(o,r)=>{const{hiddenModels:n}=t();return n.some(a=>a.providerID===o&&a.modelID===r)},hideAllModels:(o,r)=>{e(n=>{const a=n.hiddenModels.filter(s=>s.providerID!==o);return{hiddenModels:[...[...new Set(r.filter(s=>typeof s=="string"&&s.length>0))].map(s=>({providerID:o,modelID:s})),...a]}})},showAllModels:o=>{e(r=>({hiddenModels:r.hiddenModels.filter(n=>n.providerID!==o)}))},toggleModelProviderCollapsed:o=>{const r=typeof o=="string"?o.trim():"";r&&e(n=>n.collapsedModelProviders.includes(r)?{collapsedModelProviders:n.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...n.collapsedModelProviders,r]})},setModelProvidersCollapsed:(o,r)=>{const n=Array.from(new Set(o.filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean)));n.length!==0&&e(a=>{const i=new Set(n),s=a.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...s,...n]:s}})},isFavoriteModel:(o,r)=>{const{favoriteModels:n}=t();return n.some(a=>a.providerID===o&&a.modelID===r)},addRecentModel:(o,r)=>{e(n=>{const a=n.recentModels.filter(i=>!(i.providerID===o&&i.modelID===r));return{recentModels:[{providerID:o,modelID:r},...a].slice(0,5)}})},addRecentAgent:o=>{const r=typeof o=="string"?o.trim():"";r&&e(n=>{if(n.recentAgents.includes(r))return n;const a=n.recentAgents;return{recentAgents:[r,...a].slice(0,5)}})},addRecentEffort:(o,r,n)=>{const a=typeof o=="string"?o.trim():"",i=typeof r=="string"?r.trim():"";if(!a||!i)return;const s=`${a}/${i}`,c=typeof n=="string"&&n.trim().length>0?n.trim():"default";e(d=>{const l=d.recentEfforts[s]??[];if(l.includes(c))return d;const u=l;return{recentEfforts:{...d.recentEfforts,[s]:[c,...u].slice(0,5)}}})},applyTheme:()=>{const{theme:o}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),o==="system"){const n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(n)}else r.classList.add(o)},setTimelineDialogOpen:o=>{e({isTimelineDialogOpen:o})},setPromptNavigatorPanelOpen:o=>{e({isPromptNavigatorPanelOpen:o})},togglePromptNavigatorPanel:()=>{e(o=>({isPromptNavigatorPanelOpen:!o.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:o=>{e({isImagePreviewOpen:o})},setNativeNotificationsEnabled:o=>{e({nativeNotificationsEnabled:o})},setNotificationMode:o=>{e({notificationMode:o})},setShowTerminalQuickKeysOnDesktop:o=>{e({showTerminalQuickKeysOnDesktop:o})},setNotifyOnSubtasks:o=>{e({notifyOnSubtasks:o})},setDockBadgeEnabled:o=>{e({dockBadgeEnabled:o})},setNotifyOnCompletion:o=>{e({notifyOnCompletion:o})},setNotifyOnError:o=>{e({notifyOnError:o})},setNotifyOnQuestion:o=>{e({notifyOnQuestion:o})},setNotificationTemplates:o=>{e(r=>({notificationTemplates:typeof o=="function"?o(r.notificationTemplates):o}))},setSummarizeLastMessage:o=>{e({summarizeLastMessage:o})},setSummaryThreshold:o=>{e({summaryThreshold:o})},setSummaryLength:o=>{e({summaryLength:o})},setMaxLastMessageLength:o=>{e({maxLastMessageLength:o})},setPersistChatDraft:o=>{e({persistChatDraft:o})},setInputSpellcheckEnabled:o=>{e({inputSpellcheckEnabled:o})},setWideChatLayoutEnabled:o=>{e({wideChatLayoutEnabled:o})},setCodeBlockLineWrap:o=>{e({codeBlockLineWrap:o})},setShowToolFileIcons:o=>{e({showToolFileIcons:o})},setShowTurnChangedFiles:o=>{e({showTurnChangedFiles:o})},setShowExpandedBashTools:o=>{e({showExpandedBashTools:o})},setShowExpandedEditTools:o=>{e({showExpandedEditTools:o})},setTimeFormatPreference:o=>{e({timeFormatPreference:o})},setWeekStartPreference:o=>{e({weekStartPreference:o})},setDesktopWindowControlsPosition:o=>{e({desktopWindowControlsPosition:o==="left"?"left":"right"})},setDesktopWindowControlsStyle:o=>{e({desktopWindowControlsStyle:o==="traffic-lights"?"traffic-lights":"classic"})},setMermaidRenderingMode:o=>{e({mermaidRenderingMode:o})},setUserMessageRenderingMode:o=>{e({userMessageRenderingMode:o})},setCollapsibleUserMessages:o=>{e({collapsibleUserMessages:o})},setStickyUserHeader:o=>{e({stickyUserHeader:o})},setPromptNavigatorEnabled:o=>{e({promptNavigatorEnabled:o})},setExpandedEditorToolbar:o=>{e({expandedEditorToolbar:o})},setShowSplitAssistantMessageActions:o=>{e({showSplitAssistantMessageActions:o})},viewPagerPage:"center",setViewPagerPage:o=>{e({viewPagerPage:o}),e({isSessionSwitcherOpen:o==="left"})},setShortcutOverride:(o,r)=>{e(n=>({shortcutOverrides:{...n.shortcutOverrides,[o]:r}}))},clearShortcutOverride:o=>{e(r=>{const n={...r.shortcutOverrides};return delete n[o],{shortcutOverrides:n}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:o=>{e({fileEditorKeymap:ca(o)})},toggleExpandedInput:()=>{e(o=>({isExpandedInput:!o.isExpandedInput}))},setExpandedInput:o=>{e({isExpandedInput:o})}}),{name:"ui-store",storage:rn(),version:18,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const o=e;if(t<18&&(delete o.notesPanelHeight,delete o.todoPanelHeight,o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="notes"))),t<17&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="chat"))),t<16&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="chat"))),t<15&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="pr"))),t<14&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory),Array.isArray(o.contextRailOrder)&&(o.contextRailOrder=o.contextRailOrder.filter(r=>r!=="diff"))),t<13&&typeof o.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const n=localStorage.getItem("pichamber:files:auto-save-enabled");n!==null&&(r=n!=="false",localStorage.removeItem("pichamber:files:auto-save-enabled"))}}catch{r=!0}o.autoSaveEnabled=r}if(t<12&&(o.desktopWindowControlsPosition==="auto"||o.desktopWindowControlsPosition==null)&&(o.desktopWindowControlsPosition="right"),t<11&&o.terminalFontSize===13&&(o.terminalFontSize=14),t<10&&delete o.diffViewMode,t<9&&((typeof o.notesPanelHeight!="number"||!Number.isFinite(o.notesPanelHeight))&&(o.notesPanelHeight=112),(typeof o.todoPanelHeight!="number"||!Number.isFinite(o.todoPanelHeight))&&(o.todoPanelHeight=259)),t<1&&Ml(o.notificationTemplates)&&(o.notificationTemplates={completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}}),t<3){const r=new Set([90,120,180,220]),n=o.memoryLimitHistorical,a=o.memoryLimitActiveSession;typeof n=="number"&&!r.has(n)?o.messageLimit=n:typeof a=="number"&&!r.has(a)&&(o.messageLimit=a),delete o.memoryLimitHistorical,delete o.memoryLimitViewport,delete o.memoryLimitActiveSession}if(delete o.isRightSidebarOpen,delete o.rightSidebarWidth,delete o.rightSidebarTab,delete o.workStatusExpandedSections,delete o.workStatusScrollTop,delete o.workStatusPanelEnabled,delete o.workStatusHiddenSections,o.contextPanelByDirectory=De(o.contextPanelByDirectory),t<5)if(!o.shortcutOverrides||typeof o.shortcutOverrides!="object")o.shortcutOverrides={};else{const r=o.shortcutOverrides,n={};for(const[a,i]of Object.entries(r))typeof a=="string"&&typeof i=="string"&&(n[a]=i);o.shortcutOverrides=n}return t<6&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory)),t<7&&(o.contextPanelByDirectory=De(o.contextPanelByDirectory)),t<8&&o.gitChangesViewMode!=="flat"&&o.gitChangesViewMode!=="tree"&&(o.gitChangesViewMode="flat"),o.fileEditorKeymap=ca(o.fileEditorKeymap),typeof o.autoSaveEnabled!="boolean"&&(o.autoSaveEnabled=!0),o.contextRailOrder=Array.isArray(o.contextRailOrder)?o.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""&&r!=="pr"&&r!=="diff"&&r!=="chat"&&r!=="notes"):[],o},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,isSessionSwitcherOpen:e.isSessionSwitcherOpen,activeMainTab:e.activeMainTab,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,collapseThinkingByDefault:e.collapseThinkingByDefault,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,diffWrapLines:e.diffWrapLines,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,inputSpellcheckEnabled:e.inputSpellcheckEnabled,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,expandedEditorToolbar:e.expandedEditorToolbar,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Tl=e=>{if(!e||typeof e!="object")return null;const t={};return typeof e.showReasoningTraces=="boolean"&&(t.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&(t.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),typeof e.collapseThinkingByDefault=="boolean"&&(t.collapseThinkingByDefault=e.collapseThinkingByDefault),Object.keys(t).length>0?t:null},Rl=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,collapseThinkingByDefault:t.collapseThinkingByDefault}},Pl=e=>{const t=Q.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.collapseThinkingByDefault=="boolean"&&t.setCollapseThinkingByDefault(e.collapseThinkingByDefault)},Il=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),o=Rl(t);return Tl(o)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}};let da="idle";const xl=new Set;let uo=null;const fe=e=>{uo&&(clearTimeout(uo),uo=null);const t=e==="saved"?"idle":e;t!==da&&(da=t,xl.forEach(o=>o())),t==="error"&&(uo=setTimeout(()=>fe("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("pichamber:settings-save-state",{detail:e}))},e0=e=>{fe(e)},_l=e=>{if(!(typeof window>"u")&&!(typeof window.__PICHAMBER_HOME__=="string"&&window.__PICHAMBER_HOME__.length>0))try{window.__PICHAMBER_HOME__=e}catch{}},la="pichamber.settingsMirror.v2.index",Ol="pichamber.settingsMirror.v2:",Nl=5,ua=e=>`${Ol}${encodeURIComponent(e)}`,Je=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},Ll=(e,t)=>{const o={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,gitmojiEnabled:e.gitmojiEnabled,directoryShowHidden:e.directoryShowHidden,filesViewShowGitignored:e.filesViewShowGitignored,openInAppId:e.openInAppId,pwaAppName:e.pwaAppName,mobileKeyboardMode:e.mobileKeyboardMode};localStorage.setItem(ua(t),JSON.stringify(o));let r=[];try{const a=JSON.parse(localStorage.getItem(la)??"[]");Array.isArray(a)&&(r=a.filter(i=>typeof i=="string"))}catch{r=[]}const n=[t,...r.filter(a=>a!==t)].slice(0,Nl);for(const a of r)n.includes(a)||localStorage.removeItem(ua(a));localStorage.setItem(la,JSON.stringify(n))},Ul=e=>{if(!(typeof window>"u")){if(Ll(e,S()),Je("selectedThemeId",e.themeId||null),Je("selectedThemeVariant",e.themeVariant||null),Je("lightThemeId",e.lightThemeId||null),Je("darkThemeId",e.darkThemeId||null),Je("useSystemTheme",typeof e.useSystemTheme=="boolean"?String(e.useSystemTheme):null),Je("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),_l(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(o=>o.sidebarCollapsed===!0).map(o=>o.id).filter(o=>typeof o=="string"&&o.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(e.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof e.directoryShowHidden=="boolean"?localStorage.setItem("directoryTreeShowHidden",e.directoryShowHidden?"true":"false"):localStorage.removeItem("directoryTreeShowHidden"),typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),Je("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=Ci(e.pwaAppName,"");t.length>0?localStorage.setItem(sr,t):localStorage.removeItem(sr)}else localStorage.removeItem(sr);gl(e.mobileKeyboardMode)}},Dr=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("pichamber:settings-synced",{detail:e}))},Hl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const o=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,a)=>a.toUpperCase()+":");return o==="/"?"/":(o.length>1?o.replace(/\/+$/,""):o)||null},Fn="queue",yn=e=>e==="steer"||e==="queue",bn=(e,t)=>e==="immediate"?"steer":yn(e)?e:t===!1?"steer":t===!0?"queue":Fn,fa=50,lr=20,fo=(e,t)=>{if(e.runtimeKey!==S())return;const o=t.flatMap(r=>(r.attachments??[]).flatMap(n=>n.uploadState?.status==="ready"?[n.uploadState.attachmentId]:[]));for(const r of new Set(o))Ze.deleteAttachment(r,{runtimeKey:e.runtimeKey}).catch(()=>{})},jl=(e,t,o=S())=>{const r=Hl(t);return!o||!r||!e?null:{runtimeKey:o,directory:r,sessionId:e}},ye=e=>`${e.runtimeKey}
5
5
  ${e.directory}
6
6
  ${e.sessionId}`,zl=e=>{const[t,o,...r]=e.split(`
7
7
  `);return jl(r.join(`