@openchamber/web 2.7.2 → 2.7.3-canary.20261115.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AboutDialog-l-zrh7nU.js → AboutDialog-gL1x0YFW.js} +1 -1
- package/dist/assets/{AboutLogo-K3wdJM69.js → AboutLogo-cbKkZDLU.js} +1 -1
- package/dist/assets/{ArchiveView-DjRZQdOo.js → ArchiveView-0QjF07oK.js} +1 -1
- package/dist/assets/{ChangeRequestDiffUnavailable-BtH6Ad8g.js → ChangeRequestDiffUnavailable-kfarKKvU.js} +1 -1
- package/dist/assets/{CommandPalette-C7Uc4nDE.js → CommandPalette-D4bXVkJf.js} +1 -1
- package/dist/assets/{DataFileArtifact-DtnZXuug.js → DataFileArtifact-DWC11mPC.js} +1 -1
- package/dist/assets/{DiffView-CS0gR_am.js → DiffView-CSSPNDYJ.js} +1 -1
- package/dist/assets/{FilesView-tcU8_bnh.js → FilesView-D0FOaLpo.js} +3 -3
- package/dist/assets/{GitView-Ccs7O5Rf.js → GitView-CJl97ZjN.js} +1 -1
- package/dist/assets/{GuestPanelContent-CJ_wlnNr.js → GuestPanelContent-BCxvKv4H.js} +1 -1
- package/dist/assets/{HelpDialog-iH44R9qu.js → HelpDialog-DjficTGt.js} +1 -1
- package/dist/assets/{IntegrationsCatalogView-D9icTaJt.js → IntegrationsCatalogView-BvS1pCRR.js} +1 -1
- package/dist/assets/{JsonTreeView-BjPbJlHc.js → JsonTreeView-DQ6XLAW4.js} +1 -1
- package/dist/assets/{MarkdownDiffPreview-gCh_8R1F.js → MarkdownDiffPreview-C8KpNQaC.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-fohUB8r2.js → MarkdownRendererImpl-B1SjhV-G.js} +4 -4
- package/dist/assets/{MemoryDebugPanel-fX9cD8th.js → MemoryDebugPanel-BWT5owg7.js} +1 -1
- package/dist/assets/{NoteEditor-CTPSChrc.js → NoteEditor-DfHpXxIN.js} +1 -1
- package/dist/assets/{OfficeArtifact-BRviGdkx.js → OfficeArtifact-BAYHzDft.js} +2 -2
- package/dist/assets/{OfficeDocumentDiff-Hp2baXgN.js → OfficeDocumentDiff-Csvxzve7.js} +1 -1
- package/dist/assets/{OnboardingScreen-CDhZHMEt.js → OnboardingScreen-NWWMu7OG.js} +1 -1
- package/dist/assets/{OpenCodeStatusDialog-CBiLhgh9.js → OpenCodeStatusDialog-DtnVfNI4.js} +1 -1
- package/dist/assets/{OverviewView-DmNAg498.js → OverviewView-BXMN0Z8_.js} +1 -1
- package/dist/assets/{PatchDiff-rhuT-3au.js → PatchDiff-DxGkHtIk.js} +1 -1
- package/dist/assets/{PlanView-VhIl4wzm.js → PlanView-DE4sxgkq.js} +1 -1
- package/dist/assets/{ProjectActionsDialog-B_jMMuJ0.js → ProjectActionsDialog-C5q25ipO.js} +1 -1
- package/dist/assets/{ReceivedPagePanel-CCDFxXT4.js → ReceivedPagePanel-CfXyzCii.js} +5 -5
- package/dist/assets/{ReplyCommand-CUHB1iPz.js → ReplyCommand-OczgxN8d.js} +1 -1
- package/dist/assets/{ReplyUiBlock-TNOJJ_HH.js → ReplyUiBlock-D1HJeVU_.js} +1 -1
- package/dist/assets/{ReviewCards-UN_E9jl0.js → ReviewCards-D7jBPhS_.js} +1 -1
- package/dist/assets/{RunOverview-C7FUT8DD.js → RunOverview-BDblAbDp.js} +1 -1
- package/dist/assets/{ScheduledTasksDialog-DdXypryy.js → ScheduledTasksDialog-NDtZLq5t.js} +1 -1
- package/dist/assets/{SettingsView-uSZDjIcc.js → SettingsView-UjifxDq7.js} +1 -1
- package/dist/assets/{SettingsWindow-CoijA05f.js → SettingsWindow-D2K9vSYk.js} +1 -1
- package/dist/assets/{SidebarSectionsManager-d6IaYpHW.js → SidebarSectionsManager-QqwIUOdu.js} +1 -1
- package/dist/assets/{SourceBoardView-BrQkCEgn.js → SourceBoardView-CKJDJ2f4.js} +1 -1
- package/dist/assets/{SpaceAccessDialog-CymnxxLO.js → SpaceAccessDialog-G331hiT_.js} +1 -1
- package/dist/assets/{SpaceApplyDialog-DVJkF4lG.js → SpaceApplyDialog-x0rDuJEc.js} +1 -1
- package/dist/assets/{SpaceRow-CJFX1Zsr.js → SpaceRow-CsS43yrt.js} +1 -1
- package/dist/assets/{SpaceSetupOutput-Btttdq6K.js → SpaceSetupOutput-BEXQGXPw.js} +1 -1
- package/dist/assets/{SpacesView-GxzOEIeI.js → SpacesView-DFcnInBv.js} +1 -1
- package/dist/assets/{SubmoduleDiffSummary-D0Nj5PJN.js → SubmoduleDiffSummary-CTqIH0Cp.js} +1 -1
- package/dist/assets/{TableArtifact-DiRnrtL5.js → TableArtifact-Beve8fiv.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DnvhhdiH.js → ToolOutputDialog-Bn2g6tIX.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-CHdkL7BJ.js → ToolPartDiffPreview-mgtjJMMz.js} +1 -1
- package/dist/assets/{UiBlock-CvZ92eyw.js → UiBlock-DkgJyZVl.js} +2 -2
- package/dist/assets/{UsageStatsView-Dbo3dCgC.js → UsageStatsView-CLJFagDC.js} +1 -1
- package/dist/assets/{WalkthroughView-l9TMdlPB.js → WalkthroughView-Dm4-RaV3.js} +1 -1
- package/dist/assets/{WorktreesView-DNa5Soxq.js → WorktreesView-DyZy4OjB.js} +1 -1
- package/dist/assets/{appThemeRegistry-C3TUDJ7r.js → appThemeRegistry-C4Av1s90.js} +1 -1
- package/dist/assets/{codeHighlight-DyrRLTkb.js → codeHighlight-Bmb7zcc2.js} +1 -1
- package/dist/assets/{columnWidthMemory-D0i9Kdhi.js → columnWidthMemory-D8H-O0YE.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-YMtW3BEg.js → computeVirtualFileMetrics-Bc_YiqAD.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-USev-3h1.js → contextFileOpenGuard-D-HtBtn6.js} +1 -1
- package/dist/assets/{date-time-DSQbTMhf.js → date-time-DfmOsLQo.js} +1 -1
- package/dist/assets/{diffsHighlighter-DZ_8ZCaS.js → diffsHighlighter-CFc933Ip.js} +1 -1
- package/dist/assets/{documentClient-5O0az-Ma.js → documentClient-D-gfZAFK.js} +2 -2
- package/dist/assets/{documentHost-BqOqnqk5.js → documentHost-fBeQzdlp.js} +1 -1
- package/dist/assets/{editorCodeMetrics-a0NLS65y.js → editorCodeMetrics-CNBjOGNA.js} +1 -1
- package/dist/assets/{fileContentPoller-B8a010z5.js → fileContentPoller-DRoVO_sh.js} +1 -1
- package/dist/assets/{flexokiTheme-DJaL_u7G.js → flexokiTheme-CcqiI7j-.js} +1 -1
- package/dist/assets/{highlights-CSy_17b-.js → highlights-_5vZZ38i.js} +1 -1
- package/dist/assets/{index-CvHejcGo.js → index-BbbQXJ_t.js} +1 -1
- package/dist/assets/{initializeSharedPreferences-MLG8op-A.js → initializeSharedPreferences-B1ISDxLb.js} +1 -1
- package/dist/assets/{install-NTaAzPnj.js → install-DY6TBn2e.js} +1 -1
- package/dist/assets/{install-request-D5VhmtWC.js → install-request-CzRei4tp.js} +1 -1
- package/dist/assets/{isDiffPlainText-B6ZzF_T5.js → isDiffPlainText-Cx5SgKlQ.js} +1 -1
- package/dist/assets/{isFilePlainText-Bitg2337.js → isFilePlainText-Bcn3vV6J.js} +1 -1
- package/dist/assets/{katex.min-B3YMLLh4.js → katex.min-DklPh68d.js} +3 -3
- package/dist/assets/{main-Bqwtrv5m.js → main-D0ACoTpS.js} +2 -2
- package/dist/assets/{main-B61P9v4A.js → main-QZk4AKac.js} +4 -4
- package/dist/assets/{miniChat-CZx_2XHj.js → miniChat-DeYRMPYt.js} +2 -2
- package/dist/assets/{mobile-DiLdHL_W.js → mobile-DjT3KVMo.js} +2 -2
- package/dist/assets/{moveWorkspacePath-CpN2DOGn.js → moveWorkspacePath-DibtVw_Q.js} +1 -1
- package/dist/assets/{officeDocument-Ca0s-jYd.js → officeDocument-CBwDUdTr.js} +1 -1
- package/dist/assets/{parseDiffFromFile-CL7WjMrZ.js → parseDiffFromFile-D28_u-uC.js} +1 -1
- package/dist/assets/{pierreDiffTint-C4cPKKnP.js → pierreDiffTint-CLCzflgS.js} +1 -1
- package/dist/assets/{relocateRestoredSession-Bw3yb1_0.js → relocateRestoredSession-BPqdEuzx.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-DB0hWKLa.js → renderElectronMiniChatApp-C0v7P53f.js} +2 -2
- package/dist/assets/{renderMarkdownForExport-CICPn_1e.js → renderMarkdownForExport-DvKl_kjS.js} +1 -1
- package/dist/assets/{renderMobileApp-CYhEWO14.js → renderMobileApp-EVllBWS5.js} +3 -3
- package/dist/assets/{resolveLanguages-gKOTFspE.js → resolveLanguages-DqxtADuz.js} +1 -1
- package/dist/assets/{scheduledTasksApi-C1TDMoZd.js → scheduledTasksApi-v463mt0u.js} +1 -1
- package/dist/assets/{shiki-B0-fz3dN.js → shiki-3oNYFbTw.js} +1 -1
- package/dist/assets/{space-apply-DnoCDzwj.js → space-apply-j71ap5Rs.js} +1 -1
- package/dist/assets/{space-close-Bqfdl7kv.js → space-close-Bj32J79L.js} +1 -1
- package/dist/assets/{spaceNetwork-D5Fcyb33.js → spaceNetwork-BV5W32NY.js} +1 -1
- package/dist/assets/{stream-tokenizer-FniCZxxb.js → stream-tokenizer-wGP5G2_C.js} +1 -1
- package/dist/assets/{useAppFontEffects-CpxtKEGw.js → useAppFontEffects-BDLOJuy5.js} +15 -15
- package/dist/assets/{useBranchPullRequestRequest-DVy6rEsu.js → useBranchPullRequestRequest-DMiPjfPQ.js} +1 -1
- package/dist/assets/{useCallableModelProviders-DngJbZnV.js → useCallableModelProviders-aGFpVUZL.js} +1 -1
- package/dist/assets/{useDiffFindSurface-DY6lBBpH.js → useDiffFindSurface-mA0rc6AR.js} +1 -1
- package/dist/assets/{useGitCleanLine-CxdK3EQ3.js → useGitCleanLine-BwAypcLn.js} +1 -1
- package/dist/assets/{useInlineCommentController-Z8ADSR8f.js → useInlineCommentController-Wnopn0Ar.js} +1 -1
- package/dist/assets/{useMarkdownLocalAssets-CZIMWgjn.js → useMarkdownLocalAssets-BjT607tF.js} +1 -1
- package/dist/assets/{useRootScrollLock-C9UIEqnb.js → useRootScrollLock-DPhGk2Eu.js} +1 -1
- package/dist/assets/{useWalkthroughReview-BWxwaV05.js → useWalkthroughReview-BrULG_dy.js} +1 -1
- package/dist/assets/{useWholeFileComment-zterYCFS.js → useWholeFileComment-CQj6q_QX.js} +1 -1
- package/dist/assets/{useWorktreeArchiveActions-CKnDdsvh.js → useWorktreeArchiveActions-CpegLYyZ.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-BI6j-q9C.js → vendor-codemirror-language-data-CFvXza4M.js} +2 -2
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +2 -2
- package/dist/mobile.html +2 -2
- package/package.json +3 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CRnROUpT.js","assets/vendor-react--VO_rL_p.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as Ge}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as xt,d as Do,p as aa,a as aS}from"./vendor-zustand-C9tWdk0j.js";import{o as d,s as c,n as y,l as g,e as v,c as k,f as Z,_ as T,u as L,a as be,j as nt,N as nf,h as oe,i as rS,k as kr,p as Ps,q as nr,v as cS,w as Jr,x as of,y as lS,z as Sa}from"./vendor-zod-DV_WH382.js";import{e as af,C as Wp}from"./vendor-opencode-client-NJGkA1Ku.js";import{f as yt,R as sn,r as dS}from"./vendor-react--VO_rL_p.js";import{F as rf}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as uS}from"./vendor-streamdown-BbSYZ3NF.js";import{u as pS}from"./vendor-unified-1CQKw2_w.js";import{c as hS}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as gS}from"./vendor-capacitor-core-B4EWRrHz.js";const wi=1,mS=d({type:g("relay-retire"),code:y().int(),reason:c().catch("")}),fS=e=>{try{const t=mS.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},wS="openchamber-relay-v1",cf=1,lf=12,bi=1+lf,Ui=64*1024,ji=5,Sr=128,df=0,uf=1,bo=4,bS=1+bo,_l=Ui-ji-bS,yS="x-openchamber-tunnel-accept-encoding",vS="x-openchamber-tunnel-content-encoding",ce={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},kS=new Set(Object.values(ce)),SS=e=>kS.has(e),Zs={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},ys=globalThis.crypto.subtle,pf={name:"ECDH",namedCurve:"P-256"},hf=16,xc=32,CS=16,Nl=4,gf=8;class fs extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const TS=()=>ys.generateKey(pf,true,["deriveBits"]),AS=async e=>{const t=await ys.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},PS=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new fs("invalid ECDH public key JWK");try{return await ys.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:true},pf,true,[])}catch{throw new fs("invalid ECDH public key JWK")}},RS=()=>{const e=new Uint8Array(hf);return globalThis.crypto.getRandomValues(e),e},IS=async(e,t,s)=>{if(s.length!==hf)throw new fs("invalid handshake nonce length");const n=await ys.deriveBits({name:"ECDH",public:t},e,256),o=await ys.importKey("raw",n,"HKDF",false,["deriveBits"]),i=new Uint8Array(await ys.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(wS)},o,xc*2*8)),a=(r,l)=>ys.importKey("raw",r,{name:"AES-GCM"},false,l);return{clientToHost:await a(i.slice(0,xc),["encrypt","decrypt"]),hostToClient:await a(i.slice(xc),["encrypt","decrypt"])}},xS=(e,t,s)=>{for(let n=gf-1;n>=0;n-=1)e[t+n]=Number(s&0xffn),s>>=8n},ES=(e,t)=>{let s=0n;for(let n=0;n<gf;n+=1)s=s<<8n|BigInt(e[t+n]);return s},OS=e=>{const t=new Uint8Array(Nl);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(n){if(n.length>Ui)throw new fs("plaintext frame exceeds maximum size");s+=1n;const o=new Uint8Array(lf);o.set(t,0),xS(o,Nl,s);const i=new Uint8Array(await ys.encrypt({name:"AES-GCM",iv:o},e,n)),a=new Uint8Array(bi+i.length);return a[0]=cf,a.set(o,1),a.set(i,bi),a}}},DS=e=>{let t=0n;return{async decrypt(s){if(s.length<bi+CS)throw new fs("encrypted frame too short");if(s[0]!==cf)throw new fs("unsupported encrypted frame version");const n=s.slice(1,bi),o=ES(n,Nl);if(o<=t)throw new fs("frame counter regression");if(o!==t+1n)throw new fs("frame counter gap");let i;try{i=await ys.decrypt({name:"AES-GCM",iv:n},e,s.slice(bi))}catch{throw new fs("frame decryption failed")}return t=o,new Uint8Array(i)}}},Ca="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",MS=e=>{let t="";for(let s=0;s<e.length;s+=3){const n=e[s],o=s+1<e.length?e[s+1]:void 0,i=s+2<e.length?e[s+2]:void 0;t+=Ca[n>>2],t+=Ca[(n&3)<<4|(o??0)>>4],o!==void 0&&(t+=Ca[(o&15)<<2|(i??0)>>6]),i!==void 0&&(t+=Ca[i&63])}return t},qp=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const s=t;if(s.v!==wi)return null;const n=s.batch===true,o=s.flowControl===true;return s.t==="ready"?{t:"ready",v:wi,batch:n,flowControl:o}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:wi,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:n,flowControl:o}:null},FS=e=>({type:"fail",closeCode:Zs.ChannelFailure,reason:e}),_S=async(e,t={})=>{const s=t.batch!==false,n=await PS(e),o=await TS(),i=RS(),a={t:"hello",v:wi,clientPubJwk:await AS(o.publicKey),nonce:MS(i)};s&&(a.batch=true),t.flowControl!==false&&(a.flowControl=true);let r=false;return{helloText:JSON.stringify(a),get established(){return r},async handleText(l){if(r)return qp(l)?.t==="ready"?{type:"ignore"}:FS("plaintext frame on established channel");const u=qp(l);if(u?.t!=="ready")return{type:"ignore"};const p=await IS(o.privateKey,n,i);return r=true,{type:"established",batch:s&&u.batch===true,flowControl:t.flowControl!==false&&u.flowControl===true,channel:{encryptor:OS(p.clientToHost),decryptor:DS(p.hostToClient)}}}}},mf=4294967295,NS=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class ze extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Mt=(e,t,s,n=false)=>{if(!Number.isInteger(t)||t<0||t>mf)throw new ze("invalid stream id");if(s.length>_l)throw new ze("tunnel payload exceeds maximum size");const o=new Uint8Array(ji+s.length);return o[0]=n?e|Sr:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(s,ji),o},LS=e=>{if(e.length<ji)throw new ze("tunnel frame too short");const t=e[0],s=(t&Sr)!==0,n=t&~Sr;if(!SS(n))throw new ze(`unknown tunnel frame type ${n}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:n,streamId:o,payload:e.slice(ji),hasMoreFragments:s}},US=new TextEncoder,jS=new TextDecoder,Ta=e=>US.encode(JSON.stringify(e)),Aa=(e,t)=>{let s;try{s=JSON.parse(jS.decode(e))}catch{throw new ze("malformed JSON tunnel payload")}if(!t(s))throw new ze("unexpected JSON tunnel payload shape");return s},ff=(e,t=_l)=>{if(t<=0||t>_l)throw new ze("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},Gp=(e,t,s)=>{const n=ff(s);return n.map((o,i)=>Mt(e,t,o,i<n.length-1))},BS=(e=16*1024*1024)=>{const t=new Map;return{push(s){const n=`${s.streamId}:${s.frameType}`,o=t.get(n);if(!s.hasMoreFragments&&!o)return s.payload;const i=o?.chunks??[],a=(o?.totalBytes??0)+s.payload.length;if(a>e)throw t.delete(n),new ze("fragmented message exceeds maximum size");if(i.push(s.payload),s.hasMoreFragments)return t.set(n,{chunks:i,totalBytes:a}),null;t.delete(n);const r=new Uint8Array(a);let l=0;for(const u of i)r.set(u,l),l+=u.length;return r},dropStream(s){for(const n of t.keys())n.startsWith(`${s}:`)&&t.delete(n)}}},VS=e=>{if(e.length===0)throw new ze("cannot encode an empty frame batch");if(e.length===1){const o=e[0],i=new Uint8Array(1+o.length);if(i[0]=df,i.set(o,1),i.length>Ui)throw new ze("frame batch exceeds maximum plaintext size");return i}let t=1;for(const o of e)t+=bo+o.length;if(t>Ui)throw new ze("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=uf;let n=1;for(const o of e)s[n]=o.length>>>24&255,s[n+1]=o.length>>>16&255,s[n+2]=o.length>>>8&255,s[n+3]=o.length&255,n+=bo,s.set(o,n),n+=o.length;return s},HS=e=>{if(e.length<1)throw new ze("empty batch plaintext");const t=e[0];if(t===df)return[e.slice(1)];if(t!==uf)throw new ze(`unknown batch container tag ${t}`);const s=[];let n=1;for(;n<e.length;){if(n+bo>e.length)throw new ze("truncated batch frame length");const o=(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0;if(n+=bo,n+o>e.length)throw new ze("truncated batch frame body");s.push(e.slice(n,n+o)),n+=o}if(s.length===0)throw new ze("empty frame batch");return s},WS=new Set([ce.HttpBody,ce.WsText,ce.WsBinary]),wf=150,qS=24*1024,GS=32,zS=e=>{const t=e.windowMs??wf,s=e.maxBatchBytes??qS,n=e.maxBatchFrames??GS,o=e.now??(()=>Date.now()),i=e.setTimer??((S,C)=>setTimeout(S,C)),a=e.clearTimer??(S=>clearTimeout(S));let r=[],l=0,u=null,p=0,h=false;const m=()=>{u!==null&&(a(u),u=null)},w=()=>{if(m(),r.length===0)return;const S=r;r=[],l=0,p=o(),e.sendBatch(VS(S))};return{enqueue:S=>{if(h)return;const C=S[0]&~Sr;if(!WS.has(C)){r.push(S),w();return}const x=o();if(r.length===0&&x-p>=t){r.push(S),w();return}const A=bo+S.length;if(r.length>0&&1+l+A>Ui&&w(),r.push(S),l+=A,l>=s||r.length>=n){w();return}u===null&&(u=i(w,t))},flush:w,dispose(){h=true,m(),r=[],l=0}}},$S=()=>{let e=1;return{next(){if(e>mf)throw new ze("stream id space exhausted");const t=e;return e+=2,t}}},Yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KS=e=>Yr(e)&&Object.values(e).every(t=>typeof t=="string"),JS=e=>Yr(e)&&typeof e.status=="number"&&KS(e.headers),zp=e=>Yr(e)&&typeof e.reason=="string",YS=e=>Yr(e)&&typeof e.code=="number"&&typeof e.reason=="string",bf=/^[a-z][a-z\d+.-]*:\/\//i,du="http://tunnel.invalid",XS=e=>{try{const t=bf.test(e)?new URL(e):new URL(e,du);return`${t.pathname}${t.search}`}catch{return e}},Pa=e=>({async*[Symbol.asyncIterator](){yield e}}),QS=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:n}=await t.read();if(s)return;n&&(yield n)}}finally{t.releaseLock()}}}),ZS=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},eC=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:QS(e)};if(typeof e=="string")return{body:Pa(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Pa(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Pa(ZS(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,n=new Uint8Array(await t.arrayBuffer());return{body:Pa(n),contentType:s}},tC=async(e,t)=>{let s;const n=new Headers;let o="GET",i=null,a;e instanceof Request?(s=e.url,o=e.method,e.headers.forEach((h,m)=>n.set(m,h)),a=e.signal,i=e.body):s=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((h,m)=>n.set(m,h)),t.body!==void 0&&(i=t.body),t.signal&&(a=t.signal));const r=bf.test(s)?new URL(s):new URL(s,du),{body:l,contentType:u}=await eC(i);u&&!n.has("content-type")&&n.set("content-type",u);const p={};return n.forEach((h,m)=>{p[m]=h}),{method:o.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:p,body:l,signal:a}},yf="__openchamberAmbiguousTransport",vf=new WeakSet,sC=e=>(vf.add(e),e),nC=e=>vf.has(e),Ll=e=>(Object.defineProperty(e,yf,{value:true,enumerable:false,configurable:true}),e),oC=e=>!e||typeof e!="object"?false:e[yf]===true,iC=["local","remote",null],aC=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function kf(e){if(!e||typeof e!="object")return{valid:false};const t=e,s=t.localAvailable===false?{localAvailable:false}:{},n=t.target,o=t.status;if(n!==null&&(typeof n!="string"||!iC.includes(n)))return{valid:false};if(typeof o!="string"||!aC.includes(o))return{valid:false};if(n==="remote"||n==="local"){if(o==="ok"&&n==="local"){const i={target:"local",status:"ok",...s},a=c().min(1).safeParse(t.sshStartupFallbackHostId);return a.success&&(i.sshStartupFallbackHostId=a.data),{valid:true,outcome:i}}if(o==="ok"&&n==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(o==="unreachable")return n==="local"?{valid:true,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(o==="incompatible"||o==="wrong-service")return n!=="remote"?{valid:false}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:o,hostId:t.hostId,url:t.url,...s}};if(o==="missing")return n!=="remote"?{valid:false}:typeof t.hostId!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(n===null){if(o==="not-configured")return{valid:true,outcome:{target:null,status:"not-configured",...s}};if(o==="missing")return{valid:false}}return{valid:false}}function CG(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===false?{localAvailable:false}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...s};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...s}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...s};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...s};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...s};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...s};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...s};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...s}}return null}function TG(e){return!e.isDesktopShell||e.bootOutcomeKnown}function AG(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function Sf(){if(rC()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=kf(t);return s.valid?s.outcome:null}function rC(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":kf(e).valid?"valid":"malformed"}const Cr=/^[a-z][a-z\d+.-]*:\/\//i,cC=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Tr=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),lC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Tr(e)},dC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Tr(e)},uC=()=>Object.keys(_o()).length>0,pC=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Ul=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of s)o!=null&&e.searchParams.set(n,String(o))},hC=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Ul({searchParams:s},t);const n=s.toString();return n?e.includes("?")?`${e}&${n}`:`${e}?${n}`:e},$p=(e,t,s)=>{if(Cr.test(t)){const a=new URL(t);return Ul(a,s),a.toString()}const n=cC(t);if(!e)return hC(n,s);const o=new URL(e),i=new URL(`${o.origin}${o.pathname.replace(/\/+$/,"")}${n}`);return Ul(i,s),i.toString()},Ra=(e,t=QC())=>{if(!t)return e;const s=Cr.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),Cr.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},Cf=(e,t)=>{const s=Cr.test(e)?new URL(e):new URL(e,pC(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},Kp=(e,t,s)=>{if(!uC())return null;const n=dC();if(!n)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${n}/`);o.searchParams.set("url",t);const i=ZC(n);return i&&o.searchParams.set("oc_url_token",i),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Cf(o.toString(),s)):o.toString()}catch{return null}},uu=(e={})=>{const t=Tr(e.apiBaseUrl),s=Tr(e.realtimeBaseUrl),n=()=>t||lC(),o=()=>s||n(),i=(r,l)=>$p(n(),r,l),a=(r,l)=>$p(o(),r,l);return{api:i,authenticatedAsset:(r,l)=>Ra(i(r,l)),assetWithUrlToken:(r,l,u)=>Ra(i(r,u),l),auth:i,health:r=>i("/health",r),rawFile:(r,l)=>i("/api/fs/raw",{path:r,download:l?.download===true?true:void 0,allowOutsideWorkspace:l?.allowOutsideWorkspace===true?true:void 0,outsideFileGrant:l?.outsideFileGrant}),sse:(r,l)=>{const u=Ra(a(r,l));return Kp("sse",u,e)||u},websocket:(r,l)=>{const u=Cf(Ra(a(r,l)),e);return Kp("ws",u,e)||u}}};let Ar=uu();const Ss=()=>Ar,gC=e=>{Ar=e},Tf=e=>(Ar=uu(e),Ar),pu=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Bi=()=>{const e=pu();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():false},hu=(e=pu())=>!!e,jl="openchamber:runtime-endpoint-changed",Bl="openchamber:runtime-endpoint-will-change";let yo="",Vi="",Vl=0,Hl=null;const Ec=(e,t,s)=>{try{e[t]=s}catch{}},gu=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"}`}},mC="mobile-disconnected",fC="url:default",Wl=e=>e===""||e===mC||e===fC&&!hu(),Af=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Pf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Rf=(e,t)=>{if(!e||!t)return false;try{return new URL(e).origin===new URL(t).origin}catch{return false}},os=()=>yo||Af(),wC=()=>{if(Hl!==null)return Hl;const e=os();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let Oc="",Jp=null,Yp,Xp;const Qp=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},F=()=>{if(Vi)return Vi;const e=Qp("__OPENCHAMBER_API_BASE_URL__"),t=Qp("__OPENCHAMBER_LOCAL_ORIGIN__");if(Jp===yo&&Yp===e&&Xp===t)return Oc;const s=os();return Oc=Rf(s,Pf())?"local":gu(s),Jp=yo,Yp=e,Xp=t,Oc},or=()=>{const e=Vl,t=F();return()=>e===Vl&&t===F()},bC=(e={})=>{if(yo||Vi)return;const t=e.apiBaseUrl?.trim()||Af(),s=globalThis.window?.location?.origin??"",n=/^https?:\/\//.test(s)?s:"";if(!t&&!n)return;const o=Pf(),i=o&&(!t||Rf(t,o));yo=t,Vi=e.runtimeKey?.trim()||(i?"local":gu(t||n))},ql=e=>{const t=e.apiBaseUrl.trim(),s=os(),n=F(),o=e.runtimeKey?.trim()||gu(t),i=e.sshForwarded??(t===s&&o===n&&wC()),a={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:o,previousRuntimeKey:n};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bl,{detail:a})),yo=t,Vi=o,o!==n&&(Vl+=1),Hl=i,typeof window<"u"){const r=window;Ec(r,"__OPENCHAMBER_API_BASE_URL__",t),Ec(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Ec(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Tf({apiBaseUrl:t,realtimeBaseUrl:t}),Hf(e.requestHeaders||null),Vf(e.clientToken||null),e.relay?GC(e.relay):zC(),tc(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(jl,{detail:a}))},Xr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Bl,t),()=>window.removeEventListener(Bl,t)},Qr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(jl,t),()=>window.removeEventListener(jl,t)};let Gl=null;const PG=e=>{Gl=e},Mo=()=>Gl||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),yC=e=>e==="stable"||e==="canary",vC=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,RG=e=>{const t=vC.exec(e??"");if(!t)return null;const[,s,n,o,i,a]=t;return{release:s,builtOn:new Date(Date.UTC(Number(n),Number(o)-1,Number(i))),build:a?Number(a):null}},kC=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),IG=(e,t,s)=>{const n=kC(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${n} #${e.build}`:n},If=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Rs=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,Dn=()=>If()?.runtime==="electron",xf=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},SC="right",xG=()=>{if(!Dn())return false;const e=xf();return e==="linux"?If()?.nativeFrame!==true:e==="win32"},EG=e=>e==="left"?"left":SC,OG=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],rt=()=>typeof Rs()?.invoke=="function",vt=()=>Dn()&&rt(),CC=()=>{const e=Rs()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>c().parse(await t()),writeText:async n=>{g(true).parse(await s(n))}}}},TC=()=>{if(Rs()?.pickThemeFile)return{async pick(){const e=Rs()?.pickThemeFile;return e?{status:"picked",file:d({name:c(),size:y().nonnegative(),text:c()}).nullable().parse(await e())}:{status:"unsupported"}}}},ie=async(e,t)=>{const s=Rs();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},DG=e=>{xf()!=="darwin"||!vt()||ie("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},MG=()=>({apiBaseUrl:os(),clientToken:yu(),runtimeKey:F()}),FG=async()=>{if(!it()||!Ie())return false;const e=os();try{const t=v().safeParse(await ie("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===os()}catch{return false}},_G=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("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}},NG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("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}},Ef=e=>yC(e?.channel)?e.channel:null,LG=async()=>{if(!vt()||!Ie())return null;try{return Ef(await ie("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},UG=async e=>{if(!vt()||!Ie())return null;try{return Ef(await ie("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},jG=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("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}},BG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("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}},VG=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("desktop_get_mini_chat_global_shortcut");return!e||typeof e.supported!="boolean"||e.combo!==null&&typeof e.combo!="string"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get Mini Chat global shortcut status",e),null}},HG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("desktop_set_mini_chat_global_shortcut",{combo:e});return!t||typeof t.supported!="boolean"||t.combo!==null&&typeof t.combo!="string"||typeof t.active!="boolean"||t.error!==void 0&&t.error!=="unsupported-combo"?null:t}catch(t){return console.warn("Failed to set Mini Chat global shortcut",t),null}},AC=d({supported:v(),enabled:v(),combo:c().nullable(),storedCombo:c().nullable(),active:v(),heightFraction:y(),error:g("unsupported-combo").optional()}),Zr=async(e,t,s)=>{if(!vt()||!Ie())return null;try{const n=AC.safeParse(await ie(e,t));return n.success?n.data:null}catch(n){return console.warn(s,n),null}},WG=()=>Zr("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),qG=e=>Zr("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),GG=e=>Zr("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),zG=e=>Zr("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),$G=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("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}},KG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("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}},Zp=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}}},Dc=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}}},PC=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Jo=e=>{const t=PC(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ie=()=>{if(typeof window>"u"||!it())return false;if(F()==="local")return true;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Dc(e),s=Dc(os());if(!s&&t&&Sf()?.target==="local")return true;if(t&&s){if(t.origin===s.origin)return true;const a=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&a===r&&Jo(t.hostname)&&Jo(s.hostname)}const n=Dc(window.location.origin);if(t&&n){if(t.origin===n.origin)return true;const a=t.port||(t.protocol==="https:"?"443":"80"),r=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&a===r&&Jo(t.hostname)&&Jo(n.hostname)}const o=Zp(e),i=Zp(window.location.origin)||window.location.origin;return o&&i&&o===i?true:!!(n&&Jo(n.hostname))},it=()=>typeof window>"u"?false:Dn(),JG=async()=>{if(!it())return null;const e=d({visible:v()}).safeParse(await ie("desktop_get_current_window_state"));return e.success?e.data.visible:null},YG=async()=>{if(!it())return false;try{return!!await ie("desktop_focus_window")}catch{return false}},XG=(e,t,s=null)=>!t||t===F()||!vt()?false:(ie("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(o=>{console.warn("[desktop] failed to open host session",o)}),true),Of=()=>it()&&rt()&&Ie(),RC=k(d({sessionId:c().min(1),messageId:c().min(1).optional(),runtimeKey:c().min(1).optional(),requireKnownSession:v().optional()})),QG=async()=>{if(!it())return[];try{const e=k(c()).safeParse(await ie("desktop_take_pending_extension_installs"));return e.success?e.data:[]}catch{return[]}},ZG=async()=>{if(!it()||!Ie())return[];try{const e=RC.safeParse(await ie("desktop_take_pending_session_links"));return e.success?e.data.map(t=>({sessionId:t.sessionId,messageId:t.messageId??null,runtimeKey:t.runtimeKey??null,requireKnownSession:t.requireKnownSession===true})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},IC=k(Z("type",[d({type:g("pairing"),link:c().min(1)}),d({type:g("host"),hostId:c().min(1)})])),ez=async()=>{if(!it())return[];try{const e=IC.safeParse(await ie("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},xC=c().min(1),tz=e=>{if(!Of())return null;try{const t=xC.safeParse(Rs()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},sz=async()=>{if(!it())return false;try{return await ie("desktop_start_window_drag"),true}catch{return false}},Ne=()=>hu()?true:Mo()?.runtime?.isVSCode===true,nz=()=>{const t=Mo()?.runtime?.platform;return t==="web"?true:t==="desktop"||t==="vscode"?false:!Ne()},oz=(e,t=it())=>e==="web"&&!t,Df=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},iz=async e=>{if(Of())try{const t=await Rs()?.openDialog?.({directory:true,multiple:false,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:false,error:"Directory selection cancelled"}:{success:true,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:false,error:t instanceof Error?t.message:String(t)}}return{success:false,error:"Native directory picker not available"}},EC=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),az=async e=>{if(rt()&&Ie())try{const t=await Rs()?.openDialog?.({directory:false,multiple:false,title:"Select File",returnGrant:true,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:false,error:"File selection cancelled"};if(typeof t=="string")return{success:true,path:t};if(!EC(t))return{success:false,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:true,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:false,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:false,error:t instanceof Error?t.message:String(t)}}return{success:false,error:"Native file picker not available"}},rz=async e=>({success:true}),cz=async e=>({success:true}),lz=async()=>rt()?await ie("desktop_check_for_updates"):null,dz=async e=>{if(!rt())return false;const t=Rs();let s=null,n=0,o;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",i=>{const a=i?.payload;if(!a||typeof a!="object")return;const r=a,l=typeof r.event=="string"?r.event:null,u=r.data&&typeof r.data=="object"?r.data:null;if(l==="Started"){n=0,o=typeof u?.contentLength=="number"?u.contentLength:void 0,e({downloaded:n,total:o});return}if(l==="Progress"){const p=u?.downloaded,h=u?.total;typeof p=="number"&&(n=p),typeof h=="number"&&(o=h),e({downloaded:n,total:o});return}l==="Finished"&&e({downloaded:n,total:o})})),await ie("desktop_download_and_install_update"),true}catch(i){throw i instanceof Error?i:new Error(String(i))}finally{if(s)try{const i=s();i instanceof Promise&&await i}catch{}}},uz=async()=>rt()?(await ie("desktop_restart"),true):false,pz=async()=>{if(!rt())return false;try{return await ie("desktop_restart"),true}catch(e){return console.warn("Failed to restart desktop app",e),false}},hz=async()=>{if(!rt()||!Ie())return null;try{const e=await ie("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}},OC=async(e,t)=>{if(!rt()||!Ie())return false;const s=e?.trim();if(!s)return false;try{return await ie("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),true}catch(n){return console.warn("Failed to open path",n),false}},gz=async e=>{if(!rt()||!Ie())return false;const t=e?.trim();if(!t)return false;try{return await ie("desktop_reveal_path",{path:t}),true}catch{return OC(t)}},mz=async(e,t)=>{if(!rt()||!Ie())return null;const s=e?.trim();if(!s)return null;try{const n=await ie("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof n=="string"&&n.trim().length>0?n:null}catch(n){return console.warn("Failed to save markdown file",n),null}},fz=async(e,t,s)=>{if(!rt()||!Ie())return false;const n=e?.trim(),o=t?.trim(),i=s?.trim();if(!n||!o||!i)return false;try{return await ie("desktop_open_in_app",{projectPath:n,appId:o,appName:i}),true}catch(a){return console.warn("Failed to open project in app",a),false}},wz=async(e,t,s)=>{if(!rt()||!Ie())return false;const n=e?.trim(),o=t?.trim(),i=s?.trim();if(!n||!o||!i)return false;try{return await ie("desktop_open_file_in_app",{filePath:n,appId:o,appName:i}),true}catch(a){return console.warn("Failed to open file in app",a),false}},bz=async(e,t)=>{if(!rt()||!Ie())return{apps:[],success:false,hasCache:false,isCacheStale:false};const s=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];if(s.length===0)return{apps:[],success:true,hasCache:false,isCacheStale:false};try{const n=await ie("desktop_get_installed_apps",{apps:s,force:t===true?true:void 0});if(!n||typeof n!="object")return{apps:[],success:false,hasCache:false,isCacheStale:false};const o=n;return o.supported===false?{apps:[],success:true,hasCache:false,isCacheStale:false}:Array.isArray(o.apps)?{apps:o.apps.filter(a=>a&&typeof a=="object").map(a=>{const r=a;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(a=>a.name.length>0),success:true,hasCache:o.hasCache===true,isCacheStale:o.isCacheStale===true}:{apps:[],success:false,hasCache:false,isCacheStale:false}}catch(n){return console.warn("Failed to fetch installed apps",n),{apps:[],success:false,hasCache:false,isCacheStale:false}}},yz=()=>navigator.platform.toLowerCase().startsWith("linux"),Mn=()=>typeof window>"u"?false:window.Capacitor?.isNativePlatform?.()===true||window.location.protocol==="capacitor:",vz=()=>typeof window>"u"||!Mn()?false:Mf()==="ios"&&DC(),DC=()=>{if(typeof navigator>"u")return false;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Mf=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ne()?"vscode":it()?"desktop":"web"},MC="2.7.2",Ia=new Uint8Array(0),FC=typeof DecompressionStream=="function",_C=e=>e.pipeThrough(new TransformStream({transform(t,s){s.enqueue(t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t))}})).pipeThrough(new DecompressionStream("gzip")),Ff=e=>ArrayBuffer.isView(e)?e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e,NC=new TextEncoder,LC=new TextDecoder,Dt=e=>e instanceof Error?e:new Error(String(e)),xa=()=>new DOMException("The operation was aborted.","AbortError"),UC=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(Ff(s))},close(s,n){e.close(s,n)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>t.onmessage?.({data:s.data}),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),e.onerror=()=>t.onerror?.(),t},jC=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(s){s&&(e.binaryType=s)},onopen:null,onmessage:null,onerror:null,onclose:null,send(s){e.send(Ff(s))},close(s,n){e.close(s,n)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const n=s.data;(typeof n=="string"||n instanceof ArrayBuffer)&&t.onmessage?.({data:n})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},BC=e=>e?.state==="error"&&e.closeCode===Zs.LimitExceeded,eh=0,Mc=1,th=2,sh=3,VC=new Set([Zs.AuthFailed,Zs.DuplicateClient,Zs.LimitExceeded]),HC={[Zs.AuthFailed]:"relay authentication failed",[Zs.DuplicateClient]:"relay connection replaced by another client",[Zs.LimitExceeded]:"relay connection limit reached"},Fc=()=>{const e=typeof navigator<"u"&&navigator.onLine===false,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},mu=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,n=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,i=e.batchWindowMs??wf,a=e.batch!==false,r=e.reconnectBaseDelayMs??1e3,l=e.reconnectMaxDelayMs??3e4,u=e.hiddenOrOfflineMaxDelayMs??6e4,p=e.createWireSocket??(V=>UC(new WebSocket(V)));let h=false,m=null,w={state:"idle"};const b=new Set;let S=null,C=null,x=null,A=0,E=0,B=null,K=[],j=false;const H=V=>{if(!(w.state===V.state&&w.lastError===V.lastError&&w.terminal===V.terminal&&w.closeCode===V.closeCode)){w=V;for(const me of b)try{me(w)}catch{}}},z=V=>{const me=K;K=[];for(const J of me)J.reject(V)},te=V=>{const me=K;K=[];for(const J of me)J.resolve(V)},se=(V,me)=>{V.dead=true;const J=Array.from(V.streams.values());V.streams.clear();for(const X of J)try{X.fail(me)}catch{}},Ve=()=>{B!==null&&(clearTimeout(B),B=null)},Go=()=>{if(!h){if(B!==null){if(Fc())return;Ve(),Et(),jn();return}Fc()||an()}},an=()=>{h||m===null||(Et(),m=null,jn())},Y=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Go()},pt=()=>{j||typeof window>"u"||(j=true,window.addEventListener("online",Go),typeof document<"u"&&document.addEventListener("visibilitychange",Y))},Et=()=>{!j||typeof window>"u"||(j=false,window.removeEventListener("online",Go),typeof document<"u"&&document.removeEventListener("visibilitychange",Y))},zo=()=>{if(h||B!==null)return;const V=Math.max(0,E-1),me=r*2**Math.min(V,10),J=Fc()?u:l,X=Math.min(J,me);pt(),B=setTimeout(()=>{B=null,Et(),jn()},X)},Ac=()=>{const V=new URL(e.relayUrl);return V.searchParams.set("v",String(wi)),V.searchParams.set("role","client"),V.searchParams.set("serverId",e.serverId),V.searchParams.set("appId","openchamber"),V.searchParams.set("appVersion",MC),V.searchParams.set("platform",Mf()),e.grant&&V.searchParams.set("grant",e.grant),V.toString()},jn=async()=>{if(h)return;Ve(),A+=1;const V=A;H({state:E>0?"reconnecting":"connecting",lastError:w.lastError});let me;try{me=await _S(e.hostEncPubJwk,{batch:a,flowControl:e.flowControl})}catch(we){if(V!==A||h)return;Hp(V,Dt(we),true);return}if(V!==A||h)return;let J;try{J=p(Ac())}catch(we){Hp(V,Dt(we));return}C=J;let X=false,ne=null,fe=null,ht=null,He=null,re=Promise.resolve(),le=null,Me=null,cs=false,Ue=false,je=0,We=0,qe=null,ls=null,Pe=Date.now();const Ds=()=>{qe!==null&&(clearTimeout(qe),qe=null),ne!==null&&(clearInterval(ne),ne=null),fe!==null&&(clearTimeout(fe),fe=null),ht!==null&&(clearInterval(ht),ht=null),He!==null&&(clearTimeout(He),He=null),ls!==null&&(ls.dispose(),ls=null)};x=Ds;function ye(we,xe=false,ve=null){if(!(X||V!==A)){X=true,ve!==null&&(m=we),Ds(),le&&(S=null,se(le,new Error(`relay tunnel reset: ${we.message}`))),z(we);try{J.close()}catch{}if(C===J&&(C=null),!h){if(E+=1,ve!==null){pt(),H({state:"error",lastError:we.message,terminal:true,closeCode:ve});return}H({state:xe?"error":"reconnecting",lastError:we.message}),zo()}}}const $o=()=>{try{J.send(me.helloText)}catch{}},rn=(we,xe,ve)=>{Me=we,cs=xe,Ue=ve,ne!==null&&(clearInterval(ne),ne=null),fe!==null&&(clearTimeout(fe),fe=null);const gt=new Map,Ke=$S(),Ot=BS();let cn=Promise.resolve();const Ms=Ko=>{cn=cn.then(async()=>{if(ln.dead)return;const iS=await we.encryptor.encrypt(Ko);ln.dead||J.send(iS)}).catch(()=>{ye(new Error("relay encrypt/send failed"))})},Ic=xe?zS({windowMs:i,sendBatch:Ms}):null;ls=Ic;const ln={streams:gt,assembler:Ot,nextStreamId:()=>Ke.next(),dead:false,send(Ko){ln.dead||(Ic?Ic.enqueue(Ko):Ms(Ko))}};le=ln,S=ln,E=0,Pe=Date.now(),H({state:"connected"}),te(ln),ht=setInterval(()=>{Date.now()-Pe<n||(ln.send(Mt(ce.Ping,0,Ia)),He===null&&(He=setTimeout(()=>{He=null,ye(new Error("relay keepalive timeout"))},o)))},n)},ka=()=>{qe!==null&&clearTimeout(qe),qe=null,!(!le||le.dead||je===We)&&(We=je,le.send(Mt(ce.DeliveryAck,0,NS(je))))},Rc=(we,xe)=>{let ve;try{ve=LS(xe)}catch(Ot){ye(Dt(Ot));return}if(ve.frameType===ce.DeliveryAck){ye(new Error("unexpected downstream delivery acknowledgement"));return}if(Ue&&ve.streamId!==0&&(je+=xe.length,qe===null&&(qe=setTimeout(ka,10))),Pe=Date.now(),He!==null&&(clearTimeout(He),He=null),ve.frameType===ce.Ping){we.send(Mt(ce.Pong,ve.streamId,Ia));return}if(ve.frameType===ce.Pong)return;let gt=ve.payload;if(ve.frameType===ce.WsText||ve.frameType===ce.WsBinary){let Ot;try{Ot=we.assembler.push(ve)}catch(cn){ye(Dt(cn));return}if(Ot===null)return;gt=Ot}else if(ve.hasMoreFragments){ye(new Error("unexpected fragmented tunnel frame"));return}const Ke=we.streams.get(ve.streamId);Ke&&Ke.handleFrame(ve.frameType,gt)};J.onopen=()=>{X||V!==A||($o(),ne=setInterval($o,t))};const Bn=we=>{const xe=VC.has(we);ye(new Error(HC[we]??`relay socket closed (code ${we})`),xe,xe?we:null)};J.onmessage=we=>{if(X||V!==A)return;const xe=we.data;if(typeof xe=="string"){const gt=fS(xe);if(gt){Bn(gt.code);return}re=re.then(async()=>{if(X||V!==A)return;const Ke=await me.handleText(xe);if(Ke.type==="established"){if(Me)return;rn(Ke.channel,Ke.batch,Ke.flowControl)}else Ke.type==="fail"&&ye(new Error(`relay handshake failed: ${Ke.reason}`))}).catch(Ke=>{ye(Dt(Ke))});return}const ve=xe instanceof ArrayBuffer?new Uint8Array(xe):xe instanceof Uint8Array?xe:null;ve&&(re=re.then(async()=>{if(X||V!==A)return;const gt=le,Ke=Me;if(!gt||!Ke){ye(new Error("encrypted frame before handshake completed"));return}let Ot;try{Ot=await Ke.decryptor.decrypt(ve)}catch(Ms){ye(Dt(Ms));return}let cn;try{cn=cs?HS(Ot):[Ot]}catch(Ms){ye(Dt(Ms));return}for(const Ms of cn){if(X||V!==A||gt.dead)return;Rc(gt,Ms)}Ue&&je-We>=16*1024&&ka()}).catch(gt=>{ye(Dt(gt))}))},J.onclose=we=>Bn(we.code),J.onerror=()=>{},fe=setTimeout(()=>{fe=null,ye(new Error("relay handshake timeout"),true)},s);function Hp(we,xe,ve=false){we!==A||h||(z(xe),E+=1,H({state:ve?"error":"reconnecting",lastError:xe.message}),zo())}},rs=V=>h?Promise.reject(new Error("relay tunnel closed")):V?.aborted?Promise.reject(xa()):m?Promise.reject(m):S&&!S.dead?Promise.resolve(S):new Promise((me,J)=>{let X=null;const ne={resolve(fe){X&&V&&V.removeEventListener("abort",X),me(fe)},reject(fe){X&&V&&V.removeEventListener("abort",X),J(fe)}};V&&(X=()=>{K=K.filter(fe=>fe!==ne),J(xa())},V.addEventListener("abort",X,{once:true})),K.push(ne)}),Pc=async(V,me)=>{const J=await tC(V,me),X=J.signal;if(X?.aborted)throw xa();const ne=await rs(X),fe=ne.nextStreamId();return await new Promise((ht,He)=>{let re=false,le=false,Me=null,cs=null;const Ue=()=>{ne.streams.delete(fe),ne.assembler.dropStream(fe),cs&&X&&X.removeEventListener("abort",cs)},je=Pe=>{if(!le){if(le=true,Ue(),!re){He(Pe);return}try{Me?.error(Pe)}catch{}}},We=Pe=>{ne.dead||ne.send(Mt(ce.StreamAbort,fe,Ta({reason:Pe})))},qe=Pe=>Ll(new Error(Pe));cs=()=>{We("aborted"),je(xa())},ne.streams.set(fe,{handleFrame(Pe,Ds){if(Pe===ce.HttpResponse){if(re||le)return;let ye;try{ye=Aa(Ds,JS)}catch(Bn){We("malformed response head"),je(qe(Dt(Bn).message));return}const $o=ye.status===204||ye.status===205||ye.status===304;let rn=null;$o||(rn=new ReadableStream({start(Bn){Me=Bn},cancel(){le||(le=true,Ue(),We("response body cancelled"))}})),re=true;const{[vS]:ka,...Rc}=ye.headers;rn&&ka==="gzip"&&(rn=_C(rn)),ht(new Response(rn,{status:ye.status,headers:Rc})),$o&&(le=true,Ue());return}if(Pe===ce.HttpBody){if(!re||le)return;try{Me?.enqueue(Ds)}catch{}return}if(Pe===ce.StreamEnd){if(le)return;if(!re){je(qe("tunnel stream ended before response head"));return}le=true,Ue();try{Me?.close()}catch{}return}if(Pe===ce.StreamAbort){let ye="stream aborted by host";try{ye=Aa(Ds,zp).reason}catch{}je(qe(ye))}},fail(Pe){je(qe(Pe.message))}}),X&&X.addEventListener("abort",cs,{once:true});const ls={method:J.method,path:J.path,query:J.query,headers:FC?{...J.headers,[yS]:"gzip"}:J.headers,hasBody:J.body!==null};ne.send(Mt(ce.HttpRequest,fe,Ta(ls))),(async()=>{try{let Pe=false;if(J.body)for await(const Ds of J.body){if(le||ne.dead)return;for(const ye of ff(Ds))ne.send(Mt(ce.HttpBody,fe,ye)),Pe=true}!le&&!ne.dead&&(J.body&&!Pe&&ne.send(Mt(ce.HttpBody,fe,Ia)),ne.send(Mt(ce.StreamEnd,fe,Ia)))}catch(Pe){We("request body failed"),je(qe(Dt(Pe).message))}})()})},sS=V=>{const me=V.indexOf("?");return me===-1?{path:V,query:""}:{path:V.slice(0,me),query:V.slice(me+1)}},nS=(V,me)=>{let J=eh,X=null,ne=0,fe=false;const ht={get readyState(){return J},onopen:null,onmessage:null,onerror:null,onclose:null,send(re){if(J!==Mc||!X||X.dead)throw new Error("relay tunnel socket is not open");if(typeof re=="string"){for(const Me of Gp(ce.WsText,ne,NC.encode(re)))X.send(Me);return}const le=re instanceof ArrayBuffer?new Uint8Array(re.slice(0)):(()=>{const Me=new Uint8Array(re.byteLength);return Me.set(new Uint8Array(re.buffer,re.byteOffset,re.byteLength)),Me})();for(const Me of Gp(ce.WsBinary,ne,le))X.send(Me)},close(re=1e3,le=""){J===sh||J===th||(J===Mc&&X&&!X.dead&&(J=th,X.send(Mt(ce.WsClose,ne,Ta({code:re,reason:le})))),He(re,le))}},He=(re,le,Me=false)=>{if(!fe){if(fe=true,X&&(X.streams.delete(ne),X.assembler.dropStream(ne)),J=sh,Me)try{ht.onerror?.()}catch{}try{ht.onclose?.({code:re,reason:le})}catch{}}};return(async()=>{let re;try{re=await rs()}catch(Ue){He(1006,Dt(Ue).message,true);return}if(fe)return;X=re,ne=re.nextStreamId(),re.streams.set(ne,{handleFrame(Ue,je){if(Ue===ce.WsOpened){if(J===eh){J=Mc;try{ht.onopen?.()}catch{}}return}if(Ue===ce.WsText){try{ht.onmessage?.({data:LC.decode(je)})}catch{}return}if(Ue===ce.WsBinary){const We=new ArrayBuffer(je.byteLength);new Uint8Array(We).set(je);try{ht.onmessage?.({data:We})}catch{}return}if(Ue===ce.WsClose){let We=1e3,qe="";try{const ls=Aa(je,YS);We=ls.code,qe=ls.reason}catch{}He(We,qe);return}if(Ue===ce.StreamAbort){let We="stream aborted";try{We=Aa(je,zp).reason}catch{}He(1006,We,true)}},fail(Ue){He(1012,Ue.message,true)}});const{path:le,query:Me}=sS(V),cs=me&&me.length>0?{path:le,query:Me,protocols:me}:{path:le,query:Me};re.send(Mt(ce.WsOpen,ne,Ta(cs)))})(),ht},oS=()=>{if(h)return;h=true,A+=1,Ve(),Et(),x?.(),x=null;const V=S;S=null;const me=new Error("relay tunnel closed");V&&se(V,me),z(me);try{C?.close()}catch{}C=null,H({state:"idle"})};return jn(),{fetch:Pc,openWebSocket:nS,getStatus:()=>w,subscribeStatus(V){return b.add(V),()=>{b.delete(V)}},retry:an,close:oS}};let ns=null,ts=null;const zl=new Set;let _c=null;const fu=e=>{_c?.(),_c=null,ns=e,e&&(_c=e.subscribeStatus(t=>{for(const s of zl)s(t)}))},kz=e=>(zl.add(e),()=>{zl.delete(e)}),WC=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Fo=()=>ns,Sz=()=>!ns||!ts?null:{relayUrl:ts.relayUrl,serverId:ts.serverId,hostEncPubJwk:{...ts.hostEncPubJwk}},qC=()=>ns!==null,GC=e=>{if(ns&&ts&&WC(ts,e))return ns;ns?.close(),ts=e;const t=mu(e);return fu(t),t},Cz=(e,t)=>{if(ns===t){ts=e;return}ns?.close(),ts=e,fu(t)},zC=()=>{ns?.close(),fu(null),ts=null};let _f=()=>null,Nf="",Pr={},vo="",Hi=0,bn=null,co="",Wi=0,In="",yn=null,Ws="",ir=0,ar=0;const wu=1e4,$C=e=>e.toLowerCase()==="authorization",Lf=e=>{const t={};for(const[s,n]of Object.entries(e||{})){const o=s.trim(),i=n.trim();o&&i&&!$C(o)&&(t[o]=i)}return t},KC=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?false:s.every(([n,o])=>t[n]===o)},ec=e=>typeof e!="string"?"":e.trim(),JC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return ec(e)},YC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Uf=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():YC();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},bu=e=>{try{return new URL(e).origin}catch{return""}},jf=()=>{co="",Wi=0,In="",yn=null,Ws="",ir+=1},ra=()=>{vo="",Hi=0,jf()},Bf=()=>{ar+=1,bn=null,ra(),vu()},Vf=e=>{const t=ec(e);Nf=t,Bf(),_f=()=>t?{type:"bearer",token:t}:null},Hf=e=>{const t=Lf(e);KC(Pr,t)||(Pr=t,Bf())},_o=()=>{if(Object.keys(Pr).length>0)return Pr;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Lf(e):{}},yu=()=>Nf||JC(),XC=(e,t)=>{const s=ec(e);if(!s||typeof t!="number"||!Number.isFinite(t)){ra();return}vo=s,Hi=t},Wf=()=>!vo||Hi<=Date.now()+wu?(ra(),""):vo,qf=e=>{const t=bu(e);return!t||In!==t?"":!co||Wi<=Date.now()+wu?(co="",Wi=0,In="",""):co},QC=()=>{const e=Wf();return!e&&(yu()||typeof window<"u")&&tc().catch(()=>{}),e},ZC=e=>{const t=e?qf(e):"";return!t&&e&&typeof window<"u"&&Kf(e).catch(()=>{}),t},Gf=async()=>{const e=await _f(),t=e?.type==="bearer"?ec(e.token):yu();return t?{type:"bearer",token:t}:null},eT=d({token:c(),expiresAt:y(),expiresIn:y().optional()}),zf=async(e,t)=>{const s=await Gf(),n=new Headers;for(const[h,m]of Object.entries(_o()))n.set(h,m);s?.type==="bearer"&&n.set("Authorization",`Bearer ${s.token}`);const o=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",i=Fo(),a=i?await i.fetch(o,{method:"POST",headers:n}):await fetch(Uf(e,o),{method:"POST",headers:n,credentials:"include"});if(!a.ok)throw new Error(`Failed to mint runtime URL auth token (${a.status})`);const r=eT.safeParse(await a.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:l,expiresAt:u,expiresIn:p}=r.data;return{token:l.trim(),expiresAt:p===void 0?u:Date.now()+p}},Tz=async e=>{const t=await zf(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},$f=e=>{if(bn)return bn;const t=ar,n=(async()=>{let o;try{o=await zf(e)}catch(i){throw t===ar&&ra(),i}if(t!==ar)throw new Error("Runtime URL auth token response is stale");if(XC(o.token,o.expiresAt),!vo)throw new Error("Runtime URL auth token response was invalid");return vo})().finally(()=>{bn===n&&(bn=null)});return bn=n,bn},tT=e=>{const t=bu(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(yn&&Ws===t)return yn;const s=ir,o=(async()=>{const i=await fetch(Uf(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!i.ok)throw s===ir&&t===Ws&&(co="",Wi=0,In=""),new Error(`Failed to mint local runtime URL auth token (${i.status})`);const a=await i.json().catch(()=>null),r=typeof a?.token=="string"?a.token.trim():"",l=typeof a?.expiresAt=="number"?a.expiresAt:0;if(!r||!Number.isFinite(l))throw new Error("Local runtime URL auth token response was invalid");if(s!==ir||t!==Ws)throw new Error("Local runtime URL auth token response is stale");return co=r,Wi=l,In=t,r})().finally(()=>{yn===o&&(yn=null,Ws="")});return yn=o,Ws=t,yn},tc=async e=>{const t=Wf();return t||$f(e)},Kf=async e=>{const t=bu(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=qf(t);return s||((In&&In!==t||Ws&&Ws!==t)&&jf(),tT(t))};let so=0,yi=null,sT=null;const nT=5e3,Jf=()=>{yi!==null&&(clearTimeout(yi),yi=null)},vu=()=>{if(Jf(),so<=0||typeof window>"u")return;const e=Hi-wu-nT,t=Hi>0?Math.max(0,e-Date.now()):0;yi=setTimeout(()=>{yi=null,!(so<=0)&&$f(sT).catch(()=>{}).finally(()=>{vu()})},t)},Az=e=>{so+=1,vu();let t=false;return()=>{t||(t=true,so=Math.max(0,so-1),so===0&&Jf())}},Yf=async e=>{const t=new Headers(e);for(const[n,o]of Object.entries(_o()))t.has(n)||t.set(n,o);if(t.has("Authorization"))return t;const s=await Gf();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},ko=xt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Pz=e=>new Promise(t=>{if(e.aborted||ko.getState().state==="ok"){t();return}const s=()=>{n(),e.removeEventListener("abort",s),t()},n=ko.subscribe(o=>{o.state==="ok"&&s()});e.addEventListener("abort",s,{once:true})}),oT=15e3,iT=5*6e4;let $l=0,Nc=false;const aT=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),rT=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?false:!aT(t)},Xf=async()=>{if(!Nc){Nc=true;try{const{runtimeFetch:e}=await Ge(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>PT);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){ko.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:n}=ko.getState();s==="expired"&&n()}}catch{}finally{Nc=false}}},cT=(e,t)=>{if(t!==401||ko.getState().state==="expired"||!rT(e))return;const s=Date.now();s-$l<oT||($l=s,Xf())};let nh=false;const Rz=()=>{if(nh)return;nh=true;let e=Date.now();const t=()=>{if(ko.getState().state!=="ok")return;const s=Date.now();s-e<iT||(e=s,$l=s,Xf())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},lT=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,It=e=>{if(!e)return null;const t=lT.exec(e);return t?t[1]:null},Kl=e=>It(e)!==null,dT=()=>hu()||Mo()?.runtime?.isVSCode===true,uT=e=>!e||dT()||!Kl(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},Qf=e=>`/spaces/${e}`,xn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",pT=()=>typeof window>"u"?"":window.location.origin||"",ku=e=>{if(typeof window>"u")return false;const t=pT();if(t&&e.origin===t)return true;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return false}},Su=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),hT=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),hs=(e,t)=>{try{hT(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},Cu=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of s)o!=null&&e.searchParams.set(n,String(o))},gT=e=>{if(!e)return false;if(e instanceof Headers)return e.has("x-opencode-directory");const t=Array.isArray(e)?e:Object.entries(e);for(const[s]of t)if(s.toLowerCase()==="x-opencode-directory")return true;return false},mT=(e,t,s)=>{const n=uT(s);if(n===null||gT(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const o=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...o,...Object.entries(n)]}},fT=()=>{const e=Ss().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return null;const t=new URL(e);return`${t.origin}${t.pathname.replace(/\/api$/,"")}`},wT=e=>{try{const t=fT();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const n=s.pathname.replace(/\/+$/,"");return n?e.pathname!==n&&!e.pathname.startsWith(`${n}/`)?null:e.pathname.slice(n.length)||"/":e.pathname}catch{return null}},rr=e=>{const t=wT(e);return t!==null&&xn(t)},Lc=e=>{if(xn(e))return true;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return false;try{const t=new URL(e);return ku(t)&&xn(t.pathname)}catch{return false}},bT=(e,t)=>{try{const s=new URL(e);if(!ku(s))return e;const n=en(`${s.pathname}${s.search}`,t);return!Su(n)&&(s.protocol==="http:"||s.protocol==="https:")?(Cu(s,t),s.toString()):s.hash?`${n}${s.hash}`:n}catch{return e}},en=(e,t)=>e==="/health"?Ss().health(t):e.startsWith("/auth/")||e==="/auth"?Ss().auth(e,t):xn(e)?Ss().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?bT(e,t):e,Zf=e=>{const t=e instanceof Request?e.url:e.toString();if(!Su(t))return xn(t);try{return rr(new URL(t))}catch{return false}},ew=(e,t)=>Object.keys(_o()).length>0&&Mn()&&Zf(e)?{...t,redirect:"error"}:t,tw=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return false;return true},yT=(e,t)=>!tw(t),Rr=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 s=[];let n=false,o=false;for(const[i,a]of t)yT(i,a)?(s.push([i,encodeURIComponent(a)]),n=true,i.toLowerCase()==="x-opencode-directory"&&(o=true)):s.push([i,a]);return o&&s.push(["x-opencode-directory-encoding","uri"]),n?s:void 0},gs=async(e,t,s=true)=>{const n=new Headers(Rr(e)??e);return t&&new Headers(Rr(t)??t).forEach((o,i)=>n.set(i,o)),s?Yf(n):n},vT=(e,t)=>{if(!t)return e;const s=new URL(e,du);return Cu(s,t),`${s.pathname}${s.search}`},sw=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!Su(s))return xn(s)?vT(s,t):null;try{const n=new URL(s);return!ku(n)||!xn(n.pathname)?null:(Cu(n,t),`${n.pathname}${n.search}`)}catch{return null}},kT=async(e,t,s)=>{const n=Fo();if(!n)return null;const o=sw(e,s);if(o===null)return null;const i=e instanceof Request?e.headers:void 0,a=await gs(i,t.headers,true);return e instanceof Request?n.fetch(e,{...t,headers:a}):n.fetch(o,{...t,headers:a})},ST=(e,t)=>{if(typeof e=="string")return en(e,t);if(e instanceof URL)return en(e.toString(),t);const s=en(e.url,t);return s===e.url?e:new Request(s,e)},CT=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Ea=new Map,TT=(e,t,s,n)=>s||e!=="GET"||t.includes("/event")||!CT.test(t)?null:`GET ${t}\0${n.get("x-opencode-directory")??""}`;let nw=null;const AT=e=>{nw=e},P=async(e,t={})=>{const{query:s,directory:n,...o}=t,i=e,a=mT(i,o,n),r=Fo(),l=r?sw(i,s):null;let u,p,h,m;if(r&&l!==null){const E=i instanceof Request?i.headers:void 0,B=await gs(E,a.headers,true);u=i instanceof Request?()=>r.fetch(i,{...a,headers:B}):()=>r.fetch(l,{...a,headers:B}),m=B,p=l,h=String(a.method??(i instanceof Request?i.method:"GET")).toUpperCase()}else{const E=ST(i,s),B=E instanceof Request?E.headers:void 0,K=await gs(B,a.headers,Zf(E)),j=E instanceof Request?E.url:E instanceof URL?E.toString():String(E);hs(j,K);const H=ew(E,{...a,headers:K});u=E instanceof Request?()=>fetch(new Request(E,H)):()=>fetch(E,H),m=K,p=j,h=String(a.method??(E instanceof Request?E.method:"GET")).toUpperCase()}const w=u,b=nw;u=async()=>{const E=b?performance.now():0;try{const B=await w();return cT(p,B.status),b?.({method:h,url:p,status:B.status,durationMs:performance.now()-E}),B}catch(B){throw b?.({method:h,url:p,status:null,durationMs:performance.now()-E}),B}};const S=a.signal!=null||i instanceof Request,C=TT(h,p,S,m);if(!C)return u();const x=Ea.get(C);if(x)return x.then(E=>E.clone());const A=u();return Ea.set(C,A),A.then(()=>Ea.delete(C),()=>Ea.delete(C)),A.then(E=>E.clone())};let oh=false,ow=null;const iw=(e,t)=>(ow??globalThis.fetch.bind(globalThis))(e,t),aw=()=>{if(oh||typeof window>"u")return;oh=true;const e=window.fetch.bind(window);ow=e;const t=(s,n)=>e(s,ew(s,n));window.fetch=async(s,n)=>{const o=await kT(s,n??{});if(o)return o;if(typeof s=="string"){if(!Lc(s)){try{const r=new URL(s);if(rr(r)){const l=await gs(void 0,n?.headers);return hs(r.toString(),l),t(s,{...n,headers:l})}}catch{}return t(s,n)}const i=await gs(void 0,n?.headers),a=en(s);return hs(a,i),t(a,{...n,headers:i})}if(s instanceof URL){const i=s.toString();if(!Lc(i)){if(rr(s)){const l=await gs(void 0,n?.headers);return hs(s.toString(),l),t(s,{...n,headers:l})}return t(s,n)}const a=await gs(void 0,n?.headers),r=en(i);return hs(r,a),t(r,{...n,headers:a})}if(s instanceof Request){if(!Lc(s.url)){try{const l=new URL(s.url);if(rr(l)){const u=await gs(s.headers,n?.headers);return hs(l.toString(),u),t(new Request(s,{...n,headers:u}))}}catch{}return t(s,n)}const i=await gs(s.headers,n?.headers),a=en(s.url);hs(a,i);const r=a===s.url?s:new Request(a,s);return t(new Request(r,{...n,headers:i}))}return t(s,n)}},PT=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:hs,buildRuntimeFetchUrl:en,fetchBypassingRuntimeBridge:iw,installRuntimeFetchBridge:aw,isLatin1Safe:tw,runtimeFetch:P,sanitizeHeadersForBrowser:Rr,setRuntimeRequestObserver:AT},Symbol.toStringTag,{value:"Module"})),lo=16384,Ir=globalThis,RT=e=>{if(Ir.Buffer)return Ir.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let n=0;n<t.length;n+=32768)s+=String.fromCharCode(...t.slice(n,n+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},rw=e=>{try{if(Ir.Buffer)return Ir.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),n=new Uint8Array(s.length);for(let o=0;o<s.length;o+=1)n[o]=s.charCodeAt(o);return new TextDecoder().decode(n)}catch{return null}},IT=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString().replace(/\/+$/g,""))}catch{return null}},xT=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="ws:"&&s.protocol!=="wss:"?null:(s.hash="",s.toString())}catch{return null}},ih=e=>typeof e=="string"&&e.length>0,ET=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ih(t.x)||!ih(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},OT=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,DT=e=>{if(!e||typeof e!="object")return null;const t=e,s=OT(t.priority);if(t.type==="lan"||t.type==="tunnel"){const n=IT(t.url);return n?s===void 0?{type:t.type,url:n}:{type:t.type,url:n,priority:s}:null}if(t.type==="relay"){const n=xT(t.relayUrl);if(!n)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const i=ET(t.hostEncPubJwk);if(!i)return null;const a=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:n,serverId:o,hostEncPubJwk:i,...a?{grant:a}:{},...s===void 0?{}:{priority:s}}}return null},Tu=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const s=typeof t.pairingId=="string"?t.pairingId.trim():"",n=typeof t.secret=="string"?t.secret.trim():"";if(!s||!n)return null;const o=Array.isArray(t.candidates)?t.candidates.map(DT).filter(l=>!!l):[];if(o.length===0)return null;const i=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(i){const l=Date.parse(i);if(!Number.isFinite(l)||l<=Date.now())return null}const a=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,r=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:s,secret:n,...a?{label:a}:{},...r?{fingerprint:r}:{},...i?{expiresAt:i}:{},candidates:o}},Iz=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}),xz=e=>{const t=Tu(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",RT(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},MT=e=>{const t=e.trim();if(!t||t.length>lo)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const n=s.searchParams.get("p")||"";if(!n||n.length>lo)return null;const o=rw(n);return!o||o.length>lo?null:Tu(JSON.parse(o))}catch{return null}},Ez=e=>{const t=e.trim();if(!t||t.length>lo)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let n=null,o=null;for(const a of t.slice(s+1).split("&")){const r=a.indexOf("=");if(r===-1)continue;const l=a.slice(0,r),u=a.slice(r+1);l==="v"?n=u:l==="p"&&(o=u)}if(n!=="2"||!o||o.length>lo)return null;const i=rw(o);if(!i||i.length>lo)return null;try{return Tu(JSON.parse(i))}catch{return null}},So=e=>typeof e=="object"&&e!==null,FT=e=>e.trim().toLowerCase()==="authorization",_T=e=>{if(!So(e))return;const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=typeof n=="string"?n.trim():"";!o||!i||/[\r\n:]/.test(o)||/[\r\n]/.test(i)||FT(o)||(t[o]=i)}return Object.keys(t).length>0?t:void 0},NT=e=>`relay://${e}`,LT=e=>{if(!So(e))return null;const t=Qe(e,"relayUrl")||Qe(e,"relay_url"),s=Qe(e,"serverId")||Qe(e,"server_id"),n=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!So(n)?null:{relayUrl:t,serverId:s,hostEncPubJwk:n}},UT=()=>{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"},ah=15e3,Oz=async(e,t)=>{const s=MT(e);if(!s)throw new Error("invalid-connect-link");const n=await WT().catch(()=>""),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:s.pairingId,secret:s.secret,clientLabel:s.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:UT(),...n?{dedupeKey:`desktop:${n}`}:{}})},i=async C=>{if(!C.ok)return null;const x=await C.json().catch(()=>null);return(typeof x?.clientToken=="string"?x.clientToken.trim():"")||null};let a=null;const r=[...s.candidates].sort((C,x)=>(C.type==="relay"?1:0)-(x.type==="relay"?1:0));for(const C of r){if(C.type==="relay"){const A=mu({relayUrl:C.relayUrl,serverId:C.serverId,hostEncPubJwk:C.hostEncPubJwk,...C.grant?{grant:C.grant}:{}});try{const E=await i(await A.fetch("/api/client-auth/pairing/redeem",{...o,signal:AbortSignal.timeout(ah)}));if(E){a={relay:{relayUrl:C.relayUrl,serverId:C.serverId,hostEncPubJwk:C.hostEncPubJwk},token:E};break}}catch{}finally{A.close()}continue}const x=$e(C.url);if(x)try{const A=await i(await fetch(`${x}/api/client-auth/pairing/redeem`,{...o,signal:AbortSignal.timeout(ah)}));if(A){a={directUrl:x,token:A};break}}catch{}}if(!a)throw new Error("pairing-redeem-failed");const l=s.candidates.find(C=>C.type==="relay"),u=a.relay||(l?{relayUrl:l.relayUrl,serverId:l.serverId,hostEncPubJwk:l.hostEncPubJwk}:void 0),p=s.candidates.filter(C=>C.type!=="relay").map(C=>$e(C.url)).find(C=>!!C),h=a.directUrl||p,m=h||(u?NT(u.serverId):null);if(!m)throw new Error("pairing-missing-transport");const w=t.find(C=>u?C.relay?.serverId===u.serverId:!C.relay&&$e(C.apiUrl||C.url)===m),b=w?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),S={...w||{},id:b,label:s.label||w?.label||cw(m),url:m,apiUrl:h,clientToken:a.token,...u?{relay:u}:{}};return{hostId:b,hosts:w?t.map(C=>C.id===b?S:C):[S,...t]}},jT=/^(t|.*(?:token|auth|secret|api).*)$/i,$e=e=>{const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},Dz=e=>{const t=$e(e);if(!t)return null;try{const s=new URL(t);if((s.pathname.replace(/\/+$/,"")||"/")==="/connect"&&s.searchParams.has("t"))return{persistedUrl:s.origin,redeemUrl:s.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},cw=e=>{const t=$e(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const n=Array.from(new Set(Array.from(s.searchParams.keys())));for(const o of n)jT.test(o)&&s.searchParams.set(o,"[REDACTED]");return s.toString()}catch{return t}},Oa=(e,t)=>{const s=$e(e),n=$e(t);if(!s||!n)return false;try{const o=new URL(s),i=new URL(n);if(o.origin!==i.origin||i.search&&o.search!==i.search)return false;const a=i.pathname.length>1?i.pathname.replace(/\/+$/,""):i.pathname,r=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return a==="/"?true:r===a||r.startsWith(`${a}/`)}catch{return false}},Qe=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},rh=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},BT=e=>{if(!So(e))return null;const t=Qe(e,"id"),s=Qe(e,"label"),n=Qe(e,"url"),o=Qe(e,"apiUrl")||Qe(e,"api_url"),i=Qe(e,"clientToken")||Qe(e,"client_token"),a=_T(e.requestHeaders),r=LT(e.relay);if(!t||!s||!n)return null;const l={id:t,label:s,url:n,...o?{apiUrl:o}:{},...i?{clientToken:i}:{},...a?{requestHeaders:a}:{},...r?{relay:r}:{}};return e.sshForwarded===true&&(l.sshForwarded=true),l},uo=e=>$e(e.apiUrl||e.url)||e.apiUrl||e.url,Es=()=>rt()?(e,t)=>ie(e,t):null,qi=async()=>{const e=Es();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:false};const t=await e("desktop_hosts_get");if(!So(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:false};const s=t.hosts,n=Array.isArray(s)?s.map(BT).filter(r=>!!r):[],o=Qe(t,"defaultHostId")||Qe(t,"default_host_id")||Qe(t,"defaultHostID"),i=t.initialHostChoiceCompleted===true||t.initial_host_choice_completed===true,a=Qe(t,"localOrigin")||Qe(t,"local_origin");return{hosts:n,defaultHostId:o,initialHostChoiceCompleted:i,localOrigin:a}},VT=async e=>{const t=Es();if(!t)return;const s={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(s.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:s})},HT=async()=>{const e=Es();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Mz=async()=>{const e=Es();return e?await e("desktop_switch_to_local").catch(()=>false)===true:false},WT=async()=>{const e=Es();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},qT=8e3,GT=15e3,zT=400,$T=async(e,t,s,n)=>{const o=new AbortController,i=window.setTimeout(()=>o.abort(),s);try{return await e.fetch(t,{...n,signal:o.signal})}finally{window.clearTimeout(i)}},ch=async(e,t,s,n)=>{for(;;){const o=s-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await $T(e,t,Math.min(qT,o),n)}catch(i){if(e.getStatus().state==="error"||Date.now()>=s)throw i;await new Promise(a=>window.setTimeout(a,zT))}}},KT=async(e,t)=>{const s=mu({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),n=Date.now()+GT;let o=false;try{if(!(await ch(s,"/health",n)).ok)return{status:"unreachable",latencyMs:0};const a=Date.now(),r=new Headers({Accept:"application/json"});for(const[p,h]of Object.entries(t?.requestHeaders||{}))p.toLowerCase()!=="authorization"&&r.set(p,h);const l=t?.clientToken?.trim();l&&r.set("Authorization",`Bearer ${l}`);const u=await ch(s,"/auth/session",n,{headers:r});return u.status===401||u.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-a)}:u.ok?(o=t?.keepTunnel===true,{status:"ok",latencyMs:Math.max(0,Date.now()-a),...o?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:BC(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{o||s.close()}},sc=async(e,t)=>{const s=Es();if(!s)return{status:"unreachable",latencyMs:0};const n=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!So(n))return{status:"unreachable",latencyMs:0};const o=n.status,i=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",a=rh(n,"latencyMs")??rh(n,"latency_ms")??0;return{status:i,latencyMs:a}},JT=Z("status",[d({status:g("started")}),d({status:g("auth")}),d({status:g("failed"),error:c().nullable()})]),Fz=async e=>{const t=Es();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),n=JT.safeParse(s);return n.success?n.data:{status:"failed",error:null}},YT=600*1e3,XT=3e3,_z=async(e,{maxWaitMs:t=YT,intervalMs:s=XT,readHosts:n=qi,probe:o=sc}={})=>{const i=Date.now()+t;for(;Date.now()<i;){await new Promise(l=>setTimeout(l,Math.min(s,Math.max(0,i-Date.now()))));const a=(await n()).hosts.find(l=>l.id===e);if(!a)return"timeout";const r=await o(uo(a),{clientToken:a.clientToken,requestHeaders:a.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},Nz=async(e,t)=>{const s=Es();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Lz=async e=>{const t=Es();t&&await t("desktop_new_window_for_host",{hostId:e})},Xs="local",QT=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",ZT=(e,t)=>t?[{id:Xs,label:"Local",url:t},...e]:e,eA=e=>e.id===Xs?"local":`host:${e.id}`,Uz=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(m=>m.id===Xs)?.url||QT(),n=os(),o=$e(s)||s,i=$e(t)||t,a=F(),r=e.find(m=>m.relay&&eA(m)===a);if(r)return{id:r.id,label:r.label,url:r.url};if(n&&Oa(n,s))return{id:Xs,label:"Local",url:o};const l=e.find(m=>n?Oa(n,uo(m)):false);if(l)return{id:l.id,label:l.label,url:$e(uo(l))||uo(l)};if(t&&Oa(t,s))return{id:Xs,label:"Local",url:o};const u=e.find(m=>t?Oa(t,m.url):false);if(u)return{id:u.id,label:u.label,url:$e(u.url)||u.url};const p=t.startsWith("openchamber-ui://");if(p&&s&&!n)return{id:Xs,label:"Local",url:o};const h=n?$e(n)||n:p?"":i;return{id:"custom",label:cw(h||"Instance"),url:h}},xr=new Map;let lw=0;const vi=new Map,po=new Set;let Jl=0,dw={byHostId:{},isProbing:false};const Yl=new Set,Er=()=>{dw={byHostId:Object.fromEntries(xr),isProbing:Jl>0};for(const e of Yl)try{e()}catch{}},jz=e=>(Yl.add(e),()=>{Yl.delete(e)}),Bz=()=>dw,uw=(e,t)=>{xr.set(e,t),Er()},Vz=(e,t)=>{vi.set(e,++lw),po.delete(e),uw(e,t)},Hz=e=>po.has(e),tA=e=>{const t=new Set([Xs,...e]);let s=false;for(const n of Array.from(xr.keys()))t.has(n)||(xr.delete(n),vi.delete(n),po.delete(n),s=true);s&&Er()},sA=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",nA=async()=>Dn()?HT().catch(()=>""):"",oA=async(e,t)=>{const s=e.id===Xs?t:e.clientToken||"",n=async()=>{const a=await KT(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:a.status,latencyMs:a.latencyMs};return a.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return n();const o=$e(Dn()?uo(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const i=await sc(o,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(sA(i.status)&&e.relay){const a=await n();if(a.status==="ok"||a.status==="relay-limit")return a}return{status:i.status,latencyMs:i.latencyMs}},iA=async e=>{if(!it())return;const t=++lw;for(const s of e)vi.set(s.id,t),po.add(s.id);Jl+=1,Er();try{const s=await nA();await Promise.all(e.map(async n=>{const o=await oA(n,s);vi.get(n.id)===t&&(po.delete(n.id),uw(n.id,o))}))}finally{for(const s of e)vi.get(s.id)===t&&po.delete(s.id);Jl-=1,Er()}};let lh=false;const aA=async()=>{if(lh||!it())return;lh=true;const e=await qi().catch(()=>null);e&&(tA(e.hosts.map(t=>t.id)),await iA(ZT(e.hosts,e.localOrigin)))},rA=5e3,cA=1500;let Uc=false;const jc=e=>{const t=String(e??"").trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString())}catch{return null}},lA=async e=>{if(!Dn()||Uc)return;const t=`host:${e}`;if(F()===t){Uc=true;try{const s=await qi().catch(()=>null),n=s?.hosts.find(b=>b.id===e);if(!s||!n?.relay)return;const o=n.apiUrl?$e(n.apiUrl):null;if(o&&o.startsWith("https://"))return;const i=await P("/api/client-auth/connection/candidates").catch(()=>null);if(!i?.ok)return;const a=await i.json().catch(()=>null);if(!a||a.serverId!==n.relay.serverId)return;const r=Array.isArray(a.candidates)?a.candidates:[],l=[];for(const b of r){if(!b||typeof b!="object")continue;const S=b;if(S.type!=="lan"||typeof S.url!="string")continue;const C=$e(S.url);C&&!l.includes(C)&&l.push(C)}if(l.length===0)return;const u=o&&l.includes(o)?o:l[0],p=jc(u);p&&p!==jc(o)&&await VT({hosts:s.hosts.map(b=>b.id===e?{...b,apiUrl:u}:b),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const m=(await qi().catch(()=>null))?.hosts.find(b=>b.id===e)??null;if(!m||!p||jc(m.apiUrl)!==p)return;const w=await sc(u,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(w.status==="unreachable"||w.status==="wrong-service"||w.status==="incompatible"||F()!==t)return;ql({apiBaseUrl:u,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:t})}finally{Uc=false}}},dA=e=>{typeof window>"u"||window.setTimeout(()=>{lA(e).catch(()=>{})},rA)},dh=async(e,t)=>{if(!Dn())return;const s=await qi().catch(()=>null);if(!s)return;const n=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!n)return;const o=s.hosts.find(m=>m.id===n);if(!o?.relay)return;const i=`host:${o.id}`;if(F()===i&&!t?.reconnectActive)return;const a=m=>{ql({apiBaseUrl:m,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:i})},r=()=>{ql({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:o.clientToken||null,runtimeKey:i,relay:o.relay??void 0}),dA(o.id)},l=o.apiUrl?$e(uo(o)):null;if(!l){r();return}const u=m=>m.status!=="unreachable"&&m.status!=="wrong-service"&&m.status!=="incompatible",p=sc(l,{clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,expectedServerId:o.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),h=await Promise.race([p,new Promise(m=>setTimeout(()=>m(null),cA))]);if(h){if(u(h)){a(l);return}r();return}r(),p.then(m=>{u(m)&&F()===i&&a(l)})};class uh extends Error{constructor(t,s){super(`Agent '${t}' is not available in ${s??"the session's folder"}`),this.agent=t,this.directory=s,this.name="AgentUnavailableError"}agent;directory}const uA=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class Lt extends Error{reason;status;maxBytes;constructor(t,s={}){super(t),this.name="FilesystemError",this.reason=s.reason??"unknown",this.status=s.status,this.maxBytes=s.maxBytes}}const pA=e=>e instanceof Lt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),ki=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"too-large":case"outside-workspace":case"invalid-response":return e;default:return"unknown"}},hA=d({message:c()}),Wz=e=>{if(pA(e)&&e.reason==="not-found")return true;const t=hA.safeParse(e),n=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return n.includes("file not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")},dn=new Map;let Bc;async function ph(e){const t=Ss().api("/api").replace(/\/api\/?$/,""),s=Fo(),n=await Yf();if(F()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(i,a)=>{const r=i instanceof Request?i.url:String(i),l=r.startsWith("/")?`${t}${r}`:r,u=new Headers(i instanceof Request?i.headers:void 0);return new Headers(Rr(a?.headers)??a?.headers).forEach((p,h)=>u.set(h,p)),n.forEach((p,h)=>u.set(h,p)),s?s.fetch(i,{...a,headers:u}):(hs(l,u),iw(i instanceof Request?new Request(l,i):l,{...a,headers:u}))},baseUrl:t}}async function pw(e){const t=!!os()&&!Fo(),s=await ph(e);return async n=>{let o=false;const i=async()=>{if(!o){o=true;try{const r=F()===e;if(!t&&!r)return;await n(r?await ph(e):s),dn.get(e)?.delete(i),dn.get(e)?.size===0&&dn.delete(e),dn.size===0&&(Bc?.(),Bc=void 0)}catch{}finally{o=false}}},a=dn.get(e)??new Set;a.add(i),dn.set(e,a),Bc??=Qr(({runtimeKey:r})=>{for(const l of dn.get(r)??[])l()}),await i()}}const Or=()=>({active:0,waiters:[],activeSessionWaiters:[]});let qs=Or(),Cn=Or();const gA=3,hh=2;Xr(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[qs,Cn];qs=Or(),Cn=Or();for(const n of s){for(const o of[...n.activeSessionWaiters,...n.waiters])o(false);n.activeSessionWaiters.length=0,n.waiters.length=0}});const gh=()=>{for(;qs.active+Cn.active<gA;){const e=Cn.active<hh&&Cn.waiters.length>0?Cn:qs.active<hh&&(qs.activeSessionWaiters.length>0||qs.waiters.length>0)?qs:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(true)}};async function hw(e,t,s){const n=or();if(await new Promise(i=>{s==="active-session"?e.activeSessionWaiters.push(i):e.waiters.push(i),gh()}))try{if(!n())return;const i=await t();return n()?i:void 0}finally{e.active-=1,gh()}}const mA=(e,t="normal")=>hw(qs,e,t),qz=e=>hw(Cn,e,"normal"),gw="/api/opencode/trust",fA="opencode_trust_required",wA=d({kind:T(["plugin","package","mcp","lsp","formatter","shell","config","env","file","permission"]),source:c(),name:c(),detail:c()}),bA=d({directory:c(),trusted:v(),fingerprint:c().nullable(),items:k(wA)}),yA=d({code:g(fA),directory:c()});let An=null;const Xl=new Set,ci=new Map,Gi=new Set,Cs=new Map;let Ql=Promise.resolve(),Gs=0;const ho=()=>{for(const e of Xl)e()},Gz=()=>An,zz=e=>(Xl.add(e),()=>{Xl.delete(e)}),$z=e=>An?An.settle(e):Promise.resolve("skipped");Xr(()=>{Gs+=1,An?.settle("skip"),ci.clear(),Gi.clear(),Cs.clear(),Ql=Promise.resolve(),ho()});const Kz=e=>e?Cs.has(e):false,mw=(e,t)=>{Cs.set(e,e);for(const s of t)Cs.set(s,e)},zi=e=>{const t=Cs.get(e);if(t!==void 0){for(const[s,n]of Cs)n===t&&Cs.delete(s);ho()}},vA=()=>{Gi.clear()},kA=async e=>{if(e.status!==403)return null;try{const t=yA.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},fw=async e=>bA.parse(await e.json()),cr=async e=>{const t=await P(gw,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return fw(t)},SA=async e=>{const t=await P(gw,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({directory:e.directory,fingerprint:e.fingerprint})});if(t.status===409)return{kind:"changed",assessment:await fw(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},CA=(e,t,s)=>new Promise(n=>{const o=i=>{if(t!==Gs){n(false);return}An={directory:i.directory,items:i.items,settle:async a=>{if(a==="skip")return Gi.add(`${i.directory}
|
|
2
|
+
import{_ as Ge}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as xt,d as Do,p as aa,a as aS}from"./vendor-zustand-C9tWdk0j.js";import{o as d,s as c,n as y,l as g,e as v,c as k,f as Z,_ as T,u as L,a as be,j as nt,N as nf,h as oe,i as rS,k as kr,p as Ps,q as nr,v as cS,w as Jr,x as of,y as lS,z as Sa}from"./vendor-zod-DV_WH382.js";import{e as af,C as Wp}from"./vendor-opencode-client-NJGkA1Ku.js";import{f as yt,R as sn,r as dS}from"./vendor-react--VO_rL_p.js";import{F as rf}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as uS}from"./vendor-streamdown-BbSYZ3NF.js";import{u as pS}from"./vendor-unified-1CQKw2_w.js";import{c as hS}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as gS}from"./vendor-capacitor-core-B4EWRrHz.js";const wi=1,mS=d({type:g("relay-retire"),code:y().int(),reason:c().catch("")}),fS=e=>{try{const t=mS.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},wS="openchamber-relay-v1",cf=1,lf=12,bi=1+lf,Ui=64*1024,ji=5,Sr=128,df=0,uf=1,bo=4,bS=1+bo,_l=Ui-ji-bS,yS="x-openchamber-tunnel-accept-encoding",vS="x-openchamber-tunnel-content-encoding",ce={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},kS=new Set(Object.values(ce)),SS=e=>kS.has(e),Zs={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},ys=globalThis.crypto.subtle,pf={name:"ECDH",namedCurve:"P-256"},hf=16,xc=32,CS=16,Nl=4,gf=8;class fs extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const TS=()=>ys.generateKey(pf,true,["deriveBits"]),AS=async e=>{const t=await ys.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},PS=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new fs("invalid ECDH public key JWK");try{return await ys.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:true},pf,true,[])}catch{throw new fs("invalid ECDH public key JWK")}},RS=()=>{const e=new Uint8Array(hf);return globalThis.crypto.getRandomValues(e),e},IS=async(e,t,s)=>{if(s.length!==hf)throw new fs("invalid handshake nonce length");const n=await ys.deriveBits({name:"ECDH",public:t},e,256),o=await ys.importKey("raw",n,"HKDF",false,["deriveBits"]),i=new Uint8Array(await ys.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(wS)},o,xc*2*8)),a=(r,l)=>ys.importKey("raw",r,{name:"AES-GCM"},false,l);return{clientToHost:await a(i.slice(0,xc),["encrypt","decrypt"]),hostToClient:await a(i.slice(xc),["encrypt","decrypt"])}},xS=(e,t,s)=>{for(let n=gf-1;n>=0;n-=1)e[t+n]=Number(s&0xffn),s>>=8n},ES=(e,t)=>{let s=0n;for(let n=0;n<gf;n+=1)s=s<<8n|BigInt(e[t+n]);return s},OS=e=>{const t=new Uint8Array(Nl);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(n){if(n.length>Ui)throw new fs("plaintext frame exceeds maximum size");s+=1n;const o=new Uint8Array(lf);o.set(t,0),xS(o,Nl,s);const i=new Uint8Array(await ys.encrypt({name:"AES-GCM",iv:o},e,n)),a=new Uint8Array(bi+i.length);return a[0]=cf,a.set(o,1),a.set(i,bi),a}}},DS=e=>{let t=0n;return{async decrypt(s){if(s.length<bi+CS)throw new fs("encrypted frame too short");if(s[0]!==cf)throw new fs("unsupported encrypted frame version");const n=s.slice(1,bi),o=ES(n,Nl);if(o<=t)throw new fs("frame counter regression");if(o!==t+1n)throw new fs("frame counter gap");let i;try{i=await ys.decrypt({name:"AES-GCM",iv:n},e,s.slice(bi))}catch{throw new fs("frame decryption failed")}return t=o,new Uint8Array(i)}}},Ca="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",MS=e=>{let t="";for(let s=0;s<e.length;s+=3){const n=e[s],o=s+1<e.length?e[s+1]:void 0,i=s+2<e.length?e[s+2]:void 0;t+=Ca[n>>2],t+=Ca[(n&3)<<4|(o??0)>>4],o!==void 0&&(t+=Ca[(o&15)<<2|(i??0)>>6]),i!==void 0&&(t+=Ca[i&63])}return t},qp=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const s=t;if(s.v!==wi)return null;const n=s.batch===true,o=s.flowControl===true;return s.t==="ready"?{t:"ready",v:wi,batch:n,flowControl:o}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:wi,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:n,flowControl:o}:null},FS=e=>({type:"fail",closeCode:Zs.ChannelFailure,reason:e}),_S=async(e,t={})=>{const s=t.batch!==false,n=await PS(e),o=await TS(),i=RS(),a={t:"hello",v:wi,clientPubJwk:await AS(o.publicKey),nonce:MS(i)};s&&(a.batch=true),t.flowControl!==false&&(a.flowControl=true);let r=false;return{helloText:JSON.stringify(a),get established(){return r},async handleText(l){if(r)return qp(l)?.t==="ready"?{type:"ignore"}:FS("plaintext frame on established channel");const u=qp(l);if(u?.t!=="ready")return{type:"ignore"};const p=await IS(o.privateKey,n,i);return r=true,{type:"established",batch:s&&u.batch===true,flowControl:t.flowControl!==false&&u.flowControl===true,channel:{encryptor:OS(p.clientToHost),decryptor:DS(p.hostToClient)}}}}},mf=4294967295,NS=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class ze extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Mt=(e,t,s,n=false)=>{if(!Number.isInteger(t)||t<0||t>mf)throw new ze("invalid stream id");if(s.length>_l)throw new ze("tunnel payload exceeds maximum size");const o=new Uint8Array(ji+s.length);return o[0]=n?e|Sr:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(s,ji),o},LS=e=>{if(e.length<ji)throw new ze("tunnel frame too short");const t=e[0],s=(t&Sr)!==0,n=t&~Sr;if(!SS(n))throw new ze(`unknown tunnel frame type ${n}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:n,streamId:o,payload:e.slice(ji),hasMoreFragments:s}},US=new TextEncoder,jS=new TextDecoder,Ta=e=>US.encode(JSON.stringify(e)),Aa=(e,t)=>{let s;try{s=JSON.parse(jS.decode(e))}catch{throw new ze("malformed JSON tunnel payload")}if(!t(s))throw new ze("unexpected JSON tunnel payload shape");return s},ff=(e,t=_l)=>{if(t<=0||t>_l)throw new ze("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},Gp=(e,t,s)=>{const n=ff(s);return n.map((o,i)=>Mt(e,t,o,i<n.length-1))},BS=(e=16*1024*1024)=>{const t=new Map;return{push(s){const n=`${s.streamId}:${s.frameType}`,o=t.get(n);if(!s.hasMoreFragments&&!o)return s.payload;const i=o?.chunks??[],a=(o?.totalBytes??0)+s.payload.length;if(a>e)throw t.delete(n),new ze("fragmented message exceeds maximum size");if(i.push(s.payload),s.hasMoreFragments)return t.set(n,{chunks:i,totalBytes:a}),null;t.delete(n);const r=new Uint8Array(a);let l=0;for(const u of i)r.set(u,l),l+=u.length;return r},dropStream(s){for(const n of t.keys())n.startsWith(`${s}:`)&&t.delete(n)}}},VS=e=>{if(e.length===0)throw new ze("cannot encode an empty frame batch");if(e.length===1){const o=e[0],i=new Uint8Array(1+o.length);if(i[0]=df,i.set(o,1),i.length>Ui)throw new ze("frame batch exceeds maximum plaintext size");return i}let t=1;for(const o of e)t+=bo+o.length;if(t>Ui)throw new ze("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=uf;let n=1;for(const o of e)s[n]=o.length>>>24&255,s[n+1]=o.length>>>16&255,s[n+2]=o.length>>>8&255,s[n+3]=o.length&255,n+=bo,s.set(o,n),n+=o.length;return s},HS=e=>{if(e.length<1)throw new ze("empty batch plaintext");const t=e[0];if(t===df)return[e.slice(1)];if(t!==uf)throw new ze(`unknown batch container tag ${t}`);const s=[];let n=1;for(;n<e.length;){if(n+bo>e.length)throw new ze("truncated batch frame length");const o=(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0;if(n+=bo,n+o>e.length)throw new ze("truncated batch frame body");s.push(e.slice(n,n+o)),n+=o}if(s.length===0)throw new ze("empty frame batch");return s},WS=new Set([ce.HttpBody,ce.WsText,ce.WsBinary]),wf=150,qS=24*1024,GS=32,zS=e=>{const t=e.windowMs??wf,s=e.maxBatchBytes??qS,n=e.maxBatchFrames??GS,o=e.now??(()=>Date.now()),i=e.setTimer??((S,C)=>setTimeout(S,C)),a=e.clearTimer??(S=>clearTimeout(S));let r=[],l=0,u=null,p=0,h=false;const m=()=>{u!==null&&(a(u),u=null)},w=()=>{if(m(),r.length===0)return;const S=r;r=[],l=0,p=o(),e.sendBatch(VS(S))};return{enqueue:S=>{if(h)return;const C=S[0]&~Sr;if(!WS.has(C)){r.push(S),w();return}const x=o();if(r.length===0&&x-p>=t){r.push(S),w();return}const A=bo+S.length;if(r.length>0&&1+l+A>Ui&&w(),r.push(S),l+=A,l>=s||r.length>=n){w();return}u===null&&(u=i(w,t))},flush:w,dispose(){h=true,m(),r=[],l=0}}},$S=()=>{let e=1;return{next(){if(e>mf)throw new ze("stream id space exhausted");const t=e;return e+=2,t}}},Yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KS=e=>Yr(e)&&Object.values(e).every(t=>typeof t=="string"),JS=e=>Yr(e)&&typeof e.status=="number"&&KS(e.headers),zp=e=>Yr(e)&&typeof e.reason=="string",YS=e=>Yr(e)&&typeof e.code=="number"&&typeof e.reason=="string",bf=/^[a-z][a-z\d+.-]*:\/\//i,du="http://tunnel.invalid",XS=e=>{try{const t=bf.test(e)?new URL(e):new URL(e,du);return`${t.pathname}${t.search}`}catch{return e}},Pa=e=>({async*[Symbol.asyncIterator](){yield e}}),QS=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:n}=await t.read();if(s)return;n&&(yield n)}}finally{t.releaseLock()}}}),ZS=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},eC=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:QS(e)};if(typeof e=="string")return{body:Pa(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Pa(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Pa(ZS(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,n=new Uint8Array(await t.arrayBuffer());return{body:Pa(n),contentType:s}},tC=async(e,t)=>{let s;const n=new Headers;let o="GET",i=null,a;e instanceof Request?(s=e.url,o=e.method,e.headers.forEach((h,m)=>n.set(m,h)),a=e.signal,i=e.body):s=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((h,m)=>n.set(m,h)),t.body!==void 0&&(i=t.body),t.signal&&(a=t.signal));const r=bf.test(s)?new URL(s):new URL(s,du),{body:l,contentType:u}=await eC(i);u&&!n.has("content-type")&&n.set("content-type",u);const p={};return n.forEach((h,m)=>{p[m]=h}),{method:o.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:p,body:l,signal:a}},yf="__openchamberAmbiguousTransport",vf=new WeakSet,sC=e=>(vf.add(e),e),nC=e=>vf.has(e),Ll=e=>(Object.defineProperty(e,yf,{value:true,enumerable:false,configurable:true}),e),oC=e=>!e||typeof e!="object"?false:e[yf]===true,iC=["local","remote",null],aC=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function kf(e){if(!e||typeof e!="object")return{valid:false};const t=e,s=t.localAvailable===false?{localAvailable:false}:{},n=t.target,o=t.status;if(n!==null&&(typeof n!="string"||!iC.includes(n)))return{valid:false};if(typeof o!="string"||!aC.includes(o))return{valid:false};if(n==="remote"||n==="local"){if(o==="ok"&&n==="local"){const i={target:"local",status:"ok",...s},a=c().min(1).safeParse(t.sshStartupFallbackHostId);return a.success&&(i.sshStartupFallbackHostId=a.data),{valid:true,outcome:i}}if(o==="ok"&&n==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(o==="unreachable")return n==="local"?{valid:true,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(o==="incompatible"||o==="wrong-service")return n!=="remote"?{valid:false}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:o,hostId:t.hostId,url:t.url,...s}};if(o==="missing")return n!=="remote"?{valid:false}:typeof t.hostId!="string"?{valid:false}:{valid:true,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(n===null){if(o==="not-configured")return{valid:true,outcome:{target:null,status:"not-configured",...s}};if(o==="missing")return{valid:false}}return{valid:false}}function CG(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===false?{localAvailable:false}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...s};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...s}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...s};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...s};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...s};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...s};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...s};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...s}}return null}function TG(e){return!e.isDesktopShell||e.bootOutcomeKnown}function AG(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function Sf(){if(rC()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=kf(t);return s.valid?s.outcome:null}function rC(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":kf(e).valid?"valid":"malformed"}const Cr=/^[a-z][a-z\d+.-]*:\/\//i,cC=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Tr=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),lC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Tr(e)},dC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Tr(e)},uC=()=>Object.keys(_o()).length>0,pC=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Ul=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of s)o!=null&&e.searchParams.set(n,String(o))},hC=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Ul({searchParams:s},t);const n=s.toString();return n?e.includes("?")?`${e}&${n}`:`${e}?${n}`:e},$p=(e,t,s)=>{if(Cr.test(t)){const a=new URL(t);return Ul(a,s),a.toString()}const n=cC(t);if(!e)return hC(n,s);const o=new URL(e),i=new URL(`${o.origin}${o.pathname.replace(/\/+$/,"")}${n}`);return Ul(i,s),i.toString()},Ra=(e,t=QC())=>{if(!t)return e;const s=Cr.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),Cr.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},Cf=(e,t)=>{const s=Cr.test(e)?new URL(e):new URL(e,pC(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},Kp=(e,t,s)=>{if(!uC())return null;const n=dC();if(!n)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${n}/`);o.searchParams.set("url",t);const i=ZC(n);return i&&o.searchParams.set("oc_url_token",i),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Cf(o.toString(),s)):o.toString()}catch{return null}},uu=(e={})=>{const t=Tr(e.apiBaseUrl),s=Tr(e.realtimeBaseUrl),n=()=>t||lC(),o=()=>s||n(),i=(r,l)=>$p(n(),r,l),a=(r,l)=>$p(o(),r,l);return{api:i,authenticatedAsset:(r,l)=>Ra(i(r,l)),assetWithUrlToken:(r,l,u)=>Ra(i(r,u),l),auth:i,health:r=>i("/health",r),rawFile:(r,l)=>i("/api/fs/raw",{path:r,download:l?.download===true?true:void 0,allowOutsideWorkspace:l?.allowOutsideWorkspace===true?true:void 0,outsideFileGrant:l?.outsideFileGrant}),sse:(r,l)=>{const u=Ra(a(r,l));return Kp("sse",u,e)||u},websocket:(r,l)=>{const u=Cf(Ra(a(r,l)),e);return Kp("ws",u,e)||u}}};let Ar=uu();const Ss=()=>Ar,gC=e=>{Ar=e},Tf=e=>(Ar=uu(e),Ar),pu=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Bi=()=>{const e=pu();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():false},hu=(e=pu())=>!!e,jl="openchamber:runtime-endpoint-changed",Bl="openchamber:runtime-endpoint-will-change";let yo="",Vi="",Vl=0,Hl=null;const Ec=(e,t,s)=>{try{e[t]=s}catch{}},gu=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"}`}},mC="mobile-disconnected",fC="url:default",Wl=e=>e===""||e===mC||e===fC&&!hu(),Af=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Pf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Rf=(e,t)=>{if(!e||!t)return false;try{return new URL(e).origin===new URL(t).origin}catch{return false}},os=()=>yo||Af(),wC=()=>{if(Hl!==null)return Hl;const e=os();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let Oc="",Jp=null,Yp,Xp;const Qp=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},F=()=>{if(Vi)return Vi;const e=Qp("__OPENCHAMBER_API_BASE_URL__"),t=Qp("__OPENCHAMBER_LOCAL_ORIGIN__");if(Jp===yo&&Yp===e&&Xp===t)return Oc;const s=os();return Oc=Rf(s,Pf())?"local":gu(s),Jp=yo,Yp=e,Xp=t,Oc},or=()=>{const e=Vl,t=F();return()=>e===Vl&&t===F()},bC=(e={})=>{if(yo||Vi)return;const t=e.apiBaseUrl?.trim()||Af(),s=globalThis.window?.location?.origin??"",n=/^https?:\/\//.test(s)?s:"";if(!t&&!n)return;const o=Pf(),i=o&&(!t||Rf(t,o));yo=t,Vi=e.runtimeKey?.trim()||(i?"local":gu(t||n))},ql=e=>{const t=e.apiBaseUrl.trim(),s=os(),n=F(),o=e.runtimeKey?.trim()||gu(t),i=e.sshForwarded??(t===s&&o===n&&wC()),a={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:o,previousRuntimeKey:n};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bl,{detail:a})),yo=t,Vi=o,o!==n&&(Vl+=1),Hl=i,typeof window<"u"){const r=window;Ec(r,"__OPENCHAMBER_API_BASE_URL__",t),Ec(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Ec(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Tf({apiBaseUrl:t,realtimeBaseUrl:t}),Hf(e.requestHeaders||null),Vf(e.clientToken||null),e.relay?GC(e.relay):zC(),tc(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(jl,{detail:a}))},Xr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Bl,t),()=>window.removeEventListener(Bl,t)},Qr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(jl,t),()=>window.removeEventListener(jl,t)};let Gl=null;const PG=e=>{Gl=e},Mo=()=>Gl||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),yC=e=>e==="stable"||e==="canary",vC=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,RG=e=>{const t=vC.exec(e??"");if(!t)return null;const[,s,n,o,i,a]=t;return{release:s,builtOn:new Date(Date.UTC(Number(n),Number(o)-1,Number(i))),build:a?Number(a):null}},kC=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),IG=(e,t,s)=>{const n=kC(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${n} #${e.build}`:n},If=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Rs=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,Dn=()=>If()?.runtime==="electron",xf=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},SC="right",xG=()=>{if(!Dn())return false;const e=xf();return e==="linux"?If()?.nativeFrame!==true:e==="win32"},EG=e=>e==="left"?"left":SC,OG=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],rt=()=>typeof Rs()?.invoke=="function",vt=()=>Dn()&&rt(),CC=()=>{const e=Rs()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>c().parse(await t()),writeText:async n=>{g(true).parse(await s(n))}}}},TC=()=>{if(Rs()?.pickThemeFile)return{async pick(){const e=Rs()?.pickThemeFile;return e?{status:"picked",file:d({name:c(),size:y().nonnegative(),text:c()}).nullable().parse(await e())}:{status:"unsupported"}}}},ie=async(e,t)=>{const s=Rs();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},DG=e=>{xf()!=="darwin"||!vt()||ie("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},MG=()=>({apiBaseUrl:os(),clientToken:yu(),runtimeKey:F()}),FG=async()=>{if(!it()||!Ie())return false;const e=os();try{const t=v().safeParse(await ie("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===os()}catch{return false}},_G=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("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}},NG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("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}},Ef=e=>yC(e?.channel)?e.channel:null,LG=async()=>{if(!vt()||!Ie())return null;try{return Ef(await ie("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},UG=async e=>{if(!vt()||!Ie())return null;try{return Ef(await ie("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},jG=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("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}},BG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("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}},VG=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("desktop_get_mini_chat_global_shortcut");return!e||typeof e.supported!="boolean"||e.combo!==null&&typeof e.combo!="string"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get Mini Chat global shortcut status",e),null}},HG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("desktop_set_mini_chat_global_shortcut",{combo:e});return!t||typeof t.supported!="boolean"||t.combo!==null&&typeof t.combo!="string"||typeof t.active!="boolean"||t.error!==void 0&&t.error!=="unsupported-combo"?null:t}catch(t){return console.warn("Failed to set Mini Chat global shortcut",t),null}},AC=d({supported:v(),enabled:v(),combo:c().nullable(),storedCombo:c().nullable(),active:v(),heightFraction:y(),error:g("unsupported-combo").optional()}),Zr=async(e,t,s)=>{if(!vt()||!Ie())return null;try{const n=AC.safeParse(await ie(e,t));return n.success?n.data:null}catch(n){return console.warn(s,n),null}},WG=()=>Zr("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),qG=e=>Zr("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),GG=e=>Zr("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),zG=e=>Zr("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),$G=async()=>{if(!vt()||!Ie())return null;try{const e=await ie("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}},KG=async e=>{if(!vt()||!Ie())return null;try{const t=await ie("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}},Zp=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}}},Dc=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}}},PC=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Jo=e=>{const t=PC(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ie=()=>{if(typeof window>"u"||!it())return false;if(F()==="local")return true;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Dc(e),s=Dc(os());if(!s&&t&&Sf()?.target==="local")return true;if(t&&s){if(t.origin===s.origin)return true;const a=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&a===r&&Jo(t.hostname)&&Jo(s.hostname)}const n=Dc(window.location.origin);if(t&&n){if(t.origin===n.origin)return true;const a=t.port||(t.protocol==="https:"?"443":"80"),r=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&a===r&&Jo(t.hostname)&&Jo(n.hostname)}const o=Zp(e),i=Zp(window.location.origin)||window.location.origin;return o&&i&&o===i?true:!!(n&&Jo(n.hostname))},it=()=>typeof window>"u"?false:Dn(),JG=async()=>{if(!it())return null;const e=d({visible:v()}).safeParse(await ie("desktop_get_current_window_state"));return e.success?e.data.visible:null},YG=async()=>{if(!it())return false;try{return!!await ie("desktop_focus_window")}catch{return false}},XG=(e,t,s=null)=>!t||t===F()||!vt()?false:(ie("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(o=>{console.warn("[desktop] failed to open host session",o)}),true),Of=()=>it()&&rt()&&Ie(),RC=k(d({sessionId:c().min(1),messageId:c().min(1).optional(),runtimeKey:c().min(1).optional(),requireKnownSession:v().optional()})),QG=async()=>{if(!it())return[];try{const e=k(c()).safeParse(await ie("desktop_take_pending_extension_installs"));return e.success?e.data:[]}catch{return[]}},ZG=async()=>{if(!it()||!Ie())return[];try{const e=RC.safeParse(await ie("desktop_take_pending_session_links"));return e.success?e.data.map(t=>({sessionId:t.sessionId,messageId:t.messageId??null,runtimeKey:t.runtimeKey??null,requireKnownSession:t.requireKnownSession===true})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},IC=k(Z("type",[d({type:g("pairing"),link:c().min(1)}),d({type:g("host"),hostId:c().min(1)})])),ez=async()=>{if(!it())return[];try{const e=IC.safeParse(await ie("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},xC=c().min(1),tz=e=>{if(!Of())return null;try{const t=xC.safeParse(Rs()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},sz=async()=>{if(!it())return false;try{return await ie("desktop_start_window_drag"),true}catch{return false}},Ne=()=>hu()?true:Mo()?.runtime?.isVSCode===true,nz=()=>{const t=Mo()?.runtime?.platform;return t==="web"?true:t==="desktop"||t==="vscode"?false:!Ne()},oz=(e,t=it())=>e==="web"&&!t,Df=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},iz=async e=>{if(Of())try{const t=await Rs()?.openDialog?.({directory:true,multiple:false,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:false,error:"Directory selection cancelled"}:{success:true,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:false,error:t instanceof Error?t.message:String(t)}}return{success:false,error:"Native directory picker not available"}},EC=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),az=async e=>{if(rt()&&Ie())try{const t=await Rs()?.openDialog?.({directory:false,multiple:false,title:"Select File",returnGrant:true,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:false,error:"File selection cancelled"};if(typeof t=="string")return{success:true,path:t};if(!EC(t))return{success:false,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:true,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:false,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:false,error:t instanceof Error?t.message:String(t)}}return{success:false,error:"Native file picker not available"}},rz=async e=>({success:true}),cz=async e=>({success:true}),lz=async()=>rt()?await ie("desktop_check_for_updates"):null,dz=async e=>{if(!rt())return false;const t=Rs();let s=null,n=0,o;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",i=>{const a=i?.payload;if(!a||typeof a!="object")return;const r=a,l=typeof r.event=="string"?r.event:null,u=r.data&&typeof r.data=="object"?r.data:null;if(l==="Started"){n=0,o=typeof u?.contentLength=="number"?u.contentLength:void 0,e({downloaded:n,total:o});return}if(l==="Progress"){const p=u?.downloaded,h=u?.total;typeof p=="number"&&(n=p),typeof h=="number"&&(o=h),e({downloaded:n,total:o});return}l==="Finished"&&e({downloaded:n,total:o})})),await ie("desktop_download_and_install_update"),true}catch(i){throw i instanceof Error?i:new Error(String(i))}finally{if(s)try{const i=s();i instanceof Promise&&await i}catch{}}},uz=async()=>rt()?(await ie("desktop_restart"),true):false,pz=async()=>{if(!rt())return false;try{return await ie("desktop_restart"),true}catch(e){return console.warn("Failed to restart desktop app",e),false}},hz=async()=>{if(!rt()||!Ie())return null;try{const e=await ie("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}},OC=async(e,t)=>{if(!rt()||!Ie())return false;const s=e?.trim();if(!s)return false;try{return await ie("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),true}catch(n){return console.warn("Failed to open path",n),false}},gz=async e=>{if(!rt()||!Ie())return false;const t=e?.trim();if(!t)return false;try{return await ie("desktop_reveal_path",{path:t}),true}catch{return OC(t)}},mz=async(e,t)=>{if(!rt()||!Ie())return null;const s=e?.trim();if(!s)return null;try{const n=await ie("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof n=="string"&&n.trim().length>0?n:null}catch(n){return console.warn("Failed to save markdown file",n),null}},fz=async(e,t,s)=>{if(!rt()||!Ie())return false;const n=e?.trim(),o=t?.trim(),i=s?.trim();if(!n||!o||!i)return false;try{return await ie("desktop_open_in_app",{projectPath:n,appId:o,appName:i}),true}catch(a){return console.warn("Failed to open project in app",a),false}},wz=async(e,t,s)=>{if(!rt()||!Ie())return false;const n=e?.trim(),o=t?.trim(),i=s?.trim();if(!n||!o||!i)return false;try{return await ie("desktop_open_file_in_app",{filePath:n,appId:o,appName:i}),true}catch(a){return console.warn("Failed to open file in app",a),false}},bz=async(e,t)=>{if(!rt()||!Ie())return{apps:[],success:false,hasCache:false,isCacheStale:false};const s=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];if(s.length===0)return{apps:[],success:true,hasCache:false,isCacheStale:false};try{const n=await ie("desktop_get_installed_apps",{apps:s,force:t===true?true:void 0});if(!n||typeof n!="object")return{apps:[],success:false,hasCache:false,isCacheStale:false};const o=n;return o.supported===false?{apps:[],success:true,hasCache:false,isCacheStale:false}:Array.isArray(o.apps)?{apps:o.apps.filter(a=>a&&typeof a=="object").map(a=>{const r=a;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(a=>a.name.length>0),success:true,hasCache:o.hasCache===true,isCacheStale:o.isCacheStale===true}:{apps:[],success:false,hasCache:false,isCacheStale:false}}catch(n){return console.warn("Failed to fetch installed apps",n),{apps:[],success:false,hasCache:false,isCacheStale:false}}},yz=()=>navigator.platform.toLowerCase().startsWith("linux"),Mn=()=>typeof window>"u"?false:window.Capacitor?.isNativePlatform?.()===true||window.location.protocol==="capacitor:",vz=()=>typeof window>"u"||!Mn()?false:Mf()==="ios"&&DC(),DC=()=>{if(typeof navigator>"u")return false;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Mf=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ne()?"vscode":it()?"desktop":"web"},MC="2.7.3-canary.20261115.21",Ia=new Uint8Array(0),FC=typeof DecompressionStream=="function",_C=e=>e.pipeThrough(new TransformStream({transform(t,s){s.enqueue(t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t))}})).pipeThrough(new DecompressionStream("gzip")),Ff=e=>ArrayBuffer.isView(e)?e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e,NC=new TextEncoder,LC=new TextDecoder,Dt=e=>e instanceof Error?e:new Error(String(e)),xa=()=>new DOMException("The operation was aborted.","AbortError"),UC=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(Ff(s))},close(s,n){e.close(s,n)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>t.onmessage?.({data:s.data}),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),e.onerror=()=>t.onerror?.(),t},jC=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(s){s&&(e.binaryType=s)},onopen:null,onmessage:null,onerror:null,onclose:null,send(s){e.send(Ff(s))},close(s,n){e.close(s,n)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const n=s.data;(typeof n=="string"||n instanceof ArrayBuffer)&&t.onmessage?.({data:n})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},BC=e=>e?.state==="error"&&e.closeCode===Zs.LimitExceeded,eh=0,Mc=1,th=2,sh=3,VC=new Set([Zs.AuthFailed,Zs.DuplicateClient,Zs.LimitExceeded]),HC={[Zs.AuthFailed]:"relay authentication failed",[Zs.DuplicateClient]:"relay connection replaced by another client",[Zs.LimitExceeded]:"relay connection limit reached"},Fc=()=>{const e=typeof navigator<"u"&&navigator.onLine===false,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},mu=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,n=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,i=e.batchWindowMs??wf,a=e.batch!==false,r=e.reconnectBaseDelayMs??1e3,l=e.reconnectMaxDelayMs??3e4,u=e.hiddenOrOfflineMaxDelayMs??6e4,p=e.createWireSocket??(V=>UC(new WebSocket(V)));let h=false,m=null,w={state:"idle"};const b=new Set;let S=null,C=null,x=null,A=0,E=0,B=null,K=[],j=false;const H=V=>{if(!(w.state===V.state&&w.lastError===V.lastError&&w.terminal===V.terminal&&w.closeCode===V.closeCode)){w=V;for(const me of b)try{me(w)}catch{}}},z=V=>{const me=K;K=[];for(const J of me)J.reject(V)},te=V=>{const me=K;K=[];for(const J of me)J.resolve(V)},se=(V,me)=>{V.dead=true;const J=Array.from(V.streams.values());V.streams.clear();for(const X of J)try{X.fail(me)}catch{}},Ve=()=>{B!==null&&(clearTimeout(B),B=null)},Go=()=>{if(!h){if(B!==null){if(Fc())return;Ve(),Et(),jn();return}Fc()||an()}},an=()=>{h||m===null||(Et(),m=null,jn())},Y=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Go()},pt=()=>{j||typeof window>"u"||(j=true,window.addEventListener("online",Go),typeof document<"u"&&document.addEventListener("visibilitychange",Y))},Et=()=>{!j||typeof window>"u"||(j=false,window.removeEventListener("online",Go),typeof document<"u"&&document.removeEventListener("visibilitychange",Y))},zo=()=>{if(h||B!==null)return;const V=Math.max(0,E-1),me=r*2**Math.min(V,10),J=Fc()?u:l,X=Math.min(J,me);pt(),B=setTimeout(()=>{B=null,Et(),jn()},X)},Ac=()=>{const V=new URL(e.relayUrl);return V.searchParams.set("v",String(wi)),V.searchParams.set("role","client"),V.searchParams.set("serverId",e.serverId),V.searchParams.set("appId","openchamber"),V.searchParams.set("appVersion",MC),V.searchParams.set("platform",Mf()),e.grant&&V.searchParams.set("grant",e.grant),V.toString()},jn=async()=>{if(h)return;Ve(),A+=1;const V=A;H({state:E>0?"reconnecting":"connecting",lastError:w.lastError});let me;try{me=await _S(e.hostEncPubJwk,{batch:a,flowControl:e.flowControl})}catch(we){if(V!==A||h)return;Hp(V,Dt(we),true);return}if(V!==A||h)return;let J;try{J=p(Ac())}catch(we){Hp(V,Dt(we));return}C=J;let X=false,ne=null,fe=null,ht=null,He=null,re=Promise.resolve(),le=null,Me=null,cs=false,Ue=false,je=0,We=0,qe=null,ls=null,Pe=Date.now();const Ds=()=>{qe!==null&&(clearTimeout(qe),qe=null),ne!==null&&(clearInterval(ne),ne=null),fe!==null&&(clearTimeout(fe),fe=null),ht!==null&&(clearInterval(ht),ht=null),He!==null&&(clearTimeout(He),He=null),ls!==null&&(ls.dispose(),ls=null)};x=Ds;function ye(we,xe=false,ve=null){if(!(X||V!==A)){X=true,ve!==null&&(m=we),Ds(),le&&(S=null,se(le,new Error(`relay tunnel reset: ${we.message}`))),z(we);try{J.close()}catch{}if(C===J&&(C=null),!h){if(E+=1,ve!==null){pt(),H({state:"error",lastError:we.message,terminal:true,closeCode:ve});return}H({state:xe?"error":"reconnecting",lastError:we.message}),zo()}}}const $o=()=>{try{J.send(me.helloText)}catch{}},rn=(we,xe,ve)=>{Me=we,cs=xe,Ue=ve,ne!==null&&(clearInterval(ne),ne=null),fe!==null&&(clearTimeout(fe),fe=null);const gt=new Map,Ke=$S(),Ot=BS();let cn=Promise.resolve();const Ms=Ko=>{cn=cn.then(async()=>{if(ln.dead)return;const iS=await we.encryptor.encrypt(Ko);ln.dead||J.send(iS)}).catch(()=>{ye(new Error("relay encrypt/send failed"))})},Ic=xe?zS({windowMs:i,sendBatch:Ms}):null;ls=Ic;const ln={streams:gt,assembler:Ot,nextStreamId:()=>Ke.next(),dead:false,send(Ko){ln.dead||(Ic?Ic.enqueue(Ko):Ms(Ko))}};le=ln,S=ln,E=0,Pe=Date.now(),H({state:"connected"}),te(ln),ht=setInterval(()=>{Date.now()-Pe<n||(ln.send(Mt(ce.Ping,0,Ia)),He===null&&(He=setTimeout(()=>{He=null,ye(new Error("relay keepalive timeout"))},o)))},n)},ka=()=>{qe!==null&&clearTimeout(qe),qe=null,!(!le||le.dead||je===We)&&(We=je,le.send(Mt(ce.DeliveryAck,0,NS(je))))},Rc=(we,xe)=>{let ve;try{ve=LS(xe)}catch(Ot){ye(Dt(Ot));return}if(ve.frameType===ce.DeliveryAck){ye(new Error("unexpected downstream delivery acknowledgement"));return}if(Ue&&ve.streamId!==0&&(je+=xe.length,qe===null&&(qe=setTimeout(ka,10))),Pe=Date.now(),He!==null&&(clearTimeout(He),He=null),ve.frameType===ce.Ping){we.send(Mt(ce.Pong,ve.streamId,Ia));return}if(ve.frameType===ce.Pong)return;let gt=ve.payload;if(ve.frameType===ce.WsText||ve.frameType===ce.WsBinary){let Ot;try{Ot=we.assembler.push(ve)}catch(cn){ye(Dt(cn));return}if(Ot===null)return;gt=Ot}else if(ve.hasMoreFragments){ye(new Error("unexpected fragmented tunnel frame"));return}const Ke=we.streams.get(ve.streamId);Ke&&Ke.handleFrame(ve.frameType,gt)};J.onopen=()=>{X||V!==A||($o(),ne=setInterval($o,t))};const Bn=we=>{const xe=VC.has(we);ye(new Error(HC[we]??`relay socket closed (code ${we})`),xe,xe?we:null)};J.onmessage=we=>{if(X||V!==A)return;const xe=we.data;if(typeof xe=="string"){const gt=fS(xe);if(gt){Bn(gt.code);return}re=re.then(async()=>{if(X||V!==A)return;const Ke=await me.handleText(xe);if(Ke.type==="established"){if(Me)return;rn(Ke.channel,Ke.batch,Ke.flowControl)}else Ke.type==="fail"&&ye(new Error(`relay handshake failed: ${Ke.reason}`))}).catch(Ke=>{ye(Dt(Ke))});return}const ve=xe instanceof ArrayBuffer?new Uint8Array(xe):xe instanceof Uint8Array?xe:null;ve&&(re=re.then(async()=>{if(X||V!==A)return;const gt=le,Ke=Me;if(!gt||!Ke){ye(new Error("encrypted frame before handshake completed"));return}let Ot;try{Ot=await Ke.decryptor.decrypt(ve)}catch(Ms){ye(Dt(Ms));return}let cn;try{cn=cs?HS(Ot):[Ot]}catch(Ms){ye(Dt(Ms));return}for(const Ms of cn){if(X||V!==A||gt.dead)return;Rc(gt,Ms)}Ue&&je-We>=16*1024&&ka()}).catch(gt=>{ye(Dt(gt))}))},J.onclose=we=>Bn(we.code),J.onerror=()=>{},fe=setTimeout(()=>{fe=null,ye(new Error("relay handshake timeout"),true)},s);function Hp(we,xe,ve=false){we!==A||h||(z(xe),E+=1,H({state:ve?"error":"reconnecting",lastError:xe.message}),zo())}},rs=V=>h?Promise.reject(new Error("relay tunnel closed")):V?.aborted?Promise.reject(xa()):m?Promise.reject(m):S&&!S.dead?Promise.resolve(S):new Promise((me,J)=>{let X=null;const ne={resolve(fe){X&&V&&V.removeEventListener("abort",X),me(fe)},reject(fe){X&&V&&V.removeEventListener("abort",X),J(fe)}};V&&(X=()=>{K=K.filter(fe=>fe!==ne),J(xa())},V.addEventListener("abort",X,{once:true})),K.push(ne)}),Pc=async(V,me)=>{const J=await tC(V,me),X=J.signal;if(X?.aborted)throw xa();const ne=await rs(X),fe=ne.nextStreamId();return await new Promise((ht,He)=>{let re=false,le=false,Me=null,cs=null;const Ue=()=>{ne.streams.delete(fe),ne.assembler.dropStream(fe),cs&&X&&X.removeEventListener("abort",cs)},je=Pe=>{if(!le){if(le=true,Ue(),!re){He(Pe);return}try{Me?.error(Pe)}catch{}}},We=Pe=>{ne.dead||ne.send(Mt(ce.StreamAbort,fe,Ta({reason:Pe})))},qe=Pe=>Ll(new Error(Pe));cs=()=>{We("aborted"),je(xa())},ne.streams.set(fe,{handleFrame(Pe,Ds){if(Pe===ce.HttpResponse){if(re||le)return;let ye;try{ye=Aa(Ds,JS)}catch(Bn){We("malformed response head"),je(qe(Dt(Bn).message));return}const $o=ye.status===204||ye.status===205||ye.status===304;let rn=null;$o||(rn=new ReadableStream({start(Bn){Me=Bn},cancel(){le||(le=true,Ue(),We("response body cancelled"))}})),re=true;const{[vS]:ka,...Rc}=ye.headers;rn&&ka==="gzip"&&(rn=_C(rn)),ht(new Response(rn,{status:ye.status,headers:Rc})),$o&&(le=true,Ue());return}if(Pe===ce.HttpBody){if(!re||le)return;try{Me?.enqueue(Ds)}catch{}return}if(Pe===ce.StreamEnd){if(le)return;if(!re){je(qe("tunnel stream ended before response head"));return}le=true,Ue();try{Me?.close()}catch{}return}if(Pe===ce.StreamAbort){let ye="stream aborted by host";try{ye=Aa(Ds,zp).reason}catch{}je(qe(ye))}},fail(Pe){je(qe(Pe.message))}}),X&&X.addEventListener("abort",cs,{once:true});const ls={method:J.method,path:J.path,query:J.query,headers:FC?{...J.headers,[yS]:"gzip"}:J.headers,hasBody:J.body!==null};ne.send(Mt(ce.HttpRequest,fe,Ta(ls))),(async()=>{try{let Pe=false;if(J.body)for await(const Ds of J.body){if(le||ne.dead)return;for(const ye of ff(Ds))ne.send(Mt(ce.HttpBody,fe,ye)),Pe=true}!le&&!ne.dead&&(J.body&&!Pe&&ne.send(Mt(ce.HttpBody,fe,Ia)),ne.send(Mt(ce.StreamEnd,fe,Ia)))}catch(Pe){We("request body failed"),je(qe(Dt(Pe).message))}})()})},sS=V=>{const me=V.indexOf("?");return me===-1?{path:V,query:""}:{path:V.slice(0,me),query:V.slice(me+1)}},nS=(V,me)=>{let J=eh,X=null,ne=0,fe=false;const ht={get readyState(){return J},onopen:null,onmessage:null,onerror:null,onclose:null,send(re){if(J!==Mc||!X||X.dead)throw new Error("relay tunnel socket is not open");if(typeof re=="string"){for(const Me of Gp(ce.WsText,ne,NC.encode(re)))X.send(Me);return}const le=re instanceof ArrayBuffer?new Uint8Array(re.slice(0)):(()=>{const Me=new Uint8Array(re.byteLength);return Me.set(new Uint8Array(re.buffer,re.byteOffset,re.byteLength)),Me})();for(const Me of Gp(ce.WsBinary,ne,le))X.send(Me)},close(re=1e3,le=""){J===sh||J===th||(J===Mc&&X&&!X.dead&&(J=th,X.send(Mt(ce.WsClose,ne,Ta({code:re,reason:le})))),He(re,le))}},He=(re,le,Me=false)=>{if(!fe){if(fe=true,X&&(X.streams.delete(ne),X.assembler.dropStream(ne)),J=sh,Me)try{ht.onerror?.()}catch{}try{ht.onclose?.({code:re,reason:le})}catch{}}};return(async()=>{let re;try{re=await rs()}catch(Ue){He(1006,Dt(Ue).message,true);return}if(fe)return;X=re,ne=re.nextStreamId(),re.streams.set(ne,{handleFrame(Ue,je){if(Ue===ce.WsOpened){if(J===eh){J=Mc;try{ht.onopen?.()}catch{}}return}if(Ue===ce.WsText){try{ht.onmessage?.({data:LC.decode(je)})}catch{}return}if(Ue===ce.WsBinary){const We=new ArrayBuffer(je.byteLength);new Uint8Array(We).set(je);try{ht.onmessage?.({data:We})}catch{}return}if(Ue===ce.WsClose){let We=1e3,qe="";try{const ls=Aa(je,YS);We=ls.code,qe=ls.reason}catch{}He(We,qe);return}if(Ue===ce.StreamAbort){let We="stream aborted";try{We=Aa(je,zp).reason}catch{}He(1006,We,true)}},fail(Ue){He(1012,Ue.message,true)}});const{path:le,query:Me}=sS(V),cs=me&&me.length>0?{path:le,query:Me,protocols:me}:{path:le,query:Me};re.send(Mt(ce.WsOpen,ne,Ta(cs)))})(),ht},oS=()=>{if(h)return;h=true,A+=1,Ve(),Et(),x?.(),x=null;const V=S;S=null;const me=new Error("relay tunnel closed");V&&se(V,me),z(me);try{C?.close()}catch{}C=null,H({state:"idle"})};return jn(),{fetch:Pc,openWebSocket:nS,getStatus:()=>w,subscribeStatus(V){return b.add(V),()=>{b.delete(V)}},retry:an,close:oS}};let ns=null,ts=null;const zl=new Set;let _c=null;const fu=e=>{_c?.(),_c=null,ns=e,e&&(_c=e.subscribeStatus(t=>{for(const s of zl)s(t)}))},kz=e=>(zl.add(e),()=>{zl.delete(e)}),WC=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Fo=()=>ns,Sz=()=>!ns||!ts?null:{relayUrl:ts.relayUrl,serverId:ts.serverId,hostEncPubJwk:{...ts.hostEncPubJwk}},qC=()=>ns!==null,GC=e=>{if(ns&&ts&&WC(ts,e))return ns;ns?.close(),ts=e;const t=mu(e);return fu(t),t},Cz=(e,t)=>{if(ns===t){ts=e;return}ns?.close(),ts=e,fu(t)},zC=()=>{ns?.close(),fu(null),ts=null};let _f=()=>null,Nf="",Pr={},vo="",Hi=0,bn=null,co="",Wi=0,In="",yn=null,Ws="",ir=0,ar=0;const wu=1e4,$C=e=>e.toLowerCase()==="authorization",Lf=e=>{const t={};for(const[s,n]of Object.entries(e||{})){const o=s.trim(),i=n.trim();o&&i&&!$C(o)&&(t[o]=i)}return t},KC=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?false:s.every(([n,o])=>t[n]===o)},ec=e=>typeof e!="string"?"":e.trim(),JC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return ec(e)},YC=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Uf=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():YC();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},bu=e=>{try{return new URL(e).origin}catch{return""}},jf=()=>{co="",Wi=0,In="",yn=null,Ws="",ir+=1},ra=()=>{vo="",Hi=0,jf()},Bf=()=>{ar+=1,bn=null,ra(),vu()},Vf=e=>{const t=ec(e);Nf=t,Bf(),_f=()=>t?{type:"bearer",token:t}:null},Hf=e=>{const t=Lf(e);KC(Pr,t)||(Pr=t,Bf())},_o=()=>{if(Object.keys(Pr).length>0)return Pr;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Lf(e):{}},yu=()=>Nf||JC(),XC=(e,t)=>{const s=ec(e);if(!s||typeof t!="number"||!Number.isFinite(t)){ra();return}vo=s,Hi=t},Wf=()=>!vo||Hi<=Date.now()+wu?(ra(),""):vo,qf=e=>{const t=bu(e);return!t||In!==t?"":!co||Wi<=Date.now()+wu?(co="",Wi=0,In="",""):co},QC=()=>{const e=Wf();return!e&&(yu()||typeof window<"u")&&tc().catch(()=>{}),e},ZC=e=>{const t=e?qf(e):"";return!t&&e&&typeof window<"u"&&Kf(e).catch(()=>{}),t},Gf=async()=>{const e=await _f(),t=e?.type==="bearer"?ec(e.token):yu();return t?{type:"bearer",token:t}:null},eT=d({token:c(),expiresAt:y(),expiresIn:y().optional()}),zf=async(e,t)=>{const s=await Gf(),n=new Headers;for(const[h,m]of Object.entries(_o()))n.set(h,m);s?.type==="bearer"&&n.set("Authorization",`Bearer ${s.token}`);const o=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",i=Fo(),a=i?await i.fetch(o,{method:"POST",headers:n}):await fetch(Uf(e,o),{method:"POST",headers:n,credentials:"include"});if(!a.ok)throw new Error(`Failed to mint runtime URL auth token (${a.status})`);const r=eT.safeParse(await a.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:l,expiresAt:u,expiresIn:p}=r.data;return{token:l.trim(),expiresAt:p===void 0?u:Date.now()+p}},Tz=async e=>{const t=await zf(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},$f=e=>{if(bn)return bn;const t=ar,n=(async()=>{let o;try{o=await zf(e)}catch(i){throw t===ar&&ra(),i}if(t!==ar)throw new Error("Runtime URL auth token response is stale");if(XC(o.token,o.expiresAt),!vo)throw new Error("Runtime URL auth token response was invalid");return vo})().finally(()=>{bn===n&&(bn=null)});return bn=n,bn},tT=e=>{const t=bu(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(yn&&Ws===t)return yn;const s=ir,o=(async()=>{const i=await fetch(Uf(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!i.ok)throw s===ir&&t===Ws&&(co="",Wi=0,In=""),new Error(`Failed to mint local runtime URL auth token (${i.status})`);const a=await i.json().catch(()=>null),r=typeof a?.token=="string"?a.token.trim():"",l=typeof a?.expiresAt=="number"?a.expiresAt:0;if(!r||!Number.isFinite(l))throw new Error("Local runtime URL auth token response was invalid");if(s!==ir||t!==Ws)throw new Error("Local runtime URL auth token response is stale");return co=r,Wi=l,In=t,r})().finally(()=>{yn===o&&(yn=null,Ws="")});return yn=o,Ws=t,yn},tc=async e=>{const t=Wf();return t||$f(e)},Kf=async e=>{const t=bu(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=qf(t);return s||((In&&In!==t||Ws&&Ws!==t)&&jf(),tT(t))};let so=0,yi=null,sT=null;const nT=5e3,Jf=()=>{yi!==null&&(clearTimeout(yi),yi=null)},vu=()=>{if(Jf(),so<=0||typeof window>"u")return;const e=Hi-wu-nT,t=Hi>0?Math.max(0,e-Date.now()):0;yi=setTimeout(()=>{yi=null,!(so<=0)&&$f(sT).catch(()=>{}).finally(()=>{vu()})},t)},Az=e=>{so+=1,vu();let t=false;return()=>{t||(t=true,so=Math.max(0,so-1),so===0&&Jf())}},Yf=async e=>{const t=new Headers(e);for(const[n,o]of Object.entries(_o()))t.has(n)||t.set(n,o);if(t.has("Authorization"))return t;const s=await Gf();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},ko=xt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Pz=e=>new Promise(t=>{if(e.aborted||ko.getState().state==="ok"){t();return}const s=()=>{n(),e.removeEventListener("abort",s),t()},n=ko.subscribe(o=>{o.state==="ok"&&s()});e.addEventListener("abort",s,{once:true})}),oT=15e3,iT=5*6e4;let $l=0,Nc=false;const aT=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),rT=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?false:!aT(t)},Xf=async()=>{if(!Nc){Nc=true;try{const{runtimeFetch:e}=await Ge(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>PT);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){ko.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:n}=ko.getState();s==="expired"&&n()}}catch{}finally{Nc=false}}},cT=(e,t)=>{if(t!==401||ko.getState().state==="expired"||!rT(e))return;const s=Date.now();s-$l<oT||($l=s,Xf())};let nh=false;const Rz=()=>{if(nh)return;nh=true;let e=Date.now();const t=()=>{if(ko.getState().state!=="ok")return;const s=Date.now();s-e<iT||(e=s,$l=s,Xf())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},lT=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,It=e=>{if(!e)return null;const t=lT.exec(e);return t?t[1]:null},Kl=e=>It(e)!==null,dT=()=>hu()||Mo()?.runtime?.isVSCode===true,uT=e=>!e||dT()||!Kl(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},Qf=e=>`/spaces/${e}`,xn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",pT=()=>typeof window>"u"?"":window.location.origin||"",ku=e=>{if(typeof window>"u")return false;const t=pT();if(t&&e.origin===t)return true;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return false}},Su=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),hT=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),hs=(e,t)=>{try{hT(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},Cu=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of s)o!=null&&e.searchParams.set(n,String(o))},gT=e=>{if(!e)return false;if(e instanceof Headers)return e.has("x-opencode-directory");const t=Array.isArray(e)?e:Object.entries(e);for(const[s]of t)if(s.toLowerCase()==="x-opencode-directory")return true;return false},mT=(e,t,s)=>{const n=uT(s);if(n===null||gT(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const o=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...o,...Object.entries(n)]}},fT=()=>{const e=Ss().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return null;const t=new URL(e);return`${t.origin}${t.pathname.replace(/\/api$/,"")}`},wT=e=>{try{const t=fT();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const n=s.pathname.replace(/\/+$/,"");return n?e.pathname!==n&&!e.pathname.startsWith(`${n}/`)?null:e.pathname.slice(n.length)||"/":e.pathname}catch{return null}},rr=e=>{const t=wT(e);return t!==null&&xn(t)},Lc=e=>{if(xn(e))return true;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return false;try{const t=new URL(e);return ku(t)&&xn(t.pathname)}catch{return false}},bT=(e,t)=>{try{const s=new URL(e);if(!ku(s))return e;const n=en(`${s.pathname}${s.search}`,t);return!Su(n)&&(s.protocol==="http:"||s.protocol==="https:")?(Cu(s,t),s.toString()):s.hash?`${n}${s.hash}`:n}catch{return e}},en=(e,t)=>e==="/health"?Ss().health(t):e.startsWith("/auth/")||e==="/auth"?Ss().auth(e,t):xn(e)?Ss().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?bT(e,t):e,Zf=e=>{const t=e instanceof Request?e.url:e.toString();if(!Su(t))return xn(t);try{return rr(new URL(t))}catch{return false}},ew=(e,t)=>Object.keys(_o()).length>0&&Mn()&&Zf(e)?{...t,redirect:"error"}:t,tw=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return false;return true},yT=(e,t)=>!tw(t),Rr=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 s=[];let n=false,o=false;for(const[i,a]of t)yT(i,a)?(s.push([i,encodeURIComponent(a)]),n=true,i.toLowerCase()==="x-opencode-directory"&&(o=true)):s.push([i,a]);return o&&s.push(["x-opencode-directory-encoding","uri"]),n?s:void 0},gs=async(e,t,s=true)=>{const n=new Headers(Rr(e)??e);return t&&new Headers(Rr(t)??t).forEach((o,i)=>n.set(i,o)),s?Yf(n):n},vT=(e,t)=>{if(!t)return e;const s=new URL(e,du);return Cu(s,t),`${s.pathname}${s.search}`},sw=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!Su(s))return xn(s)?vT(s,t):null;try{const n=new URL(s);return!ku(n)||!xn(n.pathname)?null:(Cu(n,t),`${n.pathname}${n.search}`)}catch{return null}},kT=async(e,t,s)=>{const n=Fo();if(!n)return null;const o=sw(e,s);if(o===null)return null;const i=e instanceof Request?e.headers:void 0,a=await gs(i,t.headers,true);return e instanceof Request?n.fetch(e,{...t,headers:a}):n.fetch(o,{...t,headers:a})},ST=(e,t)=>{if(typeof e=="string")return en(e,t);if(e instanceof URL)return en(e.toString(),t);const s=en(e.url,t);return s===e.url?e:new Request(s,e)},CT=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Ea=new Map,TT=(e,t,s,n)=>s||e!=="GET"||t.includes("/event")||!CT.test(t)?null:`GET ${t}\0${n.get("x-opencode-directory")??""}`;let nw=null;const AT=e=>{nw=e},P=async(e,t={})=>{const{query:s,directory:n,...o}=t,i=e,a=mT(i,o,n),r=Fo(),l=r?sw(i,s):null;let u,p,h,m;if(r&&l!==null){const E=i instanceof Request?i.headers:void 0,B=await gs(E,a.headers,true);u=i instanceof Request?()=>r.fetch(i,{...a,headers:B}):()=>r.fetch(l,{...a,headers:B}),m=B,p=l,h=String(a.method??(i instanceof Request?i.method:"GET")).toUpperCase()}else{const E=ST(i,s),B=E instanceof Request?E.headers:void 0,K=await gs(B,a.headers,Zf(E)),j=E instanceof Request?E.url:E instanceof URL?E.toString():String(E);hs(j,K);const H=ew(E,{...a,headers:K});u=E instanceof Request?()=>fetch(new Request(E,H)):()=>fetch(E,H),m=K,p=j,h=String(a.method??(E instanceof Request?E.method:"GET")).toUpperCase()}const w=u,b=nw;u=async()=>{const E=b?performance.now():0;try{const B=await w();return cT(p,B.status),b?.({method:h,url:p,status:B.status,durationMs:performance.now()-E}),B}catch(B){throw b?.({method:h,url:p,status:null,durationMs:performance.now()-E}),B}};const S=a.signal!=null||i instanceof Request,C=TT(h,p,S,m);if(!C)return u();const x=Ea.get(C);if(x)return x.then(E=>E.clone());const A=u();return Ea.set(C,A),A.then(()=>Ea.delete(C),()=>Ea.delete(C)),A.then(E=>E.clone())};let oh=false,ow=null;const iw=(e,t)=>(ow??globalThis.fetch.bind(globalThis))(e,t),aw=()=>{if(oh||typeof window>"u")return;oh=true;const e=window.fetch.bind(window);ow=e;const t=(s,n)=>e(s,ew(s,n));window.fetch=async(s,n)=>{const o=await kT(s,n??{});if(o)return o;if(typeof s=="string"){if(!Lc(s)){try{const r=new URL(s);if(rr(r)){const l=await gs(void 0,n?.headers);return hs(r.toString(),l),t(s,{...n,headers:l})}}catch{}return t(s,n)}const i=await gs(void 0,n?.headers),a=en(s);return hs(a,i),t(a,{...n,headers:i})}if(s instanceof URL){const i=s.toString();if(!Lc(i)){if(rr(s)){const l=await gs(void 0,n?.headers);return hs(s.toString(),l),t(s,{...n,headers:l})}return t(s,n)}const a=await gs(void 0,n?.headers),r=en(i);return hs(r,a),t(r,{...n,headers:a})}if(s instanceof Request){if(!Lc(s.url)){try{const l=new URL(s.url);if(rr(l)){const u=await gs(s.headers,n?.headers);return hs(l.toString(),u),t(new Request(s,{...n,headers:u}))}}catch{}return t(s,n)}const i=await gs(s.headers,n?.headers),a=en(s.url);hs(a,i);const r=a===s.url?s:new Request(a,s);return t(new Request(r,{...n,headers:i}))}return t(s,n)}},PT=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:hs,buildRuntimeFetchUrl:en,fetchBypassingRuntimeBridge:iw,installRuntimeFetchBridge:aw,isLatin1Safe:tw,runtimeFetch:P,sanitizeHeadersForBrowser:Rr,setRuntimeRequestObserver:AT},Symbol.toStringTag,{value:"Module"})),lo=16384,Ir=globalThis,RT=e=>{if(Ir.Buffer)return Ir.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let n=0;n<t.length;n+=32768)s+=String.fromCharCode(...t.slice(n,n+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},rw=e=>{try{if(Ir.Buffer)return Ir.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),n=new Uint8Array(s.length);for(let o=0;o<s.length;o+=1)n[o]=s.charCodeAt(o);return new TextDecoder().decode(n)}catch{return null}},IT=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString().replace(/\/+$/g,""))}catch{return null}},xT=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="ws:"&&s.protocol!=="wss:"?null:(s.hash="",s.toString())}catch{return null}},ih=e=>typeof e=="string"&&e.length>0,ET=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ih(t.x)||!ih(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},OT=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,DT=e=>{if(!e||typeof e!="object")return null;const t=e,s=OT(t.priority);if(t.type==="lan"||t.type==="tunnel"){const n=IT(t.url);return n?s===void 0?{type:t.type,url:n}:{type:t.type,url:n,priority:s}:null}if(t.type==="relay"){const n=xT(t.relayUrl);if(!n)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const i=ET(t.hostEncPubJwk);if(!i)return null;const a=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:n,serverId:o,hostEncPubJwk:i,...a?{grant:a}:{},...s===void 0?{}:{priority:s}}}return null},Tu=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const s=typeof t.pairingId=="string"?t.pairingId.trim():"",n=typeof t.secret=="string"?t.secret.trim():"";if(!s||!n)return null;const o=Array.isArray(t.candidates)?t.candidates.map(DT).filter(l=>!!l):[];if(o.length===0)return null;const i=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(i){const l=Date.parse(i);if(!Number.isFinite(l)||l<=Date.now())return null}const a=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,r=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:s,secret:n,...a?{label:a}:{},...r?{fingerprint:r}:{},...i?{expiresAt:i}:{},candidates:o}},Iz=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}),xz=e=>{const t=Tu(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",RT(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},MT=e=>{const t=e.trim();if(!t||t.length>lo)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const n=s.searchParams.get("p")||"";if(!n||n.length>lo)return null;const o=rw(n);return!o||o.length>lo?null:Tu(JSON.parse(o))}catch{return null}},Ez=e=>{const t=e.trim();if(!t||t.length>lo)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let n=null,o=null;for(const a of t.slice(s+1).split("&")){const r=a.indexOf("=");if(r===-1)continue;const l=a.slice(0,r),u=a.slice(r+1);l==="v"?n=u:l==="p"&&(o=u)}if(n!=="2"||!o||o.length>lo)return null;const i=rw(o);if(!i||i.length>lo)return null;try{return Tu(JSON.parse(i))}catch{return null}},So=e=>typeof e=="object"&&e!==null,FT=e=>e.trim().toLowerCase()==="authorization",_T=e=>{if(!So(e))return;const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=typeof n=="string"?n.trim():"";!o||!i||/[\r\n:]/.test(o)||/[\r\n]/.test(i)||FT(o)||(t[o]=i)}return Object.keys(t).length>0?t:void 0},NT=e=>`relay://${e}`,LT=e=>{if(!So(e))return null;const t=Qe(e,"relayUrl")||Qe(e,"relay_url"),s=Qe(e,"serverId")||Qe(e,"server_id"),n=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!So(n)?null:{relayUrl:t,serverId:s,hostEncPubJwk:n}},UT=()=>{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"},ah=15e3,Oz=async(e,t)=>{const s=MT(e);if(!s)throw new Error("invalid-connect-link");const n=await WT().catch(()=>""),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:s.pairingId,secret:s.secret,clientLabel:s.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:UT(),...n?{dedupeKey:`desktop:${n}`}:{}})},i=async C=>{if(!C.ok)return null;const x=await C.json().catch(()=>null);return(typeof x?.clientToken=="string"?x.clientToken.trim():"")||null};let a=null;const r=[...s.candidates].sort((C,x)=>(C.type==="relay"?1:0)-(x.type==="relay"?1:0));for(const C of r){if(C.type==="relay"){const A=mu({relayUrl:C.relayUrl,serverId:C.serverId,hostEncPubJwk:C.hostEncPubJwk,...C.grant?{grant:C.grant}:{}});try{const E=await i(await A.fetch("/api/client-auth/pairing/redeem",{...o,signal:AbortSignal.timeout(ah)}));if(E){a={relay:{relayUrl:C.relayUrl,serverId:C.serverId,hostEncPubJwk:C.hostEncPubJwk},token:E};break}}catch{}finally{A.close()}continue}const x=$e(C.url);if(x)try{const A=await i(await fetch(`${x}/api/client-auth/pairing/redeem`,{...o,signal:AbortSignal.timeout(ah)}));if(A){a={directUrl:x,token:A};break}}catch{}}if(!a)throw new Error("pairing-redeem-failed");const l=s.candidates.find(C=>C.type==="relay"),u=a.relay||(l?{relayUrl:l.relayUrl,serverId:l.serverId,hostEncPubJwk:l.hostEncPubJwk}:void 0),p=s.candidates.filter(C=>C.type!=="relay").map(C=>$e(C.url)).find(C=>!!C),h=a.directUrl||p,m=h||(u?NT(u.serverId):null);if(!m)throw new Error("pairing-missing-transport");const w=t.find(C=>u?C.relay?.serverId===u.serverId:!C.relay&&$e(C.apiUrl||C.url)===m),b=w?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),S={...w||{},id:b,label:s.label||w?.label||cw(m),url:m,apiUrl:h,clientToken:a.token,...u?{relay:u}:{}};return{hostId:b,hosts:w?t.map(C=>C.id===b?S:C):[S,...t]}},jT=/^(t|.*(?:token|auth|secret|api).*)$/i,$e=e=>{const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},Dz=e=>{const t=$e(e);if(!t)return null;try{const s=new URL(t);if((s.pathname.replace(/\/+$/,"")||"/")==="/connect"&&s.searchParams.has("t"))return{persistedUrl:s.origin,redeemUrl:s.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},cw=e=>{const t=$e(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const n=Array.from(new Set(Array.from(s.searchParams.keys())));for(const o of n)jT.test(o)&&s.searchParams.set(o,"[REDACTED]");return s.toString()}catch{return t}},Oa=(e,t)=>{const s=$e(e),n=$e(t);if(!s||!n)return false;try{const o=new URL(s),i=new URL(n);if(o.origin!==i.origin||i.search&&o.search!==i.search)return false;const a=i.pathname.length>1?i.pathname.replace(/\/+$/,""):i.pathname,r=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return a==="/"?true:r===a||r.startsWith(`${a}/`)}catch{return false}},Qe=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},rh=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},BT=e=>{if(!So(e))return null;const t=Qe(e,"id"),s=Qe(e,"label"),n=Qe(e,"url"),o=Qe(e,"apiUrl")||Qe(e,"api_url"),i=Qe(e,"clientToken")||Qe(e,"client_token"),a=_T(e.requestHeaders),r=LT(e.relay);if(!t||!s||!n)return null;const l={id:t,label:s,url:n,...o?{apiUrl:o}:{},...i?{clientToken:i}:{},...a?{requestHeaders:a}:{},...r?{relay:r}:{}};return e.sshForwarded===true&&(l.sshForwarded=true),l},uo=e=>$e(e.apiUrl||e.url)||e.apiUrl||e.url,Es=()=>rt()?(e,t)=>ie(e,t):null,qi=async()=>{const e=Es();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:false};const t=await e("desktop_hosts_get");if(!So(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:false};const s=t.hosts,n=Array.isArray(s)?s.map(BT).filter(r=>!!r):[],o=Qe(t,"defaultHostId")||Qe(t,"default_host_id")||Qe(t,"defaultHostID"),i=t.initialHostChoiceCompleted===true||t.initial_host_choice_completed===true,a=Qe(t,"localOrigin")||Qe(t,"local_origin");return{hosts:n,defaultHostId:o,initialHostChoiceCompleted:i,localOrigin:a}},VT=async e=>{const t=Es();if(!t)return;const s={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(s.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:s})},HT=async()=>{const e=Es();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Mz=async()=>{const e=Es();return e?await e("desktop_switch_to_local").catch(()=>false)===true:false},WT=async()=>{const e=Es();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},qT=8e3,GT=15e3,zT=400,$T=async(e,t,s,n)=>{const o=new AbortController,i=window.setTimeout(()=>o.abort(),s);try{return await e.fetch(t,{...n,signal:o.signal})}finally{window.clearTimeout(i)}},ch=async(e,t,s,n)=>{for(;;){const o=s-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await $T(e,t,Math.min(qT,o),n)}catch(i){if(e.getStatus().state==="error"||Date.now()>=s)throw i;await new Promise(a=>window.setTimeout(a,zT))}}},KT=async(e,t)=>{const s=mu({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),n=Date.now()+GT;let o=false;try{if(!(await ch(s,"/health",n)).ok)return{status:"unreachable",latencyMs:0};const a=Date.now(),r=new Headers({Accept:"application/json"});for(const[p,h]of Object.entries(t?.requestHeaders||{}))p.toLowerCase()!=="authorization"&&r.set(p,h);const l=t?.clientToken?.trim();l&&r.set("Authorization",`Bearer ${l}`);const u=await ch(s,"/auth/session",n,{headers:r});return u.status===401||u.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-a)}:u.ok?(o=t?.keepTunnel===true,{status:"ok",latencyMs:Math.max(0,Date.now()-a),...o?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:BC(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{o||s.close()}},sc=async(e,t)=>{const s=Es();if(!s)return{status:"unreachable",latencyMs:0};const n=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!So(n))return{status:"unreachable",latencyMs:0};const o=n.status,i=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",a=rh(n,"latencyMs")??rh(n,"latency_ms")??0;return{status:i,latencyMs:a}},JT=Z("status",[d({status:g("started")}),d({status:g("auth")}),d({status:g("failed"),error:c().nullable()})]),Fz=async e=>{const t=Es();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),n=JT.safeParse(s);return n.success?n.data:{status:"failed",error:null}},YT=600*1e3,XT=3e3,_z=async(e,{maxWaitMs:t=YT,intervalMs:s=XT,readHosts:n=qi,probe:o=sc}={})=>{const i=Date.now()+t;for(;Date.now()<i;){await new Promise(l=>setTimeout(l,Math.min(s,Math.max(0,i-Date.now()))));const a=(await n()).hosts.find(l=>l.id===e);if(!a)return"timeout";const r=await o(uo(a),{clientToken:a.clientToken,requestHeaders:a.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},Nz=async(e,t)=>{const s=Es();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Lz=async e=>{const t=Es();t&&await t("desktop_new_window_for_host",{hostId:e})},Xs="local",QT=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",ZT=(e,t)=>t?[{id:Xs,label:"Local",url:t},...e]:e,eA=e=>e.id===Xs?"local":`host:${e.id}`,Uz=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(m=>m.id===Xs)?.url||QT(),n=os(),o=$e(s)||s,i=$e(t)||t,a=F(),r=e.find(m=>m.relay&&eA(m)===a);if(r)return{id:r.id,label:r.label,url:r.url};if(n&&Oa(n,s))return{id:Xs,label:"Local",url:o};const l=e.find(m=>n?Oa(n,uo(m)):false);if(l)return{id:l.id,label:l.label,url:$e(uo(l))||uo(l)};if(t&&Oa(t,s))return{id:Xs,label:"Local",url:o};const u=e.find(m=>t?Oa(t,m.url):false);if(u)return{id:u.id,label:u.label,url:$e(u.url)||u.url};const p=t.startsWith("openchamber-ui://");if(p&&s&&!n)return{id:Xs,label:"Local",url:o};const h=n?$e(n)||n:p?"":i;return{id:"custom",label:cw(h||"Instance"),url:h}},xr=new Map;let lw=0;const vi=new Map,po=new Set;let Jl=0,dw={byHostId:{},isProbing:false};const Yl=new Set,Er=()=>{dw={byHostId:Object.fromEntries(xr),isProbing:Jl>0};for(const e of Yl)try{e()}catch{}},jz=e=>(Yl.add(e),()=>{Yl.delete(e)}),Bz=()=>dw,uw=(e,t)=>{xr.set(e,t),Er()},Vz=(e,t)=>{vi.set(e,++lw),po.delete(e),uw(e,t)},Hz=e=>po.has(e),tA=e=>{const t=new Set([Xs,...e]);let s=false;for(const n of Array.from(xr.keys()))t.has(n)||(xr.delete(n),vi.delete(n),po.delete(n),s=true);s&&Er()},sA=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",nA=async()=>Dn()?HT().catch(()=>""):"",oA=async(e,t)=>{const s=e.id===Xs?t:e.clientToken||"",n=async()=>{const a=await KT(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:a.status,latencyMs:a.latencyMs};return a.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return n();const o=$e(Dn()?uo(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const i=await sc(o,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(sA(i.status)&&e.relay){const a=await n();if(a.status==="ok"||a.status==="relay-limit")return a}return{status:i.status,latencyMs:i.latencyMs}},iA=async e=>{if(!it())return;const t=++lw;for(const s of e)vi.set(s.id,t),po.add(s.id);Jl+=1,Er();try{const s=await nA();await Promise.all(e.map(async n=>{const o=await oA(n,s);vi.get(n.id)===t&&(po.delete(n.id),uw(n.id,o))}))}finally{for(const s of e)vi.get(s.id)===t&&po.delete(s.id);Jl-=1,Er()}};let lh=false;const aA=async()=>{if(lh||!it())return;lh=true;const e=await qi().catch(()=>null);e&&(tA(e.hosts.map(t=>t.id)),await iA(ZT(e.hosts,e.localOrigin)))},rA=5e3,cA=1500;let Uc=false;const jc=e=>{const t=String(e??"").trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString())}catch{return null}},lA=async e=>{if(!Dn()||Uc)return;const t=`host:${e}`;if(F()===t){Uc=true;try{const s=await qi().catch(()=>null),n=s?.hosts.find(b=>b.id===e);if(!s||!n?.relay)return;const o=n.apiUrl?$e(n.apiUrl):null;if(o&&o.startsWith("https://"))return;const i=await P("/api/client-auth/connection/candidates").catch(()=>null);if(!i?.ok)return;const a=await i.json().catch(()=>null);if(!a||a.serverId!==n.relay.serverId)return;const r=Array.isArray(a.candidates)?a.candidates:[],l=[];for(const b of r){if(!b||typeof b!="object")continue;const S=b;if(S.type!=="lan"||typeof S.url!="string")continue;const C=$e(S.url);C&&!l.includes(C)&&l.push(C)}if(l.length===0)return;const u=o&&l.includes(o)?o:l[0],p=jc(u);p&&p!==jc(o)&&await VT({hosts:s.hosts.map(b=>b.id===e?{...b,apiUrl:u}:b),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const m=(await qi().catch(()=>null))?.hosts.find(b=>b.id===e)??null;if(!m||!p||jc(m.apiUrl)!==p)return;const w=await sc(u,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(w.status==="unreachable"||w.status==="wrong-service"||w.status==="incompatible"||F()!==t)return;ql({apiBaseUrl:u,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:t})}finally{Uc=false}}},dA=e=>{typeof window>"u"||window.setTimeout(()=>{lA(e).catch(()=>{})},rA)},dh=async(e,t)=>{if(!Dn())return;const s=await qi().catch(()=>null);if(!s)return;const n=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!n)return;const o=s.hosts.find(m=>m.id===n);if(!o?.relay)return;const i=`host:${o.id}`;if(F()===i&&!t?.reconnectActive)return;const a=m=>{ql({apiBaseUrl:m,clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,runtimeKey:i})},r=()=>{ql({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:o.clientToken||null,runtimeKey:i,relay:o.relay??void 0}),dA(o.id)},l=o.apiUrl?$e(uo(o)):null;if(!l){r();return}const u=m=>m.status!=="unreachable"&&m.status!=="wrong-service"&&m.status!=="incompatible",p=sc(l,{clientToken:o.clientToken||null,requestHeaders:o.requestHeaders||null,expectedServerId:o.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),h=await Promise.race([p,new Promise(m=>setTimeout(()=>m(null),cA))]);if(h){if(u(h)){a(l);return}r();return}r(),p.then(m=>{u(m)&&F()===i&&a(l)})};class uh extends Error{constructor(t,s){super(`Agent '${t}' is not available in ${s??"the session's folder"}`),this.agent=t,this.directory=s,this.name="AgentUnavailableError"}agent;directory}const uA=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class Lt extends Error{reason;status;maxBytes;constructor(t,s={}){super(t),this.name="FilesystemError",this.reason=s.reason??"unknown",this.status=s.status,this.maxBytes=s.maxBytes}}const pA=e=>e instanceof Lt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),ki=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"too-large":case"outside-workspace":case"invalid-response":return e;default:return"unknown"}},hA=d({message:c()}),Wz=e=>{if(pA(e)&&e.reason==="not-found")return true;const t=hA.safeParse(e),n=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return n.includes("file not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")},dn=new Map;let Bc;async function ph(e){const t=Ss().api("/api").replace(/\/api\/?$/,""),s=Fo(),n=await Yf();if(F()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(i,a)=>{const r=i instanceof Request?i.url:String(i),l=r.startsWith("/")?`${t}${r}`:r,u=new Headers(i instanceof Request?i.headers:void 0);return new Headers(Rr(a?.headers)??a?.headers).forEach((p,h)=>u.set(h,p)),n.forEach((p,h)=>u.set(h,p)),s?s.fetch(i,{...a,headers:u}):(hs(l,u),iw(i instanceof Request?new Request(l,i):l,{...a,headers:u}))},baseUrl:t}}async function pw(e){const t=!!os()&&!Fo(),s=await ph(e);return async n=>{let o=false;const i=async()=>{if(!o){o=true;try{const r=F()===e;if(!t&&!r)return;await n(r?await ph(e):s),dn.get(e)?.delete(i),dn.get(e)?.size===0&&dn.delete(e),dn.size===0&&(Bc?.(),Bc=void 0)}catch{}finally{o=false}}},a=dn.get(e)??new Set;a.add(i),dn.set(e,a),Bc??=Qr(({runtimeKey:r})=>{for(const l of dn.get(r)??[])l()}),await i()}}const Or=()=>({active:0,waiters:[],activeSessionWaiters:[]});let qs=Or(),Cn=Or();const gA=3,hh=2;Xr(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[qs,Cn];qs=Or(),Cn=Or();for(const n of s){for(const o of[...n.activeSessionWaiters,...n.waiters])o(false);n.activeSessionWaiters.length=0,n.waiters.length=0}});const gh=()=>{for(;qs.active+Cn.active<gA;){const e=Cn.active<hh&&Cn.waiters.length>0?Cn:qs.active<hh&&(qs.activeSessionWaiters.length>0||qs.waiters.length>0)?qs:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(true)}};async function hw(e,t,s){const n=or();if(await new Promise(i=>{s==="active-session"?e.activeSessionWaiters.push(i):e.waiters.push(i),gh()}))try{if(!n())return;const i=await t();return n()?i:void 0}finally{e.active-=1,gh()}}const mA=(e,t="normal")=>hw(qs,e,t),qz=e=>hw(Cn,e,"normal"),gw="/api/opencode/trust",fA="opencode_trust_required",wA=d({kind:T(["plugin","package","mcp","lsp","formatter","shell","config","env","file","permission"]),source:c(),name:c(),detail:c()}),bA=d({directory:c(),trusted:v(),fingerprint:c().nullable(),items:k(wA)}),yA=d({code:g(fA),directory:c()});let An=null;const Xl=new Set,ci=new Map,Gi=new Set,Cs=new Map;let Ql=Promise.resolve(),Gs=0;const ho=()=>{for(const e of Xl)e()},Gz=()=>An,zz=e=>(Xl.add(e),()=>{Xl.delete(e)}),$z=e=>An?An.settle(e):Promise.resolve("skipped");Xr(()=>{Gs+=1,An?.settle("skip"),ci.clear(),Gi.clear(),Cs.clear(),Ql=Promise.resolve(),ho()});const Kz=e=>e?Cs.has(e):false,mw=(e,t)=>{Cs.set(e,e);for(const s of t)Cs.set(s,e)},zi=e=>{const t=Cs.get(e);if(t!==void 0){for(const[s,n]of Cs)n===t&&Cs.delete(s);ho()}},vA=()=>{Gi.clear()},kA=async e=>{if(e.status!==403)return null;try{const t=yA.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},fw=async e=>bA.parse(await e.json()),cr=async e=>{const t=await P(gw,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return fw(t)},SA=async e=>{const t=await P(gw,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({directory:e.directory,fingerprint:e.fingerprint})});if(t.status===409)return{kind:"changed",assessment:await fw(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},CA=(e,t,s)=>new Promise(n=>{const o=i=>{if(t!==Gs){n(false);return}An={directory:i.directory,items:i.items,settle:async a=>{if(a==="skip")return Gi.add(`${i.directory}
|
|
3
3
|
${i.fingerprint}`),mw(i.directory,s),An=null,ho(),n(false),"skipped";let r;try{r=await SA(i)}catch(l){return console.warn("[opencode-trust] Failed to save the answer:",l),"failed"}return t!==Gs?"skipped":r.kind==="changed"?(o(r.assessment),"changed"):(An=null,zi(i.directory),ho(),n(true),"saved")}},ho()};o(e)}),TA=(e,{deliberate:t,background:s=false,throwOnError:n=false,alias:o})=>{const i=h=>n?h:h.catch(m=>(console.warn("[opencode-trust] Could not check the folder:",m),false)),a=ci.get(e);if(a)return o&&a.spellings.add(o),i(a.request);const r=new Set([e,...o?[o]:[]]),l=h=>(Cs.has(h)&&[...r].some(m=>!Cs.has(m))&&(mw(h,r),ho()),false),u=Gs,p=(async()=>{const h=await(s?mA(()=>u===Gs?cr(e):Promise.resolve(null)):cr(e));if(!h||u!==Gs)return false;if(h.trusted)return zi(h.directory),true;if(!t&&Gi.has(`${h.directory}
|
|
4
4
|
${h.fingerprint}`))return l(h.directory);const m=Ql.then(async()=>{if(u!==Gs)return false;const w=await cr(e);return u!==Gs?false:w.trusted?(zi(w.directory),true):!t&&Gi.has(`${w.directory}
|
|
5
5
|
${w.fingerprint}`)?l(w.directory):CA(w,u,r)});return Ql=m.catch(()=>{}),m})().finally(()=>{ci.get(e)?.request===p&&ci.delete(e)});return ci.set(e,{request:p,spellings:r}),i(p)},Jz=async e=>{try{const t=await cr(e);return t.trusted&&zi(t.directory),!t.trusted}catch{return false}},AA=/\/api\/(?:session|(?:experimental\/)?session\/[^/]+\/(?:prompt|command|shell|skill|move))$/,PA=(e,t)=>e==="POST"&&AA.test(t.replace(/\/+$/,"")),he="/api/openchamber/spaces",No=c().regex(/^[0-9a-f]{12}$/),Au=d({title:c().min(1).max(120),by:T(["user","agent"])}),Fn=d({code:c(),message:c()}),Si=d({count:y().int().min(0),paths:k(c())}),RA=d({path:c().optional(),other:c().nullable().optional(),branch:c().optional(),stillThere:Si.optional(),ignoredInTheWay:Si.optional(),filteredInTheWay:Si.optional(),tooLarge:k(c()).optional(),failed:y().int().min(0).optional()});class Vc extends Error{code;status;details;constructor(t,s,n,o={}){super(s),this.name="SpacesRequestError",this.code=t,this.status=n,this.details=o}}const IA=d({id:No,name:c(),state:c()}),xA=Z("enabled",[d({enabled:g(false)}),d({enabled:g(true),spaces:k(IA).nullable(),failure:Fn.optional()})]),EA=d({id:No,name:c(),code:c(),message:c()}),OA=d({enabled:v(),stopped:k(d({id:No,name:c()})),stillRunning:k(EA),unknown:Fn.optional()}),ww=d({mode:T(["allowlist","open"]),domains:k(c())}),bw=Z("kind",[d({kind:g("model"),id:c(),provider:c(),upstream:c(),source:Z("kind",[d({kind:g("typed")}),d({kind:g("env"),name:c()})]),url:c()}),d({kind:g("login"),id:c(),provider:c(),method:c(),url:c()}),d({kind:g("custom"),id:c(),provider:c(),url:c()}),d({kind:g("domain"),id:c(),upstream:c(),url:c()})]),Yz=(e,t)=>e.find(s=>(s.kind==="model"||s.kind==="login"||s.kind==="custom")&&s.provider===t),DA=["checking_place","creating","downloading_image","preparing_tools","setting_network","bringing_code","giving_access","ready"],MA=T(DA),yw=Z("state",[d({state:g("queued"),total:y().int().min(1)}),d({state:g("running"),index:y().int().min(0),total:y().int().min(1),command:c()}),d({state:g("done"),total:y().int().min(1)}),d({state:g("failed"),index:y().int().min(0),total:y().int().min(1),command:c(),exitCode:y().int().nullable(),timedOut:v(),startedAt:c().nullable().default(null),finishedAt:c().nullable().default(null)}),d({state:g("interrupted"),total:y().int().min(1)})]),_n=d({id:No,name:c(),taskTitle:Au.nullish(),placeId:c(),machine:c().nullable().default(null),projectDirectory:c().nullable(),directory:c().nullable(),projectFolder:d({path:c().nullable(),found:v().nullable()}).default({path:null,found:null}),state:T(["preparing","running","exited","missing","failed","unreachable"]),stoppedIdle:v().default(false),step:L([MA,g("failed")]).nullable(),failure:Fn.nullable(),network:ww.nullable(),grants:k(bw),access:T(["granted","needs_access","unknown"]).nullable(),needsAccess:k(c()),accessFailures:k(d({provider:c(),code:c(),message:c()})).default([]),damage:T(["repairable","gatekeeper_gone"]).nullable().default(null),setup:yw.nullable().default(null)}),vw=["install_all","install_cli","start_colima","start_desktop"],FA=[...vw,"get_brew","linux_install","linux_start","permission","windows_install","windows_start"],Pu=d({action:T(vw),running:v(),failure:Fn.extend({output:c().default("")}).nullable()}),mh=d({remedy:T(FA).nullable().catch(null),job:Pu.nullable(),memory:d({bytes:y().min(0),engine:T(["colima","docker_desktop","other"]).catch("other"),low:v()}).nullable()}).nullable().default(null),kw=L([d({id:c(),machine:c().nullable().default(null),available:g(true),hostIsolation:v(),version:c().default(""),setup:mh}),d({id:c(),machine:c().nullable().default(null),available:g(false),code:c(),message:c(),setup:mh})]),Xz="docker-ssh",_A=d({provider:c(),method:c(),expires:c().nullable(),state:T(["usable","expired","unsupported"])}),NA=d({id:c(),name:c(),package:c(),baseURL:c().nullable(),loopback:v(),models:k(c()),hasKey:v(),supported:v()}),LA=d({code:c(),message:c(),details:RA.nullable().optional().catch(null)}),ge=async(e,t,s={})=>{const n=await P(e,{...s,headers:s.body===void 0?s.headers:{"Content-Type":"application/json",...s.headers}}),o=await n.json().catch(()=>null);if(!n.ok){const a=LA.safeParse(o);throw a.success?new Vc(a.data.code,a.data.message,n.status,a.data.details??{}):new Vc("space_request_failed",`The server answered ${n.status}.`,n.status)}const i=t.safeParse(o);if(!i.success)throw new Vc("space_answer_malformed","The server answered in a shape this version does not know.",n.status);return i.data},UA=e=>e.enabled?e.spaces!==null?{enabled:true,spaces:e.spaces}:{enabled:true,spaces:null,failure:e.failure??{code:"space_journey_failed",message:""}}:{enabled:false},Qz=async e=>UA(await ge(`${he}/switch`,xA,{signal:e})),Zz=e=>ge(`${he}/switch`,OA,{method:"PUT",body:JSON.stringify({enabled:e})}),e$=async e=>(await ge(`${he}/places`,d({places:k(kw)}),{signal:e})).places,t$=async e=>(await ge(`${he}/machine`,d({place:kw.nullable()}),{method:"PUT",body:JSON.stringify({machine:e})})).place,Ru=d({imageBytes:y().min(0).nullable(),imagePulling:v().default(false),imageFailure:Fn.nullable().default(null),toolsBytes:y().min(0),spacesBytes:y().min(0),bytesBySpace:be(c(),y().min(0)).default({}),freeBytes:y().min(0),freesImage:v()}),jA=d({freedBytes:y().min(0),kept:k(d({kind:c(),reason:T(["in_use","failed"])})),disk:Ru}),s$=(e,t)=>ge(`${he}/places/${encodeURIComponent(e)}/disk`,Ru,{signal:t}),n$=e=>ge(`${he}/places/${encodeURIComponent(e)}/clean-up`,jA,{method:"POST"}),o$=async e=>(await ge(`${he}/places/local/setup`,d({job:Pu.nullable()}),{signal:e})).job,i$=async e=>(await ge(`${he}/places/local/setup`,d({job:Pu.nullable()}),{method:"POST",body:JSON.stringify({action:e})})).job,a$=e=>ge(`${he}/places/${encodeURIComponent(e)}/image`,Ru,{method:"POST"}),BA=async e=>(await ge(he,d({spaces:k(_n)}),{signal:e})).spaces,r$=e=>ge(he,_n,{method:"POST",body:JSON.stringify(e)}),c$=async e=>(await ge(`${he}/logins`,d({logins:k(_A)}),{signal:e})).logins,VA=async(e,t)=>(await ge(`${he}/custom-providers?directory=${encodeURIComponent(e)}`,d({providers:k(NA)}),{signal:t})).providers,l$=async(e,t)=>(await ge(`${he}/${e}/grants`,d({grant:bw}),{method:"POST",body:JSON.stringify(t)})).grant,d$=async(e,t)=>(await ge(`${he}/${e}/network/domains`,d({network:ww}),{method:"POST",body:JSON.stringify({domain:t})})).network,HA=d({at:c(),listener:c(),host:c(),port:y(),decision:c()}),WA=d({records:k(HA),dropped:y(),since:c()}),u$=(e,t)=>ge(`${he}/${e}/journal`,WA,{signal:t}),qA=d({saved:y().int().min(0)}),Sw=d({id:No,removed:v(),failures:k(Fn),chats:qA.nullable().default(null)}),p$=e=>ge(`${he}/${e}/start`,_n,{method:"POST"}),h$=async(e,t)=>{await ge(`${he}/${e}/task-title`,d({applied:v(),taskTitle:Au.nullable()}),{method:"PUT",body:JSON.stringify({title:t})})},g$=e=>ge(`${he}/${e}/stop`,_n,{method:"POST"}),m$=e=>ge(`${he}/${e}/restart`,_n,{method:"POST"}),f$=e=>ge(`${he}/${e}/restart-opencode`,_n,{method:"POST"}),GA=1,zA=168,Cw=d({enabled:v(),hours:y().int().min(GA).max(zA)}),w$=e=>ge(`${he}/idle-stop`,Cw,{signal:e}),b$=e=>ge(`${he}/idle-stop`,Cw,{method:"PUT",body:JSON.stringify(e)}),y$=(e,t)=>ge(`${he}/${e}/setup`,_n,{method:"POST",body:JSON.stringify({commands:t})}),$A=d({setup:yw.nullable(),output:c().nullable()}),v$=(e,t)=>ge(`${he}/${e}/setup`,$A,{signal:t}),k$=(e,{deleteUnsavedChats:t=false}={})=>ge(`${he}/${e}${t?"?unsavedChats=delete":""}`,Sw,{method:"DELETE"}),KA=d({spaceId:No,name:c(),directory:c()}),S$=async e=>(await ge(`${he}/archives`,d({archives:k(KA)}),{signal:e})).archives,JA=d({changedPaths:y().int().min(0),changedBytes:y().min(0),nestedRepositories:Si,unmerged:Si,changesRoute:T(["open","closed"]),lastApplied:c().nullable(),newPaths:y().int().min(0).nullable(),newPathsUndecided:v().default(false)}),YA=L([d({status:g("applied"),branch:c()}),d({status:g("applied"),appliedPaths:y().int().min(0)}),d({status:g("nothing_to_apply")})]),XA=d({applied:YA,removal:Sw.nullable(),kept:Fn.nullable().default(null)}),C$=(e,t)=>ge(`${he}/${e}/apply`,JA,{signal:t}),T$=(e,t)=>ge(`${he}/${e}/apply`,XA,{method:"POST",body:JSON.stringify(t)}),Tw=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,fh=/^(?:\/\/\?\/)?[A-Za-z]:$/u,QA=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/UNC\/[^/]+\/[^/]+)$/iu,Oe=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const s=t.replace(/\\/g,"/").replace(/^([a-z]):/,(o,i)=>i.toUpperCase()+":");return s==="/"?"/":Tw.test(s)?s.replace(/\/+$/u,"/"):(s.length>1?s.replace(/\/+$/,""):s)||null},ZA=e=>{if(e==="/"||Tw.test(e)||fh.test(e)||QA.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const s=e.slice(0,t);return fh.test(s)?`${s}/`:s},eP=e=>Oe(e)??"",tP=d({id:c().regex(/^[0-9a-f]{12}$/),name:c().default(""),taskTitle:Au.nullish(),state:T(["complete","partial","stale","unknown"]),projectDirectory:c().nullable().default(null),directory:c().nullable().default(null)}),Zl=new Map,Vn=new Map,sP=(e,t)=>t.step==="failed"?{...e,state:"failed",failure:t.failure}:{...e,state:t.step==="ready"?"running":"preparing",step:t.step==="ready"?null:t.step,failure:null},wh=(e,t,s)=>{const n=e.get(t);if(!n||n.state===s)return e;const o=new Map(e);return o.set(t,{...n,state:s}),o},at=xt((e,t)=>({spaces:Zl,journey:null,progressRevision:0,applyJourney:(s,n)=>e(o=>{const i=new Map(s.map(a=>[a.id,a]));for(const[a,r]of Vn){const l=o.journey?.get(a);r>n&&l&&i.set(a,l)}return{journey:i}}),addJourneyEntry:s=>e(n=>{const o=n.progressRevision+1;Vn.set(s.id,o);const i=new Map(n.journey??[]);return i.set(s.id,s),{journey:i,progressRevision:o}}),noteTaskTitle:(s,n)=>{const o=t(),i=o.journey?.get(s),a=o.spaces.get(s),r=o.progressRevision+1;Vn.set(s,r);const l=i?new Map(o.journey).set(s,{...i,taskTitle:n}):o.journey,u=a?new Map(o.spaces).set(s,{...a,taskTitle:n}):o.spaces;return e({journey:l,spaces:u,progressRevision:r}),!!i},noteGrantGiven:(s,n)=>e(o=>{const i=o.journey?.get(s);if(!i)return o;const a=o.progressRevision+1;Vn.set(s,a);const r=new Map(o.journey);return r.set(s,{...i,grants:[...i.grants.filter(l=>l.id!==n.id),n],needsAccess:i.needsAccess.filter(l=>l!==n.id),accessFailures:n.kind==="domain"?i.accessFailures:i.accessFailures.filter(l=>l.provider!==n.provider)}),{journey:r,progressRevision:a}}),customProviders:new Map,noteCustomProviders:(s,n)=>e(o=>{const i=new Map(o.customProviders);return i.set(s,n),{customProviders:i}}),accessDialog:null,openAccessDialog:(s,n=null)=>e({accessDialog:{spaceId:s,providerId:n}}),closeAccessDialog:()=>e({accessDialog:null}),actions:new Map,noteAction:(s,n)=>e(o=>{const i=new Map(o.actions);return n?i.set(s,n):i.delete(s),{actions:i}}),applyDialog:null,openApplyDialog:s=>e({applyDialog:s}),closeApplyDialog:()=>e({applyDialog:null}),deleteDialog:null,deleteUnsaved:null,openDeleteDialog:(s,n=null)=>e({deleteDialog:s,deleteUnsaved:n}),closeDeleteDialog:()=>e({deleteDialog:null,deleteUnsaved:null}),archivedNotice:null,noteChatsArchived:s=>e({archivedNotice:s}),setupOutputDialog:null,openSetupOutputDialog:s=>e({setupOutputDialog:s}),closeSetupOutputDialog:()=>e({setupOutputDialog:null}),actionsSheet:null,openActionsSheet:s=>e({actionsSheet:s}),closeActionsSheet:()=>e({actionsSheet:null}),noteProgress:s=>{const n=t().progressRevision+1;Vn.set(s.spaceId,n);const o=t().journey?.get(s.spaceId);if(!o)return e({progressRevision:n}),false;const i=new Map(t().journey);return i.set(s.spaceId,sP(o,s)),e({journey:i,progressRevision:n}),true},applyMarks:s=>e(n=>{const o=new Map(s.map(i=>[i.id,i]));return o.size===0&&n.spaces.size===0?n:{spaces:o}}),noteStream:(s,n)=>e(o=>n==="connected"?o:{spaces:wh(o.spaces,s,"stale")}),noteReachable:s=>e(n=>({spaces:wh(n.spaces,s,"complete")})),resetForRuntimeSwitch:()=>{Vn.clear(),Co+=1,e({spaces:Zl,journey:null,progressRevision:0,customProviders:new Map,accessDialog:null,actions:new Map,applyDialog:null,deleteDialog:null,deleteUnsaved:null,archivedNotice:null,setupOutputDialog:null,actionsSheet:null})},forgetForSwitchOff:()=>t().resetForRuntimeSwitch()}));let Co=0;const A$=()=>Co,nP=async()=>{const e=Co,t=at.getState().progressRevision,s=await BA();if(e===Co){at.getState().applyJourney(s,t);for(const n of new Set(s.flatMap(o=>o.projectDirectory?[o.projectDirectory]:[])))at.getState().customProviders.has(n)||oP(n)}},Hc=new Map,oP=e=>{const t=Hc.get(e);if(t)return t;const s=Co,n=VA(e).then(o=>{s===Co&&at.getState().noteCustomProviders(e,o)}).catch(()=>{}).finally(()=>{Hc.delete(e)});return Hc.set(e,n),n},iP=e=>at.getState().spaces.get(e)??null,Aw=e=>e?.state==="exited"||e?.state==="missing"||e?.state==="unreachable",aP=e=>Aw(at.getState().journey?.get(e)),Pw=e=>e?.state==="failed"||e?.state==="missing"||e?.state==="unreachable",P$=e=>{const t=yt.c(2);let s;return t[0]!==e?(s=n=>e!=null&&Pw(n.journey?.get(e)),t[0]=e,t[1]=s):s=t[1],at(s)},R$=e=>{const t=It(e);return t!==null&&Pw(at.getState().journey?.get(t))},Rw=(e,t)=>{const s=It(t);return s===null?null:e.spaces.get(s)?.projectDirectory??e.journey?.get(s)?.projectDirectory??null},I$=e=>Rw(at.getState(),e),x$=e=>{const t=yt.c(2);let s;return t[0]!==e?(s=n=>Rw(n,e),t[0]=e,t[1]=s):s=t[1],at(s)},E$=e=>{const t=It(e);return t!==null&&aP(t)},rP=e=>new Set([...e.spaces.keys(),...e.journey?.keys()??[]]),O$=e=>{const t=It(e);return t===null||rP(at.getState()).has(t)},D$=(e,t)=>Array.from(e).filter(s=>!t.has(s)),M$=e=>{const t=yt.c(4);let s;t[0]!==e?(s=It(e),t[0]=e,t[1]=s):s=t[1];const n=s;let o;return t[2]!==n?(o=i=>n!==null&&Aw(i.journey?.get(n)),t[2]=n,t[3]=o):o=t[3],at(o)},cP=(e,t)=>{const s=Array.from(e.values(),n=>{const o=t?.get(n.id);return o?{...n,taskTitle:o.taskTitle??null}:n});for(const n of t?.values()??[])e.has(n.id)||n.projectDirectory===null||n.directory===null||s.push({id:n.id,name:n.name,taskTitle:n.taskTitle??null,state:"complete",projectDirectory:n.projectDirectory,directory:n.directory});return s},F$=e=>{const t=yt.c(7),s=e===void 0?true:e;let n;t[0]!==s?(n=l=>s?l.spaces:Zl,t[0]=s,t[1]=n):n=t[1];const o=at(n);let i;t[2]!==s?(i=l=>s?l.journey:null,t[2]=s,t[3]=i):i=t[3];const a=at(i);let r;return t[4]!==a||t[5]!==o?(r=cP(o,a),t[4]=a,t[5]=o,t[6]=r):r=t[6],r},_$=(e,t)=>{const s=Oe(t);return Array.from(e.values()).filter(n=>s!==null&&Oe(n.projectDirectory)===s)},N$=e=>Array.from(e.values()).filter(t=>t.projectDirectory===null),L$=()=>{const e=yt.c(5),t=at(lP),[s,n]=sn.useState(null);let o,i;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{let r=true;return nP().then(()=>{r&&n(null)},l=>{r&&n(l)}),()=>{r=false}},i=[],e[0]=o,e[1]=i):(o=e[0],i=e[1]),sn.useEffect(o,i);let a;return e[2]!==s||e[3]!==t?(a={journey:t,error:s},e[2]=s,e[3]=t,e[4]=a):a=e[4],a};function lP(e){return e.journey}const bh=500,Iw=()=>{if(typeof window>"u")return false;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("OPENCHAMBER_STARTUP_TRACE")==="1"}catch{return false}},U$=()=>Iw(),Nt=(e,t)=>{if(!Iw())return;const s=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=s,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(s-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>bh&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-bh)},dP=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(n=>n.name==="ModelControls:ready"),s=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,s).filter(n=>n.name.includes("checkConnection")||n.name.includes("checkHealth")||n.name.includes("initializeApp")||n.name.includes("initApp")||n.name.includes("loadProviders")||n.name.includes("loadAgents")||n.name.includes("config.defaults")||n.name.includes("modelsMetadata")||n.name.includes("ModelControls")||n.name.includes("activateDirectory")||n.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=dP);const j$=async(e,t,s)=>{const n=typeof performance<"u"?performance.now():Date.now();Nt(`${e}:start`,s);try{const o=await t(),i=typeof performance<"u"?performance.now():Date.now();return Nt(`${e}:end`,{durationMs:Math.round(i-n)}),o}catch(o){const i=typeof performance<"u"?performance.now():Date.now();throw Nt(`${e}:error`,{durationMs:Math.round(i-n),error:o instanceof Error?o.message:String(o)}),o}},uP=3,pP=3e4,hP=32e3,gP=3600*1e3,mP=600*1e3,fP=200,wP=new Set([429,502,503,504]),ws=new Map,Iu=e=>JSON.stringify([F(),e]);function bP(){const e=Date.now();for(const[t,s]of ws){const n=Math.max(s.lastErrorAt,s.circuitOpenAt);e-n>gP&&ws.delete(t)}}typeof setInterval<"u"&&setInterval(bP,mP).unref?.();function yP(e){const t=Iu(e);let s=ws.get(t);if(!s)for(s={consecutiveErrors:0,lastErrorAt:0,circuitOpen:false,circuitOpenAt:0,circuitCooldownMs:pP},ws.set(t,s);ws.size>fP;){const n=ws.keys().next().value;if(!n)break;ws.delete(n)}return s}function vP(e){e&&ws.delete(Iu(e))}function kP(e,t){if(!e)return;const s=yP(e);s.consecutiveErrors+=1,s.lastErrorAt=Date.now(),SP(t)&&s.consecutiveErrors>=uP&&(s.circuitOpen=true,s.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${s.consecutiveErrors} consecutive errors`))}function SP(e){return e!==void 0&&wP.has(e)}function CP(e){const t=ws.get(Iu(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=false,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,hP*4),false):true:false}function TP(e){if(!(!e||!CP(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}function Wc({providerID:e,id:t,variant:s}){return s?{providerID:e,id:t,variant:s}:{providerID:e,id:t}}function B$(e,t){return e.providerID===t.providerID&&e.id===t.id&&(e.variant??"default")===(t.variant??"default")}function V$(e,t){if(!(!e||!t))return e.find(s=>s.id===t)??e.find(s=>s.modelID===t)}function ae(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const go={text:(e,t)=>`${e}:text:${t}`,reasoning:(e,t)=>`${e}:reasoning:${t}`,tool:e=>e,userText:e=>`${e}:text:0`,userFile:(e,t)=>`${e}:file:${t}`,userAgent:(e,t)=>`${e}:agent:${t}`},H$=e=>e==="completed"||e==="error",xw=e=>e.role==="user"||e.role==="assistant",W$=e=>e==="user"||e==="assistant",q$=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s&&xw(s))return s}},G$=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s?.info&&xw(s.info))return s}},z$=e=>e?.role==="assistant"&&e.time.completed===void 0,q={edit:"edit",execute:"execute",glob:"glob",grep:"grep",patch:"patch",question:"question",read:"read",shell:"shell",skill:"skill",subagent:"subagent",todowrite:"todowrite",webfetch:"webfetch",websearch:"websearch",write:"write",sessionRename:"session_rename",sessionMove:"session_move",models:"models"};function ot(e){const t=e?.trim().toLowerCase();if(!t)return"";const s=t.replace(/:\d+$/,"");if(!s.includes("."))return s;const n=s.split(".").filter(Boolean);return n[n.length-1]??s}const Os=e=>t=>ot(t)===e,AP=Os(q.shell),$$=Os(q.execute),xu=Os(q.subagent),K$=Os(q.question),J$=Os(q.skill),Y$=Os(q.edit),X$=Os(q.write),Q$=Os(q.patch),Z$=Os(q.todowrite),PP=new Set([q.read,q.skill]),RP=e=>PP.has(ot(e)),IP=new Set([q.edit,q.write,q.patch]),xP=new Set([q.read,q.grep,q.glob,q.skill]),EP=new Set([q.webfetch,q.websearch]),eK=e=>IP.has(ot(e)),tK=e=>{const t=ot(e);return t===q.edit||t===q.patch},sK=e=>xP.has(ot(e)),nK=e=>EP.has(ot(e)),oK=e=>ot(e)===q.websearch,W=c().trim().min(1).optional().catch(void 0),yh=y().int().nonnegative().optional().catch(void 0),$i=L([v(),T(["true","false"]).transform(e=>e==="true")]).optional().catch(void 0),OP=d({path:W,filePath:W,file_path:W,command:W,description:W,agent:W,name:W,id:W,server:W,uri:W,prompt:W,title:W,directory:W,search:W,provider:W,patchText:W,pattern:W,query:W,url:W,code:W,questions:k(oe()).optional().catch(void 0),action:W,parameters:d({title:W,name:W,prompt:W,path:W,url:W,query:W,text:W,selector:W,taskId:W,providerId:W,body:W,identifier:W,link:d({identifier:W,title:W}).optional().catch(void 0)}).optional().catch(void 0)}).catch({}),DP=d({file:W,patch:W,additions:yh,deletions:yh,status:T(["added","deleted","modified"]).optional().catch(void 0)}),MP=d({tool:W,status:W,input:nt().optional().catch(void 0)}),Lo=d({files:k(DP.nullable().catch(null)).optional().catch(void 0),sessionID:W,sessionId:W,shellID:W,status:W,name:W,toolCalls:k(MP.nullable().catch(null)).optional().catch(void 0),truncated:v().optional().catch(void 0),outputPath:W}).catch({}),Nn=e=>OP.parse(e??{}),vh=d({recipients:k(c()).catch([]),summary:W,expectAnswer:$i}),FP=L([vh,c().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:"custom",message:"share is not JSON"}),nf}}).pipe(vh)]),ed=d({html:c().optional().catch(void 0),ui:c().optional().catch(void 0),title:W,awaitAnswer:$i,answerLater:$i,share:FP.optional().catch(void 0)}),_P=ed.extend({parameters:ed.optional().catch(void 0)}).catch({}),kh=be(c(),nt()),NP=d({action:c()}).transform(({action:e})=>{let t;try{t=JSON.parse(e)}catch{return{}}const s=kh.safeParse(t);if(!s.success)return{};const{parameters:n,...o}=s.data,i=kh.safeParse(n);return ed.parse({...o,...i.data})}).catch({}),Ew=e=>NP.parse(e??{}),LP=L([d({answered:g(true),summary:c(),data:nt().catch(null)}),d({answered:g(false),reason:c().optional().catch(void 0)})]),Sh=d({openchamber:d({ok:v().optional().catch(void 0),answer:LP.optional().catch(void 0)}).optional().catch(void 0)}).catch({});function UP(e){const t=Nn(e);return t.path??t.filePath??t.file_path}function td(e){return(Lo.parse(e??{}).files??[]).filter(s=>s!==null&&s.file!==void 0)}const Ch=160;function iK(e){const t=Lo.parse(e??{});return t.shellID||t.status==="running"&&(t.sessionID||t.sessionId)?true:(t.toolCalls??[]).some(s=>s?.status==="running"&&(AP(s.tool)||xu(s.tool)))}function Ow(e){const t=Lo.parse(e??{}).toolCalls??[],s=[];for(const n of t){if(!n?.tool)continue;const o={tool:n.tool},i=Vw(n.tool,n.input)?.action;i&&(o.action=i),n.status&&(o.status=n.status);const a=HP(n.input);a&&a!=="{}"&&a!=="null"&&(o.input=a.length>Ch?`${a.slice(0,Ch)}\u2026`:a),s.push(o)}return s}const Eu=d({toolCalls:k(d({tool:W,status:W,input:nt().optional().catch(void 0)}).nullable().catch(null)).optional().catch(void 0),error:v().optional().catch(void 0)}).catch({});function aK(e){const t=Eu.parse(e??{}).toolCalls??[];for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n?.tool)return{tool:n.tool,input:n.input}}}function Dw(e){const t=Eu.parse(e??{}).toolCalls??[];if(!(t.length!==1||!t[0]?.tool))return{...t[0],tool:t[0].tool}}function Mw(e,{input:t,status:s}){return{tool:e,input:t&&typeof t=="object"&&!Array.isArray(t)?t:{},status:s}}function rK(e){const t=Dw(e);if(!t)return;const s=Fu(t.tool),n=Vw(t.tool,t.input)?.tool??(s?`opencode.${s}`:void 0);return n?Mw(n,t):void 0}function jP(e){return e.replaceAll(".","_")}const BP=new Set(["search","fetch"]),VP=new Set(Object.values(q));function cK(e){const t=Dw(e);if(!t||t.status!=="completed"||BP.has(t.tool)||Eu.parse(e??{}).error)return;const s=jP(t.tool);return VP.has(ot(s))?void 0:Mw(s,t)}function lK(e){const t=new Set(Ow(e).map(({tool:n})=>{if(Fu(n))return"opencode";if(ca.has(ot(n)))return ot(n);const o=n.indexOf(".");return o>0?n.slice(0,o).toLowerCase():""})),[s]=t;return t.size===1&&s?s:void 0}function HP(e){if(e!=null)try{return JSON.stringify(e)}catch{return}}function dK(e){const t=Lo.parse(e??{});return t.truncated?t.outputPath?{outputPath:t.outputPath}:{}:null}function uK(e){return Nn(e).code}const WP=d({content:c().trim().min(1),status:T(["pending","in_progress","completed","cancelled"]).catch("pending")}),qP=d({todos:k(WP.nullable().catch(null)).optional().catch(void 0)}).catch({});function GP(e){const t=qP.parse(e??{}).todos;return t?t.filter(s=>s!==null):null}const zP=e=>e===Mu,$P={amp:"&",lt:"<",gt:">",quot:'"',"#39":"'",apos:"'",nbsp:" "},KP=120,Th=(e,t)=>(t.exec(e)?.[1]??"").replace(/<[^>]*>/g," ").replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g,(s,n)=>$P[n]).replace(/\s+/g," ").trim(),JP=e=>(Th(e,/<title\b[^>]*>([\s\S]*?)<\/title>/i)||Th(e,/<h[1-3]\b[^>]*>([\s\S]*?)<\/h[1-3]>/i)).slice(0,KP).trim();function YP(e,t){if(!zP(e))return null;const s=_P.parse(t.input??{}),n=Ew(t.input),o=s.parameters?.html??s.html??n.html??"",i=s.parameters?.ui??s.ui??n.ui,a=i?.trim()?{html:"",ui:i}:o.trim()?{html:o}:null;if(!a)return null;const r=(s.parameters?.title??s.title??n.title)?.trim()||JP(o),l=s.parameters?.share??s.share??n.share;if(l)return t.status!=="completed"?null:Sh.parse(t.metadata??{}).openchamber?.ok===true?{...a,title:r,ask:{kind:"show"},share:l}:null;if((s.parameters?.awaitAnswer??s.awaitAnswer??n.awaitAnswer)===true){if(t.status==="running")return{...a,title:r,ask:{kind:"waiting"}};if(t.status==="error")return{...a,title:r,ask:{kind:"unanswered"}}}if(t.status!=="completed")return null;const u=Sh.parse(t.metadata??{}).openchamber;if(u?.ok!==true)return null;const p=u.answer;if((s.parameters?.answerLater??s.answerLater??n.answerLater)===true&&!p)return{...a,title:r,ask:{kind:"later"}};if(p?.answered===true)return{...a,title:r,ask:{kind:"answered",summary:p.summary,data:p.data}};if(p?.answered===false){const h=p.reason==="chat-sent-earlier"?"chat-sent-earlier":p.reason==="ui-not-drawn"?"not-drawn":p.reason==="declined"?"declined":"answered-in-chat";return{...a,title:r,ask:{kind:h}}}return{...a,title:r,ask:{kind:"show"}}}const Ah=d({label:W,reason:W,placeholder:W}),Fw=Ah.extend({parameters:Ah.optional().catch(void 0)}).catch({}),XP=d({env:c().trim().min(1),label:c().trim().min(1),placeholder:W}),Ph=d({program:W,args:k(c()).optional().catch(void 0),reason:W,inputs:k(XP).min(1).optional().catch(void 0)}),Ou=Ph.extend({action:c().optional().catch(void 0),parameters:Ph.optional().catch(void 0)}).catch({}),_w=e=>e==="secret.run"||e==="run",Nw=e=>e==="secret.forget"||e==="forget";function Lw(e,t){const s=i=>i<32||i>=127&&i<=159||i===1564||i>=8203&&i<=8207||i>=8232&&i<=8238||i>=8288&&i<=8297||i===65279,n=i=>Array.from(i,a=>{const r=a.codePointAt(0)??0;return s(r)?`\\u{${r.toString(16).toUpperCase().padStart(4,"0")}}`:a}).join(""),o=i=>/^[A-Za-z0-9_/.,:=@%+-]+$/.test(i)?i:`'${n(i).replaceAll("'","'\\''")}'`;return[e,...t].map(o).join(" ")}function Uw(e,t){if(e==="secret.run"||e==="run"){const s=Ou.parse(t??{}),n=s.parameters?.program??s.program;return n?Lw(n,s.parameters?.args??s.args??[]):void 0}if(e==="secret.request"||e==="request"){const s=Fw.parse(t??{});return s.parameters?.label??s.label}}function QP(e,t){if(e!==nc||t.status!=="running")return null;const s=Ou.parse(t.input??{});if(!_w(s.action))return null;const n=s.parameters?.program??s.program,o=s.parameters?.reason??s.reason,i=s.parameters?.inputs??s.inputs;if(!n||!o||!i)return null;const a=s.parameters?.args??s.args??[];return{reason:o,program:n,command:Lw(n,a),fields:i.map(r=>({env:r.env,label:r.label,placeholder:r.placeholder}))}}function ZP(e,t){if(e!==nc||t.status!=="running")return null;const s=Ou.parse(t.input??{}).action;if(_w(s)||Nw(s))return null;const n=Fw.parse(t.input??{}),o=n.parameters?.label??n.label,i=n.parameters?.reason??n.reason;return!o||!i?null:{label:o,reason:i,placeholder:n.parameters?.placeholder??n.placeholder}}function pK(e){return Nn(e).agent}function hK(e){return Nn(e).description}function eR(e){const t=Lo.parse(e??{});return t.sessionID??t.sessionId}const Du=100,tR=4,sR=120,Mu="openchamber_render",nc="openchamber_secret",jw="openchamber_workflow",Bw="openchamber_image",ca=new Set(["openchamber","openchamber_schedule","openchamber_web","openchamber_memory","openchamber_knowledge","openchamber_notify","openchamber_usage",Mu,Bw,nc,jw]),gK=e=>ca.has(ot(e)),nR=d({ok:g(true),action:g("workflow.run"),data:d({runId:c().min(1)})});function oR(e,t){if(e!==jw||t.status!=="completed")return null;let s;try{s=JSON.parse(t.output)}catch{return null}const n=nR.safeParse(s);return n.success?n.data.data.runId:null}const iR=d({ok:g(true),action:g("image.generate"),data:d({images:k(d({path:c().min(1)})).min(1)})});function aR(e,t){if(e!==Bw||t.status!=="completed")return[];let s;try{s=JSON.parse(t.output)}catch{return[]}const n=iR.safeParse(s);return n.success?n.data.data.images.map(o=>o.path):[]}const mK=(e,t)=>YP(e,t)!==null||oR(e,t)!==null||aR(e,t).length>0||ZP(e,t)!==null||QP(e,t)!==null,rR=d({action:W,awaitAnswer:$i,parameters:d({awaitAnswer:$i}).optional().catch(void 0)}).catch({}),cR=new Set(["session_rename","session_move","worktree_create","worktree_list","worktree_remove","models","list_mcp_resources","read_mcp_resource","schedule_create","schedule_list","schedule_pause","schedule_resume","schedule_delete","artifact_create","artifact_read","artifact_update","artifact_delete"]),Rh="opencode_";function Fu(e){const t=e?.trim().toLowerCase()??"",s=t.startsWith(Rh)?t.slice(Rh.length):ot(t);return cR.has(s)?s:void 0}function fK(e,t){const s=e?.trim()??"";let n;for(const o of t){const i=`${o.replace(/[^a-zA-Z0-9_-]/g,"_")}_`;s.length>i.length&&s.startsWith(i)&&o.length>(n?.length??0)&&(n=o)}return n}function Vw(e,t){const s=ot(e);if(!ca.has(s))return null;const n=rR.parse(t??{}),o=s===Mu?Ew(t).awaitAnswer:void 0,i=n.parameters?.awaitAnswer??n.awaitAnswer??o,a=s===nc&&!Nw(n.action)||i===true;return{tool:s,action:n.action,awaitsAnswer:a}}function Hw(e){const t=e.parameters,s=t?.link;return(s?[s.identifier,s.title].filter(Boolean).join(" "):void 0)||t?.identifier||t?.title||t?.name||t?.path||t?.url||t?.query||t?.text||t?.selector||t?.prompt?.split(`
|
|
@@ -84,6 +84,6 @@ ${e.sessionId}`,Yt=e=>{const[t,s,...n]=e.split(`
|
|
|
84
84
|
${t}`,ni=(e,t)=>({...t,directory:e.directory}),fl=(e,t)=>eo(oU,"/api/message-queue",{directory:e?`/spaces/${e}`:null,signal:t}),Ja=new Set,tm=new Map,Qt=new Map,oi=new Map;let wl=0;const sm=e=>Object.fromEntries(Object.entries(e).map(([t,s])=>[t,s.map(n=>({...n,text:n.text??n.content}))])),dU=(e,t)=>{const s=e??{},n=t<2?s.queuedMessages??{}:{};return{queuedMessages:t<2?{}:sm(s.queuedMessages??{}),quarantinedLegacyMessages:sm({...s.quarantinedLegacyMessages??{},...n}),followUpBehavior:Z0(s.followUpBehavior,s.queueModeEnabled??null)}},Js=(e,t)=>{const{[t]:s,...n}=e;return n},Ya=(e,t,s)=>{const n=(e.queuedMessages[t]??[]).filter(o=>o.id!==s);return n.length===0?{queuedMessages:Js(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:n}}},nm=(e,t,s,n,o)=>{let i=e.queuedMessages,a=e.sendingIds;for(const r of new Set([...Object.keys(i),...Object.keys(a)])){const l=Yt(r);l?.runtimeKey!==t||l.sessionId!==s||o!==void 0&&ps(l.directory)!==o||(Qt.get(r)??-1)>n||(Qt.set(r,n),i=Js(i,r),a=Js(a,r))}return{queuedMessages:i,sendingIds:a}},om=(e,t,s)=>{let n=-1;for(const[o,i]of Qt){if(i<=n)continue;const a=Yt(o);a?.runtimeKey===e&&a.sessionId===s&&ps(a.directory)===t&&(n=i)}return n},Ud=xt()(Do(aa((e,t)=>{let s=null,n=false;const o=(l,u,p,h="")=>{if(p!==F()||ps(l.directory)!==h||(oi.get(em(p,h))??-1)>u)return;const m=Ld(l.sessionId,l.directory,p);if(!m){if(l.items.length>0)return;e(b=>nm(b,p,l.sessionId,u));return}const w=mt(m);om(p,h,l.sessionId)>u||e(b=>{const S=nm(b,p,l.sessionId,u,h);Qt.set(w,u);const C=l.items.map(Ka),x=C.length>0?{...S.queuedMessages,[w]:C}:S.queuedMessages,A=l.sendingId?{...S.sendingIds,[w]:[l.sendingId]}:S.sendingIds;return{queuedMessages:x,sendingIds:A}})},i=async l=>{const u=ps(l.directory);try{const p=await fl(u),h=p.sessions.find(m=>m.sessionId===l.sessionId)??{sessionId:l.sessionId,directory:l.directory,items:[],sendingId:null};o(h,p.revision,l.runtimeKey,u)}catch{}},a=async(l,u,p)=>{try{const h=await eo(Ei,u,ni(l,p));o(h.session,h.revision,l.runtimeKey,ps(l.directory))}catch(h){console.warn("[queue] server update failed:",h),await i(l)}},r=(l,u,p)=>{const h=em(u,p);return(oi.get(h)??-1)>l.revision?false:(oi.set(h,l.revision),e(m=>{const w=A=>(Qt.get(A)??-1)>l.revision,b=A=>{const E=Yt(A);return E?.runtimeKey===u&&ps(E.directory)===p},S=A=>!b(A)||w(A),C={},x={};for(const[A,E]of Object.entries(m.queuedMessages))S(A)&&(C[A]=E);for(const[A,E]of Object.entries(m.sendingIds))S(A)&&(x[A]=E);for(const A of l.sessions){if(ps(A.directory)!==p)continue;const E=Ld(A.sessionId,A.directory,u);if(!E)continue;const B=mt(E);om(u,p,A.sessionId)>l.revision||(Qt.set(B,l.revision),A.items.length>0&&(C[B]=A.items.map(Ka)),A.sendingId&&(x[B]=[A.sendingId]))}return{queuedMessages:C,sendingIds:x}}),true)};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:Ov,sendingIds:{},addToQueue:async(l,u)=>{const p=mt(l),h=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,m={id:h,content:u.content,text:u.text??u.content,createdAt:Date.now(),sendConfig:u.sendConfig};if(u.agentMention&&(m.agentMention=u.agentMention),u.attachments&&u.attachments.length>0&&(m.attachments=u.attachments),u.context&&u.context.length>0&&(m.context=u.context),u.goal&&(m.goal=u.goal),e(S=>{const C=S.queuedMessages[p]??[],x={...S.queuedMessages,[p]:[...C,m].slice(-20)},A=Object.keys(x);if(A.length>Xg){A.sort((E,B)=>(x[E]?.[0]?.createdAt??0)-(x[B]?.[0]?.createdAt??0));for(const E of A.slice(0,A.length-Xg))delete x[E]}return{queuedMessages:x}}),!ds())return;if(!u.sendConfig)throw e(S=>Ya(S,p,h)),new Error("A queued message needs a provider and model to be delivered later.");const w=iM(l.runtimeKey,l.directory,l.sessionId),b=cM(u.content,u.attachments??[]);try{const S=await eo(Ei,`${fn(l.sessionId)}/items`,ni(l,mn("POST",{directory:l.directory,item:Zg(u,u.sendConfig)})));e(C=>Ya(C,p,h)),o(S.session,S.revision,l.runtimeKey,ps(l.directory)),w&&gi.getState().appendSubmissions(w,[b])}catch(S){throw e(C=>Ya(C,p,h)),S}},removeFromQueue:(l,u)=>{const p=mt(l);e(h=>Ya(h,p,u)),ds()&&a(l,`${fn(l.sessionId)}/items/${encodeURIComponent(u)}`,mn("DELETE"))},reorderQueue:(l,u,p)=>{if(u===p)return;const h=mt(l),m=t().queuedMessages[h];if(!m)return;const w=m.findIndex(x=>x.id===u),b=m.findIndex(x=>x.id===p);if(w===-1||b===-1)return;const S=m.slice(),[C]=S.splice(w,1);if(S.splice(b,0,C),e(x=>({queuedMessages:{...x.queuedMessages,[h]:S}})),ds()){const x=S.map(A=>A.id);a(l,`${fn(l.sessionId)}/order`,mn("PUT",{itemIds:x}))}},popToInput:async(l,u)=>{const[p]=await t().takeForSend(l,u);return p??null},takeForSend:async(l,u)=>{const p=mt(l);if(ds())try{const S=ps(l.directory);if(u){const x=await eo(iU,`${fn(l.sessionId)}/items/${encodeURIComponent(u)}/take`,ni(l,mn("POST")));return o(x.session,x.revision,l.runtimeKey,S),[Ka(x.item)]}const C=await eo(aU,`${fn(l.sessionId)}/take`,ni(l,mn("POST")));return o(C.session,C.revision,l.runtimeKey,S),C.items.map(Ka)}catch(S){throw await i(l),S}const h=t(),m=h.sendingIds[p]??[],w=(h.queuedMessages[p]??[]).filter(S=>(u?S.id===u:true)&&!m.includes(S.id));if(w.length===0)return[];const b=new Set(w.map(S=>S.id));return e(S=>{const C=(S.queuedMessages[p]??[]).filter(x=>!b.has(x.id));return C.length===0?{queuedMessages:Js(S.queuedMessages,p)}:{queuedMessages:{...S.queuedMessages,[p]:C}}}),w},clearQueue:l=>{const u=mt(l);e(p=>{const h=p.sendingIds[u]??[],m=(p.queuedMessages[u]??[]).filter(w=>h.includes(w.id));return m.length>0?{queuedMessages:{...p.queuedMessages,[u]:m}}:{queuedMessages:Js(p.queuedMessages,u)}}),ds()&&a(l,fn(l.sessionId),mn("DELETE"))},forgetQueue:l=>{const u=mt(l);Qt.delete(u),e(p=>({queuedMessages:Js(p.queuedMessages,u),sendingIds:Js(p.sendingIds,u)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(l,u)=>{const p=mt(l);e(h=>{const m=h.sendingIds[p]??[];return m.includes(u)?h:{sendingIds:{...h.sendingIds,[p]:[...m,u]}}})},clearSending:(l,u)=>{const p=mt(l);e(h=>{const m=h.sendingIds[p];if(!m||!m.includes(u))return h;const w=m.filter(b=>b!==u);return w.length===0?{sendingIds:Js(h.sendingIds,p)}:{sendingIds:{...h.sendingIds,[p]:w}}})},getSendableQueue:l=>{const u=mt(l),p=t(),h=p.queuedMessages[u]??[],m=p.sendingIds[u];return!m||m.length===0?h:h.filter(w=>!m.includes(w.id))},followSessionMove:l=>{if(ds())return;const u=mt(l);e(p=>{const h={...p.queuedMessages},m={...p.sendingIds};let w=false;for(const b of new Set([...Object.keys(p.queuedMessages),...Object.keys(p.sendingIds)])){if(b===u)continue;const S=Yt(b);if(S?.runtimeKey!==l.runtimeKey||S.sessionId!==l.sessionId)continue;w=true;const C=h[b]??[];if(delete h[b],C.length>0){const A=h[u]??[];h[u]=[...A,...C.filter(E=>!A.some(B=>B.id===E.id))]}const x=m[b]??[];delete m[b],x.length>0&&(m[u]=[...new Set([...m[u]??[],...x])])}return w?{queuedMessages:h,sendingIds:m}:{}})},locateQueuedMessage:(l,u)=>{const{queuedMessages:p,sendingIds:h}=t();for(const m of new Set([...Object.keys(p),...Object.keys(h)])){const w=Yt(m);if(!(w?.runtimeKey!==l.runtimeKey||w.sessionId!==l.sessionId)&&(p[m]?.some(b=>b.id===u)||h[m]?.includes(u)))return w}return l},setFollowUpBehavior:l=>{e({followUpBehavior:l}),Zt({followUpBehavior:l})},getQueueForTarget:l=>t().queuedMessages[mt(l)]??[],hydrate:()=>{if(!ds())return Promise.resolve();const l=F();if(s?.runtimeKey===l)return s.promise;const u=++wl,p=()=>u===wl&&l===F(),h=(async()=>{let b=tm.get(l);for(b||(b={items:Object.entries(t().queuedMessages).flatMap(([C,x])=>{const A=Yt(C);return!A||A.runtimeKey!==l?[]:x.map(E=>({target:A,message:E}))}),pending:null},tm.set(l,b));b.pending||b.items.length>0;){if(!p())return;if(b.pending){await b.pending;continue}const S=b.items.shift();if(!S?.message.sendConfig)continue;const{target:C,message:x}=S,A=eo(Ei,`${fn(C.sessionId)}/items`,ni(C,mn("POST",{directory:C.directory,item:Zg(x,S.message.sendConfig)}))).then(()=>{}).catch(B=>{console.warn("[queue] failed to migrate a locally queued message to the server:",B)});b.pending=A;const E=b;A.then(()=>{E.pending===A&&(E.pending=null)}),await A}if(p())do{n=false;let S;try{S=await fl("",AbortSignal.timeout(15e3))}catch(C){if(!p())return;if(n)continue;throw C}if(!p())return;Ja.add(l),r(S,l,"")}while(n&&p())})(),m={runtimeKey:l,promise:h};s=m;const w=()=>{s===m&&(s=null)};return h.then(w,w),h},resync:()=>(s?.runtimeKey===F()&&(n=true),t().hydrate()),refreshSpaceQueue:async l=>{if(!ds())return;const u=F();let p;try{p=await fl(l,AbortSignal.timeout(15e3))}catch{return}u===F()&&(Ja.add(u),r(p,u,l))},applyServerSession:o,resetForRuntimeSwitch:l=>{if(wl+=1,s=null,n=false,l){for(const u of oi.keys())u.startsWith(`${l}
|
|
85
85
|
`)&&oi.delete(u);for(const u of Qt.keys())Yt(u)?.runtimeKey===l&&Qt.delete(u)}!l||!Ja.has(l)||e(u=>{const p={},h={};for(const[m,w]of Object.entries(u.queuedMessages))Yt(m)?.runtimeKey===l?Qt.delete(m):p[m]=w;for(const[m,w]of Object.entries(u.sendingIds))Yt(m)?.runtimeKey!==l&&(h[m]=w);return{queuedMessages:p,sendingIds:h}})}}},{name:"message-queue-store",version:3,storage:Uu(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const s=Yt(t)?.runtimeKey;return!s||!Ja.has(s)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:dU}),{name:"message-queue-store"})),uU=d({type:g("openchamber:message-queue.updated"),properties:d({revision:y(),session:fp,spaceId:c().optional()})}),K4=(e,t)=>{if(!ds())return;const s=uU.safeParse(e);if(!s.success)return;const{session:n,revision:o,spaceId:i}=s.data.properties;Ud.getState().applyServerSession(n,o,t,i??"")},Dv=[{id:"server",icon:"server"},{id:"cloud",icon:"cloud"},{id:"database",icon:"database-2"},{id:"terminal",icon:"terminal-box"},{id:"code",icon:"code-box"},{id:"ai",icon:"brain-ai-3"}],pU=new Set(Dv.map(e=>e.id)),hU=e=>typeof e=="string"&&pU.has(e),J4=e=>Dv.find(t=>t.id===e)?.icon??"server",gU=(e,t=[])=>{const s=t.length>0?` ${t.join(" ")}`:"",n="'self' data: blob:",o=[e,...t].filter(i=>!!i);return["default-src 'none'",`script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${n}`,`style-src 'unsafe-inline' ${n}${s}`,`img-src ${n}${s}`,`font-src ${n}${s}`,`media-src ${n}${s}`,`worker-src ${n}`,`frame-src ${n}`,`connect-src ${o.length>0?o.join(" "):"'none'"}`,"object-src 'none'","form-action 'none'"].join("; ")},bl="https://extension.invalid",mU=500,fU=40*1024*1024,im=64*1024*1024,fr=async e=>{const t=new Uint8Array(await e.arrayBuffer());let s="";for(let n=0;n<t.length;n+=8192)s+=String.fromCharCode(...t.subarray(n,n+8192));return`data:${e.type||"application/octet-stream"};base64,${btoa(s)}`},wU=e=>e.replace(/\\(?:([0-9a-f]{1,6})\s?|([\s\S]))/gi,(t,s,n)=>{if(s){const o=Number.parseInt(s,16);return o>0&&o<=1114111?String.fromCodePoint(o):"\uFFFD"}return n===`
|
|
86
86
|
`||n==="\r"?"":n??""}),bU=/\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\burl\(\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:\\[\s\S]|[^'\\])*)'|((?:\\[\s\S]|[^)\\])*?))\s*\)|@import\s+(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:\\[\s\S]|[^'\\])*)')/gi,Y4=async(e,t,s,n=[])=>{const o=`/api/guests/${e}/`,i=new URL(t,`${bl}${o}`),a=new Map;let r=0,l=0;const u=async S=>{if(S.origin!==bl||!S.pathname.startsWith(o))throw new Error("Extension resource is outside its package");const C=await s(`${S.pathname}${S.search}`);if(!C.ok)throw new Error(`Could not load extension resource (HTTP ${C.status})`);const x=C.body?.getReader();if(!x)throw new Error("Extension resource has no response body");const A=[];try{for(;;){const{done:E,value:B}=await x.read();if(E)break;if(r+=B.byteLength,r>fU)throw new Error("Extension document exceeds the resource size limit");A.push(new Uint8Array(B))}}catch(E){throw await x.cancel().catch(()=>{}),E}finally{x.releaseLock()}return new Blob(A,{type:C.headers.get("content-type")?.split(";")[0]||"application/octet-stream"})},p=async(S,C,x)=>{const A=S.trim();if(!A||A.startsWith("#"))return S;const E=new URL(A,C);if(E.origin!==bl)return E.href;const B=E.hash;E.hash="";const K=E.href;if(x.includes(K))throw new Error("Circular extension resource reference");let j=a.get(K);if(!j){if(a.size>=mU)throw new Error("Extension document has too many resources");const z=[...x,K];j=u(E).then(async te=>{const se=te.type.split(";")[0];return se==="text/css"||E.pathname.endsWith(".css")?fr(new Blob([await h(await te.text(),E,z)],{type:"text/css"})):fr(se==="text/html"?new Blob([await w(await te.text(),E,z)],{type:"text/html"}):te)}),a.set(K,j)}const H=`${await j}${B}`;if(l+=H.length,l>im)throw new Error("Extension document exceeds the embedded size limit");return H},h=async(S,C,x)=>{let A="",E=0;for(const B of S.matchAll(bU)){const K=B[1]??B[2]??B[3]??B[4]??B[5];if(K===void 0)continue;A+=S.slice(E,B.index);const j=await p(wU(K.trim()),C,x),H=JSON.stringify(j);A+=B[4]!==void 0||B[5]!==void 0?`@import url(${H})`:`url(${H})`,E=B.index+B[0].length}return A+S.slice(E)},m=async(S,C,x)=>{const A=[];let E=S;for(;E.trim();){E=E.replace(/^[\s,]+/,"");const B=/^\S+/.exec(E);if(!B)break;const K=B[0];E=E.slice(K.length);let j="";if(!K.endsWith(",")){const z=E.indexOf(",");j=(z<0?E:E.slice(0,z)).trim(),E=z<0?"":E.slice(z+1)}const H=await p(K.replace(/,+$/,""),C,x);A.push(j?`${H} ${j}`:H)}return A.join(", ")},w=async(S,C,x)=>{const A=new DOMParser().parseFromString(S,"text/html"),E=A.querySelector("base[href]")?.getAttribute("href"),B=A.querySelector("base[target]")?.getAttribute("target"),K=E?new URL(E,C):C;for(const te of A.querySelectorAll("base"))te.remove();const j=A.createElement("base");j.href=K.href,B&&(j.target=B),A.head.prepend(j);const H=A.createElement("meta");H.httpEquiv="Content-Security-Policy",H.content=gU(null,n),A.head.prepend(H);for(const te of A.querySelectorAll("script[src], link[href], img[src], source[src], video[src], audio[src], iframe[src], embed[src], object[data], image[href], image[xlink\\:href], use[href], use[xlink\\:href]"))for(const se of["src","href","data","xlink:href"]){const Ve=te.getAttribute(se);Ve!==null&&te.setAttribute(se,await p(Ve,K,x))}for(const te of A.querySelectorAll("[poster]"))te.setAttribute("poster",await p(te.getAttribute("poster")??"",K,x));for(const te of A.querySelectorAll("img[srcset], source[srcset]"))te.setAttribute("srcset",await m(te.getAttribute("srcset")??"",K,x));for(const te of A.querySelectorAll("style"))te.textContent=await h(te.textContent??"",K,x);for(const te of A.querySelectorAll("[style]"))te.setAttribute("style",await h(te.getAttribute("style")??"",K,x));const z=`<!doctype html>
|
|
87
|
-
${A.documentElement.outerHTML}`;if(z.length>im)throw new Error("Extension document exceeds the size limit");return z},b=await u(i);if(b.type.split(";")[0]!=="text/html")throw new Error("Extension entry is not HTML");return w(await b.text(),i,[i.href])},yU=200,vU=/^image\/(?:png|jpeg|webp|gif)\b/,Ht=new Map,kU=(e,t)=>[os()||"same-origin",e,t].join("|"),SU=()=>{for(;Ht.size>yU;){const e=Ht.keys().next().value;if(typeof e!="string")return;const t=Ht.get(e);t?.url&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(t.url),Ht.delete(e)}},CU=(e,t,s)=>{const n=Ht.get(e);if(n?.url)return Promise.resolve(n.url);if(n?.promise)return n.promise;const o=P(t,{method:"GET",headers:{Accept:"image/*"},query:new URLSearchParams(s)}).then(async i=>{if(!i.ok||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;const a=await i.blob(),r=vU.test(a.type)?URL.createObjectURL(a):await fr(a);return Ht.set(e,{url:r}),SU(),r}).catch(()=>null).finally(()=>{const i=Ht.get(e);i?.promise===o&&!i.url&&Ht.delete(e)});return Ht.set(e,{promise:o}),o},TU=(e,t)=>{const s=yt.c(10);let n;s[0]!==e||s[1]!==t?(n=e?kU(e,t):null,s[0]=e,s[1]=t,s[2]=n):n=s[2];const o=n;let i;s[3]!==o?(i=()=>({url:o?Ht.get(o)?.url??null:null,failed:false}),s[3]=o,s[4]=i):i=s[4];const[a,r]=sn.useState(i);let l,u;return s[5]!==o||s[6]!==e||s[7]!==t?(l=()=>{const p=(w,b)=>r(S=>S.url===w&&S.failed===b?S:{url:w,failed:b});if(!o||!e){p(null,false);return}const h=Ht.get(o)?.url;if(h){p(h,false);return}let m=false;return p(null,false),CU(o,e,t).then(w=>{m||p(w,w===null)}),()=>{m=true}},u=[o,e,t],s[5]=o,s[6]=e,s[7]=t,s[8]=l,s[9]=u):(l=s[8],u=s[9]),sn.useEffect(l,u),a},AU=["image/png","image/jpeg","image/webp","image/svg+xml"],PU=1024*1024,Mv=T(AU),Fv=d({mime:Mv,updatedAt:y().int().positive()}),X4=()=>!Ne(),wp=e=>`/api/provider/${encodeURIComponent(e)}/logo`,RU=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["webp","image/webp"],["svg","image/svg+xml"]]),_v=e=>Mv.safeParse(e.type.trim().toLowerCase()).data??RU.get(e.name.toLowerCase().split(".").pop()??"")??null,Q4=e=>_v(e)?e.size<=0||e.size>PU?"size":null:"type",IU=(e,t)=>new Promise((s,n)=>{const o=new FileReader;o.onload=()=>{const i=c().safeParse(o.result);i.success?s(i.data.replace(/^data:[^;,]*;/i,`data:${t};`)):n(new Error("Could not read the file"))},o.onerror=()=>n(o.error??new Error("Could not read the file")),o.readAsDataURL(e)}),Nv=async e=>{const t=await e.json().catch(()=>null),s=d({error:c()}).safeParse(t).data?.error;return new Error(s??`HTTP ${e.status}`)},Z4=async(e,t)=>{const s=_v(t);if(!s)throw new Error("Logo must be PNG, JPEG, WebP or SVG");const n=await P(wp(e),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:await IU(t,s)})});if(!n.ok)throw await Nv(n);const o=d({logo:Fv}).safeParse(await n.json().catch(()=>null));if(!o.success)throw new Error("Unexpected response");return o.data.logo},eJ=async e=>{const t=await P(wp(e),{method:"DELETE",headers:{Accept:"application/json"}});if(!t.ok)throw await Nv(t)},tJ=(e,t,s)=>{const n=yt.c(6);let o;n[0]!==t||n[1]!==e?(o=t?wp(e):null,n[0]=t,n[1]=e,n[2]=o):o=n[2];const i=o;let a;return n[3]!==t||n[4]!==s?(a=t?new URLSearchParams(t.mime==="image/svg+xml"?{v:String(t.updatedAt),theme:s}:{v:String(t.updatedAt)}).toString():"",n[3]=t,n[4]=s,n[5]=a):a=n[5],TU(i,a)},xU=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const s=new TextEncoder().encode(t);let n="";for(const i of s)n+=String.fromCharCode(i);return`path_${typeof btoa=="function"?btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},sJ=e=>{if(!e.startsWith("path_"))return"";const t=e.slice(5);if(!t||!/^[A-Za-z0-9_-]+$/.test(t))return"";try{const s=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(s,n=>n.charCodeAt(0)))}catch{return""}},G=e=>t=>{const s=e.safeParse(t);return s.success?s.data:void 0},Bo=y().refine(Number.isFinite),ut=c().transform(e=>e.trim()),Fe=ut.pipe(c().min(1)),is=be(c(),oe()),O=G(v()),Be=G(c().min(1)),to=G(ut),wn=G(Fe),Kn=e=>G(c().max(e)),Jn=e=>G(ut.transform(t=>t.slice(0,e))),ue=e=>G(ut.pipe(T(e))),_s=G(Bo),Xa=(e,t)=>G(Bo.transform(s=>Math.max(e,Math.min(t,Math.round(s))))),yl=e=>G(Bo.transform(t=>Math.max(e,Math.round(t)))),EU=G(Bo.positive().transform(Math.floor)),OU=G(L([Ps(),Bo])),DU=G(L([Ps(),ut.transform(e=>e.length>0?e:null)])),MU=G(L([Ps(),ut])),bp=k(oe()).transform(e=>e.filter(t=>c().min(1).safeParse(t).success)),Yn=G(bp.transform(e=>Array.from(new Set(e.map(String))))),vl=G(bp.transform(e=>e.map(String))),FU=is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=k(oe()).safeParse(n);o.success&&(t[s]=o.data.filter(i=>c().safeParse(i).success).map(String))}return t}),kl=G(FU.pipe(be(c(),k(c())).refine(e=>Object.keys(e).length>0))),_U=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[s,n]of Object.entries(e)){const o=s.trim();o&&hU(n)&&(t[o]=n)}return t},NU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=Fv.safeParse(n);o&&i.success&&(t[o]=i.data)}return t})),LU=d({providerID:Fe,modelID:Fe}),Sl=e=>G(k(oe()).transform(t=>{const s=[],n=new Set;for(const o of t){const i=LU.safeParse(o);if(!i.success)continue;const a=`${i.data.providerID}/${i.data.modelID}`;if(!n.has(a)&&(n.add(a),s.push(i.data),s.length>=e))break}return s})),UU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){if(!s)continue;const o=bp.safeParse(n);if(!o.success)continue;const i=Array.from(new Set(o.data.map(String)));i.length>0&&(t[s]=i.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),jU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim();if(!o)continue;if(n===null){t[o]=null;continue}const i=Fe.safeParse(n);i.success&&(t[o]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),BU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=Fe.safeParse(n);!o||!i.success||(t[o]=i.data)}return t})),Qa={completion:{title:"Task Complete",message:"Your task has finished."},error:{title:"Error Occurred",message:"An error occurred while processing your task."},question:{title:"Input Needed",message:"Please provide input to continue."},subtask:{title:"Subtask Complete",message:"A subtask has finished."}},VU=d({title:c().catch(""),message:c().catch("")}),HU=G(is.transform(e=>{const t=a=>{const r=VU.safeParse(e[a]);return r.success?r.data:void 0},s=t("completion"),n=t("error"),o=t("question"),i=t("subtask");if(!(!s&&!n&&!o&&!i))return{completion:s??Qa.completion,error:n??Qa.error,question:o??Qa.question,subtask:i??Qa.subtask}}).pipe(Jr(e=>e!==void 0))),am=is.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,s])=>{const n=c().safeParse(s);return n.success?[[t,n.data]]:[]}))),WU=d({id:oe().transform(e=>String(e??"")),label:oe().transform(e=>String(e??"")),models:k(oe()).transform(e=>e.filter(t=>c().safeParse(t).success).map(String)).catch([]),order:y().catch(0)}),qU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=is.safeParse(n);if(!o.success)continue;const i={},a=k(oe()).safeParse(o.data.customGroups);a.success&&(i.customGroups=a.data.flatMap(u=>{const p=WU.safeParse(u);return p.success?[p.data]:[]}));const r=am.safeParse(o.data.modelAssignments);r.success&&(i.modelAssignments=r.data);const l=am.safeParse(o.data.renamedGroups);l.success&&(i.renamedGroups=l.data),Object.keys(i).length>0&&(t[s]=i)}return t}).refine(e=>Object.keys(e).length>0)),GU=d({id:Fe,name:Fe,hostname:Fe.transform(e=>e.toLowerCase())}),zU=G(k(oe()).transform(e=>{const t=[],s=new Set,n=new Set;for(const o of e){const i=GU.safeParse(o);i.success&&(s.has(i.data.id)||n.has(i.data.hostname)||(s.add(i.data.id),n.add(i.data.hostname),t.push(i.data)))}return t})),$U=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=Fe.safeParse(n);!o||!i.success||(t[o]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),KU=d({id:Fe,label:Fe,source:Fe,subpath:ut.optional().catch(void 0),gitIdentityId:ut.optional().catch(void 0)}),JU=G(k(oe()).transform(e=>{const t=[],s=new Set;for(const n of e){const o=KU.safeParse(n);if(!o.success||s.has(o.data.id))continue;s.add(o.data.id);const i={id:o.data.id,label:o.data.label,source:o.data.source};o.data.subpath&&(i.subpath=o.data.subpath),o.data.gitIdentityId&&(i.gitIdentityId=o.data.gitIdentityId),t.push(i)}return t})),YU=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Cl=Bo.nonnegative(),XU=d({path:Fe,label:Fe.optional().catch(void 0),labelSource:T(["auto","manual"]).optional().catch(void 0),icon:Fe.optional().catch(void 0),iconImage:L([Ps(),d({mime:Fe,updatedAt:Cl.transform(Math.round).pipe(y().positive()),source:T(["custom","auto"])})]).optional().catch(void 0),color:Fe.optional().catch(void 0),iconBackground:L([Ps(),ut.pipe(c().regex(YU)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:Cl.optional().catch(void 0),lastOpenedAt:Cl.optional().catch(void 0),sidebarCollapsed:v().optional().catch(void 0),defaultModel:Fe.optional().catch(void 0),defaultAgent:Fe.optional().catch(void 0),defaultVariant:Fe.optional().catch(void 0)}),QU=G(k(oe()).transform(e=>{const t=[],s=new Set,n=new Set;for(const o of e){const i=XU.safeParse(o);if(!i.success)continue;const a=Oe(i.data.path);if(!a)continue;const r=xU(a);if(!r||s.has(r)||n.has(a))continue;s.add(r),n.add(a);const l={id:r,path:a};i.data.label&&(l.label=i.data.label),i.data.label&&i.data.labelSource&&(l.labelSource=i.data.labelSource),i.data.icon&&(l.icon=i.data.icon),i.data.iconImage!==void 0&&(l.iconImage=i.data.iconImage),i.data.color&&(l.color=i.data.color),i.data.iconBackground!==void 0&&(l.iconBackground=i.data.iconBackground),i.data.addedAt!==void 0&&(l.addedAt=i.data.addedAt),i.data.lastOpenedAt!==void 0&&(l.lastOpenedAt=i.data.lastOpenedAt),i.data.defaultModel&&(l.defaultModel=i.data.defaultModel),i.data.defaultAgent&&(l.defaultAgent=i.data.defaultAgent),i.data.defaultVariant&&(l.defaultVariant=i.data.defaultVariant),i.data.sidebarCollapsed!==void 0&&(l.sidebarCollapsed=i.data.sidebarCollapsed),t.push(l)}return t}).refine(e=>e.length>0)),ZU=T(["steer","queue"]),ej=(e,t)=>{const s=ZU.safeParse(e);if(s.success)return s.data;if(e==="immediate")return"steer";const n=v().safeParse(t.queueModeEnabled);if(n.success)return n.data?"queue":"steer"},tj=T(["default","wider","full"]),sj=(e,t)=>{const s=tj.safeParse(e);if(s.success)return s.data;const n=v().safeParse(t.wideChatLayoutEnabled);if(n.success)return n.data?"full":"default"},nj=ut.pipe(T(["collapsed","summary"])),oj=(e,t)=>{if(t.chatRenderMode==="sorted")return"collapsed";const s=nj.safeParse(e);return s.success?s.data:void 0},ij=G(ut.pipe(T(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),aj=G(ut.pipe(T(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),rj=G(ut.transform(e=>e.replace(/\s+/g," ").slice(0,64))),cj=e=>G(k(oe()).transform(t=>{const s=[];for(const n of t){const o=ut.transform(i=>i.toLowerCase()).safeParse(n);o.success&&e(o.data)&&!s.includes(o.data)&&s.push(o.data)}return s})),yp=e=>G(Jr(e)),Zi=(e,t)=>(s,n)=>{const o=e(s,n);return o===void 0?void 0:t(o)},f=e=>e,R=(e,t,s={})=>({read:()=>I.getState()[e],write:t,autoSave:s.autoSave??true}),kt=e=>t=>{I.setState({[e]:t})},rm=()=>globalThis.window?.__zustand_config_store__??null,$t=e=>({read:()=>rm()?.getState()[e],write:t=>{rm()?.setState({[e]:t})},autoSave:false}),ft=e=>({read:()=>Ut.getState()[e],write:t=>{Ut.setState({[e]:t})},autoSave:false}),lj=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],dj=yp(Xu),uj=yp(ex),pj=yp(tx),hj=G(c().refine(sy)),gj=G(y().refine(Yu)),mj=Zi(to,e=>ic(e,void 0)),fj=Zi(G(k(oe())),nO),wj=Zi(G(k(oe())),e=>kb(e)),bj=ue(["ask","attach","inline","inline-double-paste"]),yj=ue(["default","vim"]),vj=(e,t)=>{let s=e;const n=(o,i)=>{if(s.some(l=>l.type==="command"&&l.name===o))return;const a=s.findIndex(l=>l.type==="command"&&l.name===i),r=a>=0?a+1:s.length;s=[...s.slice(0,r),{type:"command",name:o},...s.slice(r)]};return t.draftStartersCraftGoalAdded!==true&&n("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==true&&n("schedule-task","craft-goal"),s},pa={themeId:f({scope:"profile",perSurface:true,parse:Be}),useSystemTheme:f({scope:"profile",perSurface:true,parse:O}),themeVariant:f({scope:"profile",derived:true,parse:ue(["light","dark"])}),lightThemeId:f({scope:"profile",perSurface:true,parse:Be}),darkThemeId:f({scope:"profile",perSurface:true,parse:Be}),locale:f({scope:"profile",parse:ue(rO),ui:{read:()=>Ur.getState().locale,write:e=>Ur.getState().setLocale(e),autoSave:false}}),lastDirectory:f({scope:"instance",adopt:"bootstrap-only",parse:Be}),homeDirectory:f({scope:"instance",parse:Be}),opencodeBinary:f({scope:"instance",parse:to}),serverUpdateChannel:f({scope:"instance",surfaces:["web"],parse:ue(["stable","canary"])}),projects:f({scope:"instance",parse:QU}),activeProjectId:f({scope:"instance",adopt:"bootstrap-only",parse:Be}),securityScopedBookmarks:f({scope:"instance",surfaces:["desktop"],parse:vl}),pinnedDirectories:f({scope:"instance",parse:Yn}),desktopLanAccessEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopKeepAwakeEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopMinimizeToTrayEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopUpdateChannel:f({scope:"instance",surfaces:["desktop"],parse:ue(["stable","canary"])}),desktopMacMenuBarEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopLinuxNativeFrame:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopUiPassword:f({scope:"instance",secret:true,surfaces:["desktop"],parse:to}),hasDesktopUiPassword:f({scope:"instance",computed:true,surfaces:["desktop"],parse:O}),desktopLanAccessActive:f({scope:"instance",computed:true,surfaces:["desktop"],parse:O}),desktopLanAccessBlockedReason:f({scope:"instance",computed:true,surfaces:["desktop"],parse:to}),githubClientId:f({scope:"instance",parse:wn}),githubScopes:f({scope:"instance",parse:wn}),gitlabClientId:f({scope:"instance",parse:wn}),skillCatalogs:f({scope:"instance",parse:JU}),defaultGitIdentityId:f({scope:"instance",parse:to}),permissionAutoAccept:f({scope:"instance",parse:G(d({sessions:be(c().min(1),L([v(),T(["ask","safety","auto"])])).catch({}),revision:y().int().nonnegative().catch(0)}))}),permissionDefaultMode:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:G(T(["ask","safety","auto"])),ui:R("permissionDefaultMode",e=>I.getState().setPermissionDefaultMode(e))}),messageSearchEnabled:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:O,ui:R("messageSearchEnabled",e=>I.getState().setMessageSearchEnabled(e))}),messageSearchReasoningEnabled:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:O,ui:R("messageSearchReasoningEnabled",e=>I.getState().setMessageSearchReasoningEnabled(e))}),agentControlToolEnabled:f({scope:"instance",parse:O,ui:R("agentControlToolEnabled",e=>I.getState().setAgentControlToolEnabled(e))}),agentScheduleToolEnabled:f({scope:"instance",parse:O,ui:R("agentScheduleToolEnabled",e=>I.getState().setAgentScheduleToolEnabled(e))}),agentWebToolEnabled:f({scope:"instance",parse:O,ui:R("agentWebToolEnabled",e=>I.getState().setAgentWebToolEnabled(e))}),browserProvider:f({scope:"instance",parse:Be,ui:R("browserProvider",e=>I.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:f({scope:"instance",parse:O,ui:R("agentNotifyToolEnabled",e=>I.getState().setAgentNotifyToolEnabled(e))}),agentRenderToolEnabled:f({scope:"instance",parse:O,ui:R("agentRenderToolEnabled",e=>I.getState().setAgentRenderToolEnabled(e))}),agentUsageToolEnabled:f({scope:"instance",parse:O,ui:R("agentUsageToolEnabled",e=>I.getState().setAgentUsageToolEnabled(e))}),agentImageToolEnabled:f({scope:"instance",parse:O,ui:R("agentImageToolEnabled",e=>I.getState().setAgentImageToolEnabled(e))}),agentImageModel:f({scope:"instance",parse:Be,ui:R("agentImageModel",e=>I.getState().setAgentImageModel(e))}),agentSecretToolEnabled:f({scope:"instance",parse:O,ui:R("agentSecretToolEnabled",e=>I.getState().setAgentSecretToolEnabled(e))}),agentMemoryToolEnabled:f({scope:"instance",parse:O,ui:R("agentMemoryToolEnabled",e=>I.getState().setAgentMemoryToolEnabled(e))}),agentMemoryDreamingEnabled:f({scope:"instance",parse:O,ui:R("agentMemoryDreamingEnabled",e=>I.getState().setAgentMemoryDreamingEnabled(e))}),agentMemoryDreamingModel:f({scope:"instance",parse:G(c()),ui:R("agentMemoryDreamingModel",e=>I.getState().setAgentMemoryDreamingModel(e))}),agentMemoryDreamingVariant:f({scope:"instance",parse:G(c()),ui:R("agentMemoryDreamingVariant",e=>I.getState().setAgentMemoryDreamingVariant(e))}),agentKnowledgeToolEnabled:f({scope:"instance",parse:O,ui:R("agentKnowledgeToolEnabled",e=>I.getState().setAgentKnowledgeToolEnabled(e))}),agentWorkflowToolEnabled:f({scope:"instance",parse:O,ui:R("agentWorkflowToolEnabled",e=>I.getState().setAgentWorkflowToolEnabled(e))}),isolatedSpacesEnabled:f({scope:"instance",parse:O,ui:R("isolatedSpacesEnabled",e=>I.getState().setIsolatedSpacesEnabled(e))}),isolatedSpacesIdleStop:f({scope:"instance",parse:G(d({enabled:v(),hours:y().int().min(1).max(168)}).strict())}),isolatedSpacesSshHost:f({scope:"instance",parse:Jn(320)}),agentMemoryFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("agentMemoryFeatureAvailable",e=>I.getState().setAgentMemoryFeatureAvailable(e),{autoSave:false})}),agentWorkflowFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("agentWorkflowFeatureAvailable",e=>I.getState().setAgentWorkflowFeatureAvailable(e),{autoSave:false})}),overviewFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("overviewFeatureAvailable",e=>I.getState().setOverviewFeatureAvailable(e),{autoSave:false})}),routingFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("routingFeatureAvailable",e=>I.getState().setRoutingFeatureAvailable(e),{autoSave:false})}),openCodeUpdateToastDismissedVersion:f({scope:"instance",parse:Jn(128)}),autoDeleteEnabled:f({scope:"instance",parse:O,ui:R("autoDeleteEnabled",e=>I.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:f({scope:"instance",parse:Xa(1,365),ui:R("autoDeleteAfterDays",e=>I.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:f({scope:"instance",parse:O,ui:R("sessionRetentionOnlyArchived",e=>I.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionIncludeInWork:f({scope:"instance",parse:O,ui:R("sessionRetentionIncludeInWork",e=>I.getState().setSessionRetentionIncludeInWork(e))}),sessionRetentionAction:f({scope:"instance",parse:ue(["archive","delete"]),ui:R("sessionRetentionAction",e=>I.getState().setSessionRetentionAction(e))}),mergedWorktreeCleanupEnabled:f({scope:"instance",parse:O,ui:R("mergedWorktreeCleanupEnabled",e=>I.getState().setMergedWorktreeCleanupEnabled(e))}),worktreeArchiveOnDoneEnabled:f({scope:"instance",parse:O,ui:R("worktreeArchiveOnDoneEnabled",e=>I.getState().setWorktreeArchiveOnDoneEnabled(e))}),terminalShell:f({scope:"instance",parse:dj,ui:R("terminalShell",e=>I.getState().setTerminalShell(e))}),terminalLoginShells:f({scope:"instance",parse:cj(Xu),ui:R("terminalLoginShells",e=>I.getState().setTerminalLoginShells(e))}),openInAppId:f({scope:"instance",parse:wn}),dictationEnabled:f({scope:"profile",parse:O,ui:$t("dictationEnabled")}),dictationAutoSend:f({scope:"profile",parse:O,ui:$t("dictationAutoSend")}),sttProvider:f({scope:"instance",parse:ij,ui:$t("sttProvider")}),sttServerUrl:f({scope:"instance",parse:Jn(2048),ui:$t("sttServerUrl")}),sttEndpointPath:f({scope:"instance",parse:G(c().trim().max(1024)),ui:$t("sttEndpointPath")}),sttModel:f({scope:"instance",parse:Jn(256),ui:$t("sttModel")}),sttLocalModel:f({scope:"instance",parse:Jn(256),ui:$t("sttLocalModel")}),sttLanguage:f({scope:"profile",parse:Jn(64),ui:$t("sttLanguage")}),sttCorrectTranscript:f({scope:"profile",parse:O,ui:$t("sttCorrectTranscript")}),tunnelProvider:f({scope:"instance",parse:Zi(wn,e=>e.toLowerCase())}),tunnelMode:f({scope:"instance",parse:G(c().transform(e=>e.trim().toLowerCase()).pipe(T(["quick","managed-remote","managed-local","serve","funnel"])))}),tunnelHttpsPort:f({scope:"instance",parse:Xa(1,65535)}),tunnelBootstrapTtlMs:f({scope:"instance",parse:OU}),tunnelSessionTtlMs:f({scope:"instance",parse:_s}),managedLocalTunnelConfigPath:f({scope:"instance",parse:DU}),managedRemoteTunnelHostname:f({scope:"instance",parse:to}),managedRemoteTunnelToken:f({scope:"instance",secret:true,parse:MU}),hasManagedRemoteTunnelToken:f({scope:"instance",computed:true,parse:O}),managedRemoteTunnelPresets:f({scope:"instance",parse:zU}),managedRemoteTunnelSelectedPresetId:f({scope:"instance",parse:wn}),managedRemoteTunnelPresetTokens:f({scope:"instance",secret:true,parse:$U}),sidebarProjectDisplayMode:f({scope:"profile",parse:ue(["all","single"]),ui:ft("projectDisplayMode")}),sidebarViewMode:f({scope:"profile",perSurface:true,parse:ue(["projects","timeline"]),ui:ft("sidebarViewMode")}),sidebarListSessionGrouping:f({scope:"profile",perSurface:true,parse:ue(["project","time"]),ui:ft("listSessionGrouping")}),sidebarGrouping:f({scope:"profile",perSurface:true,parse:ue(["project","time"]),ui:ft("sidebarGrouping")}),sidebarKeepWorkInPlace:f({scope:"profile",perSurface:true,parse:O,ui:ft("keepWorkInPlace")}),sidebarKeepPinnedInPlace:f({scope:"profile",perSurface:true,parse:O,ui:ft("keepPinnedInPlace")}),sidebarSessionBatchSize:f({scope:"profile",parse:Xa(Nb,Lb),ui:ft("sessionBatchSize")}),sidebarProjectSortOrder:f({scope:"profile",parse:ue(["manual","a-z","z-a","date-added","recent"]),ui:ft("projectSortOrder")}),sidebarShowChatsSection:f({scope:"profile",perSurface:true,parse:O,ui:ft("showChatsSection")}),sidebarShowWorkSection:f({scope:"profile",perSurface:true,parse:O,ui:ft("showWorkSection")}),sidebarShowPinnedSection:f({scope:"profile",perSurface:true,parse:O,ui:ft("showPinnedSection")}),sidebarDetailedZoneRows:f({scope:"profile",perSurface:true,parse:O,ui:ft("detailedZoneRows")}),sidebarWorktreeNameByBranch:f({scope:"profile",parse:O,ui:ft("worktreeNameByBranch")}),sidebarSections:f({scope:"profile",parse:G(hd),ui:{read:()=>Ut.getState().sections,write:e=>Ut.getState().setSections(e),autoSave:false}}),sidebarPinLists:f({scope:"profile",parse:G(Vb),ui:{read:()=>Ut.getState().pinLists,write:e=>Ut.getState().setPinLists(e),autoSave:false}}),sidebarHiddenSections:f({scope:"profile",perSurface:true,parse:G(Hb),ui:{read:()=>Ut.getState().hiddenSections,write:e=>Ut.getState().setHiddenSections(e),autoSave:false}}),workStatusSectionOrder:f({scope:"profile",parse:Zi(vl,mo),ui:R("workStatusSectionOrder",(e,t)=>{const s=t.workStatusSectionOrderExplicit===true;I.setState({workStatusSectionOrder:mo(e,s),workStatusSectionOrderExplicit:s})})}),workStatusSectionOrderExplicit:f({scope:"profile",parse:O,ui:R("workStatusSectionOrderExplicit",e=>I.setState({workStatusSectionOrderExplicit:e}))}),workStatusPanelEnabled:f({scope:"profile",parse:O,ui:R("workStatusPanelEnabled",e=>I.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:f({scope:"profile",parse:wj,ui:{read:()=>I.getState().workStatusHiddenSections,write:(e,t)=>{const s=t.workStatusHiddenSectionsExplicit===true;I.setState({workStatusHiddenSections:kb(e,s),workStatusHiddenSectionsExplicit:s})},autoSave:true}}),workStatusHiddenSectionsExplicit:f({scope:"profile",parse:O,ui:R("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:f({scope:"profile",parse:O,ui:R("showReasoningTraces",e=>I.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:f({scope:"profile",perSurface:true,parse:O,ui:R("streamingAutoFollowEnabled",e=>I.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:f({scope:"profile",parse:O,ui:R("collapsibleThinkingBlocks",e=>I.getState().setCollapsibleThinkingBlocks(e))}),expandReasoningWhileStreaming:f({scope:"profile",parse:O,ui:R("expandReasoningWhileStreaming",e=>I.getState().setExpandReasoningWhileStreaming(e))}),showTextJustificationActivity:f({scope:"profile",parse:O}),chatRenderMode:f({scope:"profile",parse:ue(["sorted","live"])}),activityRenderMode:f({scope:"profile",parse:oj,ui:R("activityRenderMode",e=>I.getState().setActivityRenderMode(e))}),mermaidRenderingMode:f({scope:"profile",parse:ue(["svg","ascii"]),ui:R("mermaidRenderingMode",e=>I.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:f({scope:"profile",parse:ue(["markdown","plain"]),ui:R("userMessageRenderingMode",e=>I.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:f({scope:"profile",parse:O,ui:R("collapsibleUserMessages",e=>I.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:f({scope:"profile",perSurface:true,parse:O,ui:R("stickyUserHeader",e=>I.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:f({scope:"profile",perSurface:true,parse:O,ui:R("promptNavigatorEnabled",e=>I.getState().setPromptNavigatorEnabled(e))}),chatWidth:f({scope:"profile",perSurface:true,parse:sj,ui:R("chatWidth",e=>I.getState().setChatWidth(e))}),wideChatLayoutEnabled:f({scope:"profile",perSurface:true,parse:O}),showSplitAssistantMessageActions:f({scope:"profile",parse:O,ui:R("showSplitAssistantMessageActions",e=>I.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:f({scope:"profile",parse:O,ui:R("showToolFileIcons",e=>I.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:f({scope:"profile",parse:O,ui:R("codeBlockLineWrap",e=>I.getState().setCodeBlockLineWrap(e))}),tableCellWrap:f({scope:"profile",parse:O,ui:R("tableCellWrap",e=>I.getState().setTableCellWrap(e))}),copyMessagesAsPlainText:f({scope:"profile",parse:O,ui:R("copyMessagesAsPlainText",e=>I.getState().setCopyMessagesAsPlainText(e))}),selectionApprovalText:f({scope:"profile",parse:Kn(1e3),ui:R("selectionApprovalText",e=>I.getState().setSelectionApprovalText(e))}),showTurnChangedFiles:f({scope:"profile",parse:O,ui:R("showTurnChangedFiles",e=>I.getState().setShowTurnChangedFiles(e))}),toolJsonViewMode:f({scope:"profile",parse:ue(["summary","formatted","raw"]),ui:R("toolJsonViewMode",e=>I.getState().setToolJsonViewMode(e))}),timeFormatPreference:f({scope:"profile",parse:ue(["auto","12h","24h"]),ui:R("timeFormatPreference",e=>I.getState().setTimeFormatPreference(e))}),weekStartPreference:f({scope:"profile",parse:ue(["auto","sunday","monday"]),ui:R("weekStartPreference",e=>I.getState().setWeekStartPreference(e))}),messageStreamTransport:f({scope:"profile",parse:ue(["auto","ws","sse"]),ui:$t("settingsMessageStreamTransport")}),diffLayoutPreference:f({scope:"profile",parse:ue(["dynamic","inline","side-by-side"]),ui:R("diffLayoutPreference",e=>I.getState().setDiffLayoutPreference(e))}),diffWrapLines:f({scope:"profile",parse:O,ui:R("diffWrapLines",e=>I.getState().setDiffWrapLines(e))}),diffHideWhitespace:f({scope:"profile",parse:O,ui:R("diffHideWhitespace",e=>I.getState().setDiffHideWhitespace(e))}),gitChangesViewMode:f({scope:"profile",parse:ue(["flat","tree"]),ui:R("gitChangesViewMode",e=>I.getState().setGitChangesViewMode(e))}),gitmojiEnabled:f({scope:"profile",parse:O}),defaultFileViewerPreview:f({scope:"profile",parse:O}),directoryShowHidden:f({scope:"profile",parse:O,ui:{read:eO,write:e=>tO(e,{persist:false}),autoSave:false}}),filesViewShowGitignored:f({scope:"profile",parse:O,ui:{read:iO,write:e=>aO(e,{persist:false}),autoSave:false}}),fileEditorKeymap:f({scope:"profile",parse:yj,ui:R("fileEditorKeymap",e=>I.getState().setFileEditorKeymap(e))}),fileEditorVimMappings:f({scope:"profile",parse:Kn(1e4),ui:R("fileEditorVimMappings",e=>I.getState().setFileEditorVimMappings(e))}),autoSaveEnabled:f({scope:"profile",parse:O,ui:R("autoSaveEnabled",e=>I.getState().setAutoSaveEnabled(e))}),fileEditorWrapLines:f({scope:"profile",parse:O,ui:R("fileEditorWrapLines",e=>I.getState().setFileEditorWrapLines(e))}),confirmFileTreeMove:f({scope:"profile",parse:O,ui:R("confirmFileTreeMove",e=>I.getState().setConfirmFileTreeMove(e))}),fileTreeSide:f({scope:"profile",surfaces:["web","desktop"],parse:ue(["left","right"]),ui:R("fileTreeSide",e=>I.getState().setFileTreeSide(e))}),layoutAnimations:f({scope:"profile",surfaces:["web","desktop"],parse:O,ui:R("layoutAnimations",e=>I.getState().setLayoutAnimations(e))}),openLinksInBrowserPanel:f({scope:"profile",surfaces:["desktop"],parse:O,ui:R("openLinksInBrowserPanel",e=>I.getState().setOpenLinksInBrowserPanel(e))}),liveBrowserTabLimit:f({scope:"profile",surfaces:["desktop"],parse:Xa(hb,gb),ui:R("liveBrowserTabLimit",e=>I.getState().setLiveBrowserTabLimit(e))}),agentBrowserSharesLogins:f({scope:"profile",surfaces:["desktop"],parse:O,ui:R("agentBrowserSharesLogins",e=>I.getState().setAgentBrowserSharesLogins(e))}),openTrackerLinksOnBoard:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:O,ui:R("openTrackerLinksOnBoard",e=>I.getState().setOpenTrackerLinksOnBoard(e))}),terminalCloseOnExit:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:O,ui:R("terminalCloseOnExit",e=>I.getState().setTerminalCloseOnExit(e))}),terminalOpenOnProjectAction:f({scope:"profile",surfaces:["web","desktop"],parse:O,ui:R("terminalOpenOnProjectAction",e=>I.getState().setTerminalOpenOnProjectAction(e))}),autoCreateWorktree:f({scope:"profile",parse:O}),sessionTabsEnabled:f({scope:"profile",surfaces:["web","desktop","vscode"],parse:O,ui:R("sessionTabsEnabled",e=>I.getState().setSessionTabsEnabled(e))}),sessionTabsPerWorkspace:f({scope:"profile",surfaces:["web","desktop"],parse:O,ui:R("sessionTabsPerWorkspace",e=>I.getState().setSessionTabsPerWorkspace(e))}),allowPromptingSubagentSessions:f({scope:"profile",parse:O,ui:R("allowPromptingSubagentSessions",e=>I.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:f({scope:"profile",parse:O,ui:R("inputSpellcheckEnabled",e=>I.getState().setInputSpellcheckEnabled(e))}),enterToSend:f({scope:"profile",parse:O,ui:R("enterToSend",e=>I.getState().setEnterToSend(e))}),enterToSendConfigured:f({scope:"profile",parse:O,ui:R("enterToSendConfigured",e=>I.getState().setEnterToSendConfigured(e))}),mobileReturnKeySends:f({scope:"profile",parse:O,ui:R("mobileReturnKeySends",e=>I.getState().setMobileReturnKeySends(e))}),largeTextPasteBehavior:f({scope:"profile",parse:bj,ui:R("largeTextPasteBehavior",e=>I.getState().setLargeTextPasteBehavior(e))}),savePastedImagesAsFiles:f({scope:"profile",parse:O,ui:R("savePastedImagesAsFiles",e=>I.getState().setSavePastedImagesAsFiles(e))}),followUpBehavior:f({scope:"profile",parse:ej,ui:{read:()=>Ud.getState().followUpBehavior,write:e=>Ud.getState().setFollowUpBehavior(e),autoSave:false}}),queueModeEnabled:f({scope:"profile",parse:O}),inputHistoryScope:f({scope:"profile",parse:hj,ui:{read:()=>gi.getState().scope,write:e=>gi.getState().applyScope(e),autoSave:false}}),inputHistoryLimit:f({scope:"profile",parse:gj,ui:{read:()=>gi.getState().entryLimit,write:e=>gi.getState().applyEntryLimit(e),autoSave:false}}),draftStarters:f({scope:"profile",parse:fj,ui:{read:()=>I.getState().globalDraftStarters??void 0,write:(e,t)=>I.getState().setGlobalDraftStarters(vj(e,t)),autoSave:false}}),draftStartersVisible:f({scope:"profile",parse:O,ui:R("draftStartersVisible",e=>I.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:f({scope:"profile",parse:O}),draftStartersScheduleTaskAdded:f({scope:"profile",parse:O}),fontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("fontSize",e=>I.getState().setFontSize(e))}),chatFontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("chatFontSize",e=>I.getState().setChatFontSize(e))}),terminalFontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("terminalFontSize",e=>I.getState().setTerminalFontSize(e))}),editorFontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("editorFontSize",e=>I.getState().setEditorFontSize(e))}),uiFont:f({scope:"profile",parse:uj,ui:R("uiFont",e=>I.getState().setUiFont(e))}),monoFont:f({scope:"profile",parse:pj,ui:R("monoFont",e=>I.getState().setMonoFont(e))}),customUiFont:f({scope:"profile",parse:Kn(100),ui:R("customUiFont",e=>I.getState().setCustomUiFont(e))}),customMonoFont:f({scope:"profile",parse:Kn(100),ui:R("customMonoFont",e=>I.getState().setCustomMonoFont(e))}),uiFontWeight:f({scope:"profile",parse:ue(zI),ui:R("uiFontWeight",e=>I.getState().setUiFontWeight(e))}),padding:f({scope:"profile",perSurface:true,parse:_s,ui:R("padding",e=>I.getState().setPadding(e))}),cornerRadius:f({scope:"profile",perSurface:true,parse:_s,ui:R("cornerRadius",e=>I.getState().setCornerRadius(e))}),shortcutOverrides:f({scope:"profile",parse:BU,ui:R("shortcutOverrides",kt("shortcutOverrides"))}),defaultModel:f({scope:"profile",parse:Be}),defaultVariant:f({scope:"profile",parse:Be}),defaultAgent:f({scope:"profile",parse:Be}),smallModelUseDefault:f({scope:"profile",parse:O}),smallModelOverride:f({scope:"profile",parse:Be}),smallModelVariant:f({scope:"profile",parse:Be}),walkthroughModelOverride:f({scope:"profile",parse:Be}),walkthroughModelVariant:f({scope:"profile",parse:Be}),fallbackModel:f({scope:"profile",parse:Be}),fallbackVariant:f({scope:"profile",parse:Be}),accountSwitchProviders:f({scope:"profile",parse:Yn}),zenModel:f({scope:"profile",parse:wn}),favoriteModels:f({scope:"profile",parse:Sl(64),ui:R("favoriteModels",kt("favoriteModels"),{autoSave:false})}),hiddenModels:f({scope:"profile",parse:Sl(1024),ui:R("hiddenModels",kt("hiddenModels"),{autoSave:false})}),collapsedModelProviders:f({scope:"profile",parse:Yn,ui:R("collapsedModelProviders",kt("collapsedModelProviders"),{autoSave:false})}),customProviderIcons:f({scope:"profile",parse:_U,ui:R("customProviderIcons",kt("customProviderIcons"),{autoSave:false})}),customProviderLogos:f({scope:"profile",parse:NU,ui:R("customProviderLogos",kt("customProviderLogos"),{autoSave:false})}),recentModels:f({scope:"profile",parse:Sl(16),ui:R("recentModels",kt("recentModels"),{autoSave:false})}),lastSelectedModel:f({scope:"profile",parse:Be,ui:R("lastSelectedModel",kt("lastSelectedModel"))}),recentAgents:f({scope:"profile",parse:Yn,ui:R("recentAgents",kt("recentAgents"),{autoSave:false})}),favoriteAgents:f({scope:"profile",parse:Yn,ui:R("favoriteAgents",kt("favoriteAgents"),{autoSave:false})}),recentEfforts:f({scope:"profile",parse:UU,ui:R("recentEfforts",kt("recentEfforts"),{autoSave:false})}),lastUsedEfforts:f({scope:"profile",parse:jU,ui:R("lastUsedEfforts",kt("lastUsedEfforts"),{autoSave:false})}),providerOrder:f({scope:"profile",parse:Yn,ui:R("providerOrder",e=>I.getState().setProviderOrder(e))}),sessionRecapEnabled:f({scope:"profile",parse:O,ui:R("sessionRecapEnabled",e=>I.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:f({scope:"profile",parse:O,ui:R("sessionSuggestionEnabled",e=>I.getState().setSessionSuggestionEnabled(e))}),sessionWorkEnabled:f({scope:"profile",parse:O,ui:R("sessionWorkEnabled",e=>I.getState().setSessionWorkEnabled(e))}),sessionReviewOfferEnabled:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:O,ui:R("sessionReviewOfferEnabled",e=>I.getState().setSessionReviewOfferEnabled(e))}),sessionGoalEnabled:f({scope:"profile",parse:O,ui:R("sessionGoalEnabled",e=>I.getState().setSessionGoalEnabled(e))}),sessionGoalChecker:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:ue(["classifier","small-model"]),ui:R("sessionGoalChecker",e=>I.getState().setSessionGoalChecker(e))}),sessionGoalMaxAutoTurns:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:G(y().refine(sb)),ui:R("sessionGoalMaxAutoTurns",e=>I.getState().setSessionGoalMaxAutoTurns(e))}),sessionGoalDefaultBudgetEnabled:f({scope:"profile",parse:O,ui:R("sessionGoalDefaultBudgetEnabled",e=>I.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:f({scope:"profile",parse:EU,ui:R("sessionGoalDefaultBudget",e=>I.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:f({scope:"profile",parse:O,ui:R("summarizeLastMessage",e=>I.getState().setSummarizeLastMessage(e))}),summaryThreshold:f({scope:"profile",parse:yl(0),ui:R("summaryThreshold",e=>I.getState().setSummaryThreshold(e))}),summaryLength:f({scope:"profile",parse:yl(10),ui:R("summaryLength",e=>I.getState().setSummaryLength(e))}),maxLastMessageLength:f({scope:"profile",parse:yl(10),ui:R("maxLastMessageLength",e=>I.getState().setMaxLastMessageLength(e))}),showDeletionDialog:f({scope:"profile",parse:O,ui:R("showDeletionDialog",e=>I.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:f({scope:"profile",parse:O,ui:R("nativeNotificationsEnabled",e=>I.getState().setNativeNotificationsEnabled(e))}),notificationMode:f({scope:"profile",parse:ue(["always","hidden-only"]),ui:R("notificationMode",e=>I.getState().setNotificationMode(e))}),notifyOnSubtasks:f({scope:"profile",parse:O,ui:R("notifyOnSubtasks",e=>I.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:f({scope:"profile",parse:O,ui:R("notifyOnCompletion",e=>I.getState().setNotifyOnCompletion(e))}),notifyOnPullRequests:f({scope:"profile",parse:O,ui:R("notifyOnPullRequests",e=>I.getState().setNotifyOnPullRequests(e))}),notifyOnError:f({scope:"profile",parse:O,ui:R("notifyOnError",e=>I.getState().setNotifyOnError(e))}),notifyOnQuestion:f({scope:"profile",parse:O,ui:R("notifyOnQuestion",e=>I.getState().setNotifyOnQuestion(e))}),notificationTemplates:f({scope:"profile",parse:HU,ui:R("notificationTemplates",e=>I.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:f({scope:"profile",parse:O,ui:R("showOpenCodeUpdateNotifications",e=>I.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:f({scope:"profile",parse:O,ui:R("reportUsage",e=>I.getState().setReportUsage(e))}),usageDisplayMode:f({scope:"profile",parse:ue(["usage","remaining"])}),usageDropdownProviders:f({scope:"profile",parse:vl}),usageSelectedModels:f({scope:"profile",parse:kl}),usageCollapsedFamilies:f({scope:"profile",parse:kl}),usageExpandedFamilies:f({scope:"profile",parse:kl}),usageModelGroups:f({scope:"profile",parse:qU}),globalBehaviorPrompt:f({scope:"profile",parse:Kn(1024*1024)}),responseStyleEnabled:f({scope:"profile",parse:O}),responseStylePreset:f({scope:"profile",parse:ue(lj)}),responseStyleCustomInstructions:f({scope:"profile",parse:Kn(5e4)}),pwaAppName:f({scope:"instance",surfaces:["web"],parse:rj}),pwaOrientation:f({scope:"instance",surfaces:["web"],parse:ue(["system","portrait","landscape"])}),mobileKeyboardMode:f({scope:"device",surfaces:["mobile"],parse:mj,ui:R("mobileKeyboardMode",e=>I.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:f({scope:"device",surfaces:["desktop"],parse:aj,ui:R("desktopWindowControlsPosition",e=>I.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:f({scope:"device",surfaces:["desktop"],parse:ue(["classic","traffic-lights"]),ui:R("desktopWindowControlsStyle",e=>I.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:f({scope:"device",surfaces:["mobile","web"],parse:_s,ui:R("inputBarOffset",e=>I.getState().setInputBarOffset(e))})},kj=e=>Object.prototype.hasOwnProperty.call(pa,e),ha=Object.keys(pa).filter(kj),Lv=e=>pa[e].scope==="device",ga=e=>pa[e],Sj=e=>!pa[e].computed&&!Lv(e),Cj=be(c(),oe()),Tj=e=>{const t=Cj.safeParse(e);if(!t.success)return null;const s=t.data,n={};for(const o of ha){const a=ga(o).parse(s[o],s);a!==void 0&&Object.assign(n,{[o]:a})}return n},Aj=(e,t)=>e===t?true:e===void 0||t===void 0?false:JSON.stringify(e)===JSON.stringify(t),Pj=e=>{for(const t of ha){const s=ga(t);if(!s.ui)continue;const n=e[t];n!==void 0&&(Aj(s.ui.read(),n)||s.ui.write(n,e))}},Rj=ha.filter(e=>ga(e).ui?.autoSave===true),nJ=()=>{const e={};for(const t of Rj){const n=ga(t).ui?.read();n!==void 0&&Object.assign(e,{[t]:n})}return e},Ij=ha.filter(e=>{const t=ga(e);return t.scope!=="device"&&!t.secret&&!t.computed}),Uv=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},cm="openchamber.settingsMirror.v2.index",xj="openchamber.deviceSeeded.v1:",Ej=e=>`${xj}${encodeURIComponent(e)}`,Oj=(e,t)=>{const s=Ej(t);let n=false;try{n=localStorage.getItem(s)===null,n&&localStorage.setItem(s,String(Date.now()))}catch{n=false}if(n)return e;const o={};for(const i of ha)e[i]===void 0||Lv(i)||Object.assign(o,{[i]:e[i]});return o},Dj="openchamber.settingsMirror.v2:",Mj=5,jd=e=>`${Dj}${encodeURIComponent(e)}`,Ns=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},Fj=(e,t)=>{const s={};for(const i of Ij)e[i]!==void 0&&Object.assign(s,{[i]:e[i]});localStorage.setItem(jd(t),JSON.stringify(s));let n=[];try{const i=JSON.parse(localStorage.getItem(cm)??"[]");Array.isArray(i)&&(n=i.filter(a=>typeof a=="string"))}catch{n=[]}const o=[t,...n.filter(i=>i!==t)].slice(0,Mj);for(const i of n)o.includes(i)||localStorage.removeItem(jd(i));localStorage.setItem(cm,JSON.stringify(o))},_j=e=>{if(!(typeof window>"u")){if(Fj(e,F()),Ns("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),Uv(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(s=>s.sidebarCollapsed===true).map(s=>s.id).filter(s=>typeof s=="string"&&s.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"),Ns("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}else localStorage.removeItem("openchamber.pwaName");if(db(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion=="string"){const t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem("opencode-update-toast-dismissed-version",t):localStorage.removeItem("opencode-update-toast-dismissed-version")}else localStorage.removeItem("opencode-update-toast-dismissed-version");typeof e.dictationEnabled=="boolean"?localStorage.setItem("dictationEnabled",String(e.dictationEnabled)):localStorage.removeItem("dictationEnabled"),e.dictationAutoSend!==void 0?localStorage.setItem("dictationAutoSend",String(e.dictationAutoSend)):localStorage.removeItem("dictationAutoSend"),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),Ns("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),Ns("sttEndpointPath",e.sttEndpointPath??null),Ns("sttModel",typeof e.sttModel=="string"?e.sttModel:null),Ns("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),Ns("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null),Ns("sttCorrectTranscript",e.sttCorrectTranscript===void 0?null:String(e.sttCorrectTranscript))}},Bd=(e,t,s=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:s}}))};let Vd="idle",Za=null;const Hd=new Set,Nj=()=>Vd,Lj=e=>(Hd.add(e),()=>Hd.delete(e)),Uj=e=>{gc(),Bt(e)},Bt=e=>{Za&&(clearTimeout(Za),Za=null);const t=e==="saved"?"idle":e;t!==Vd&&(Vd=t,Hd.forEach(s=>s())),t==="error"&&(Za=setTimeout(()=>Bt("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},jv=()=>{const e=I.persist;if(e&&typeof e=="object")return e},Bv=()=>Mo()?.settings??null,Vv=()=>`/api/config/settings?${Db}=${lc()}`,jj=e=>{Pj(e)},Hr=e=>Tj(e);class Bj{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const s=this.mutations.at(-1),n=s?[...this.operations].some(o=>o.revision>=s.revision):true;s&&!n?(s.revision=this.revision,s.changes={...s.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const s={revision:t};return this.operations.add(s),s}reconcile(t,s){let n=t;for(const o of this.mutations)o.revision<=s.revision||(n={...n,...o.changes});return n}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const s=Math.min(...[...this.operations].map(({revision:n})=>n));this.mutations=this.mutations.filter(n=>n.revision>s)}reset(){this.mutations=[],this.operations.clear()}}let vp=0,Ys=null,Ro={},Wd=false;const Vj=()=>Wd,qd=e=>{Wd=true;try{jj(e)}finally{Wd=false}};let vn=null,qt=null,ss=null,lt=null,Oi=[],lm=false,Wr=0,wr=[];const wt=new Bj,Hj=2e3,Wj=200,kp=()=>({runtimeKey:F(),generation:vp}),hc=e=>Object.keys(e),Hv=(e,t)=>e===t?true:e===void 0||t===void 0?false:JSON.stringify(e)===JSON.stringify(t),br=e=>{Ro={...Ro,...e}},qj=e=>{const t={...Ro};for(const s of e)delete t[s];Ro=t},Gj=e=>{const t={};for(const s of hc(e))Hv(e[s],Ro[s])||Object.assign(t,{[s]:e[s]});return t},ea=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,Wv=e=>{let t=null;for(const s of wr)ea(s.context,e)&&(t={...t??{},...s.changes});return qt&&ss&&ea(ss,e)&&(t={...t??{},...qt}),t},dm=(e,t)=>{const s=Wv(t);return e&&s?{...e,...s}:e},_e=e=>e.generation===vp&&e.runtimeKey===F(),ii=()=>{qt&&(lt&&(clearTimeout(lt),lt=null),qr({keepalive:true}))},gc=()=>{if(!(lm||typeof window>"u")){lm=true,Xr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(lt&&clearTimeout(lt),qt&&qr())}),Qr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(vp+=1,wt.reset(),Wr=0,Ys=null,vn=null,Ro={},Bt("saved"))});try{window.addEventListener("pagehide",ii,{capture:true}),window.addEventListener("beforeunload",ii,{capture:true}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&ii()}),document.addEventListener("freeze",ii)),Mn()&&Ge(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||ii()})).catch(()=>{})}catch{}}},qv=async(e=kp())=>{if(gc(),Ys&&ea(Ys.context,e)&&Date.now()-Ys.at<Hj)return dm(Ys.value,e);if(vn&&ea(vn.context,e))return vn.promise;const t=wt.begin(),s=Wv(e),n=i=>{if(!_e(e)||!i)return null;const a=dm(wt.reconcile({...i,...s},t),e);Ys={value:a,at:Date.now(),context:e};const r={};for(const l of hc(i))Hv(i[l],a?.[l])&&Object.assign(r,{[l]:i[l]});return br(r),a},o={context:e,promise:(async()=>{const i=Bv();if(i)try{const a=await i.load();if(!_e(e))return null;const r=Hr(a.settings);return n(r)}catch(a){if(!_e(e))return null;console.warn("Failed to load shared settings from runtime settings API:",a)}if(!_e(e))return null;try{const a=await P(Vv(),{method:"GET",headers:{Accept:"application/json"}});if(!_e(e)||!a.ok)return null;const r=await a.json().catch(()=>null);if(!_e(e))return null;const l=Hr(r);return n(l)}catch(a){return _e(e)&&console.warn("Failed to load shared settings from server:",a),null}})()};return vn=o,o.promise.finally(()=>{wt.finish(t),vn===o&&(vn=null)}),o.promise},zj=async e=>{const t=e?.bootstrap!==false,s=e?.adoptTheme??t;if(typeof window>"u")return;gc();const n=kp(),o=wt.begin(),i=[jv(),Ut.persist],a=p=>!p?.hasHydrated||p.hasHydrated()||!p.onFinishHydration?Promise.resolve():new Promise(h=>{let m=false;const w=()=>{m||(m=true,h())},b=p.onFinishHydration(()=>{b?.(),w()});p.hasHydrated?.()&&w()}),r=()=>Promise.all(i.map(a)).then(()=>{}),l=p=>!qt||!ss||!_e(ss)?p:{...p,...qt},u=async p=>{if(!_e(n))return;let h=l(wt.reconcile(p,o));if(await r(),!!_e(n)){h=Oj(l(wt.reconcile(p,o)),n.runtimeKey);try{_j(h)}catch(m){console.warn("persistToLocalStorage failed:",m)}try{qd(h)}catch(m){console.warn("applyDesktopUiPreferences failed:",m)}Bd(h,t,s)}};try{const p=await qv(n);p&&_e(n)?await u(p):_e(n)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(p){_e(n)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",p)}finally{wt.finish(o)}};async function qr({keepalive:e=false}={}){let t=false;const s=qt,n=ss,o=Wr,i=Oi;qt=null,ss=null,Wr=0,lt=null,Oi=[];try{if(!s||!n||Object.keys(s).length===0||!_e(n)){t=true,Bt("saved");return}const a=wt.begin(o),r={context:n,changes:{...s}};wr.push(r),br(s);const l=()=>qj(hc(s));try{const u=Bv();if(u)try{const p=Hr(await u.save(s));if(!_e(n))return;if(p){br(p);const h=wt.reconcile(p,a);qd(h),Bd(h,false),Ys=null}p||l(),t=!!p,Bt(p?"saved":"error");return}catch(p){if(!_e(n))return;console.warn("Failed to update settings via runtime settings API:",p)}if(!_e(n))return;try{const p=await P(Vv(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s),keepalive:e});if(!_e(n))return;if(!p.ok){console.warn("Failed to update shared settings via API:",p.status,p.statusText),l(),Bt("error");return}const h=Hr(await p.json().catch(()=>null));if(!_e(n))return;if(h){br(h);const m=wt.reconcile(h,a);qd(m),Bd(m,false),t=true,Bt("saved"),Ys=null}else l(),Bt("error")}catch(p){_e(n)&&(console.warn("Failed to update shared settings via API:",p),l(),Bt("error"))}}finally{wr=wr.filter(u=>u!==r),wt.finish(a)}}finally{i.forEach(a=>a({ok:t}))}}const $j=()=>qv(),Zt=async e=>{if(typeof window>"u")return{ok:false};gc();const t=kp();ss&&!ea(ss,t)&&(lt&&clearTimeout(lt),qr());const s={};for(const a of hc(e))Sj(a)&&Object.assign(s,{[a]:e[a]});const n=wt.record(s),o=Gj({...qt??{},...s});if(Object.keys(o).length===0){qt=null,ss=null,lt&&(clearTimeout(lt),lt=null);const a=Oi;return Oi=[],a.forEach(r=>r({ok:true})),Bt("saved"),{ok:true}}qt=o,ss=t,Wr=n,Bt("saving"),lt&&clearTimeout(lt);const i=new Promise(a=>{Oi.push(a)});return lt=setTimeout(()=>{qr()},Wj),i},Kj=async()=>{if(typeof window>"u")return;const e=jv();try{const t=await fE();if(!t)return;const s=()=>mE(t);if(e?.hasHydrated?.()){s();return}if(s(),e?.onFinishHydration){const n=e.onFinishHydration(()=>{n?.(),s()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},oJ=Object.freeze(Object.defineProperty({__proto__:null,applyPersistedHomeDirectoryToWindow:Uv,getRuntimeSettingsMirrorStorageKey:jd,getSettingsSaveState:Nj,initializeAppearancePreferences:Kj,isApplyingServerSettings:Vj,loadDesktopSettings:$j,reportSettingsSaveState:Uj,subscribeToSettingsSaveState:Lj,syncDesktopSettings:zj,updateDesktopSettings:Zt},Symbol.toStringTag,{value:"Module"})),iJ="openchamber:chats",Tl=new Map,Gv=new Map,Gd=new Set,zv=(e,...t)=>[e.replace(/[\\/]+$/,""),...t].join("/");function $v(e){const t=Oe(e);return t?zv(t,".config","openchamber","chats"):null}const Jj=/(?:^|\/)\.\.?(?:\/|$)/;function oo(e,t){return(e===t||e.length>t.length&&e.charCodeAt(t.length)===47&&e.startsWith(t))&&!Jj.test(e)}function Kv(){return Gv.get(F())}function Yj(e){const t=Oe(e),s=Kv();return!t||!s?null:oo(t,s.configured)||oo(t,s.canonicalConfigured)?s.configured:oo(t,s.legacy)||oo(t,s.canonicalLegacy)?s.legacy:null}function Xj(e){return Yj(e)!==null}function aJ(e,t){if(Xj(e))return true;const s=Oe(e),n=$v(t);return!!(s&&n&&oo(s,n))}function Qj(){return Kv()?.configured??null}function rJ(e){return Gd.add(e),()=>Gd.delete(e)}async function ma(){const e=F(),t=Tl.get(e);if(t)return t;const s=et.getFilesystemHomeInfo().then(({home:n,chatsRoot:o,canonicalChatsRoot:i,canonicalLegacyChatsRoot:a})=>{const r=$v(n),l=Oe(o)??r;if(!r||!l)throw new Error("Unable to resolve chat directories");const u={configured:l,legacy:r,canonicalConfigured:Oe(i)??l,canonicalLegacy:Oe(a)??r};Gv.set(e,u);for(const p of Gd)p();return u}).catch(n=>{throw Tl.delete(e),n});return Tl.set(e,s),s}async function Zj(){await ma()}async function eB(){return(await ma()).configured}function cJ(){return Zj().catch(()=>{})}async function lJ(e=new Date){const t=F(),s=await ma();if(F()!==t)throw new Error("Runtime changed while preparing chat directory");const n=[e.getFullYear(),String(e.getMonth()+1).padStart(2,"0"),String(e.getDate()).padStart(2,"0")].join("-"),o=globalThis.crypto?.randomUUID?.()??`${e.getTime()}-${Math.random().toString(36).slice(2)}`,i=zv(s.configured,n,`session-${o}`);return await et.createDirectory(i),i}async function Jv(e,t,s){const n=Oe(e);if(!n)return;const o=[t.configured,t.legacy,t.canonicalConfigured,t.canonicalLegacy];if(o.includes(n)||!o.some(a=>oo(n,a)))return;const i=await s("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!i.ok&&i.status!==404)throw new Error(`Failed to delete chat directory (${i.status})`)}async function dJ(e){if(!Oe(e))return;const t=F(),s=await ma();if(F()!==t)throw new Error("Runtime changed while deleting chat directory");await Jv(e,s,P)}async function uJ(e){const t=await pw(e),s=await ma();if(F()!==e)throw new Error("Runtime changed while preparing chat cleanup");return async n=>{await t(async({fetch:o})=>{await Jv(n,s,o)})}}const tB=3e4,sB=40,nB=60,oB=(e,t,s,n,o,i,a)=>{const r=t.trim(),l=s.trim().toLowerCase();return JSON.stringify([e,r,l,n,o,i,a])},um=(e,t)=>{try{const s=JSON.parse(e);return Array.isArray(s)&&s[1]===t}catch{return false}},pm=new WeakMap,hm=(e,t)=>{if(!t){e.waiters=1/0;return}e.waiters+=1,t.addEventListener("abort",()=>{e.waiters-=1,e.waiters===0&&e.abandon()},{once:true})},iB=xt()(Do((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=nB,i){if(!s||s.trim().length===0)return[];const a=s.trim(),r=F(),l=typeof n=="string"?n.trim():"",u=!!i?.includeHidden,p=i?.respectGitignore??true,h=i?.type==="directory"?"directory":"file",m=oB(r,a,l,o,u,p,h),w=Date.now(),b=t().cache[m];if(b&&w-b.timestamp<tB)return b.files;const S=t().inFlight[m];if(S){const H=pm.get(S);return H&&hm(H,i?.signal),S}const C=h==="file"&&(u||!p)?Mo()?.files:void 0,x=C?t().searchFiles(a,l,o,{type:h}):et.searchFiles(l,{directory:a,limit:o,type:h});let A=false;const E=new AbortController,B=C?C.search({directory:a,query:l,maxResults:o,includeHidden:u,respectGitignore:p,signal:E.signal}).then(H=>H.map(z=>{const te=z.path.replace(/\\/g,"/"),se=z.preview?.[0]?z.preview[0].replace(/\\/g,"/"):te,Ve=se.split("/").filter(Boolean).pop()||te.split("/").filter(Boolean).pop()||"";return{name:Ve,path:te,relativePath:se,extension:Ve.includes(".")?Ve.split(".").pop()?.toLowerCase():void 0}})).catch(H=>(A=true,E.signal.aborted||console.warn("Supplemental file search failed; keeping indexed results:",H),[])):Promise.resolve([]),K=Promise.all([x,B]).then(([H,z])=>{if(z.length===0)return H;const te=new Set(H.map(se=>se.path.replace(/\\/g,"/")));return[...H,...z.filter(se=>te.has(se.path)?false:(te.add(se.path),true))].slice(0,o)}).then(H=>(A||e(z=>{if(z.inFlight[m]!==K)return z;const te={...z.cache,[m]:{files:H,timestamp:Date.now()}},se=z.cacheKeys.filter(Ve=>Ve!==m);for(se.push(m);se.length>sB;){const Ve=se.shift();Ve&&delete te[Ve]}return{cache:te,cacheKeys:se}}),H)).finally(j);function j(){e(H=>{if(H.inFlight[m]!==K)return H;const z={...H.inFlight};return delete z[m],{inFlight:z}})}if(e(H=>({inFlight:{...H.inFlight,[m]:K}})),C){const H={controller:E,waiters:0,abandon:()=>{E.abort(),j()}};pm.set(K,H),hm(H,i?.signal)}return K},invalidateDirectory(s){if(!s||s.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const n=s.trim();e(o=>{const i={...o.cache},a=o.cacheKeys.filter(u=>um(u,n)?(delete i[u],false):true),r=Object.entries(o.inFlight).filter(([u])=>!um(u,n)),l=Object.fromEntries(r);return{cache:i,cacheKeys:a,inFlight:l}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),aB=()=>{if(typeof window>"u")return false;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return false}},zd="openchamber_stream_perf",rB=()=>{if(typeof window>"u")return false;try{return window.localStorage.getItem(zd)==="1"}catch{return false}};let Yv=rB(),Xv=false;const Un=()=>Yv||Xv,Qv=()=>{Un()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},gm=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Zv=()=>{if(!Un()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},ek=e=>Array.from(e.entries()).map(([t,s])=>({metric:t,count:s.count,avg:s.count>0?Number((s.total/s.count).toFixed(3)):0,max:Number(s.max.toFixed(3)),total:Number(s.total.toFixed(3)),last:Number(s.last.toFixed(3))})).sort((t,s)=>s.total-t.total||s.count-t.count),Sp=(e,t)=>{const s=Zv();if(!s)return;const n=s.counters.get(e)??{count:0,total:0,max:0,last:0};n.count+=1,n.total+=t,n.max=Math.max(n.max,t),n.last=t,s.counters.set(e,n),s.lastUpdatedAt=Date.now()},cB=e=>{if(Yv=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(zd,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(zd),Qv()}catch{}},pJ=e=>{if(Xv=e,!(typeof window>"u")){if(e){Zv();return}Qv()}},lB=()=>{typeof window>"u"||(Un()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},dB=()=>{if(typeof window>"u")return{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!Un()||!e?{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:true,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:ek(e.counters)}},hJ=()=>{if(typeof window>"u")return{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!Un()||!e)return{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,s=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:true,startedAt:t,lastUpdatedAt:s,durationMs:t?Math.max(0,Date.now()-t):0,entries:ek(e.counters)}},gJ=(e,t=1)=>{Sp(e,t)},mJ=(e,t)=>{Sp(e,t)},fJ=e=>{!Un()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},wJ=(e,t)=>{if(!Un())return t();const s=gm();try{return t()}finally{Sp(e,gm()-s)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:cB,reset:lB,getSnapshot:dB});var uB={};const pB=e=>!e.isHomeReady&&(e.currentDirectory==="/"||e.currentDirectory===""),mm=(e,t)=>Bi()?t||"":!Ne()&&t||e,tk=async()=>{if(Ne()&&!Bi())return null;const e=F();try{const t=await eB();return F()!==e?null:(Bi()&&await et.createDirectory(t),t)}catch{return null}};let vs=null,$d=0,sk=true;const Tt=la(),fm=Tt.getItem("lastDirectory"),hB=typeof fm=="string"&&fm.length>0,Xn=e=>{try{iB.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Io=e=>Oe(e)??"",gB=(e,t)=>{const s=e.trim();return s.startsWith("~")?s==="~"?t||s:(s.startsWith("~/")||s.startsWith("~\\"))&&t?`${t}${s.slice(1)}`:s:s},yr=(e,t)=>{const s=gB(e,t);return Io(s)},mB=()=>{const e=Tt.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Io(e);return t.length>0?t:null},fB=()=>{const e=Tt.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Io(e);return t.length>0?t:null},wB=()=>{if(typeof process>"u")return null;const e=uB,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const n=Io(t);return n.length>0?n:null}const s=process?.cwd?.();if(typeof s=="string"&&s.trim().length>0){const n=Io(s);return n.length>0?n:null}return null},Cp=()=>{if(typeof window<"u"){if(vs)return vs;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return vs=t,Tt.setItem("homeDirectory",t),t;const s=mB();if(s&&!Ne())return vs=s,s}const e=wB();return e||"/"},fi=e=>{const t=Oe(e);return t&&t!=="/"?t:null},nk=async()=>{try{const s=await et.getFilesystemHome(),n=fi(s);if(n)return n}catch(s){console.warn("Failed to obtain filesystem home directory:",s)}if(!sk)return"/";try{const s=await et.getSystemInfo(),n=fi(s?.homeDirectory);if(n)return n}catch(s){console.warn("Failed to get home directory from system info:",s)}try{const s=await Df(),n=fi(s);if(n)return n}catch(s){console.warn("Failed to obtain desktop-integrated home directory:",s)}const e=Cp(),t=fi(e);return t||e},bB=()=>{if(!Ne())return null;const e=pu()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Io(e);return t.length>0?t:null},ta=bB()||Cp(),sa=(()=>{const e=fB();return e&&!Ne()?yr(e,ta):Ne()&&!Bi()?ta:""})();sa&&et.setDirectory(sa);const yB=!!(ta&&ta!=="/"&&sa),Tp=xt()(Do((e,t)=>({currentDirectory:sa,directoryHistory:[sa],historyIndex:0,homeDirectory:ta,hasPersistedDirectory:hB,isHomeReady:yB,isSwitchingDirectory:false,setDirectory:(s,n)=>{const o=vs||t().homeDirectory||Tt.getItem("homeDirectory"),i=yr(s,o);aB()&&console.log("[DirectoryStore] setDirectory called with path:",i),et.setDirectory(i),Xn(),e(a=>{const r=a.directoryHistory[a.historyIndex]===i,l=r?a.directoryHistory:[...a.directoryHistory.slice(0,a.historyIndex+1),i];return Tt.setItem("lastDirectory",i),Zt({lastDirectory:i}),{currentDirectory:i,directoryHistory:l,historyIndex:r?a.historyIndex:l.length-1,hasPersistedDirectory:true,isHomeReady:true,isSwitchingDirectory:false}})},goBack:()=>{const s=t();if(s.historyIndex>0){const n=s.historyIndex-1,o=s.directoryHistory[n];et.setDirectory(o),Xn(),Tt.setItem("lastDirectory",o),Zt({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:true,isHomeReady:true,isSwitchingDirectory:false})}},goForward:()=>{const s=t();if(s.historyIndex<s.directoryHistory.length-1){const n=s.historyIndex+1,o=s.directoryHistory[n];et.setDirectory(o),Xn(),Tt.setItem("lastDirectory",o),Zt({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:true,isHomeReady:true,isSwitchingDirectory:false})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=t(),o=vs||t().homeDirectory||Cp();if(s===o)return;const i=ZA(s);i&&n(i)},goToNoProjectDirectory:async()=>{const s=F(),n=t().currentDirectory,[o,i]=await Promise.all([vs||t().homeDirectory||nk(),tk()]);if(F()!==s||t().currentDirectory!==n)return;const a=mm(o,i);et.setDirectory(a),Xn(),Tt.removeItem("lastDirectory"),Zt({lastDirectory:""}),e(r=>{const l=r.directoryHistory[r.historyIndex]===a,u=l?r.directoryHistory:[...r.directoryHistory.slice(0,r.historyIndex+1),a];return{currentDirectory:a,directoryHistory:u,historyIndex:l?r.historyIndex:u.length-1,hasPersistedDirectory:false,isHomeReady:true,isSwitchingDirectory:false}})},synchronizeHomeDirectory:(s,n)=>{const o=t(),i=s;vs=i;const a=o.homeDirectory!==i,r=Tt.getItem("lastDirectory"),l=typeof r=="string"&&r.length>0,u=mm(i,n),p=pB(o)||!l&&(o.currentDirectory==="/"||o.currentDirectory===o.homeDirectory||o.currentDirectory===Qj()||!o.currentDirectory);if(!a&&!p){o.isHomeReady||e({isHomeReady:true});return}const h=typeof i=="string"&&i!==""&&i!=="/",m=o.currentDirectory?yr(o.currentDirectory,i):o.currentDirectory,w=o.directoryHistory.map(A=>yr(A,i)),b=w.some((A,E)=>A!==o.directoryHistory[E]),S=!!(m&&m!==o.currentDirectory),C=p&&(!Ne()||Bi())&&!n,x={homeDirectory:i,hasPersistedDirectory:l,isHomeReady:h&&!C};if(p?(x.currentDirectory=u,x.directoryHistory=[u],x.historyIndex=0,x.isSwitchingDirectory=false):(S||b)&&(x.currentDirectory=m,x.directoryHistory=w,x.historyIndex=Math.min(o.historyIndex,w.length-1),x.isSwitchingDirectory=false),e(()=>x),(p||S)&&h&&!C){const A=p?u:m;et.setDirectory(A),Xn(),p||(Tt.setItem("lastDirectory",A),Zt({lastDirectory:A}))}Zt({homeDirectory:i})},resetForRuntimeSwitch:()=>{et.setDirectory(void 0),Xn(),e({currentDirectory:"/",directoryHistory:["/"],historyIndex:0,homeDirectory:"/",hasPersistedDirectory:false,isHomeReady:false,isSwitchingDirectory:false})}}),{name:"directory-store"}));let Di=null;const Kd=()=>{const e=++$d,t=Promise.all([nk(),tk()]).then(([s,n])=>{if(e!==$d)return;const o=fi(s);o&&Tt.setItem("homeDirectory",o),Tp.getState().synchronizeHomeDirectory(s,n)}).finally(()=>{Di===t&&(Di=null)});return Di=t,t},bJ=async()=>{Di&&await Di,!Tp.getState().isHomeReady&&await Kd()};typeof window<"u"&&(Kd(),Qr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(sk=false),vs=null,$d+=1,queueMicrotask(()=>{Kd()})}));const vB=Z("type",[d({id:c(),type:g("open")}),d({id:c(),type:g("message"),data:c(),binary:v()}),d({id:c(),type:g("error")}),d({id:c(),type:g("close"),code:y().int(),reason:c()})]),kB=gS("RuntimeWebSocket"),SB=(e,t,s)=>{const n=new URL(e),o=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"||n.username||n.password?null:(n.protocol=n.protocol==="wss:"?"https:":"http:",n.origin===o.origin&&n.pathname.startsWith(o.pathname)?{...s}:null)},CB=e=>{const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let s="";for(let n=0;n<t.length;n+=8192)s+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(s)},TB=(e,t,s=[],n=kB)=>{if(new Set(s).size!==s.length||s.some(b=>!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(b)))throw new SyntaxError("Invalid WebSocket protocols");const o=crypto.randomUUID();let i=0,a=null,r=false,l=Promise.resolve(),u=0;const p=(b,S)=>{i!==3&&(i=3,a?.remove().catch(()=>{}),a=null,globalThis.window?.removeEventListener("pagehide",w),m.onclose?.({code:b,reason:S}))},h=()=>{i!==3&&(m.onerror?.(),p(1006,""),r&&n.close({id:o,code:1e3,reason:""}).catch(()=>{}))},m={get readyState(){return i},binaryType:"arraybuffer",onopen:null,onmessage:null,onerror:null,onclose:null,send(b){if(i===0)throw new DOMException("WebSocket is connecting","InvalidStateError");if(i!==1)return;const S=b instanceof ArrayBuffer||ArrayBuffer.isView(b),C=S?b.byteLength:new TextEncoder().encode(b).byteLength;if(u+=C,u>16*1024*1024){h();return}const x=S?CB(b):b;l=l.then(async()=>{i!==3&&await n.send({id:o,data:x,binary:S})}).catch(h).finally(()=>{u-=C})},close(b=1e3,S=""){if(b!==1e3&&(b<3e3||b>4999||!Number.isInteger(b)))throw new DOMException("Invalid close code","InvalidAccessError");if(new TextEncoder().encode(S).byteLength>123)throw new SyntaxError("Close reason is too long");if(!(i>=2)){if(i=2,!r){p(1e3,"");return}l=l.then(()=>n.close({id:o,code:b,reason:S})).catch(h)}}},w=()=>m.close();return globalThis.window?.addEventListener("pagehide",w),n.addListener("socketEvent",b=>{const S=vB.safeParse(b);if(!S.success||S.data.id!==o||i===3)return;const C=S.data;switch(C.type){case"open":if(i!==0)return;i=1,m.onopen?.();break;case"message":{if(i!==1)return;let x=C.data;if(C.binary)try{x=Uint8Array.from(atob(C.data),A=>A.charCodeAt(0)).buffer}catch{h();return}m.onmessage?.({data:x});break}case"error":h();break;case"close":p(C.code,C.reason);break}}).then(async b=>{if(i===3){await b.remove();return}a=b,r=true,l=n.open({id:o,url:e,headers:{...t},protocols:s}),await l}).catch(h),m},AB=(e,t)=>{const s=Fo();if(s)return s.openWebSocket(XS(e),t);const n=_o();if(Object.keys(n).length>0&&Mn()){const o=SB(e,Ss().api("/"),n);if(o)return TB(e,o,t)}return jC(new WebSocket(e))},ok=1,PB=2,RB=typeof DecompressionStream=="function",IB=e=>new Response(new Blob([new Uint8Array(e,1)]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer(),io=512*1024,Al=8*1024,xB=0,Qn=1,EB=15e3,xo=new TextEncoder,Ap=new TextDecoder,Pp=T(["interactive","command"]),ik=T(["running","exited","error"]),OB=T(["node","bun"]),Rp=Z("type",[d({type:g("terminal")}),d({type:g("project-action"),actionId:c(),executionId:c()})]),DB=d({sessionId:c(),cols:y(),rows:y(),status:ik,mode:Pp.optional(),purpose:Rp.optional()}),MB=d({sessionId:c(),cwd:c(),status:T(["running","exited"]),createdAt:y().nullable().optional().transform(e=>e??null),mode:Pp.optional(),purpose:Rp.optional()}),wm={mode:Pp.optional(),purpose:Rp.optional()},FB=Z("t",[d({t:g("hello")}),d({t:g("pong")}),d({t:g("error"),s:c().optional(),message:c().optional(),code:c().optional(),fatal:v().optional()}),d({t:g("snapshot"),s:c(),q:y().int().nonnegative().default(0),history:c().default(""),status:ik,cols:y().int().positive().optional(),rows:y().int().positive().optional(),exitCode:y().nullish().transform(e=>e??void 0),signal:y().nullable().optional(),runtime:OB.optional(),ptyBackend:c().optional(),...wm}),d({t:g("output"),s:c(),q:y().int().nonnegative(),d:c(),r:c().optional()}),d({t:g("exit"),s:c(),q:y().int().nonnegative(),exitCode:y().nullish().transform(e=>e??void 0),signal:y().nullable().optional()}),d({t:g("restarted"),s:c(),q:y().int().nonnegative(),history:c().default(""),...wm})]),_B=e=>{const t=xo.encode(JSON.stringify(e)),s=new Uint8Array(t.length+1);return s[0]=ok,s.set(t,1),s},NB=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):xo.encode(e);t[0]===ok&&(t=t.subarray(1));try{return FB.safeParse(JSON.parse(Ap.decode(t))).data??null}catch{return null}};class LB extends Error{code;constructor(t,s){super(t),this.name="TerminalRequestError",this.code=s}}const yJ=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,UB=d({error:c().optional(),code:c().optional()}),mc=async(e,t)=>{const s=UB.safeParse(await e.json().catch(()=>null)).data;return new LB(s?.error??t,s?.code??null)},jB=e=>{const t=xo.encode(e);if(t.byteLength<=io)return e;let s=t.byteLength-io;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;return Ap.decode(t.subarray(s))},Jd=e=>{for(let t=0;t<e.length;t+=1){const s=e.charCodeAt(t);if(s>=55296&&s<=56319){const n=e.charCodeAt(++t);if(n<56320||n>57343||Number.isNaN(n))return false}else if(s>=56320&&s<=57343)return false}return true},Yd=e=>{if(e.malformed!==null)return e.malformed;const t=new Uint8Array(e.byteLength);let s=0;for(const n of e.parts)t.set(n.bytes.subarray(n.start,n.end),s),s+=n.end-n.start;return Ap.decode(t)},Xd=(e,t)=>{if(t.length>=io){let n=t.length-io;for(;n<t.length&&(t[n]&192)===128;)n+=1;const o=t.slice(n);e.parts=[{bytes:o,start:0,end:o.length}],e.byteLength=o.length;return}const s=e.parts.at(-1);if(s&&s.bytes.length===Al&&s.end+t.length<=s.bytes.length)s.bytes.set(t,s.end),s.end+=t.length;else if(t.length<Al){const n=new Uint8Array(Al);n.set(t),e.parts.push({bytes:n,start:0,end:t.length})}else e.parts.push({bytes:t,start:0,end:t.length});for(e.byteLength+=t.length;e.byteLength>io;){const n=e.parts[0],o=e.byteLength-io,i=n.start+o;if(i>=n.end){e.byteLength-=n.end-n.start,e.parts.shift();continue}let a=i;for(;a<n.end&&(n.bytes[a]&192)===128;)a+=1;e.byteLength-=a-n.start,n.start=a,n.start===n.end&&e.parts.shift()}},BB=(e,t)=>{if(t){if(e.malformed!==null||!Jd(t)){const s=jB(Yd(e)+t);if(e.parts=[],e.byteLength=0,!Jd(s)){e.malformed=s;return}e.malformed=null,Xd(e,xo.encode(s));return}Xd(e,xo.encode(t))}},bm=e=>{const t={parts:[],byteLength:0,malformed:null};return Jd(e)?e&&Xd(t,xo.encode(e)):t.malformed=e,t},VB=d({sessions:k(oe())});class HB{constructor(t=ak(null)){this.dependencies=t}dependencies;socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=false;inflating=null;gunzipFailed=false;subscribe(t,s){this.cancelIdleClose();const n={handlers:s,lastSequence:-1},o=this.subscribers.get(t)??new Set,i=o.size===0;o.add(n),this.subscribers.set(t,o);const a=this.projections.get(t);a&&(n.lastSequence=a.sequence,s.onEvent({type:"snapshot",sequence:a.sequence,data:Yd(a.history),cols:a.cols,rows:a.rows,status:a.status,mode:a.mode,purpose:a.purpose,exitCode:a.exitCode,signal:a.signal,runtime:a.runtime,ptyBackend:a.ptyBackend}));const r=this.socket?.readyState===Qn;return this.ensureConnected().then(()=>{const l=this.subscribers.get(t);i&&r&&l===o&&l.size>0&&this.attach(t)}).catch(l=>{o.has(n)&&(s.onError?.(l,false),this.scheduleReconnect())}),()=>{const l=this.subscribers.get(t);if(l?.delete(n),l?.size===0&&(this.subscribers.delete(t),this.projections.delete(t),this.send({t:"detach",v:3,s:t})),this.subscribers.size===0){if(this.cancelReconnect(),this.failures=0,this.socket?.readyState===Qn){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,s){if(s&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s}))))throw new Error("Terminal connection is unavailable")}dispose(){this.disposed=true,this.generation+=1,this.opening=null,this.subscribers.clear(),this.projections.clear(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.cancelIdleClose(),this.wakeCleanup?.(),this.wakeCleanup=null,this.closeSocket()}forget(t){this.projections.delete(t)}noteResize(t,s,n){const o=this.projections.get(t);o&&this.projections.set(t,{...o,cols:s,rows:n})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===Qn)return;if(this.opening)return await this.opening,this.socket?.readyState===Qn?void 0:this.ensureConnected();const t=this.generation,s=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((n,o)=>{let i=false,a=false,r=false,l=null;const u=()=>t===this.generation&&!this.disposed&&l!==null&&this.socket===l,p=()=>{r||a||!u()||(r=true,this.dependencies.clearUrlAuthToken?.())},h=w=>{i||(i=true,clearTimeout(m),w?o(w):n())},m=setTimeout(()=>{p(),l?.close(),h(new Error("Terminal connection timed out"))},1e4);try{const w=this.dependencies.openSocket();l=w,w.binaryType="arraybuffer",this.socket=w,w.onopen=()=>{if(!u()){w.close(),h(new Error("Terminal runtime changed"));return}a=true,this.failures=0,this.send({t:"hello",v:3});for(const b of this.subscribers.keys())this.attach(b);this.startKeepalive(),h()},w.onmessage=b=>this.receive(w,b.data),w.onerror=()=>{const b=u();b&&p(),h(new Error("Terminal WebSocket failed")),b&&this.subscribers.size>0&&this.scheduleReconnect()},w.onclose=()=>{const b=u();b&&(this.stopKeepalive(),p()),this.socket===w&&(this.socket=null),h(new Error("Terminal WebSocket closed")),b&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(w){h(w instanceof Error?w:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=s;try{await s}finally{this.opening===s&&(this.opening=null)}}attach(t){this.send({t:"attach",v:3,s:t,...RB&&!this.gunzipFailed?{z:1}:{}})}receive(t,s){const n=s instanceof ArrayBuffer&&s.byteLength>1&&new Uint8Array(s,0,1)[0]===PB;if(!n&&!this.inflating){this.handleMessage(s);return}const o=(this.inflating??Promise.resolve()).then(()=>n?IB(s):s).then(i=>{this.socket===t&&this.handleMessage(i)}).catch(()=>{this.gunzipFailed=true,this.socket===t&&t.close()}).finally(()=>{this.inflating===o&&(this.inflating=null)});this.inflating=o}handleMessage(t){const s=NB(t);if(!s||s.t==="hello"||s.t==="pong")return;if(s.t==="error"){const i=new Error(s.message??"Terminal error");i.code=s.code;const a=s.s?[s.s]:[...this.subscribers.keys()];for(const r of a)for(const l of this.subscribers.get(r)??[])l.handlers.onError?.(i,s.fatal===true);return}if(!s.s)return;const n=this.subscribers.get(s.s);if(!n)return;if(s.t==="snapshot"){const i={sequence:s.q??0,history:bm(s.history??""),cols:s.cols,rows:s.rows,status:s.status,mode:s.mode,purpose:s.purpose,exitCode:s.exitCode,signal:s.signal??null,runtime:s.runtime,ptyBackend:s.ptyBackend};this.projections.set(s.s,i);const a=Yd(i.history);for(const r of n)r.lastSequence=i.sequence,r.handlers.onEvent({type:"snapshot",sequence:i.sequence,data:a,cols:i.cols,rows:i.rows,status:i.status,mode:i.mode,purpose:i.purpose,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend});return}const o=this.projections.get(s.s);o&&s.q>o.sequence&&(s.t==="output"?(BB(o.history,s.r??s.d),this.projections.set(s.s,{...o,sequence:s.q})):s.t==="exit"?this.projections.set(s.s,{...o,sequence:s.q,status:"exited",exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&this.projections.set(s.s,{...o,sequence:s.q,history:bm(s.history??""),status:"running",mode:s.mode??o.mode,purpose:s.purpose??o.purpose,exitCode:void 0,signal:null}));for(const i of n)s.q<=i.lastSequence||(i.lastSequence=s.q,s.t==="output"?i.handlers.onEvent({type:"data",sequence:s.q,data:s.d,replayData:s.r}):s.t==="exit"?i.handlers.onEvent({type:"exit",sequence:s.q,exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&i.handlers.onEvent({type:"snapshot",sequence:s.q,data:s.history??"",status:"running",mode:s.mode??o?.mode,purpose:s.purpose??o?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==Qn)return false;try{return this.socket.send(_B(t)),true}catch{return false}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const s=typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine?6e4:Math.min(500*2**Math.min(this.failures-1,10),8e3);for(const o of this.subscribers.values())for(const i of o)i.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const n=()=>{typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null,this.ensureConnected().catch(()=>this.scheduleReconnect()))};typeof window<"u"&&window.addEventListener("online",n),typeof document<"u"&&document.addEventListener("visibilitychange",n),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",n),typeof document<"u"&&document.removeEventListener("visibilitychange",n)},this.reconnectTimer=setTimeout(n,s)}scheduleIdleClose(){this.idleCloseTimer||this.disposed||(this.idleCloseTimer=setTimeout(()=>{this.idleCloseTimer=null,!(this.disposed||this.subscribers.size>0)&&(this.generation+=1,this.opening=null,this.closeSocket())},EB))}cancelIdleClose(){this.idleCloseTimer&&(clearTimeout(this.idleCloseTimer),this.idleCloseTimer=null)}startKeepalive(){this.stopKeepalive(),this.keepaliveTimer=setInterval(()=>this.send({t:"ping",v:3}),45e3)}stopKeepalive(){this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null}cancelReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null}closeSocket(){this.stopKeepalive();const t=this.socket;this.socket=null,t&&(t.readyState===xB||t.readyState===Qn)&&t.close()}}const WB="",Gr=new Map,qB=e=>e===null?"/api/terminal/ws":`/api/terminal/ws?directory=${encodeURIComponent(Qf(e))}`;function ak(e){return{refreshAuth:tc,openSocket:()=>AB(Ss().websocket(qB(e))),clearUrlAuthToken:ra}}function fa(e){const t=It(e),s=t??WB,n=Gr.get(s);if(n)return n;const o=new HB(ak(t));return Gr.set(s,o),o}async function GB(e){const t=await P("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),directory:e.cwd});if(!t.ok)throw await mc(t,"Failed to create terminal session");const s=await t.json().catch(()=>null),n=DB.safeParse(s).data;if(!n)throw new Error("Failed to create terminal session");return n}async function zB(e){const t=await P(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`,{directory:e});if(!t.ok)throw await mc(t,"Failed to list terminal sessions");const s=await t.json().catch(()=>null),n=VB.safeParse(s).data?.sessions;if(!Array.isArray(n))throw new Error("Failed to list terminal sessions");const o=[];for(const i of n){const a=MB.safeParse(i).data;a&&o.push(a)}return o}async function $B(e,t){e.length!==0&&await Vo("/api/terminal/touch","POST",{sessionIds:e},t)}async function KB(){const e=await P("/api/terminal/shells");if(!e.ok)throw await mc(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(s=>s&&typeof s=="object"&&Xu(s.id)&&typeof s.name=="string"&&typeof s.supportsLogin=="boolean"):[]}function JB(e,t,s,n){return fa(n).subscribe(e,{onEvent:t,onError:s})}async function YB(e,t,s){await fa(s).write(e,t)}async function Vo(e,t,s,n){const o={method:t,directory:n};s!==void 0&&(o.headers={"Content-Type":"application/json"},o.body=JSON.stringify(s));const i=await P(e,o);if(!i.ok)throw await mc(i,"Terminal command failed");return i}async function XB(e,t,s,n){await Vo(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:s},n),fa(n).noteResize(e,t,s)}async function QB(e,t,s){await Vo(`/api/terminal/${e}/appearance`,"POST",t,s)}async function ZB(e,t){await Vo(`/api/terminal/${e}`,"DELETE",void 0,t),fa(t).forget(e)}async function eV(e,t){return(await Vo(`/api/terminal/${e}/restart`,"POST",t,t.cwd)).json()}async function tV(e){const s=await(await Vo("/api/terminal/force-kill","POST",e,e.cwd)).json().catch(()=>null),n=fa(e.cwd);if(Array.isArray(s?.killedSessionIds))for(const o of s.killedSessionIds)typeof o=="string"&&n.forget(o);else e.sessionId&&n.forget(e.sessionId)}function vJ(){for(const e of Gr.values())e.dispose();Gr.clear()}const sV=()=>({async listShells(){return KB()},async listSessions(e){return zB(e)},async touchSessions(e,t){await $B(e,t)},async createSession(e){return GB(e)},connect(e,t,s){const n=JB(e,t.onEvent,t.onError,s);return{close:()=>n()}},async sendInput(e,t,s){await YB(e,t,s)},async resize(e){await XB(e.sessionId,e.cols,e.rows,e.directory)},async updateAppearance(e,t,s){await QB(e,t,s)},async close(e,t){await ZB(e,t)},async restartSession(e,t){return eV(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows,themeMode:t.themeMode,terminalBackground:t.terminalBackground,terminalForeground:t.terminalForeground,shell:t.shell,loginShell:t.loginShell})},async forceKill(e){await tV(e)}});class Ip extends Error{code;status;constructor(t,s,n){super(s),this.name="GitNetworkOperationRequestError",this.code=t,this.status=n}}class xp extends Error{code;status;remoteName;constructor(t,s,n,o){super(s),this.name="GitWorktreeRequestError",this.code=t,this.status=n,this.remoteName=o}}class nV extends Error{provider;constructor(t,s){super(t),this.name="SourceControlInstanceOtherProviderError",this.provider=s}}class oV extends Error{reason;alias;constructor(t,s,n){super(t),this.name="SourceControlInstanceAliasError",this.reason=s,this.alias=n}}const iV=c().trim().min(1).max(200),Mi=c().trim().min(1).max(512),er=c().trim().max(512).nullable().optional(),aV=d({provider:Ks,instance:Mi,accountId:Mi}).strict(),rV=T(["account","ssh","system","anonymous"]),Eo=d({id:iV,name:Mi,userName:Mi,userEmail:Mi,account:aV.nullable().optional(),transport:rV.optional(),sshCredentialId:er,signCommits:v().optional(),signingKey:er,color:er,icon:er}).strict().superRefine((e,t)=>{e.transport==="account"&&!e.account&&t.addIssue({code:"custom",path:["account"],message:"An account transport requires an account"}),e.transport==="ssh"&&!e.sshCredentialId?.trim()&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"An SSH transport requires a managed key"}),e.transport!=="ssh"&&e.sshCredentialId&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"Only an SSH transport names a managed key"})}),kJ=e=>e?.transport??"system",cV=k(Eo).max(256).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Git identity profile IDs must be unique"),rk=d({userName:c().max(512).nullable(),userEmail:c().max(512).nullable()}).strict(),lV=d({success:v(),profile:Eo.nullable()}).strict(),SJ=e=>!!e.userName&&!!e.userEmail&&(e.transport==="account"&&!!e.account||e.transport==="anonymous"||e.transport==="system"||e.transport===void 0||e.transport==="ssh"&&!!e.sshCredentialId),Qd=new Set,dV=e=>(Qd.add(e),()=>{Qd.delete(e)}),ck=e=>{for(const t of Qd)t(e)},Zd=new Set,uV=(e,t)=>JSON.stringify([t,Oe(e)]);function CJ(e){return Zd.add(e),()=>{Zd.delete(e)}}function pV(e,t){const s=uV(e,t);for(const n of Zd)n(s)}class hV extends Error{reason;constructor(t,s){super(t),this.name="GitPathUnavailableError",this.reason=s}}const gV=d({error:c(),code:T(["path_not_found","nested_repository","untracked_directory"])}),Ep=d({headCommit:c().nullable(),indexCommit:c().nullable(),worktreeCommit:c().nullable(),hasTrackedChanges:v(),hasUntrackedFiles:v(),hasConflict:v()}),Op="GIT_REPOSITORY_UNREADABLE";class lk extends Error{code=Op;constructor(t){super(t),this.name="GitRepositoryUnreadableError"}}const M="/api/git",mV=d({original:c(),modified:c()}),dk=d({diff:c()}),fV=d({files:k(d({path:c(),status:c(),previousPath:c().optional(),revision:c().optional()}))}),wV=d({error:c()}),bV=d({error:c(),code:g(Op)}),yV=d({files:k(d({path:c(),previousPath:c().optional(),changeType:c(),insertions:y(),deletions:y(),isBinary:v()}))}),ym=d({hash:c(),date:c(),message:c(),refs:c(),body:c(),author_name:c(),author_email:c(),filesChanged:y(),insertions:y(),deletions:y(),parents:k(c())}),vV=d({all:k(ym),latest:ym.nullable(),total:y()}),kV=d({diff:c(),submodule:Ep.nullable().default(null)}),SV=d({diffs:k(L([d({path:c(),diff:c(),submodule:Ep.nullable().default(null)}),d({path:c(),error:c(),code:T(["path_not_found","nested_repository","untracked_directory"]).nullable()})]))}),CV=d({original:c(),modified:c(),path:c(),isBinary:v().optional(),submodule:Ep.nullable().default(null)});async function Dp(e,t){const s=await e.json().catch(()=>null),n=d({code:g("not_repository"),error:c()}).safeParse(s);if(e.status===409&&n.success)return new Error(n.data.error);const o=gV.safeParse(s);return o.success&&(e.status===404||e.status===422)?new hV(o.data.error,o.data.code):new Error(`${t}: ${e.statusText}`)}async function wa(e,t){const s=wV.safeParse(await e.json().catch(()=>null));return new Error(s.success?s.data.error:`${t}: ${e.statusText}`)}const uk=1200,pk=5e3,na=new Map,ao=new Map,hk=new Map,zr=new Map,tr=new Map,TV=256,AV=900*1e3,PV=3600*1e3,ba=8192,RV=/^[A-Za-z0-9_-]{1,200}$/,eu=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i,IV=/^[A-Za-z0-9_-]{43}$/,xV=/^SHA256:[A-Za-z0-9+/]{43}=?$/,as=e=>c().trim().min(1).max(e),gk=c().regex(RV),fc=c().regex(IV),Hs=as(1024),Mp=as(4096),Ee=as(512),mk=c().min(1).max(4096).refine(e=>e.trim()===e&&!Array.from(e).some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)&&e!==".."&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")&&!/^[A-Za-z]:\//.test(e),"Checkout path must be repository-relative"),vm=c().max(4096).refine(e=>{if(!e)return true;try{const t=new URL(e);return!t.username&&!t.password&&!t.search&&!t.hash}catch{return e.includes("://")?false:!/[?#]/.test(e)}},"Git remote display URLs must not contain credentials, query parameters, or fragments"),EV=k(d({name:Ee,fetchUrl:vm,pushUrl:vm}).strict()).max(256),OV=d({selectionId:gk,provenanceRevision:y().int().safe().positive(),sourceSha:c().regex(eu),expiresInMs:y().int().safe().positive().max(900*1e3)}).strict(),DV=d({remote:d({name:Ee,endpoint:d({displayUrl:Mp,fingerprint:fc}).strict()}).strict(),transportMode:g("managed"),classification:T(["contributor-fork","own-fork","bound-repository","other"])}).strict(),MV=Z("kind",[d({kind:g("ordinary")}).strict(),d({kind:g("contributor"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,provenanceRevision:y().int().safe().positive(),candidates:k(DV).max(128)}).strict()]),FV=d({state:g("awaiting-trust"),digest:fc,actions:k(d({kind:T(["post-checkout-hook","project-start-command","setup-command"]),label:c().max(65536)}).strict()).max(3)}).strict(),Vt=new Map,_V=e=>{if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&t[1].split("/").every(s=>s&&s!=="."&&s!==".."))}try{const t=new URL(e),s=decodeURIComponent(t.pathname);return(t.protocol==="https:"||t.protocol==="ssh:")&&!t.username&&!t.password&&!t.search&&!t.hash&&!!(t.hostname&&t.pathname&&t.pathname!=="/")&&!/[\0-\x20\x7f\\]/.test(s)&&s.split("/").slice(1).every(n=>n&&n!=="."&&n!=="..")}catch{return false}},ro=d({displayUrl:Mp.refine(_V),fingerprint:fc}).strict(),NV=d({displayName:as(1024),fingerprint:fc}).strict(),LV=d({id:Ee,platform:T(["web","desktop","vscode"]),label:as(512).optional()}).strict(),UV=Z("kind",[d({kind:g("provider"),provider:Ee,instance:Mp,accountId:Ee,login:Ee.optional()}).strict(),d({kind:g("ssh-key"),fingerprint:c().regex(xV)}).strict()]),Pl=Z("mode",[d({mode:g("anonymous"),verification:d({status:g("anonymous")}).strict()}).strict(),d({mode:g("managed"),verification:d({status:g("verified"),method:T(["credential","git-identity"])}).strict(),actor:UV.optional()}).strict(),d({mode:g("system"),verification:d({status:g("unverified"),reason:g("system-credentials")}).strict()}).strict()]),jV=L([Pl,d({fetch:Pl,push:Pl}).strict()]),vr=d({name:Ee,endpoint:ro}).strict(),Rl={repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,sourceRef:Hs,destinationRef:Hs},BV=Z("operation",[d({operation:g("push"),...Rl,forceWithLease:d({expectedRemoteSha:c().regex(eu)}).strict().optional(),configureUpstream:v().optional()}).strict(),Z("fetchScope",[d({operation:g("fetch"),fetchScope:g("ref").optional(),...Rl}).strict(),d({operation:g("fetch"),fetchScope:g("remote"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,force:v()}).strict()]),d({operation:g("pull"),...Rl}).strict(),d({operation:g("delete-remote-branch"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,destinationRef:Hs}).strict(),d({operation:g("checkout-hydration"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,requirements:k(d({kind:T(["submodule","lfs"]),path:mk,endpoint:ro}).strict()).max(256)}).strict(),d({operation:g("sync"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,fetch:d({name:Ee,endpoint:ro,sourceRef:Hs,destinationRef:Hs}).strict(),pull:d({destinationRef:Hs}).strict(),push:d({name:Ee,endpoint:ro,sourceRef:Hs,destinationRef:Hs,forceWithLease:d({expectedRemoteSha:c().regex(eu)}).strict().optional()}).strict()}).strict(),d({operation:g("clone"),remote:ro,destination:NV}).strict()]),VV=T(["validated","authenticated","transferred","updated-local-repository","checked-out","cleaned-up"]),wc=T(["INVALID_REQUEST","NOT_FOUND","STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","REMOTE_URL_USERINFO","AUTHENTICATION_REQUIRED","DESTINATION_SELECTION_REQUIRED","CONTRIBUTOR_MANAGED_TRANSPORT_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","CONFLICT","CANCELLED","TIMEOUT","OUTCOME_UNKNOWN","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","PATH_LENGTH_LIMIT","BRANCH_NAME_CONFLICT","UNKNOWN"]),ai=e=>d({code:T(e),message:as(ba)}).strict(),HV=d({step:T(["fetch","pull","push"]),status:T(["succeeded","skipped","conflicted","failed","cancelled"]),error:d({code:wc,message:as(ba)}).strict().optional()}).strict(),fk=T(["succeeded","authorization-required","invalid","client-missing","failed","cancelled","not-needed"]),WV=["cancelled","invalid","client-missing","authorization-required","failed"],km=d({path:mk,status:fk,endpoint:ro.optional(),error:d({code:wc,message:as(ba)}).strict().optional()}).strict().superRefine((e,t)=>{(e.status!=="succeeded"&&e.status!=="not-needed")!==(e.error!==void 0)&&t.addIssue({code:"custom",message:"Git hydration status and error do not match"})}),wk=d({status:fk,submodules:k(km).max(256),lfs:k(km).max(256)}).strict().superRefine((e,t)=>{const s=[...e.submodules,...e.lfs].map(o=>o.status);let n="succeeded";!s.length||s.every(o=>o==="not-needed")?n="not-needed":n=WV.find(o=>s.includes(o))??"succeeded",e.status!==n&&t.addIssue({code:"custom",message:"Git hydration summary does not match its results"})}),qV=d({status:T(["pending","ready","failed"]),phase:T(["directory-created","git-ready","setup-ready"]).optional(),error:as(ba).nullable(),errorCode:wc.optional(),updatedAt:y().int().safe().nonnegative(),hydration:wk.optional()}).strict().superRefine((e,t)=>{e.status!=="failed"&&(e.errorCode||e.hydration)&&t.addIssue({code:"custom",message:"Only failed worktree bootstrap status may include failure details"})}),Fp=d({error:as(ba),code:wc}).strict(),Ls={operationId:gk,runtimeIdentity:LV,transport:jV,target:BV,completedSteps:k(VV),stepResults:k(HV).length(3).optional(),hydration:wk.optional()},GV=Z("state",[d({...Ls,state:g("planned")}).strict(),d({...Ls,state:g("running")}).strict(),d({...Ls,state:g("succeeded")}).strict(),d({...Ls,state:g("partial"),error:ai(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),d({...Ls,state:g("failed"),error:ai(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),d({...Ls,state:g("cancelled"),error:ai(["CANCELLED","TIMEOUT"])}).strict(),d({...Ls,state:g("outcome-unknown"),error:ai(["OUTCOME_UNKNOWN"])}).strict(),d({...Ls,state:g("conflicted"),error:ai(["STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","CONFLICT"])}).strict()]).superRefine((e,t)=>{e.target.operation==="clone"&&e.state==="partial"&&!e.completedSteps.includes("checked-out")&&t.addIssue({code:"custom",message:"Partial clone must retain a completed checkout"});const s=e.target.operation==="sync",n=e.state!=="planned"&&e.state!=="running";s&&n&&e.stepResults===void 0&&t.addIssue({code:"custom",message:"Sync operation result is missing step results"});for(const o of e.stepResults??[])(o.status!=="succeeded"&&o.status!=="skipped")!==(o.error!==void 0)&&t.addIssue({code:"custom",message:"Git sync step status and error do not match"});!s&&e.stepResults!==void 0&&t.addIssue({code:"custom",message:"Non-sync operation contains sync step results"}),e.state==="succeeded"&&e.hydration&&e.hydration.status!=="succeeded"&&e.hydration.status!=="not-needed"&&t.addIssue({code:"custom",message:"Successful Git operation contains incomplete hydration"}),s!=="fetch"in e.transport&&t.addIssue({code:"custom",message:"Git operation transport does not match its target"})}),bk=e=>e.trim(),ya=(e,t)=>JSON.stringify([e,bk(t)]),bc=(e,t,s)=>JSON.stringify([e,bk(t),s??"full"]),oa=(e,t)=>hk.get(ya(e,t))??0,_p=(e,t)=>{const s=ya(e,t);hk.set(s,oa(e,t)+1);for(const n of[void 0,"light"]){const o=bc(e,t,n);na.delete(o),ao.delete(o)}},zV=(e,t,s)=>JSON.stringify([e,t,s]),Np=(e=Date.now())=>{for(const[t,s]of Vt){const n=s.terminalState?PV:AV;s.observedAt<=e-n&&Vt.delete(t)}for(;Vt.size>TV;){let t=null;for(const[s,n]of Vt)n.terminalState&&(!t||n.observedAt<t.observedAt)&&(t={key:s,observedAt:n.observedAt});if(!t)for(const[s,n]of Vt)(!t||n.observedAt<t.observedAt)&&(t={key:s,observedAt:n.observedAt});if(!t)return;Vt.delete(t.key)}},tu=(e,t,s)=>{Np();for(const[n,o]of Vt)if(o.runtimeKey===e&&o.operationId===t&&(!s||o.runtimeIdentity.id===s))return{key:n,value:o};return null},$V=(e,t)=>{let s=null;for(const[n,o]of Vt)if(o.runtimeKey===e&&o.operationId===t){if(s)return;s=n}s&&Vt.delete(s)},KV=(e,t)=>{Np();const s=Date.now();for(const n of Vt.values())n.runtimeKey===e&&n.operationId===t&&!n.terminalState&&(n.observedAt=s)},es=(e,t)=>JSON.stringify(e)===JSON.stringify(t),JV=e=>JSON.stringify(e,(t,s)=>{if(t==="forceWithLease")return;if(t!=="displayUrl")return s;const n=c().safeParse(s);if(!n.success||n.data.includes("://"))return s;const o=n.data.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/);return o?`${o[1]}:${o[2]}`:n.data}),YV=e=>{const t=e.trim();try{const s=new URL(t);return s.username="",s.password="",s.hostname=s.hostname.toLowerCase(),s.search="",s.hash="",s.toString().replace(/\/$/,"")}catch{const s=t.match(/^([^@/:\s]+)@([^/:\s]+):(.+)$/);return s?`${s[1]}@${s[2].toLowerCase()}:${s[3].replace(/[?#].*$/,"")}`:t.replace(/[?#].*$/,"")}},XV=(e,t)=>{if(t.target.operation!==e.operation)throw new Error("Malformed Git network operation plan response");if(e.operation==="sync"){if(!("fetch"in t.transport)||t.transport.fetch.mode!==e.fetch.transportMode||t.transport.push.mode!==e.push.transportMode)throw new Error("Malformed Git network operation plan response");const o={...e.push.remote,sourceRef:e.push.sourceRef,destinationRef:e.push.destinationRef,forceWithLease:e.push.forceWithLease},i={operation:"sync",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,fetch:{...e.fetch.remote,sourceRef:e.fetch.sourceRef,destinationRef:e.fetch.destinationRef},pull:e.pull,push:o};if(!es(t.target,i))throw new Error("Malformed Git network operation plan response");return}if("fetch"in t.transport)throw new Error("Malformed Git network operation plan response");if(e.operation==="checkout-hydration"){const o=t.target;if(o.operation!=="checkout-hydration"||!es({repositoryId:o.repositoryId,bindingRevision:o.bindingRevision,configRevision:o.configRevision,remote:o.remote},{repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote}))throw new Error("Malformed Git network operation plan response");return}if(t.transport.mode!==e.transportMode)throw new Error("Malformed Git network operation plan response");if(e.operation==="clone"){const o=t.target;if(o.operation!=="clone")throw new Error("Malformed Git network operation plan response");const i=e.destinationPath.trim().split(/[\\/]/).filter(Boolean).at(-1);if(o.remote.displayUrl!==YV(e.remoteUrl)||o.destination.displayName!==i)throw new Error("Malformed Git network operation plan response");return}if(e.operation==="delete-remote-branch"){if(!es(t.target,{operation:"delete-remote-branch",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,destinationRef:e.destinationRef}))throw new Error("Malformed Git network operation plan response");return}if(e.operation==="fetch"&&e.fetchScope==="remote"){const o=t.target;if(o.operation!=="fetch"||o.fetchScope!=="remote"||!es(o,{operation:"fetch",fetchScope:"remote",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,force:o.force}))throw new Error("Malformed Git network operation plan response");return}const s={repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,sourceRef:e.sourceRef,destinationRef:e.destinationRef},n=e.operation==="fetch"?{operation:"fetch",fetchScope:e.fetchScope,...s}:{operation:e.operation,...s};if(e.operation==="push"&&e.forceWithLease&&Object.assign(n,{forceWithLease:e.forceWithLease}),e.operation==="push"&&e.configureUpstream&&Object.assign(n,{configureUpstream:true}),!es(t.target,n))throw new Error("Malformed Git network operation plan response")},QV=e=>e.target.operation==="clone"?false:e.state==="succeeded"?true:e.completedSteps.includes("transferred")||e.completedSteps.includes("updated-local-repository"),su=(e,t,s=false)=>"fetch"in e||"fetch"in t?"fetch"in e&&"fetch"in t&&su(e.fetch,t.fetch,s)&&su(e.push,t.push,s):e.mode===t.mode&&es(e.verification,t.verification)&&(e.mode!=="managed"||t.mode==="managed"&&(!e.actor||s&&!t.actor||es(e.actor,t.actor)));dV(e=>{_p(F(),e),zr.delete(ya(F(),e))});const Ho=e=>{ck(e)},De=async(e,t)=>{const s=await t.json();return Ho(e),s};function _(e,t,s){const n={...s};return t&&(n.directory=t),Ss().api(e,n)}const ZV=15,Sm=200,eH=e=>e==="worktrees"?`${M}/project-worktrees`:`${M}/projects`,tH=(e,t)=>JSON.stringify(e==="status"||e==="root"?{directories:t,fields:[e]}:{directories:t}),sH=(e,t)=>`${e}\0${It(t)??""}`,Fi=new Map,Cm=async e=>{const t=Fi.get(e);if(Fi.delete(e),!t)return;if(t.runtimeKey!==F()){const r=new Error("Runtime changed before project repository batch was sent");for(const l of t.waiters.values())for(const u of l)u.reject(r);return}const s=[...t.waiters.keys()],n=new Map;for(const r of s)n.set(r,oa(t.runtimeKey,r));const o=eH(t.field),i=new Map,a=[];for(let r=0;r<s.length;r+=Sm)a.push(s.slice(r,r+Sm));await Promise.all(a.map(async r=>{try{const l=await P(_(o,r[0]),{method:"POST",headers:{"Content-Type":"application/json"},body:tH(t.field,r)});if(!l.ok)throw new Error(`Failed to read project repositories: ${l.statusText}`);const u=await l.json();for(const p of u?.projects??[])i.set(p.directory,p)}catch(l){const u=l instanceof Error?l.message:"Failed to read project repositories";for(const p of r)i.set(p,{directory:p,error:u})}}));for(const[r,l]of i)typeof l.isGitRepository=="boolean"&&zr.set(ya(t.runtimeKey,r),{value:l.isGitRepository,expiresAt:Date.now()+pk}),l.status&&oa(t.runtimeKey,r)===n.get(r)&&na.set(bc(t.runtimeKey,r,void 0),{value:l.status,expiresAt:Date.now()+uk});for(const[r,l]of t.waiters){const u=i.get(r)??null;for(const p of l)u?u.error?p.reject(u.code===Op?new lk(u.error):new Error(u.error)):u.errors?.includes(t.field)?p.reject(new Error(`Failed to read project ${t.field}`)):p.resolve(u):p.reject(new Error("Project repository read missing from batch response"))}},yc=(e,t)=>{const s=F(),n=sH(t,e),o=Fi.get(n);o&&o.runtimeKey!==s&&Cm(n);let i=Fi.get(n);i||(i={runtimeKey:s,field:t,waiters:new Map,timer:null},Fi.set(n,i));const a=i;return new Promise((r,l)=>{const u=a.waiters.get(e)??[];u.push({resolve:r,reject:l}),a.waiters.set(e,u),a.timer===null&&(a.timer=setTimeout(()=>{Cm(n)},ZV))})};async function nH(e){const t=F(),s=Date.now(),n=e.filter(o=>{const i=bc(t,o,void 0),a=na.get(i);return!(a&&a.expiresAt>s)&&!ao.has(i)});await Promise.allSettled(n.map(o=>yc(o,"status")))}async function oH(e){const t=ya(F(),e),s=Date.now(),n=zr.get(t);if(n&&n.expiresAt>s)return n.value;const o=tr.get(t);if(o)return o;const i=(async()=>{const r=(await yc(e,"repo")).isGitRepository===true;return zr.set(t,{value:r,expiresAt:Date.now()+pk}),r})();tr.set(t,i);try{return await i}finally{tr.get(t)===i&&tr.delete(t)}}class iH extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function TJ(e){const t=await P("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new iH;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const s=await t.json();if(!Array.isArray(s?.repositories))throw new Error("Unexpected git directories response");return s.repositories.map(n=>Oe(n?.path??null)).filter(n=>n!==null)}async function aH(e,t){const s=t?.mode,n=F();t?.fresh&&_p(n,e);const o=bc(n,e,s),i=Date.now(),a=na.get(o);if(a&&a.expiresAt>i)return a.value;const r=ao.get(o);if(r)return r;const l=(async()=>{const u=oa(n,e),p=await P(_(`${M}/status`,e,s?{mode:s}:void 0));if(!p.ok){const m=bV.safeParse(await p.json().catch(()=>null));throw m.success?new lk(m.data.error):new Error(`Failed to get git status: ${p.statusText}`)}const h=await p.json();return oa(n,e)===u&&na.set(o,{value:h,expiresAt:Date.now()+uk}),h})();ao.set(o,l);try{return await l}finally{ao.get(o)===l&&ao.delete(o)}}async function AJ(e){const t=await yc(e,"root");return{root:t.root?t.root:e}}async function PJ(e){const t=await P(_(`${M}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve the repository folder: ${t.statusText}`);const s=await t.json().catch(()=>({}));if(s.prefix===void 0||s.prefix===null)throw new Error("The server did not report the repository folder");return s.prefix}async function RJ(e){const t=await P(_(`${M}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const s=await t.json().catch(()=>({}));return{root:typeof s.root=="string"&&s.root?s.root:e}}async function IJ(e,t){const s=await P(_(`${M}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!s.ok)throw new Error(`Failed to get git commit summaries: ${s.statusText}`);const n=await s.json().catch(()=>({}));return{commits:Array.isArray(n.commits)?n.commits.map(o=>({sha:typeof o.sha=="string"?o.sha:"",short:typeof o.short=="string"?o.short:"",subject:typeof o.subject=="string"?o.subject:""})).filter(o=>o.sha&&o.short):[]}}async function rH(e,t){const{path:s,staged:n,contextLines:o,previousPath:i}=t;if(!s)throw new Error("path is required to fetch git diff");const a=await P(_(`${M}/diff`,e,{path:s,staged:n?"true":void 0,context:o,previousPath:i||void 0}));if(!a.ok)throw await Dp(a,"Failed to get git diff");return kV.parse(await a.json())}const Tm=1e3;async function cH(e,t){const{paths:s,staged:n,contextLines:o}=t,i=[];for(let a=0;a<s.length;a+=Tm){const r=await P(_(`${M}/diffs`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s.slice(a,a+Tm),staged:n===true,context:o})});if(!r.ok)throw await Dp(r,"Failed to get git diffs");for(const l of SV.parse(await r.json()).diffs)i.push("diff"in l?{path:l.path,ok:true,diff:{diff:l.diff,submodule:l.submodule}}:{path:l.path,ok:false,error:l.error,reason:l.code})}return i}async function lH(e,t){const{base:s,head:n,path:o,contextLines:i,includeWorkingTree:a,previousPath:r}=t;if(!s||!n)throw new Error("base and head are required to fetch git range diff");const l=await P(_(`${M}/range-diff`,e,{base:s,head:n,path:o||void 0,context:i,includeWorkingTree:a,previousPath:r||void 0}));if(!l.ok)throw await wa(l,"Failed to get git range diff");return dk.parse(await l.json())}async function dH(e,t){const s=await P(_(`${M}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!s.ok)throw await wa(s,"Failed to get commit diff");return dk.parse(await s.json())}async function uH(e,t){const{base:s,head:n,includeWorkingTree:o}=t;if(!s||!n)throw new Error("base and head are required to fetch git range files");const i=await P(_(`${M}/range-files`,e,{base:s,head:n,includeWorkingTree:o}));if(!i.ok)throw await wa(i,"Failed to get git range files");return fV.parse(await i.json()).files}async function pH(e,t){if(!t)throw new Error("branch is required to get branch base");const s=await P(_(`${M}/branch-base`,e,{branch:t}));if(!s.ok)throw new Error(`Failed to get branch base: ${s.statusText}`);return s.json()}async function hH(e,t){const{path:s,staged:n,previousPath:o}=t;if(!s)throw new Error("path is required to fetch git file diff");const i=await P(_(`${M}/file-diff`,e,{path:s,staged:n?"true":void 0,previousPath:o||void 0}));if(!i.ok)throw await Dp(i,"Failed to get git file diff");return CV.parse(await i.json())}async function gH(e,t,s){if(!t)throw new Error("path is required to revert git changes");const n=await P(_(`${M}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:s?.scope})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to revert git changes")}Ho(e)}async function mH(e,t){await yk(e,[t])}async function yk(e,t){const s=t.map(o=>o.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to stage git changes");const n=await P(_(`${M}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to stage git changes")}Ho(e)}async function fH(e,t){await vk(e,[t])}async function vk(e,t){const s=t.map(o=>o.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to unstage git changes");const n=await P(_(`${M}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to unstage git changes")}Ho(e)}async function wH(e,t,s){await Lp(e,t,s,"stage")}async function bH(e,t,s){await Lp(e,t,s,"unstage")}async function yH(e,t,s){await Lp(e,t,s,"discard")}async function Lp(e,t,s,n){if(!t)throw new Error("path is required to apply a git hunk");if(typeof s!="string"||!s.trim())throw new Error("patch is required to apply a git hunk");const o=await P(_(`${M}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:s,action:n})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to apply git hunk")}Ho(e)}async function vH(e){if(!e)return false;const t=await P(_(`${M}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function kH(e,t){const s=await P(_(`${M}/branches`,e,t?.remote?{remote:t.remote}:void 0));if(!s.ok)throw new Error(`Failed to get branches: ${s.statusText}`);return s.json()}async function SH(e,t){const s=await P(_(`${M}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!s.ok)throw new Error(`Failed to get branch push status: ${s.statusText}`);return s.json()}async function CH(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const s=await P(_(`${M}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to delete branch")}return De(e,s)}async function TH(e,t){const s=t?.remote?.trim();if(!s)throw new Error("remote is required to remove a remote");const n=await P(_(`${M}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to remove remote")}return De(e,n)}async function AH(e,t,s){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const n={files:t};s?.zenModel&&(n.zenModel=s.zenModel),s?.providerId&&(n.providerId=s.providerId),s?.modelId&&(n.modelId=s.modelId);const o=await P(_(`${M}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){const l=await o.json().catch(()=>({error:o.statusText}));console.error("[git-generation][browser] http error",{status:o.status,statusText:o.statusText,error:l});const u=typeof l?.traceId=="string"&&l.traceId?` (traceId: ${l.traceId})`:"";throw new Error(`${l.error||"Failed to generate commit message"}${u}`)}const i=await o.json();if(!i?.message||typeof i.message!="object")throw new Error("Malformed commit generation response");const a=typeof i.message.subject=="string"&&i.message.subject.trim().length>0?i.message.subject.trim():"",r=Array.isArray(i.message.highlights)?i.message.highlights.filter(l=>typeof l=="string"&&l.trim().length>0).map(l=>l.trim()):[];return{message:{subject:a,highlights:r}}}async function PH(e,t){const{base:s,head:n,context:o,zenModel:i,providerId:a,modelId:r}=t;if(!s||!n)throw new Error("base and head are required");const l={base:s,head:n};o?.trim()&&(l.context=o.trim()),i&&(l.zenModel=i),a&&(l.providerId=a),r&&(l.modelId=r);const u=await P(_(`${M}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok){const w=await u.json().catch(()=>({error:u.statusText}));throw new Error(w.error||"Failed to generate PR description")}const p=await u.json().catch(()=>null),h=typeof p?.title=="string"?p.title:"",m=typeof p?.body=="string"?p.body:"";if(!h&&!m)throw new Error("Malformed PR description response");return{title:h,body:m}}async function Am(e){return(await yc(e,"worktrees")).worktrees??[]}async function Pm(e,t){const s=await P(_(`${M}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to validate worktree")}return s.json()}async function RH(e){const t=await P(_(`${M}/worktrees/bootstrap-status`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to get worktree bootstrap status")}return qV.parse(await t.json())}async function IH(e,t){const s=await P(_(`${M}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to preview worktree")}return s.json()}async function Rm(e,t){const s=await P(_(`${M}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=d({error:c().optional(),code:c().optional(),remoteName:c().optional()}).strict().parse(await s.json().catch(()=>({error:s.statusText})));throw new xp(n.code||"UNKNOWN",n.error||"Failed to create worktree",s.status,n.remoteName)}return s.json()}async function Im(e,t){const s=await P(_(`${M}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});return s.ok||await kk(s,"Failed to delete worktree"),s.json()}async function xH(e,t){const s=await P(_(`${M}/worktrees/teardown`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return s.ok||await kk(s,"Failed to tear down worktree"),s.json()}const kk=async(e,t)=>{const s=d({error:c().optional(),code:c().optional()}).catch({}).parse(await e.json().catch(()=>null)),n=s.error||e.statusText||t;throw s.code?new xp(s.code,n,e.status):new Error(n)},EH=d({title:c(),branch:c()});async function OH(e,t,s="user"){const n=await P(_(`${M}/worktrees/title`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t,by:s})}),o=await n.json().catch(()=>null);if(!n.ok){const a=d({error:c()}).safeParse(o).data?.error;throw new Error(a||"Failed to rename the task")}const i=EH.safeParse(o);if(!i.success)throw new Error("Malformed task title response");return i.data}const DH=d({pinned:v(),branch:c()});async function MH(e,t,s=null){const n=await P(_(`${M}/worktrees/pin`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s?{pinned:t,list:s}:{pinned:t})}),o=await n.json().catch(()=>null);if(!n.ok){const a=d({error:c()}).safeParse(o).data?.error;throw new Error(a||"Failed to pin the task")}const i=DH.safeParse(o);if(!i.success)throw new Error("Malformed pin response");return i.data}const Sk=d({id:c().min(1),ref:c().min(1),commit:c().min(1),head:c(),path:c().min(1),branch:c(),branchExists:v(),title:c(),archivedAt:y(),sessionIds:k(c())}),vc=async(e,t,s,n,o)=>{const i=await P(_(`${M}/worktrees/archives${e}`,t),{...s,headers:s.body?{"Content-Type":"application/json"}:void 0});if(!i.ok){const a=d({error:c().optional(),code:c().optional()}).catch({}).parse(await i.json().catch(()=>null)),r=a.error||i.statusText||o;throw a.code?new xp(a.code,r,i.status):new Error(r)}return n.parse(await i.json())},FH=(e,t)=>vc("",e,{method:"POST",body:JSON.stringify(t)},Sk,"Failed to archive worktree"),_H=async e=>(await vc("",e,{method:"GET"},d({archives:k(Sk)}),"Failed to list worktree archives")).archives,NH=(e,t)=>vc("/restore",e,{method:"POST",body:JSON.stringify({id:t})},d({id:c(),conflicts:v()}),"Failed to restore worktree archive"),LH=(e,t)=>vc("",e,{method:"DELETE",body:JSON.stringify(t)},d({id:c(),branchDeleted:v()}),"Failed to delete worktree archive"),UH=d({ref:c(),commit:c().min(1),head:c().min(1)});async function jH(e,t){const s=await P(_(`${M}/worktrees/snapshot`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to snapshot worktree")}return UH.parse(await s.json())}async function BH(e,t,s={}){const n=await P(_(`${M}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:s.addAll??false,files:s.files,stageFiles:s.stageFiles})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create commit")}return De(e,n)}async function VH(e,t={}){const s=F(),n=await P(_(`${M}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to push")}const o=await De(e,n);return o.success&&pV(e,s),o}async function HH(e,t={}){const s=await P(_(`${M}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to pull")}return De(e,s)}async function WH(e,t={}){const s=await P(_(`${M}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to fetch")}return De(e,s)}const Ck=async(e,t,s)=>{const n=await P(e,t);if(!n.ok){const o=Fp.parse(await n.json());throw o.code==="NOT_FOUND"&&s&&$V(s.runtimeKey,s.operationId),new Ip(o.code,o.error,n.status)}return GV.parse(await n.json())},qH=(e,t,s)=>{if(s.operationId!==e)throw new Error("Malformed Git network operation response");const n=tu(t,e,s.runtimeIdentity.id);if(!n&&tu(t,e))throw new Error("Malformed Git network operation response");if(n){const o=n.value.transport,i=s.state!=="planned"&&s.state!=="running",a=es(n.value.target,s.target)||i&&JV(n.value.target)===JSON.stringify(s.target);if(!es(n.value.runtimeIdentity,s.runtimeIdentity)||!a||!su(o,s.transport,i))throw new Error("Malformed Git network operation response");if(n.value.terminalState&&(s.state==="planned"||s.state==="running"||s.state!==n.value.terminalState))throw new Error("Malformed Git network operation response");es(o,s.transport)===false&&(n.value.transport=s.transport),s.state!=="planned"&&s.state!=="running"?n.value.terminalState||(QV(s)&&(_p(n.value.runtimeKey,n.value.directory),n.value.runtimeKey===F()&&ck(n.value.directory)),n.value.terminalState=s.state,n.value.observedAt=Date.now()):n.value.observedAt=Date.now()}if(F()!==t)throw new Error("Git network operation response belongs to a stale runtime");return s};async function GH(e){const t=F(),s=await Ck(`${M}/network-operations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(s.state!=="planned")throw new Error("Malformed Git network operation plan response");if(F()!==t)throw new Error("Git network operation response belongs to a stale runtime");XV(e,s);const n=zV(t,s.runtimeIdentity.id,s.operationId);if(tu(t,s.operationId,s.runtimeIdentity.id)?.value.terminalState)throw new Error("Malformed Git network operation plan response");return Vt.set(n,{operationId:s.operationId,runtimeKey:t,directory:e.operation==="clone"?e.destinationPath:e.directory,runtimeIdentity:s.runtimeIdentity,transport:s.transport,target:s.target,observedAt:Date.now()}),Np(),s}async function zH(e){const t=await P(`${M}/contributor-destinations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const s=Fp.parse(await t.json());throw new Ip(s.code,s.error,t.status)}return OV.parse(await t.json())}async function $H(e){const t=F(),s=await P(_(`${M}/contributor-destinations`,e));if(!s.ok){const o=Fp.parse(await s.json());throw new Ip(o.code,o.error,s.status)}const n=MV.parse(await s.json());if(F()!==t)throw new Error("Contributor destinations belong to a stale runtime");return n}async function KH(e){const t=await P(_(`${M}/worktrees/checkout-trust`,e));if(!t.ok)throw new Error((await t.json()).error||"Failed to inspect checkout actions");return FV.parse(await t.json())}async function JH(e,t,s){const n=await P(_(`${M}/worktrees/checkout-trust`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({digest:t,decision:s})});if(!n.ok)throw new Error((await n.json()).error||"Failed to apply checkout trust decision");return d({state:c().min(1)}).passthrough().parse(await n.json())}const Up=async(e,t)=>{const s=F();KV(s,e);const n=t?`/${t}`:"",o=t?{method:"POST"}:void 0,i=await Ck(`${M}/network-operations/${encodeURIComponent(e)}${n}`,o,{runtimeKey:s,operationId:e});return qH(e,s,i)};async function YH(e){return Up(e,"execute")}async function XH(e){return Up(e)}async function QH(e){return Up(e,"cancel")}async function ZH(e){const t=await P(_(`${M}/stashes`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to list stashes")}return t.json()}async function e1(e,t){const s=await P(_(`${M}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to count stash files")}return s.json()}async function Tk(e,t={}){const s=await P(_(`${M}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to stash changes")}return De(e,s)}const jp=async(e,t,s)=>{const n=await P(_(`${M}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||`Failed to ${t}`)}return De(e,n)},t1=(e,t)=>jp(e,"stash/apply",t),Ak=(e,t)=>jp(e,"stash/pop",t),s1=(e,t)=>jp(e,"stash/drop",t);async function n1(e,t){const s=await P(_(`${M}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to checkout branch")}return De(e,s)}async function o1(e,t,s){const n=await P(_(`${M}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create branch")}return De(e,n)}async function i1(e,t,s){const n=await P(_(`${M}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to rename branch")}return De(e,n)}async function a1(e,t={}){const s=await P(_(`${M}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(`Failed to get git log: ${n.error||s.statusText}`)}return vV.parse(await s.json())}const r1=d({sha:c().regex(/^[0-9a-f]{40}$/),changeId:c().regex(/^I[0-9a-f]{40}$/)});async function c1(e,t){const s=await P(_(`${M}/change-id`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedHead:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to add a Change-Id")}return Ho(e),r1.parse(await s.json())}async function l1(e,t){const s=await P(_(`${M}/commit-files`,e,{hash:t}));if(!s.ok)throw await wa(s,"Failed to get commit files");return yV.parse(await s.json())}async function xJ(e,t){const{base:s,head:n,path:o,previousPath:i,includeWorkingTree:a}=t,r=await P(_(`${M}/range-file-versions`,e,{base:s,head:n,path:o,previousPath:i,includeWorkingTree:a?"true":void 0}));if(!r.ok)throw await wa(r,"Failed to read file versions");return mV.parse(await r.json())}async function d1(e,t,s,n,o){const i=await P(_(`${M}/commit-file-diff`,e,{hash:t,path:s,binary:n?"true":void 0,previousPath:o}));if(!i.ok)throw new Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function u1(){const e=await P(_(`${M}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return cV.parse(await e.json())}async function p1(e){const t=Eo.parse(e),s=await P(_(`${M}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to create git identity")}return Eo.parse(await s.json())}async function h1(e,t){const s=Eo.parse(t);if(s.id!==e)throw new Error("Git identity profile ID does not match the update target");const n=await P(_(`${M}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to update git identity")}return Eo.parse(await n.json())}async function g1(e){const t=await P(_(`${M}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to delete git identity")}}async function m1(e){if(!e)return null;const t=await P(_(`${M}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const s=await t.json();return s?rk.parse(s):null}async function f1(e){if(!e)return false;const t=await P(_(`${M}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===true}async function w1(){const e=await P(_(`${M}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();if(!t)return null;const s=rk.parse(t);return s.userName||s.userEmail?s:null}async function b1(e,t){const s=await P(_(`${M}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to set git identity")}return lV.parse(await s.json())}async function y1(e){const t=await P(_(`${M}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return EV.parse(await t.json())}async function v1(e,t){const s=await P(_(`${M}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to rebase")}return De(e,s)}async function k1(e){const t=await P(_(`${M}/rebase/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort rebase")}return De(e,t)}async function S1(e,t){const s=await P(_(`${M}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to merge")}return De(e,s)}async function C1(e,t){const s=await P(_(`${M}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to checkout commit")}return De(e,s)}async function T1(e,t){const s=await P(_(`${M}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to cherry-pick")}return De(e,s)}async function A1(e,t){const s=await P(_(`${M}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to revert commit")}return De(e,s)}async function P1(e,t,s,n){const o=await P(_(`${M}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:s,force:n})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to reset")}return De(e,o)}async function R1(e){const t=await P(_(`${M}/merge/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort merge")}return De(e,t)}async function I1(e){const t=await P(_(`${M}/rebase/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue rebase")}return De(e,t)}async function x1(e){const t=await P(_(`${M}/merge/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue merge")}return De(e,t)}async function E1(e,t){return await Tk(e,{message:t?.message}),{success:true}}async function O1(e){return await Ak(e,{ref:"stash@{0}"}),{success:true}}async function D1(e){const t=await P(_(`${M}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function M1(e,t){const s=await P(`${M}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!s.ok)throw new Error(`Failed to validate worktree directory: ${s.statusText}`);return s.json()}async function F1(e){const t=await P(`${M}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const _1=/^[a-z][a-z0-9-]{0,31}$/,$r=e=>Object.prototype.toString.call(e)==="[object String]"&&_1.test(e),xm="ext-",Pk=e=>$r(e)&&e.startsWith(xm)&&$r(e.slice(xm.length)),Rk=(e,t,s)=>{if(typeof s!="string"||!s.startsWith(`${t}#`))return false;const n=s.slice(t.length+1);return Pk(e)?n.length>0&&n.length<=256:/^\d+$/.test(n)},N1=e=>Object.prototype.toString.call(e)==="[object String]"&&/^[\x20-\x39\x3b-\x7e]{1,256}$/.test(e)&&e.trim()===e,Ik=e=>e!==null&&Object.prototype.toString.call(e)==="[object Object]"&&Object.getPrototypeOf(e)===Object.prototype,L1=e=>Object.prototype.toString.call(e)==="[object String]",Ct=e=>L1(e)&&e.length>0,Em=(e,t=512)=>Ct(e)&&e.length<=t&&e.trim()===e&&!/[\0\r\n]/.test(e),U1=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/,j1=e=>{const t=e.toLowerCase();return t==="localhost"||t==="::1"||t==="[::1]"||U1.test(t)},B1=e=>{if(!e.instance.includes("://"))return/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(e.instance);try{const t=new URL(e.instance),s=j1(t.hostname);return t.origin===e.instance&&!t.username&&!t.password&&["","/"].includes(t.pathname)&&!t.search&&!t.hash&&(t.protocol==="https:"||t.protocol==="http:"&&s)}catch{return false}},bs=(e,t,s=[])=>Ik(e)&&t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>t.includes(n)||s.includes(n)),Om=e=>{let t;try{t=decodeURIComponent(e)}catch{return false}const s=t.replace(/^\/+|\/+$/g,"");return!!(s&&!/[\0\r\n]/.test(s)&&!s.split("/").some(n=>!n||n==="."||n===".."))},V1=e=>{if(!Ct(e)||e.trim()!==e||e.length>4096||/[\0\r\n]/.test(e))return false;if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&Om(`/${t[1]}`))}try{const t=new URL(e);return["http:","https:","ssh:"].includes(t.protocol)&&!!t.hostname&&(!t.username||t.protocol==="ssh:")&&!t.password&&!t.search&&!t.hash&&Om(t.pathname)}catch{return false}},nu=e=>bs(e,["displayUrl","fingerprint"])&&V1(e.displayUrl)&&Ct(e.fingerprint)&&e.fingerprint.length<=128&&/^[A-Za-z0-9_-]+$/.test(e.fingerprint),sr=nu,Dm=e=>["managed","system","anonymous"].includes(e.mode)&&(e.mode==="managed"?Ct(e.credentialId):!Object.hasOwn(e,"credentialId")),H1=e=>Ik(e)&&Object.hasOwn(e,"status")&&(e.status==="unavailable"&&bs(e,["status"])||e.status==="available"&&(bs(e,["status","transport","fingerprint"])&&e.transport==="ssh"&&/^SHA256:[A-Za-z0-9+/]{43}=?$/.test(e.fingerprint)||bs(e,["status","transport","provider","instance","source","username","providerUserId"])&&e.transport==="https"&&$r(e.provider)&&["oauth","pat","cli"].includes(e.source)&&Em(e.instance,2048)&&N1(e.username)&&Em(e.providerUserId)&&B1(e)&&Rk(e.provider,e.instance,e.providerUserId))),Il=(e,t)=>new Set(e.map(t)).size===e.length,ri=()=>Object.assign(new Error("Source control binding storage is invalid"),{code:"INVALID_SOURCE_CONTROL_BINDINGS"}),W1=(e,t=false)=>{if(!bs(e,["repositoryId","revision","state","configRevision","providers","remotes"],["auxiliary"])||!Ct(e.repositoryId)||!Number.isSafeInteger(e.revision)||e.revision<1||!Ct(e.configRevision)||!["bound","needs-attention"].includes(e.state)||!Array.isArray(e.providers)||!Array.isArray(e.remotes)||!Array.isArray(e.auxiliary))throw ri();for(const s of e.providers)if(!bs(s,["provider","instance","accountId","primaryRemote","readiness","endpoint"],["repository"])||!$r(s.provider)||!Ct(s.instance)||!Ct(s.accountId)||!Ct(s.primaryRemote)||s.repository!==void 0&&(!bs(s.repository,["owner","name"])||!Ct(s.repository.owner)||!Ct(s.repository.name))||!["ready","confirmation-required","account-unavailable","config-changed"].includes(s.readiness)||!(s.endpoint===null&&s.readiness!=="ready"||sr(s.endpoint)))throw ri();for(const s of e.remotes)if(!bs(s,["name","fetch","push","mode","readiness"],["credentialId",...t&&s.mode==="managed"?["presentation"]:[],...t?["inherited"]:[]])||!Ct(s.name)||!sr(s.fetch)||!sr(s.push)||!Dm(s)||s.presentation!==void 0&&!H1(s.presentation)||s.inherited!==void 0&&(s.inherited!==true||s.readiness!=="ready")||s.mode==="anonymous"&&!s.fetch.displayUrl.startsWith("https://")||!["ready","confirmation-required","config-changed"].includes(s.readiness))throw ri();for(const s of e.auxiliary??[])if(!bs(s,["kind","endpoint","mode","readiness"],["credentialId"])||!["submodule","lfs"].includes(s.kind)||!sr(s.endpoint)||!Dm(s)||s.mode==="anonymous"&&!s.endpoint.displayUrl.startsWith("https://")||!["ready","confirmation-required"].includes(s.readiness))throw ri();if((e.auxiliary?.length??0)>256||!Il(e.remotes,s=>s.name)||!Il(e.providers,s=>`${s.provider}\0${s.instance}\0${s.primaryRemote}`)||!Il(e.auxiliary??[],s=>`${s.kind}\0${s.endpoint.fingerprint}`))throw ri()},q1=e=>[...e.providers,...e.remotes,...e.auxiliary].some(t=>t.readiness!=="ready")?"needs-attention":"bound",G1=e=>(W1(e,true),structuredClone(e)),z1=(e,t)=>{const s=new Map(t.remotes.map(a=>[a.name,a])),n=e.providers.map(a=>a.readiness==="ready"&&a.endpoint?.fingerprint!==s.get(a.primaryRemote)?.fetch.fingerprint?{...a,readiness:"config-changed"}:a),o=e.remotes.map(a=>{const r=s.get(a.name);return a.readiness==="ready"&&(!r||a.fetch.fingerprint!==r.fetch.fingerprint||a.push.fingerprint!==r.push.fingerprint)?{...a,readiness:"config-changed"}:a}),i={...e,providers:n,remotes:o};return i.state=q1(i),i},Mm={referenceSearch:false,referenceDetail:false,listStatuses:false,referencesAcross:false,startThread:false,authorCanReview:false,projectUploads:false,issueCloseReason:false,changeRequestTemplates:[],changeRequestPatch:false},xk=[{id:"github",label:"GitHub",order:0,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:true,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"github",filledSprite:"github-fill"},repository:{nestedNamespaces:false},instances:{format:"host",defaultInstance:"github.com",defaultInstances:["github.com"],multiple:true,allowLoopbackHttp:false,allowPort:false,reserved:["github.com"],placeholder:"https://github.example.com",legacyFlow:{instance:"github.com",kind:"github-com-device"}},auth:{methods:["device","pat","cli"],cliName:"gh",cliTransport:true,token:{scopes:["repo","read:org","workflow","read:user","user:email"],createPath:"/settings/tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:false},{id:"token",kind:"personal-access-token",secret:true}]},urls:{changeRequest:["/{owner}/{repo}/pull/{number}"],issue:["/{owner}/{repo}/issues/{number}"],commit:["/{owner}/{repo}/commit/{sha}"],user:["/{user}"]},features:{...Mm,referenceSearch:true,referenceDetail:true,listStatuses:true,referencesAcross:true,issueCloseReason:true,changeRequestPatch:true}},{id:"gitlab",label:"GitLab",order:1,terminology:{changeRequest:"mergeRequest",changeRequestPrefix:"!",issuePrefix:"#",sharedNumberSpace:false,abbreviation:"MR",promptNoun:"merge request",ci:"pipeline"},icon:{sprite:"gitlab"},repository:{nestedNamespaces:true},instances:{format:"origin",defaultInstance:"https://gitlab.com",defaultInstances:["https://gitlab.com"],multiple:true,allowLoopbackHttp:true,allowPort:true,reserved:[],placeholder:"https://gitlab.example.com"},auth:{methods:["device","pat","cli"],cliName:"glab",cliTransport:false,token:{scopes:["api"],createPath:"/-/user_settings/personal_access_tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:false},{id:"token",kind:"personal-access-token",secret:true}]},urls:{changeRequest:["/{namespace+}/{repo}/-/merge_requests/{number}"],issue:["/{namespace+}/{repo}/-/issues/{number}","/{namespace+}/{repo}/-/work_items/{number}"],commit:["/{namespace+}/{repo}/-/commit/{sha}"],user:["/{user}"]},features:{...Mm,startThread:true,authorCanReview:true,projectUploads:true,changeRequestPatch:true,changeRequestTemplates:[".gitlab/merge_request_templates/Default.md"]}}],Wo=(e,t)=>`/api/source-control/${e.provider}${t}`,$1=d({providers:k(oe())}),K1=d({error:c()}),J1=async e=>{const t=await e("/api/source-control/providers",{headers:{Accept:"application/json"}});if(t.status===404)return _d.parse(xk);const s=await t.json().catch(()=>null);if(!t.ok){const i=K1.safeParse(s);throw new Error(i.success&&i.data.error||t.statusText||"Failed to load source control providers")}const n=$1.parse(s).providers,o=_d.parse(n);if(n.length>0&&o.length===0)throw new Error("Source control providers response contained no readable provider");return o},Ek=d({state:T(["success","failure","pending","unknown"]),total:y(),success:y(),failure:y(),pending:y(),inProgress:y().optional(),queued:y().optional(),startedAt:c().optional()}),xl={number:y(),title:c(),url:c(),body:c(),bodyTruncated:v(),createdAt:c().nullable(),updatedAt:c().nullable(),author:d({login:c(),avatarUrl:c().optional()}).nullable(),labels:k(d({name:c(),color:c().optional()})),commentCount:y(),sourceRepo:d({owner:c(),repo:c(),source:c()})},Ok=Z("kind",[d({kind:g("issue"),...xl,state:T(["open","completed","not_planned"])}),d({kind:g("pull"),...xl,state:T(["open","closed","merged"]),draft:v(),head:c(),base:c(),headSha:c(),headRepo:d({owner:c(),repo:c(),url:c(),cloneUrl:c().optional(),sshUrl:c().optional()}).nullable()}),d({kind:g("discussion"),...xl,state:T(["open","resolved","outdated","duplicate"]),answered:v().nullable(),upvotes:y(),locked:v(),category:d({name:c(),emoji:c().nullable(),answerable:v()})})]),Y1=Z("connected",[d({connected:g(false)}),d({connected:g(true),repo:d({owner:c(),repo:c(),url:c()}).nullable(),items:k(Ok),cursor:c().nullable(),hasMore:v(),total:y()})]),Fm={author:d({login:c(),avatarUrl:c().optional()}).nullable(),body:c(),createdAt:c().nullable(),url:c(),path:c().nullable(),line:y().nullable(),review:T(["approved","changes_requested","commented","dismissed"]).nullable(),excerpt:d({startLine:y().int().positive(),lines:k(c()).max(200)}).optional().catch(void 0)},X1=Z("connected",[d({connected:g(false)}),d({connected:g(true),detail:d({number:y(),comments:k(d({...Fm,thread:d({id:c().min(1),resolved:v(),canResolve:v(),canReply:v(),replies:k(d(Fm))}).optional(),answer:d({chosen:v(),canChange:v()}).optional()})),commentTotal:y(),pull:d({reviewDecision:T(["approved","changes_requested","review_required"]).nullable(),reviewers:k(d({id:c(),login:c(),avatarUrl:c().optional()})).default([]),checks:Ek.nullable().optional(),additions:y(),deletions:y(),changedFiles:y(),commits:k(d({sha:c(),headline:c(),author:d({login:c(),avatarUrl:c().optional()}).nullable(),authorName:c().nullable(),committedAt:c().nullable(),url:c().nullable()})).default([]),commitTotal:y().nullable().default(null),stack:d({number:y().nullable(),base:c(),layers:k(d({number:y(),title:c(),url:c(),state:T(["open","closed","merged"]),draft:v(),head:c()}))}).nullable().optional().catch(void 0)}).nullable(),discussion:d({canComment:v(),canClose:v(),canReopen:v()}).optional()}).nullable()})]),Q1=Sa({items:k(Ok.and(d({directory:c().min(1)}))),cursor:c().nullable(),hasMore:v(),total:y().int().nonnegative(),repositories:k(L([Sa({directory:c().min(1),status:g("included"),repo:Sa({owner:c(),repo:c(),url:c(),host:c().optional()})}),Sa({directory:c().min(1),status:T(["no-repo","disconnected","invalid-context","error"])})]))}),Z1=Z("connected",[d({connected:g(false)}),d({connected:g(true),statuses:k(d({owner:c(),repo:c(),number:y(),checks:Ek.nullable(),mergeable:v().nullable(),mergeableState:c().nullable()}))})]),eW=d({error:c()}),kc=e=>{const t=new URLSearchParams({directory:e.directory,instance:e.instance,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},va=async(e,t,s)=>{const n=await e.json().catch(()=>null);if(!e.ok){const o=eW.safeParse(n);throw new Error(o.success&&o.data.error||e.statusText||s)}return t.parse(n)},tW=async(e,t,s)=>{const n=kc(t);n.set("kind",s.kind),s.state&&n.set("state",s.state),s.people&&n.set("people",s.people),s.query?.trim()&&n.set("query",s.query.trim()),s.cursor&&n.set("cursor",s.cursor);const o=await e(Wo(t,"/references"),{query:n,headers:{Accept:"application/json"}}),i=await va(o,Y1,"Failed to load issues and pull requests");return i.connected?{...i,items:i.items.map(a=>({...a,provider:t.provider}))}:i},sW=async(e,t,s)=>{const n=kc(t);n.set("owner",s.owner),n.set("repo",s.repo),n.set("number",String(s.number)),s.kind==="discussion"&&n.set("kind","discussion");const o=s.host?.trim();o&&o!=="github.com"&&n.set("host",o);const i=await e(Wo(t,"/references/detail"),{query:n,headers:{Accept:"application/json"}});return va(i,X1,"Failed to load issue or pull request detail")},_m=d({login:c(),avatarUrl:c().optional()}).nullable(),Nm=T(["old","new"]),nW=Z("connected",[d({connected:g(false)}),d({connected:g(true),viewerIsAuthor:v(),headSha:c(),draft:d({id:c(),body:c(),comments:k(d({id:c(),path:c(),side:Nm,line:y().int().nullable(),startLine:y().int().nullable(),body:c(),author:_m}))}).nullable(),threads:k(d({id:c(),path:c(),side:Nm,line:y().int().nullable(),startLine:y().int().nullable(),resolved:v(),canReply:v(),canResolve:v(),comments:k(d({id:c(),body:c(),createdAt:c(),url:c(),author:_m}))})),truncated:v()})]),oW=async(e,t,s)=>{const n=kc(t);n.set("owner",s.owner),n.set("repo",s.repo),n.set("number",String(s.number));const o=await e(Wo(t,"/pr/review/state"),{query:n,headers:{Accept:"application/json"}});return va(o,nW,"Failed to load the review")},iW=async(e,t,s)=>{const[n]=t;if(!n||t.some(a=>a.provider!==n.provider))throw new Error("A search across repositories needs contexts of one provider");const o=await e(Wo(n,"/references/across"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({contexts:t,...s,query:s.query?.trim()})}),i=await va(o,Q1,"Failed to load issues and pull requests");return{...i,items:i.items.map(a=>({...a,provider:n.provider}))}},aW=async(e,t,s)=>{const n=kc(t);n.set("pulls",s.map(i=>{const a=i.host?.trim().toLowerCase();return`${i.owner}/${i.repo}#${i.number}${a&&a!=="github.com"?`@${a}`:""}`}).join(","));const o=await e(Wo(t,"/references/status"),{query:n,headers:{Accept:"application/json"}});return va(o,Z1,"Failed to load pull request statuses")};class ks extends Error{constructor(t,s){super(t),this.code=s}code}const Sc=new Map,Dk=e=>{for(const t of e)Sc.set(t.id,{format:t.instances.format,label:t.label,pathStyle:t.repository.pathStyle==="path"})},Bp=(e,t)=>Q(t)&&(t.trim().length>0||t===""&&Sc.get(e.provider)?.pathStyle!==false);Dk(xk);const ia=e=>Sc.get(e.provider)?.label??e.provider,rW=e=>{const t=e.instance.trim();let s;try{s=new URL(t.includes("://")?t:`https://${t}`)}catch{throw new Error(`Invalid source control instance: ${e.instance}`)}const n=["localhost","127.0.0.1","::1","[::1]"].includes(s.hostname.toLowerCase());if(s.username||s.password||s.search||s.hash||s.pathname&&s.pathname!=="/"||s.protocol!=="https:"&&!(s.protocol==="http:"&&n))throw new Error(`Invalid ${ia(e)} instance: ${e.instance}`);return{provider:e.provider,instance:s.origin}},cW=e=>{const t=e.instance.trim().toLowerCase().replace(/\.$/,"");let s=t;if(t.includes("://"))try{const n=new URL(t);if(n.protocol!=="https:"||n.username||n.password||n.port||n.search||n.hash||n.pathname&&n.pathname!=="/")throw new Error(`Invalid ${ia(e)} instance: ${e.instance}`);s=n.hostname.toLowerCase().replace(/\.$/,"")}catch{throw new Error(`Invalid ${ia(e)} instance: ${e.instance}`)}return{provider:e.provider,instance:s}},$=e=>{const t=(Sc.get(e.provider)?.format??"origin")==="host"?cW(e):rW(e),s=e.instanceSshUrl?.trim()?{...t,instanceSshUrl:e.instanceSshUrl.trim()}:t,n=Array.isArray(e.instanceAliases)?e.instanceAliases.filter(D):[];return n.length?{...s,instanceAliases:n}:s},Mk=e=>{if(!e||!Q(e.repositoryId)||!e.repositoryId||!Q(e.configRevision)||!e.configRevision||Object.prototype.toString.call(e.bare)!=="[object Boolean]"||!Array.isArray(e.remotes))throw new Error("Source control response contained an invalid repository context");const t=e.remotes.map(s=>{if(!s||!Q(s.name)||!s.name||!nu(s.fetch)||!nu(s.push))throw new Error("Source control response contained an invalid repository remote");return{name:s.name,fetch:{displayUrl:s.fetch.displayUrl,fingerprint:s.fetch.fingerprint},push:{displayUrl:s.push.displayUrl,fingerprint:s.push.fingerprint}}});return{repositoryId:e.repositoryId,configRevision:e.configRevision,bare:e.bare,remotes:t}},wo=e=>{const t=Mk(e.repository);if(!Number.isInteger(e.revision)||e.revision<0)throw new Error("Source control response contained an invalid binding revision");if(e.binding===null)return{status:"missing",repository:t,revision:e.revision,binding:null};const s=G1(e.binding);if(!s||s.repositoryId!==t.repositoryId||s.revision!==e.revision||!Q(s.configRevision)||!Array.isArray(s.providers)||!Array.isArray(s.auxiliary)||s.state!=="bound"&&s.state!=="needs-attention")throw new Error("Source control response contained an invalid repository binding");const n=z1({...s,providers:s.providers.map(o=>({...o,...$(o)}))},t);return{status:n.state,repository:t,revision:e.revision,binding:n}},Lm=async(e,t,s)=>{const n=await e(t,{query:new URLSearchParams({directory:s}),headers:{Accept:"application/json"}}),o=await n.json();if(!n.ok)throw new ks(o.error||n.statusText||"Source control repository request failed",o.code);return o},lW=async(e,t=P)=>{const s=await t("/api/source-control/binding/transport",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new ks(n.error||"Git transport configuration failed",n.code);return{status:"configured",binding:wo(n)}},dW=async(e,t=P)=>{const s=await t("/api/source-control/binding/transport/remove",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new ks(n.error||"Git transport removal failed",n.code);return{status:"removed",binding:wo(n)}},uW=async(e,t=P)=>{const s=await t("/api/source-control/binding/auxiliary",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new ks(n.error||"Git auxiliary transport configuration failed",n.code);return{status:"configured",binding:wo(n)}},Xe=async(e,t,s,n={},o)=>{const i=$(t),a=await e(Wo(i,s),{...n,query:new URLSearchParams([["instance",i.instance],...o?Array.from(o.entries()):[]]),headers:{Accept:"application/json",...n.headers}}),r=await a.json();if(!a.ok){const l=r?.error||a.statusText||"Source control request failed";throw r?.code==="SOURCE_CONTROL_INSTANCE_OTHER_PROVIDER"&&D(r.provider)?new nV(l,r.provider):new ks(l,r?.code)}return r},us=e=>{const t=new URLSearchParams({directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},pW=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!D(t)))throw new Error("Source control response contained invalid incomplete projects");return[...e]}},de=(e,t,s,n)=>Xe(e,t,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),Wt=(e,t)=>{const s=Object.keys(e);return s.length===t.length&&s.every(n=>t.includes(n))};function ke(e,t,s){const n=e.target;if(!D(e.directory)||!D(e.repositoryId)||!D(e.accountId)||!Nk(e.bindingRevision)||!D(e.primaryRemote)||!D(e.idempotencyKey)||!n||!Bp(t,n.project?.owner)||!D(n.project?.name)||s==="create"&&("number"in n||"headSha"in n)||s==="create"&&(!D(n.head)||!D(n.base))||s==="existing"&&!Gt(n.number)||n.number!==void 0&&!Gt(n.number)||n.head!==void 0&&!D(n.head)||n.base!==void 0&&!D(n.base)||n.headSha!==void 0&&!D(n.headSha))throw new Error("Source control mutation context is invalid");const o={...t,directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:e.bindingRevision,primaryRemote:e.primaryRemote,idempotencyKey:e.idempotencyKey};if(s==="create"){if(!D(n.head)||!D(n.base))throw new Error("Source control mutation context is invalid");return{...o,target:{project:{owner:n.project.owner,name:n.project.name},head:n.head,base:n.base}}}if(!Gt(n.number))throw new Error("Source control mutation context is invalid");const i={project:{owner:n.project.owner,name:n.project.name},number:n.number};return n.head!==void 0&&(i.head=n.head),n.base!==void 0&&(i.base=n.base),n.headSha!==void 0&&(i.headSha=n.headSha),{...o,target:i}}const hW=(e,t)=>e.repositoryId===t.repositoryId&&e.bindingRevision===t.bindingRevision&&e.primaryRemote===t.primaryRemote&&e.project.owner===t.target.project.owner&&e.project.name===t.target.project.name&&(t.target.number===void 0||e.number===t.target.number)&&(t.target.head===void 0||e.head===t.target.head)&&(t.target.base===void 0||e.base===t.target.base)&&(t.target.headSha===void 0||e.headSha===t.target.headSha),Se=(e,t,s,n)=>{const o=e?.actor,i=e?.target,a=i?.project;if(!e||!Wt(e,["status","actor","target","replayed","result"])||e.status!=="succeeded"||!Re(e.replayed)||!o||!Wt(o,["provider","instance","providerAccountId"])||o.provider!==s.provider||o.instance!==s.instance||!D(o.providerAccountId)||!Rk(s.provider,s.instance,o.providerAccountId)||!i||!Wt(i,["repositoryId","bindingRevision","primaryRemote","project",...["number","head","base","headSha"].filter(l=>i[l]!==void 0)])||!D(i.repositoryId)||!Nk(i.bindingRevision)||!D(i.primaryRemote)||!a||!Wt(a,["id","owner","name"])||!D(a.id)||!Bp(s,a.owner)||!D(a.name)||i.number!==void 0&&!Gt(i.number)||i.head!==void 0&&!D(i.head)||i.base!==void 0&&!D(i.base)||i.headSha!==void 0&&!D(i.headSha)||!hW(i,t)||!e.result||Object.prototype.toString.call(e.result)!=="[object Object]")throw new Error("Source control response contained an invalid mutation receipt");const r={repositoryId:i.repositoryId,bindingRevision:i.bindingRevision,primaryRemote:i.primaryRemote,project:{id:a.id,owner:a.owner,name:a.name}};return i.number!==void 0&&(r.number=i.number),i.head!==void 0&&(r.head=i.head),i.base!==void 0&&(r.base=i.base),i.headSha!==void 0&&(r.headSha=i.headSha),{status:"succeeded",actor:{...s,providerAccountId:o.providerAccountId},target:r,replayed:e.replayed,result:n(e.result)}},Ye=e=>{if(!Wt(e,[]))throw new Error("Source control response contained an invalid mutation result");return{}},gW=["queued","merging","auto-merge","cancelled"],mW=e=>gW.find(t=>t===e)??null,fW=e=>{if(!Wt(e,e.stacked===void 0?[]:["stacked"])||e.stacked!==void 0&&!Re(e.stacked))throw new Error("Source control response contained an invalid create result");return e.stacked===void 0?{}:{stacked:e.stacked}},wW=e=>{const t=["merged",...e.message===void 0?[]:["message"],...e.outcome===void 0?[]:["outcome"]],s=e.outcome===void 0?void 0:mW(e.outcome);if(!Wt(e,t)||!Re(e.merged)||e.message!==void 0&&!Q(e.message)||s===null)throw new Error("Source control response contained an invalid merge result");const n={merged:e.merged};return e.message!==void 0&&(n.message=e.message),s!==void 0&&(n.outcome=s),n},bW=e=>{if(!Wt(e,["commented"])||!Re(e.commented))throw new Error("Source control response contained an invalid review result");return{commented:e.commented}},Um=async(e,t,s,n)=>{const o=$(t),i=us(t);i.set("owner",s.owner),i.set("repo",s.repo);const a=await Xe(e,o,n,{},i);if(a.connected!==true)throw new Error(`${ia(o)} is not connected`);if(!Array.isArray(a.items))throw new Error("Source control response contained an invalid list");return a.items},yW=e=>e.map(t=>{if(!D(t.name)||t.color!==void 0&&!Q(t.color))throw new Error("Source control response contained an invalid label");return t.color?{name:t.name,color:t.color}:{name:t.name}}),vW=e=>e.map(t=>{if(!D(t.id)||!D(t.login)||t.avatarUrl!==void 0&&!xs(t.avatarUrl))throw new Error("Source control response contained an invalid user");return t.avatarUrl?{id:t.id,login:t.login,avatarUrl:t.avatarUrl}:{id:t.id,login:t.login}}),El=e=>{if(!Wt(e,["state"])||e.state!=="open"&&e.state!=="closed")throw new Error("Source control response contained an invalid state result");return{state:e.state}},kW=e=>{if(!Wt(e,["ready"])||!Re(e.ready))throw new Error("Source control response contained an invalid ready result");return{ready:e.ready}},SW=e=>{if(!Wt(e,["draft"])||!Re(e.draft))throw new Error("Source control response contained an invalid draft result");return{draft:e.draft}},bt=(e,t)=>{const s=e?.username||e?.login,n=Pk(t.provider)?typeof e?.id=="string"&&e.id.length>0&&e.id.length<=256||Gt(e?.id):e&&As(e.id);if(!e||!n||!D(s)||!NW(e,t)||e.avatarUrl!==void 0&&!xs(e.avatarUrl)||e.name!==void 0&&!Q(e.name)||e.email!==void 0&&!Q(e.email))throw new Error("Source control response contained an invalid user");const o={...t,id:String(e.id),username:s};return e.avatarUrl&&(o.avatarUrl=e.avatarUrl),e.name&&(o.name=e.name),e.email&&(o.email=e.email),o},Oo=(e,t)=>{if(!e||!As(e.id)||!Bp(t,e.owner)||!D(e.name)||!xs(e.url)||!Pt(e,t)||e.cloneUrl!==void 0&&!D(e.cloneUrl)||e.sshUrl!==void 0&&!D(e.sshUrl)||e.defaultBranch!==void 0&&!D(e.defaultBranch)||e.defaultBranchSha!==void 0&&e.defaultBranchSha!==null&&!D(e.defaultBranchSha)||e.remoteName!==void 0&&e.remoteName!==null&&!D(e.remoteName))throw new Error("Source control response contained an invalid project");const s={...t,id:String(e.id),owner:e.owner,name:e.name,url:e.url};return e.cloneUrl&&(s.cloneUrl=e.cloneUrl),e.sshUrl&&(s.sshUrl=e.sshUrl),e.defaultBranch&&(s.defaultBranch=e.defaultBranch),e.defaultBranchSha!==void 0&&(s.defaultBranchSha=e.defaultBranchSha),e.remoteName!==void 0&&(s.remoteName=e.remoteName),s},Fk=(e,t)=>{if(e==null)return null;if(!e.summary)throw new Error("Source control response contained an invalid CI summary");if(jW(e.summary),e.runs!==void 0){if(!Array.isArray(e.runs)||e.runs.some(s=>!s||!As(s.id)||!D(s.name)||!Pt(s,t)||s.detailsUrl!==void 0&&!xs(s.detailsUrl)))throw new Error("Source control response contained invalid CI runs");for(const s of e.runs){if(s.startedAt!==void 0&&!D(s.startedAt)||s.completedAt!==void 0&&!D(s.completedAt)||s.status!==void 0&&!D(s.status)||s.conclusion!==void 0&&s.conclusion!==null&&!Q(s.conclusion))throw new Error("Source control response contained invalid CI run fields");if(s.application!==void 0&&(Object.prototype.toString.call(s.application)!=="[object Object]"||s.application.name!==void 0&&!Q(s.application.name)||s.application.slug!==void 0&&!Q(s.application.slug)))throw new Error("Source control response contained an invalid CI application");if(s.job!==void 0&&(Object.prototype.toString.call(s.job)!=="[object Object]"||s.job.runId!==void 0&&!As(s.job.runId)||s.job.jobId!==void 0&&!As(s.job.jobId)||s.job.url!==void 0&&!xs(s.job.url)||s.job.name!==void 0&&!Q(s.job.name)||s.job.workflowName!==void 0&&!Q(s.job.workflowName)||s.job.conclusion!==void 0&&s.job.conclusion!==null&&!Q(s.job.conclusion)))throw new Error("Source control response contained an invalid CI job");if(s.job?.steps!==void 0&&(!Array.isArray(s.job.steps)||s.job.steps.some(n=>!n||!D(n.name)||n.status!==void 0&&!Q(n.status)||n.conclusion!==void 0&&n.conclusion!==null&&!Q(n.conclusion)||n.number!==void 0&&(!Number.isInteger(n.number)||n.number<0)||n.startedAt!==void 0&&!D(n.startedAt)||n.completedAt!==void 0&&!D(n.completedAt))))throw new Error("Source control response contained invalid CI steps");if(s.output!==void 0&&(Object.prototype.toString.call(s.output)!=="[object Object]"||s.output.title!==void 0&&!Q(s.output.title)||s.output.summary!==void 0&&!Q(s.output.summary)||s.output.text!==void 0&&!Q(s.output.text)))throw new Error("Source control response contained invalid CI output");if(s.annotations!==void 0&&(!Array.isArray(s.annotations)||s.annotations.some(n=>!n||!D(n.message)||n.path!==void 0&&!Q(n.path)||n.startLine!==void 0&&(!Number.isInteger(n.startLine)||n.startLine<0)||n.endLine!==void 0&&(!Number.isInteger(n.endLine)||n.endLine<0)||n.level!==void 0&&!Q(n.level)||n.title!==void 0&&!Q(n.title)||n.rawDetails!==void 0&&!Q(n.rawDetails))))throw new Error("Source control response contained invalid CI annotations")}}return{summary:{state:e.summary.state,total:e.summary.total,success:e.summary.success,failure:e.summary.failure,pending:e.summary.pending,inProgress:e.summary.inProgress,queued:e.summary.queued,startedAt:e.summary.startedAt},runs:e.runs?.map(s=>({...t,id:String(s.id),name:s.name,status:s.status,conclusion:s.conclusion,startedAt:s.startedAt,completedAt:s.completedAt,detailsUrl:s.detailsUrl,application:s.application,job:s.job,output:s.output,annotations:s.annotations}))}},ou=(e,t)=>{if(!e||!As(e.id)||!Number.isInteger(e.number)||e.number<1||!D(e.title)||!xs(e.url)||!["open","closed","merged"].includes(e.state)||!Re(e.draft)||!D(e.base)||!D(e.head)||!Pt(e,t)||e.body!==void 0&&!Q(e.body)||e.headSha!==void 0&&!D(e.headSha)||e.author!==void 0&&e.author!==null&&!Pt(e.author,t)||e.createdAt!==void 0&&!D(e.createdAt)||e.updatedAt!==void 0&&!D(e.updatedAt)||e.headLabel!==void 0&&!D(e.headLabel)||e.mergeable!==void 0&&e.mergeable!==null&&!Re(e.mergeable)||e.mergeableState!==void 0&&e.mergeableState!==null&&!Q(e.mergeableState)||e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(n=>!n||!D(n.name)||n.color!==void 0&&!Q(n.color)))||e.workInProgress!==void 0&&!Re(e.workInProgress)||e.private!==void 0&&!Re(e.private)||e.topic!==void 0&&!Q(e.topic)||e.hashtags!==void 0&&(!Array.isArray(e.hashtags)||e.hashtags.some(n=>!D(n)))||e.revisionNumber!==void 0&&!Gt(e.revisionNumber))throw new Error("Source control response contained an invalid change request");const s={...t,id:String(e.id),number:e.number,project:Oo(e.project,t),title:e.title,url:e.url,state:e.state,draft:e.draft,base:e.base,head:e.head};return e.body!==void 0&&(s.body=e.body),e.headSha&&(s.headSha=e.headSha),e.author!==void 0&&e.author!==null&&(s.author=bt(e.author,t)),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),e.headLabel&&(s.headLabel=e.headLabel),e.headProject!==void 0&&e.headProject!==null&&(s.headProject=Oo(e.headProject,t)),e.mergeable!==void 0&&(s.mergeable=e.mergeable),e.mergeableState!==void 0&&(s.mergeableState=e.mergeableState),e.labels!==void 0&&(s.labels=e.labels.map(n=>({name:n.name,color:n.color}))),e.workInProgress!==void 0&&(s.workInProgress=e.workInProgress),e.private!==void 0&&(s.private=e.private),e.topic&&(s.topic=e.topic),e.hashtags!==void 0&&(s.hashtags=[...e.hashtags]),e.revisionNumber!==void 0&&(s.revisionNumber=e.revisionNumber),s},jm=(e,t)=>{if(!e||!As(e.id)||!Number.isInteger(e.number)||e.number<1||!D(e.title)||!xs(e.url)||e.state!=="open"&&e.state!=="closed"||!Pt(e,t)||e.body!==void 0&&!Q(e.body)||e.author!==void 0&&e.author!==null&&!Pt(e.author,t)||e.createdAt!==void 0&&!D(e.createdAt)||e.updatedAt!==void 0&&!D(e.updatedAt))throw new Error("Source control response contained an invalid issue");if(e.assignees!==void 0&&(!Array.isArray(e.assignees)||e.assignees.some(n=>!Pt(n,t))))throw new Error("Source control response contained invalid issue assignees");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(n=>!n||!D(n.name)||n.color!==void 0&&!Q(n.color))))throw new Error("Source control response contained invalid issue labels");const s={...t,id:String(e.id),number:e.number,project:Oo(e.project,t),title:e.title,url:e.url,state:e.state};return e.body!==void 0&&(s.body=e.body),e.author!==void 0&&(s.author=e.author?bt(e.author,t):null),e.assignees!==void 0&&(s.assignees=e.assignees.map(n=>bt(n,t))),e.labels!==void 0&&(s.labels=e.labels.map(n=>({name:n.name,color:n.color}))),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),s},CW=e=>{if(!e||!D(e.sha)||!Q(e.headline)||e.authorName!==null&&!Q(e.authorName)||e.committedAt!==null&&!D(e.committedAt)||e.url!==null&&!xs(e.url))throw new Error("Source control response contained an invalid commit");return{sha:e.sha,headline:e.headline,authorName:e.authorName,committedAt:e.committedAt,url:e.url}},TW=["open","closed","merged"],AW=e=>{if(!e||!D(e.base)||!Array.isArray(e.layers)||e.number!==null&&!Number.isSafeInteger(e.number))throw new Error("Source control response contained an invalid merge request chain");return{number:e.number,base:e.base,layers:e.layers.map(t=>{const s=TW.find(n=>n===t?.state);if(!t||!Number.isSafeInteger(t.number)||!Q(t.title)||!xs(t.url)||!s||!Re(t.draft)||!D(t.head))throw new Error("Source control response contained an invalid merge request chain");return{number:t.number,title:t.title,url:t.url,state:s,draft:t.draft,head:t.head}})}},_k=e=>{try{return AW(e)}catch{return}},PW=(e,t)=>{if(!e||e.state!=="approved"&&e.state!=="changes_requested"||!D(e.url)||e.createdAt!==null&&!D(e.createdAt))throw new Error("Source control response contained an invalid review verdict");const s={state:e.state,url:e.url,createdAt:e.createdAt};return e.author&&(s.author=bt(e.author,t)),s},RW=["approved","rejected","recommended","disliked","neutral"],IW=["satisfied","unsatisfied","overridden","not-applicable","error","forced"],xW=["rework","trivial-rebase","merge-first-parent-update","no-code-change","no-change"],_i=e=>Cc(e)&&Number.isInteger(e)&&e>=-10&&e<=10,EW=(e,t)=>{if(!e||!_i(e.value)||e.revision!==void 0&&!Gt(e.revision))throw new Error("Source control response contained an invalid vote");const s={user:bt(e.user,t),value:e.value};return e.revision!==void 0&&(s.revision=e.revision),s},OW=(e,t)=>{const s=RW.find(n=>n===e?.status);if(!e||!D(e.name)||!s||!_i(e.defaultValue)||!Re(e.blocking)||!Array.isArray(e.values)||e.values.some(n=>!n||!_i(n.value)||!Q(n.description))||!Array.isArray(e.permitted)||e.permitted.some(n=>!_i(n))||!Array.isArray(e.votes))throw new Error("Source control response contained an invalid vote label");return{name:e.name,values:e.values.map(n=>({value:n.value,description:n.description})),defaultValue:e.defaultValue,permitted:[...e.permitted],blocking:e.blocking,status:s,votes:e.votes.map(n=>EW(n,t))}},DW=e=>{const t=IW.find(n=>n===e?.status);if(!e||!D(e.name)||!t||e.description!==void 0&&!Q(e.description))throw new Error("Source control response contained an invalid submit requirement");const s={name:e.name,status:t};return e.description&&(s.description=e.description),s},MW=(e,t)=>{const s=e?.kind===void 0?void 0:xW.find(o=>o===e.kind);if(!e||!Gt(e.number)||!D(e.sha)||!D(e.ref)||e.createdAt!==null&&!D(e.createdAt)||e.kind!==void 0&&!s)throw new Error("Source control response contained an invalid revision");const n={number:e.number,sha:e.sha,createdAt:e.createdAt,ref:e.ref};return e.uploader&&(n.uploader=bt(e.uploader,t)),s&&(n.kind=s),n},FW=e=>{if(!e||!D(e.sha)||e.changeId!==null&&!D(e.changeId)||e.uploadedAs!==null&&!Gt(e.uploadedAs))throw new Error("Source control response contained an invalid local revision");return{sha:e.sha,changeId:e.changeId,uploadedAs:e.uploadedAs}},_W=(e,t)=>{if(e?.revision!==void 0&&!Gt(e.revision))throw new Error("Source control response contained an invalid review comment");const s={...iu(e,t),path:e.path,line:e.line,position:e.position};return e.revision!==void 0&&(s.revision=e.revision),s},iu=(e,t)=>{if(!e||!As(e.id)||!D(e.url)||!Q(e.body)||!Pt(e,t)||e.author!==void 0&&e.author!==null&&!Pt(e.author,t)||e.createdAt!==void 0&&!D(e.createdAt)||e.updatedAt!==void 0&&!D(e.updatedAt))throw new Error("Source control response contained an invalid comment");const s=e.thread;if(s!==void 0&&(!s||!As(s.id)||!Re(s.resolved)||!Re(s.resolvable)||!Re(s.first)||s.canResolve!==void 0&&!Re(s.canResolve)||s.canReply!==void 0&&!Re(s.canReply)))throw new Error("Source control response contained an invalid comment thread");const n={...t,id:String(e.id),url:e.url,body:e.body};return s&&(n.thread={id:String(s.id),resolved:s.resolved,resolvable:s.resolvable,first:s.first},s.canResolve!==void 0&&(n.thread.canResolve=s.canResolve),s.canReply!==void 0&&(n.thread.canReply=s.canReply)),e.author&&(n.author=bt(e.author,t)),e.createdAt&&(n.createdAt=e.createdAt),e.updatedAt&&(n.updatedAt=e.updatedAt),n},Q=e=>Object.prototype.toString.call(e)==="[object String]",Re=e=>Object.prototype.toString.call(e)==="[object Boolean]",Cc=e=>Object.prototype.toString.call(e)==="[object Number]",D=e=>Q(e)&&e.trim().length>0,Gt=e=>Cc(e)&&Number.isSafeInteger(e)&&e>=1,Nk=e=>Cc(e)&&Number.isSafeInteger(e)&&e>=0,As=e=>D(e)||Number.isFinite(e),xs=e=>{if(!D(e))return false;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"}catch{return false}},Pt=(e,t)=>e?.provider===t.provider&&e.instance===t.instance,NW=(e,t)=>e.provider===void 0&&e.instance===void 0?true:Pt(e,t),LW=(e,t)=>{if(!Cc(e)||!Number.isInteger(e)||e<1||!Re(t))throw new Error("Source control response contained invalid pagination");return{page:e,hasMore:t}},Bm=(e,t)=>{const s={items:t,...LW(e.page,e.hasMore)},n=pW(e.incompleteProjectIds);return n?.length&&(s.incompleteProjectIds=n),s},UW=e=>{if(!e||!Array.isArray(e.branches)||e.branches.some(t=>!D(t)))throw new Error("Source control response contained invalid branches");return[...e.branches]},jW=e=>{if(!["success","failure","pending","unknown"].includes(e.state)||!Number.isInteger(e.total)||e.total<0||!Number.isInteger(e.success)||e.success<0||!Number.isInteger(e.failure)||e.failure<0||!Number.isInteger(e.pending)||e.pending<0||e.inProgress!==void 0&&(!Number.isInteger(e.inProgress)||e.inProgress<0)||e.queued!==void 0&&(!Number.isInteger(e.queued)||e.queued<0)||e.startedAt!==void 0&&!D(e.startedAt))throw new Error("Source control response contained an invalid CI summary")},BW=(e,t,s)=>{if(!e||!Pt(e.identity,t)||!D(e.branch)||e.branch!==s||e.project===void 0||e.changeRequest===void 0||e.fetchedAt!==void 0&&(!Number.isFinite(e.fetchedAt)||e.fetchedAt<0)||e.canMerge!==void 0&&!Re(e.canMerge)||e.defaultBranch!==void 0&&e.defaultBranch!==null&&!D(e.defaultBranch)||e.resolvedRemoteName!==void 0&&e.resolvedRemoteName!==null&&!D(e.resolvedRemoteName))throw new Error("Source control response contained an invalid change request status");const n={identity:t,project:e.project===null?null:Oo(e.project,t),branch:e.branch,changeRequest:e.changeRequest===null?null:ou(e.changeRequest,t)};if(e.ci!==void 0&&(n.ci=Fk(e.ci,t)),e.canMerge!==void 0&&(n.canMerge=e.canMerge),e.defaultBranch!==void 0&&(n.defaultBranch=e.defaultBranch),e.resolvedRemoteName!==void 0&&(n.resolvedRemoteName=e.resolvedRemoteName),e.fetchedAt!==void 0&&(n.fetchedAt=e.fetchedAt),e.localRevision!==void 0&&(n.localRevision=FW(e.localRevision)),e.stack===null)n.stack=null;else if(e.stack!==void 0){const o=_k(e.stack);o&&(n.stack=o)}return n},Ol=(e,t)=>(e??[]).map(s=>{if(!D(s.id)||s.id!==s.credentialId||!Gt(s.credentialRevision)||!D(s.providerUserId)||!["available","unavailable"].includes(s.providerUserStatus)||!Re(s.current)||!["oauth","pat","cli"].includes(s.source)||!["valid","invalid"].includes(s.status))throw new Error("Source control response contained an invalid auth credential");return{id:s.id,credentialId:s.credentialId,credentialRevision:s.credentialRevision,providerUserId:s.providerUserId,providerUserStatus:s.providerUserStatus,user:bt(s.user,t),scope:s.scope,current:s.current,source:s.source,status:s.status}}),Dl=(e,t)=>{if(!e.connected){if(!e.status){const s={...t,status:"disconnected",connected:false};return e.cli&&(s.cli={available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?bt(e.cli.user,t):void 0}),s.accounts=Ol(e.accounts,t),s}return{...e,...t,connected:false,accounts:Ol(e.accounts,t)}}return{...t,status:"connected",connected:true,user:bt(e.user,t),scope:e.scope,accounts:Ol(e.accounts,t),cli:e.cli?{available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?bt(e.cli.user,t):void 0}:void 0}},VW=(e={})=>{const t=e.fetch??P;return{repositoryContext:async s=>Mk(await Lm(t,"/api/source-control/repository-context",s)),repositoryBinding:async s=>wo(await Lm(t,"/api/source-control/binding",s)),resetRepositoryBinding:async s=>{const n=await t("/api/source-control/binding/reset",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),o=await n.json();if(!n.ok)throw new ks(o.error||n.statusText||"Source control binding reset failed",o.code);return wo(o)},repositoryProviderBindingMutate:async s=>{const n=await t("/api/source-control/binding/provider",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),o=await n.json();if(!n.ok)throw new ks(o.error||n.statusText||"Source control binding request failed",o.code);return wo(o)},providers:async()=>{const s=await J1(t);return Dk(s),s},authInstances:async()=>{const s=await t("/api/source-control/instances",{headers:{Accept:"application/json"}}),n=await s.json();if(!s.ok)throw new Error(n.error||s.statusText||"Failed to list source control instances");return n.instances.map($)},capabilities:async s=>{const n=await Xe(t,s,"/capabilities");return{identity:$(n.identity),authentication:n.authentication,authenticationMethods:n.authenticationMethods,multipleAccounts:n.multipleAccounts,projects:n.projects,issues:n.issues,changeRequests:n.changeRequests,draftChangeRequests:n.draftChangeRequests,draftConversion:n.draftConversion===true,mergeChangeRequests:n.mergeChangeRequests,mergeMethods:n.mergeMethods?[...n.mergeMethods]:void 0,ci:n.ci}},authStatus:async s=>{const n=$(s);return Dl(await Xe(t,n,"/auth/status"),n)},authStart:async s=>{const n=await Xe(t,s,"/auth/start",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),o={flowId:n.flowId,userCode:n.userCode,verificationUri:n.verificationUri,expiresIn:n.expiresIn,interval:n.interval};return n.verificationUriComplete&&(o.verificationUriComplete=n.verificationUriComplete),n.scope&&(o.scope=n.scope),o},authComplete:async(s,n)=>{let o;try{o=await de(t,s,"/auth/complete",{flowId:n})}catch(a){if(a instanceof ks&&a.code==="SOURCE_CONTROL_OAUTH_FLOW_UNAVAILABLE")return{status:"error",code:"expired",message:a.message};throw a}if(o.connected){const a={status:"connected",user:bt(o.user,$(s))};return o.scope&&(a.scope=o.scope),a}if(o.status==="authorization_pending"||o.status==="slow_down"){const a={status:"pending"};return o.status==="slow_down"&&(a.slowDown=true),a}let i="provider-error";return o.status==="access_denied"?i="access-denied":o.status==="expired_token"&&(i="expired"),{status:"error",code:i,message:o.error||o.status||`${ia(s)} authentication failed`}},authSetToken:async(s,n,o)=>{const i=$(s);return await de(t,i,"/auth/token",o?.username?{token:n,username:o.username}:{token:n}),Dl(await Xe(t,i,"/auth/status"),i)},authSetSshUrl:async(s,n)=>{const o=$(s),i=await de(t,o,"/auth/ssh-url",{sshUrl:n});if(i.sshUrl!==null&&!D(i.sshUrl))throw new Error("Source control response contained an invalid SSH URL");return{sshUrl:i.sshUrl??null}},setInstanceAliases:async(s,n)=>{const o=$(s),i=await t("/api/source-control/instances/aliases",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({provider:o.provider,instance:o.instance,aliases:n})}),a=await i.json();if(!i.ok){const r=a.error||i.statusText||"Failed to save instance aliases";throw(a.code==="INVALID_INSTANCE_ALIAS"||a.code==="INSTANCE_ALIAS_TAKEN")&&D(a.alias)?new oV(r,a.code==="INSTANCE_ALIAS_TAKEN"?"taken":"invalid",a.alias):new ks(r,a.code)}if(!Array.isArray(a.aliases)||!a.aliases.every(D))throw new Error("Source control response contained invalid instance aliases");return{aliases:[...a.aliases]}},authDisconnect:async(s,n)=>{if(!D(n)||n.trim()!==n)throw new Error("Source control credential accountId is required");const o=new URLSearchParams({accountId:n}),i=await Xe(t,s,"/auth",{method:"DELETE"},o);if(!Re(i.removed))throw new Error("Source control response contained an invalid account removal result");return{removed:i.removed}},authActivate:async(s,n)=>{const o=$(s);return Dl(await de(t,o,"/auth/activate",{accountId:n}),o)},authSetCliDisabled:async(s,n)=>{const o=$(s);return{disabled:!!(await de(t,o,"/auth/cli",{disabled:n})).disabled}},changeRequestStatus:async(s,n,o)=>{const i=$(s),a=us(s);a.set("branch",n),o?.force&&a.set("force","true");const r=await Xe(t,i,"/pr/status",{},a);return BW(r,i,n)},changeRequestCreate:async s=>{const n=$(s),i={...ke(s,n,"create"),title:s.title};s.body!==void 0&&(i.body=s.body),s.draft!==void 0&&(i.draft=s.draft),s.remote&&(i.remote=s.remote),s.headRemote&&(i.headRemote=s.headRemote);const a=await de(t,n,"/pr/create",i);return Se(a,s,n,fW)},changeRequestUpdate:async s=>{const n=$(s),o={...ke(s,n,"existing"),title:s.title};s.body!==void 0&&(o.body=s.body);const i=await de(t,n,"/pr/update",o);return Se(i,s,n,Ye)},changeRequestMerge:async s=>{const n=$(s),o=await de(t,n,"/pr/merge",{...ke(s,n,"existing"),method:s.method,cancel:s.cancel});return Se(o,s,n,wW)},changeRequestReady:async s=>{const n=$(s),o=await de(t,n,"/pr/ready",ke(s,n,"existing"));return Se(o,s,n,kW)},changeRequestDraft:async s=>{const n=$(s),o=await de(t,n,"/pr/draft",ke(s,n,"existing"));return Se(o,s,n,SW)},changeRequestComment:async s=>{const n=$(s),o=await de(t,n,"/pr/comment",{...ke(s,n,"existing"),body:s.body});return Se(o,s,n,Ye)},changeRequestStartThread:async s=>{const n=$(s),o=await de(t,n,"/pr/thread/start",{...ke(s,n,"existing"),body:s.body});return Se(o,s,n,Ye)},changeRequestReplyToThread:async s=>{const n=$(s),o=await de(t,n,"/pr/thread/reply",{...ke(s,n,"existing"),threadId:s.threadId,body:s.body});return Se(o,s,n,Ye)},changeRequestResolveThread:async s=>{const n=$(s),o=await de(t,n,"/pr/thread/resolve",{...ke(s,n,"existing"),threadId:s.threadId,resolved:s.resolved});return Se(o,s,n,Ye)},changeRequestReview:async s=>{const n=$(s),o=ke(s,n,"existing");let i;if(s.votes!==void 0){const r=Object.entries(s.votes);if(s.verdict!==void 0||r.length===0&&s.publishDrafts!==true||r.some(([l,u])=>!D(l)||!_i(u)))throw new Error("Source control review input is invalid");i={...o,votes:Object.fromEntries(r),publishDrafts:s.publishDrafts}}else i={...o,verdict:s.verdict};s.body!==void 0&&(i.body=s.body);const a=await de(t,n,"/pr/review",i);return Se(a,s,n,bW)},changeRequestReviewState:(s,n)=>oW(t,s,n),changeRequestReviewComment:async s=>{const n=$(s),o=s.line===void 0?{path:s.path}:{path:s.path,side:s.side,line:s.line,startLine:s.startLine},i=await de(t,n,"/pr/review/comment",{...ke(s,n,"existing"),...o,body:s.body});return Se(i,s,n,Ye)},changeRequestReviewCommentUpdate:async s=>{const n=$(s),o=await de(t,n,"/pr/review/comment/update",{...ke(s,n,"existing"),commentId:s.commentId,body:s.body});return Se(o,s,n,Ye)},changeRequestReviewCommentDelete:async s=>{const n=$(s),o=await de(t,n,"/pr/review/comment/delete",{...ke(s,n,"existing"),commentId:s.commentId});return Se(o,s,n,Ye)},changeRequestReviewDiscard:async s=>{const n=$(s),o=await de(t,n,"/pr/review/discard",ke(s,n,"existing"));return Se(o,s,n,Ye)},changeRequestSetState:async s=>{const n=$(s),o=await de(t,n,"/pr/state",{...ke(s,n,"existing"),state:s.state});return Se(o,s,n,El)},issueSetState:async s=>{const n=$(s),o=await de(t,n,"/issues/state",{...ke(s,n,"existing"),state:s.state});return Se(o,s,n,El)},changeRequestSetLabels:async s=>{const n=$(s),o=await de(t,n,"/pr/labels",{...ke(s,n,"existing"),labels:s.labels});return Se(o,s,n,Ye)},issueSetLabels:async s=>{const n=$(s),o=await de(t,n,"/issues/labels",{...ke(s,n,"existing"),labels:s.labels});return Se(o,s,n,Ye)},changeRequestSetReviewers:async s=>{const n=$(s),o=await de(t,n,"/pr/reviewers",{...ke(s,n,"existing"),reviewers:s.reviewers});return Se(o,s,n,Ye)},refreshProviderReads:async(s,n)=>{const o="item"in n?new URLSearchParams({scope:"item",owner:n.item.owner,repo:n.item.repo,number:String(n.item.number)}):new URLSearchParams({scope:"lists"});await Xe(t,s,"/read-cache/refresh",{method:"POST"},o)},referenceLabels:async(s,n)=>yW(await Um(t,s,n,"/references/labels")),referenceReviewers:async(s,n)=>vW(await Um(t,s,n,"/references/reviewers")),issueComment:async s=>{const n=$(s),o=await de(t,n,"/issues/comment",{...ke(s,n,"existing"),body:s.body});return Se(o,s,n,Ye)},discussionComment:async s=>{const n=$(s),o={...ke(s,n,"existing"),body:s.body};s.replyTo&&(o.replyTo=s.replyTo);const i=await de(t,n,"/discussions/comment",o);return Se(i,s,n,Ye)},discussionSetState:async s=>{const n=$(s),o=ke(s,n,"existing"),i=await de(t,n,"/discussions/state",s.state==="closed"?{...o,state:"closed",reason:s.reason}:{...o,state:"open"});return Se(i,s,n,El)},discussionSetAnswer:async s=>{const n=$(s),o=await de(t,n,"/discussions/answer",{...ke(s,n,"existing"),commentId:s.commentId,answer:s.answer});return Se(o,s,n,Ye)},discussionSetLabels:async s=>{const n=$(s),o=await de(t,n,"/discussions/labels",{...ke(s,n,"existing"),labels:s.labels});return Se(o,s,n,Ye)},changeRequestsList:async(s,n)=>{const o=$(s),i=us(s);i.set("page",String(n?.page??1)),n?.query&&i.set("query",n.query),n?.state&&i.set("state",n.state),n?.people&&i.set("people",n.people);const a=await Xe(t,o,"/pulls/list",{},i);if(!a||!Array.isArray(a.items))throw new Error("Source control response contained invalid change requests");return Bm(a,a.items.map(r=>ou(r,o)))},changeRequestContext:async(s,n,o)=>{const i=$(s),a=us(s);a.set("number",String(n)),o?.includeDiff&&a.set("diff","1"),o?.includeCIDetails&&a.set("checkDetails","1"),o?.includeTimeline&&a.set("timeline","1"),o?.revision&&a.set("revision",o.revision),o?.project&&(a.set("owner",o.project.owner),a.set("repo",o.project.name));const r=await Xe(t,i,"/pulls/context",{},a),l={identity:i,project:r.project?Oo(r.project,i):null,changeRequest:r.changeRequest?ou(r.changeRequest,i):null,issueComments:r.issueComments.map(u=>iu(u,i)),reviewComments:r.reviewComments.map(u=>_W(u,i)),files:r.files.map(u=>({...u})),diff:r.diff,ci:Fk(r.ci,i),fetchedAt:r.fetchedAt};if(r.commits&&(l.commits=r.commits.map(CW),l.commitsComplete=r.commitsComplete!==false,l.verdicts=(r.verdicts??[]).map(u=>PW(u,i)),r.reviewers&&(l.reviewers=r.reviewers.map(u=>bt(u,i)))),r.stack===null)l.stack=null;else if(r.stack!==void 0){const u=_k(r.stack);u&&(l.stack=u)}if(r.voteLabels!==void 0){if(!Array.isArray(r.voteLabels))throw new Error("Source control response contained invalid vote labels");l.voteLabels=r.voteLabels.map(u=>OW(u,i))}if(r.submitRequirements!==void 0){if(!Array.isArray(r.submitRequirements))throw new Error("Source control response contained invalid submit requirements");l.submitRequirements=r.submitRequirements.map(DW)}if(r.revisions!==void 0){if(!Array.isArray(r.revisions))throw new Error("Source control response contained invalid revisions");l.revisions=r.revisions.map(u=>MW(u,i))}return l},issuesList:async(s,n)=>{const o=$(s),i=us(s);i.set("page",String(n?.page??1)),n?.query&&i.set("query",n.query),n?.state&&i.set("state",n.state),n?.people&&i.set("people",n.people);const a=await Xe(t,o,"/issues/list",{},i);if(!a||!Array.isArray(a.items))throw new Error("Source control response contained invalid issues");return Bm(a,a.items.map(r=>jm(r,o)))},issueGet:async(s,n,o)=>{const i=$(s),a=us(s);a.set("number",String(n)),o&&(a.set("owner",o.owner),a.set("repo",o.name));const r=await Xe(t,i,"/issues/get",{},a);return r===null?null:jm(r,i)},issueComments:async(s,n,o)=>{const i=$(s),a=us(s);a.set("number",String(n)),o&&(a.set("owner",o.owner),a.set("repo",o.name));const r=await Xe(t,i,"/issues/comments",{},a);if(!Array.isArray(r))throw new Error("Source control response contained invalid comments");return r.map(l=>iu(l,i))},projectUpstream:async s=>{const n=$(s),o=us(s),i=await Xe(t,n,"/repo/upstream",{},o);if(!i||!Pt(i.identity,n)||!Re(i.isFork)||i.upstream!==null&&i.upstream===void 0||i.isFork!==!!i.upstream)throw new Error("Source control response contained an invalid upstream");return{identity:n,isFork:i.isFork,upstream:i.upstream?Oo(i.upstream,n):null}},projectBranches:async(s,n,o)=>{const i=$(s),a=us(s);a.set("owner",n),a.set("repo",o);const r=await Xe(t,i,"/repo/branches",{},a);return UW(r)},references:(s,n)=>tW(t,s,n),referencesAcross:(s,n)=>iW(t,s,n),referenceDetail:(s,n)=>sW(t,s,n),changeRequestListStatuses:(s,n)=>aW(t,s,n)}},HW=d({status:g("unsupported"),reason:g("host-setup-required")}).strict(),Lk=c().regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/),au=d({credentialId:c().regex(/^ocgit:v1:ssh:[A-Za-z0-9_-]{1,267}$/),label:g("SSH"),fingerprint:Lk,capability:L([d({status:g("ready")}).strict(),d({status:g("unavailable"),reason:T(["unreadable","encrypted-or-unverifiable","fingerprint-mismatch"])}).strict()])}).strict(),WW=au.extend({capability:d({status:g("ready")}).strict()}),Vm=c().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),qW=L([d({candidateId:c().regex(/^[A-Za-z0-9_-]{1,200}$/),label:Vm,fingerprint:Lk,capability:d({status:g("ready")}).strict()}).strict(),d({label:Vm,capability:d({status:g("unavailable"),reason:T(["unreadable","encrypted-or-unverifiable","insecure-permissions"])}).strict()}).strict()]),GW=L([HW,d({status:g("available"),credentials:k(au).max(256)}).strict(),d({status:g("discovered"),candidates:k(qW).max(128),truncated:v()}).strict(),d({status:g("imported"),credentials:k(au).max(256),selectedCredential:WW}).strict(),d({status:g("rejected"),reason:T(["candidate-expired","candidate-changed","fingerprint-mismatch","candidate-unavailable","inventory-full"])}).strict()]),zW=async(e,t=P)=>{const s=await t("/api/git/managed-ssh-credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw new Error("Managed SSH inventory request failed");const n=GW.parse(await s.json());if(n.status==="imported"&&!n.credentials.some(o=>o.credentialId===n.selectedCredential.credentialId&&o.fingerprint===n.selectedCredential.fingerprint&&o.capability.status==="ready"))throw new Error("Managed SSH import response is inconsistent");return n},$W=()=>({managedSshCredentials:zW,configureTransportBinding:lW,removeTransportBinding:dW,configureAuxiliaryBinding:uW,checkIsGitRepository:oH,getGitStatus:aH,prefetchProjectStatuses:nH,getGitDiff:rH,getGitDiffs:cH,getGitFileDiff:hH,getGitRangeDiff:lH,getGitRangeFiles:uH,getBranchBase:pH,revertGitFile:gH,stageGitFile:mH,stageGitFiles:yk,unstageGitFile:fH,unstageGitFiles:vk,stageGitHunk:wH,unstageGitHunk:bH,revertGitHunk:yH,isLinkedWorktree:vH,getGitBranches:kH,getGitUnpushedBranchCounts:SH,deleteGitBranch:CH,removeRemote:TH,generateCommitMessage:AH,generatePullRequestDescription:PH,listGitWorktrees:Am,validateGitWorktree:Pm,createGitWorktree:Rm,deleteGitWorktree:Im,validateWorktreeDirectory:M1,canonicalizeWorktreeState:F1,createGitCommit(e,t,s){return BH(e,t,s)},gitPush:VH,gitPull:HH,gitFetch:WH,planNetworkOperation:GH,issueContributorDestination:zH,listContributorDestinations:$H,inspectCheckoutTrust:KH,decideCheckoutTrust:JH,executeNetworkOperation:YH,getNetworkOperation:XH,cancelNetworkOperation:QH,listGitStashes:ZH,countGitStashFiles:e1,stashGitChanges:Tk,applyGitStash:t1,popGitStash:Ak,dropGitStash:s1,checkoutBranch:n1,createBranch:o1,renameBranch:i1,getGitLog(e,t){return a1(e,t)},addChangeIdToHead:c1,getCommitFiles:l1,getCommitFileDiff:d1,getGitCommitDiff:dH,getCurrentGitIdentity:m1,hasLocalIdentity:f1,setGitIdentity:b1,getGitIdentities:u1,createGitIdentity:p1,updateGitIdentity:h1,deleteGitIdentity:g1,getGlobalGitIdentity:w1,getRemotes:y1,rebase:v1,abortRebase:k1,continueRebase:I1,merge:S1,abortMerge:R1,continueMerge:x1,checkoutCommit:C1,cherryPick:T1,revertCommit:A1,resetToCommit:P1,stash:E1,stashPop:O1,getConflictDetails:D1,worktree:{list:Am,validate:Pm,bootstrapStatus:RH,preview:IH,create:Rm,remove:Im,teardown:xH,setTitle:OH,setPinned:MH,snapshot:jH,archive:FH,listArchives:_H,restoreArchive:NH,deleteArchive:LH}});let Hm=null;const KW=()=>window.Capacitor,JW=e=>e.getPlatform?.()!=="android"||!e.registerPlugin?null:(Hm??=e.registerPlugin("FileShare"),Hm),YW=async e=>{const t=new Uint8Array(await e.arrayBuffer());let s="";for(let n=0;n<t.length;n+=32768)s+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(s)},XW=async e=>{const t=KW(),s=t?JW(t):null;if(s){await s.share({fileName:e.name,mimeType:e.type||"application/octet-stream",data:await YW(e)});return}if(!navigator.canShare?.({files:[e]}))throw new Error("File sharing is unavailable in this mobile runtime");await navigator.share({files:[e]})},Ae=e=>e.replace(/\\/g,"/"),QW=(e,t)=>et.searchFiles(e,t),ZW=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Lt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:Ae(t?.directory||t?.path||e),entries:t.entries.filter(n=>!!(n&&typeof n.name=="string"&&typeof n.path=="string")).map(n=>({name:n.name,path:Ae(n.path),isDirectory:!!n.isDirectory}))}},St=(e,t,s)=>{const n=e?.(),o=It(s),i=t||(o!==null&&It(n)!==o?Qf(o):n);return i?{"x-opencode-directory":i}:void 0},eq=d({matches:k(d({path:c(),relativePath:c(),line:y().int().positive(),column:y().int().positive(),text:c(),ranges:k(kr([y().int().nonnegative(),y().int().nonnegative()])),cutStart:v()})),stopped:T(["limit","deadline"]).nullable()}),tq=d({error:c().optional(),reason:c().optional()}),sq=d({files:k(d({path:c(),relativePath:c()}))}),nq=({getDirectory:e,searchFiles:t=QW})=>({async listDirectory(s,n){const o=Ae(s),i=new URLSearchParams;o&&i.set("path",o),n?.respectGitignore&&i.set("respectGitignore","true");const a=await P("/api/fs/list",{query:i,headers:St(e,void 0,o)});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Lt(l.error||"Failed to list directory",{reason:ki(l.reason),status:a.status})}const r=await a.json();return ZW(o,r)},async search(s){const n=Ae(s.directory),o=!!s.includeHidden,i=s.respectGitignore!==false;if(o||!i){const r=new URLSearchParams;r.set("query",s.query),n&&r.set("directory",n),typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)&&r.set("limit",String(s.maxResults)),o&&r.set("includeHidden","true"),i||r.set("respectGitignore","false");const l=await P("/api/fs/search",{query:r,signal:s.signal,headers:St(e,n)});if(!l.ok){const p=await l.json().catch(()=>({error:l.statusText}));throw new Error(p.error||"Failed to search files")}const u=sq.safeParse(await l.json().catch(()=>null));if(!u.success)throw new Lt("File search returned an invalid response",{reason:"invalid-response"});return u.data.files.map(p=>({path:Ae(p.path),preview:[Ae(p.relativePath)]}))}return(await t(s.query,{directory:n,limit:typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)?s.maxResults:void 0,type:"file"})).map(r=>({path:Ae(r.path),preview:[Ae(r.relativePath)]}))},async searchContents(s){const n=Ae(s.directory),o=new URLSearchParams({query:s.query,regex:s.regex?"true":"false"});s.limit!==void 0&&o.set("limit",String(s.limit)),s.includeHidden&&o.set("includeHidden","true"),s.respectGitignore===false&&o.set("respectGitignore","false");const i=await P("/api/fs/find-in-files",{query:o,cache:"no-store",signal:s.signal,headers:St(e,n)});if(i.ok){const l=eq.safeParse(await i.json().catch(()=>null));if(!l.success)throw new Lt("Content search returned an invalid response",{reason:"invalid-response"});return{status:"ok",matches:l.data.matches.map(u=>({...u,path:Ae(u.path)})),stopped:l.data.stopped}}const a=tq.safeParse(await i.json().catch(()=>null)),r=a.success?a.data.reason:void 0;if(i.status===501&&r==="search-unavailable")return{status:"unavailable"};if(i.status===400&&r==="invalid-pattern")return{status:"invalid-pattern",message:a.success&&a.data.error?a.data.error:"Invalid regular expression"};throw new Lt(a.success&&a.data.error||i.statusText||"Failed to search file contents",{status:i.status})},async createDirectory(s){const n=Ae(s),o=await P("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,n)},body:JSON.stringify({path:n})});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to create directory")}const i=await o.json();return{success:!!i?.success,path:typeof i?.path=="string"?Ae(i.path):n}},async statFile(s,n){const o=Ae(s),i=new URLSearchParams({path:o});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant);const a=await P("/api/fs/stat",{query:i,signal:AbortSignal.timeout(3e4),headers:St(e,n?.directory,o)});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Error(l.error||"Failed to stat file")}const r=await a.json().catch(()=>({}));return{path:typeof r.path=="string"?Ae(r.path):o,isFile:!!r.isFile,size:typeof r.size=="number"?r.size:0,mtimeMs:typeof r.mtimeMs=="number"?r.mtimeMs:void 0}},async readFile(s,n){const o=Ae(s),i=new URLSearchParams({path:o});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&i.set("optional","true");const a=await P("/api/fs/read",{query:i,signal:AbortSignal.timeout(3e4),cache:n?.optional||n?.fresh?"no-store":"default",headers:St(e,n?.directory,o)});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Error(l.error||"Failed to read file")}return{content:await a.text(),path:o}},async writeFile(s,n){const o=Ae(s),i=await P("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,o)},body:JSON.stringify({path:o,content:n})});if(!i.ok){const r=await i.json().catch(()=>({error:i.statusText}));throw new Error(r.error||"Failed to write file")}const a=await i.json().catch(()=>({}));return{success:!!a.success,path:typeof a.path=="string"?Ae(a.path):o}},async uploadFile(s,n,o){const i=Ae(s),a=await P("/api/fs/upload",{method:"POST",query:{path:i,overwrite:o?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...St(e,o?.directory,i)},body:n});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Lt(l.error||"Failed to upload file",{reason:ki(l.reason),status:a.status,maxBytes:l.maxBytes})}const r=await a.json().catch(()=>({}));return{success:!!r.success,path:r.path?Ae(r.path):i}},async delete(s){const n=Ae(s),o=await P("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,n)},body:JSON.stringify({path:n})});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to delete file")}return{success:!!(await o.json().catch(()=>({}))).success}},async rename(s,n){const o=await P("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,s)},body:JSON.stringify({oldPath:s,newPath:n})});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Lt(a.error||"Failed to rename file",{reason:ki(a.reason),status:o.status})}const i=await o.json().catch(()=>({}));return{success:!!i.success,path:i.path?Ae(i.path):n}},async revealPath(s){const n=await P("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,s)},body:JSON.stringify({path:Ae(s)})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(s,n){const o=Ae(s),i=new URLSearchParams({path:o,download:"true"});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant);const a=await P("/api/fs/raw",{query:i,headers:St(e,n?.directory,o)});if(!a.ok)throw new Error(`Download failed (${a.status})`);const r=await a.blob(),l=o.split("/").pop()||"file";if(window.Capacitor?.isNativePlatform?.()===true){await XW(new File([r],l,{type:r.type||"application/octet-stream"}));return}const p=URL.createObjectURL(r),h=document.createElement("a");h.href=p,h.download=l,document.body.appendChild(h),h.click(),document.body.removeChild(h),setTimeout(()=>URL.revokeObjectURL(p),100)}}),oq="/api/config/settings",Wm=()=>`${oq}?${Db}=${lc()}`,iq="/api/config/reload",qm=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},aq=()=>({async load(){const e=await P(Wm(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:qm(await e.json()),source:"web"}},async save(e){const t=await P(Wm(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to save settings")}return qm(await t.json())},async restartOpenCode(){const e=await P(iq,{method:"POST"});if(!e.ok){const t=await e.json().catch(()=>({error:e.statusText}));throw new Error(t.error||"Failed to restart OpenCode")}return{restarted:true}}}),rq=()=>({async requestDirectoryAccess(e){return{success:true,path:e.path}},async startAccessingDirectory(e){return{success:true}},async stopAccessingDirectory(e){return{success:true}}}),cq=d({type:g("openchamber:notification-navigation"),url:c().url(),expiresAt:y().finite()});let Ni=null;function Uk(e){if(!Ni)return false;try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin&&t.pathname===window.location.pathname&&Ni(t)}catch{return false}}function EJ(e){Ni=e;const t="serviceWorker"in navigator?navigator.serviceWorker:null,s=n=>{const o=cq.safeParse(n.data),i=n.ports[0];if(!(!o.success||!i))try{const a=n.origin===window.location.origin&&Date.now()<o.data.expiresAt&&Uk(o.data.url);i.postMessage(a)}catch{i.postMessage(false)}finally{i.close()}};return t?.addEventListener("message",s),()=>{t?.removeEventListener("message",s),Ni===e&&(Ni=null)}}const lq=1500,ru=5e3,dq="openchamber-notification-claim:",Li=new Map,uq=()=>typeof document>"u"?true:document.visibilityState==="visible"&&document.hasFocus(),pq=e=>{if(typeof e!="string")return null;const t=e.trim();return t?`/?session=${encodeURIComponent(t)}`:null},jk=e=>{const t=typeof e?.sessionId=="string"?e.sessionId.trim():"";if(!t)return;const s=pq(t);if(s)return{url:s,sessionId:t}},Bk=(e,t)=>{const s={body:e?.body,tag:e?.tag};return t&&(s.data=t),s},hq=e=>{try{if(typeof window>"u"||(typeof window.focus=="function"&&window.focus(),!e)||`${window.location.pathname}${window.location.search}`===e.url||Uk(e.url))return;window.location.assign(e.url)}catch{}},gq=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.trim()).join("|")},mq=e=>{for(const[t,s]of Li)e-s>ru&&Li.delete(t)},fq=e=>{const t=gq(e);if(!t)return true;const s=Date.now();mq(s);const n=Li.get(t)??0;if(s-n<ru)return false;try{if(typeof window<"u"&&window.localStorage){const o=`${dq}${t}`,i=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(i)&&s-i<ru)return Li.set(t,i),false;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(s))}}catch{}return Li.set(t,s),true},Vk=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(s=>{setTimeout(()=>s(null),lq)})])??e}catch{return e}},wq=async e=>{const t=await Vk();if(!t||typeof t.showNotification!="function")return false;try{const s=jk(e);return await t.showNotification(e?.title??"OpenChamber",Bk(e,s)),true}catch(s){return console.warn("Failed to send notification via service worker",s),false}},bq=async()=>{const e=await Vk();if(!e||!("pushManager"in e)||!e.pushManager)return false;try{return!!await e.pushManager.getSubscription()}catch{return false}},yq=async e=>{if(e?.requireHidden&&typeof document<"u"&&document.hasFocus())return true;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",e),false;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),false;if(!uq()&&await bq()||!fq(e))return true;try{if(await wq(e))return true;const t=jk(e),s=new Notification(e?.title??"OpenChamber",Bk(e,t));return s.onclick=n=>{n.preventDefault(),hq(t),s.close()},true}catch(t){return console.warn("Failed to send notification",t),false}},vq=async e=>{if(typeof window>"u")return false;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return false;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,runtimeKey:e?.runtimeKey,requireHidden:e?.requireHidden,showWhenFocused:e?.showWhenFocused}}),true}catch(s){return console.warn("Failed to send native notification (desktop)",s),false}},kq=()=>({async notifyAgentCompletion(e){return await vq(e)||await yq(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?true:typeof Notification<"u"?Notification.permission==="granted":false}),Zn=async(e,t)=>{try{const s=await P(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return s.ok?await s.json():null}catch{return null}},Sq=()=>({async getVapidPublicKey(){return Zn("/api/push/vapid-public-key")},async subscribe(e){return Zn("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return Zn("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return Zn("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:true})},async registerApnsToken(e){return Zn("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return Zn("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),Cq=new Set(kv),Tq=c().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!Cq.has(e),{message:"Reserved tracker id"}),Aq=e=>{try{return new RegExp(e),true}catch{return false}},Gm=c().min(1).max(2048).refine(Aq),Kt=v().catch(false),Pq=d({id:Tq,name:c().min(1).max(64),authMethods:k(c()).transform(e=>e.filter(t=>t==="oauth"||t==="token")),capabilities:d({multipleAccounts:Kt,stateUpdate:Kt,children:Kt,labels:Kt,priority:Kt,filters:d({people:Kt,priority:Kt}).catch({people:false,priority:false}),projectMapping:Kt,sessionComments:Kt,hostAccess:Kt}),stateFilters:k(c().min(1).max(32)).max(32),urlPatterns:k(d({host:c().min(1).max(256),path:Gm,query:d({name:c().min(1).max(64)}).optional().catch(void 0)}).nullable().catch(null)).max(8).transform(e=>e.filter(t=>t!==null)),identifierPattern:Gm}),Rq=k(Pq.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const n of e)!n||t.has(n.id)||(t.add(n.id),s.push(n));return s}),zm=new Map,OJ=e=>{const t=zm.get(e);if(t)return t;const s={id:e,name:e,authMethods:[],capabilities:{multipleAccounts:false,stateUpdate:false,children:false,labels:false,priority:false,filters:{people:false,priority:false},projectMapping:false,sessionComments:false,hostAccess:false},stateFilters:["open","all"],urlPatterns:[],identifierPattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$"};return zm.set(e,s),s},Iq=d({error:c()}),Hk=async(e,t)=>{const s=Iq.safeParse(await e.json().catch(()=>null));return new Error(s.success&&s.data.error.trim()||e.statusText||t)};async function Wk(e,t,s,n,o){const i=new Headers({Accept:"application/json"});s.body!==void 0&&i.set("Content-Type","application/json");const a=await e(t,{method:s.method,body:s.body,headers:i});if(!a.ok)throw await Hk(a,o);const r=n.safeParse(await a.json().catch(()=>null));if(!r.success)throw new Error(`${o}: unreadable answer`);return r.data}const Ze=c().trim().min(1),Rt=c().trim().nullish().catch(null).transform(e=>e||null),qk=T(["triage","backlog","todo","in-progress","done","canceled"]),xq=T(["none","urgent","high","medium","low"]),nn=e=>k(oe()).catch([]).transform(t=>t.flatMap(s=>{const n=e.safeParse(s);return n.success?[n.data]:[]})),Vp=d({name:Rt,avatarUrl:Rt}).nullish().catch(null).transform(e=>e&&(e.name||e.avatarUrl)?e:null),Eq=c().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null}),Oq=d({id:Rt,name:c().trim().catch(""),category:qk.nullable().catch(null)}).nullish().catch(null).transform(e=>e??null),Dq=d({total:y().int().positive(),done:y(),more:v().catch(false)}).nullish().catch(null).transform(e=>e?{...e,done:Math.min(Math.max(e.done,0),e.total)}:null),Gk={provider:Ze,id:Ze,identifier:Ze,title:Ze,url:Ze,state:Oq,priority:xq.nullish().catch(null),assignee:Vp.optional(),container:d({id:Ze,key:Rt,name:Ze}).nullish().catch(null),updatedAt:Rt.optional()},zk=d(Gk),$k=d({...Gk,labels:nn(d({id:Ze,name:Ze,color:Eq})).optional(),parent:zk.nullish().catch(null),progress:Dq.optional()}),Mq=$k,Fq=d({id:Ze,body:c().catch(""),createdAt:Rt,author:Vp}),_q=$k.extend({description:c().nullish().catch(null).transform(e=>e??null),comments:nn(Fq),children:nn(zk),childrenMore:v().catch(false)}),qo=d({connected:g(false)}).transform(()=>({connected:false})),Nq=L([qo,d({connected:g(true),items:nn(Mq),cursor:Rt,hasMore:v().catch(false)})]),$m=L([qo,d({connected:g(true),item:_q.nullish().catch(null).transform(e=>e??null)})]),Lq=d({id:Ze,name:Ze,category:qk.nullable().catch(null),position:y().catch(0)}),Uq=L([qo,d({connected:g(true),states:nn(Lq)})]),Ml=d({id:Ze,name:Rt,user:Vp.optional(),current:v().catch(false),authorizedAt:y().nullish().catch(null),status:T(["valid","invalid"]).optional().catch(void 0),invalidReason:c().trim().min(1).max(256).optional().catch(void 0),method:T(["oauth","token"]).optional().catch(void 0)}),Km=d({instance:c().trim().min(1).max(2048).nullable().catch(null),instances:L([d({kind:g("fixed"),origin:c().trim().min(1).max(2048)}),d({kind:g("user"),label:c().trim().min(1).max(64),placeholder:c().trim().min(1).max(256).optional()})]),hasClient:v().catch(false),redirectUri:c().trim().min(1).max(2048).nullable().catch(null)}),Jm=L([d({connected:g(false),accounts:nn(Ml).optional(),connect:Km.optional().catch(void 0)}),d({connected:g(true),account:Ml.nullish().catch(null),accounts:nn(Ml),connect:Km.optional().catch(void 0)})]),jq=["UNSUPPORTED","INSTANCE_REQUIRED","INSTANCE_MISMATCH","UNSUPPORTED_INSTANCE","TOKEN_REQUIRED","TOKEN_REFUSED","USERNAME_REQUIRED","USERNAME_INVALID","CLIENT_MISSING","CONNECT_SUPERSEDED","TRACKER_UNAVAILABLE"],Bq=d({error:c().optional(),code:c().optional()}),Ym=async e=>{if(e.ok)return{ok:true};const t=Bq.safeParse(await e.json().catch(()=>null));if(!t.success)return{ok:false,code:"failed",message:null};const s=T(jq).safeParse(t.data.code);return{ok:false,code:s.success?s.data:"failed",message:t.data.error?.trim()||null}},Vq=d({authorizationUrl:Ze,expiresIn:y().positive()}),Xm=L([qo,d({connected:g(true),defaultProjectPath:Rt,containers:nn(d({id:Ze,key:Rt,name:Ze,projectPath:Rt}))})]),Kr=d({sessionComments:v()}),Kk=L([qo,d({connected:g(true),posted:g(true),commentId:Rt}),d({connected:g(true),posted:g(false),skipped:T(["already-posted","issue-not-found","not-started","disabled","origin-not-public"])})]),Hq=new Map([["triage","triage"],["backlog","backlog"],["unstarted","todo"],["started","in-progress"],["completed","done"],["canceled","canceled"],["duplicate","canceled"]]),Jk=e=>e?Hq.get(e)??null:null,Wq=new Map([["linear","linear"]]),DJ=e=>Wq.get(e)??"tracker",Yk={id:"linear",name:"Linear",authMethods:["oauth"],capabilities:{multipleAccounts:true,stateUpdate:true,children:true,labels:true,priority:true,filters:{people:true,priority:true},projectMapping:true,sessionComments:true,hostAccess:true},stateFilters:["open","all","backlog","todo","in-progress","inReview","done","canceled","duplicate"],urlPatterns:[{host:"linear.app",path:"^/[^/]+/issue/([A-Za-z][A-Za-z0-9]*-\\d+)(?:/|$)"}],identifierPattern:"^[A-Za-z][A-Za-z0-9]*-\\d+$"},qq=["none","urgent","high","medium","low"],Gq=new Map([["in-progress","started"],["done","completed"]]),tt=c().trim().min(1),st=c().trim().nullish().catch(null).transform(e=>e||null),Rn=e=>k(oe()).catch([]).transform(t=>t.flatMap(s=>{const n=e.safeParse(s);return n.success?[n.data]:[]})),Tc=d({name:st,displayName:st,avatarUrl:st}).nullish().catch(null).transform(e=>{const t=e?.displayName||e?.name||null,s=e?.avatarUrl??null;return t||s?{name:t,avatarUrl:s}:null}),zq=d({id:st,name:st,type:st}).nullish().catch(null).transform(e=>e&&(e.id||e.name||e.type)?{id:e.id,name:e.name??"",category:Jk(e.type)}:null),Xk={id:tt,identifier:tt,title:tt,url:tt,state:zq,assignee:Tc,team:d({id:tt,key:st,name:tt}).nullish().catch(null),priority:y().int().nullish().catch(null),updatedAt:st},cu=(e,t)=>({provider:t,id:e.id,identifier:e.identifier,title:e.title,url:e.url,state:e.state,priority:e.priority!=null?qq[e.priority]??null:null,assignee:e.assignee,container:e.team?{id:e.team.id,key:e.team.key,name:e.team.name}:null,updatedAt:e.updatedAt}),Qk=d(Xk),Zk=d({...Xk,labels:Rn(d({id:tt,name:tt,color:c().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null})})),parent:Qk.nullish().catch(null),subIssueProgress:d({total:y().int().positive(),done:y(),more:v().catch(false)}).nullish().catch(null)}),eS=(e,t)=>({...cu(e,t),labels:e.labels,parent:e.parent?cu(e.parent,t):null,progress:e.subIssueProgress?{...e.subIssueProgress,done:Math.min(Math.max(e.subIssueProgress.done,0),e.subIssueProgress.total)}:null}),$q=Zk.extend({description:c().nullish().catch(null),comments:Rn(d({id:tt,body:c().catch(""),createdAt:st,user:Tc})),subIssues:Rn(Qk),subIssuesMore:v().catch(false)}),Kq=(e,t)=>({...eS(e,t),description:e.description??null,comments:e.comments.map(s=>({id:s.id,body:s.body,createdAt:s.createdAt,author:s.user})),children:e.subIssues.map(s=>cu(s,t)),childrenMore:e.subIssuesMore}),Jq=d({id:tt,name:st,current:v().catch(false),user:Tc,authorizedAt:y().nullish().catch(null)}),Qm=d({connected:v(),user:Tc,organization:d({id:tt,name:st}).nullish().catch(null),workspaces:Rn(Jq)}).transform(e=>{if(!e.connected)return{connected:false};const t=[...e.workspaces];return t.length===0&&e.organization&&t.push({id:e.organization.id,name:e.organization.name,user:e.user,current:true,authorizedAt:null}),{connected:true,account:t.find(s=>s.current)??null,accounts:t}}),Yq=e=>{const t=new URLSearchParams,s=(i,a)=>{const r=a?.trim();r&&t.set(i,r)},n=e?.state?.trim();s("query",e?.query),s("cursor",e?.cursor),s("status",n?Gq.get(n)??n:void 0),s("assignee",e?.people),s("teamId",e?.containerId),s("priority",e?.priority);const o=t.toString();return o?`?${o}`:""},Xq=e=>{const t=async(a,r,l,u,p)=>{if(a!==Yk.id)throw new Error(`Unknown tracker: ${a}`);return Wk(e,`/api/linear${r}`,l,u,p)},s={method:"GET"},n=a=>L([qo,a]),o=a=>n(d({connected:g(true),issue:$q.nullish().catch(null)}).transform(({issue:r})=>({connected:true,item:r?Kq(r,a):null}))),i=n(d({connected:g(true),defaultProjectPath:st,teams:Rn(d({id:tt,key:st,name:tt,projectPath:st}))}).transform(({defaultProjectPath:a,teams:r})=>({connected:true,defaultProjectPath:a,containers:r})));return{authStatus:a=>t(a,"/auth/status",s,Qm,"Failed to load Linear status"),authStart:(a,r)=>t(a,"/auth/start",{method:"POST",body:JSON.stringify({origin:r})},d({authorizationUrl:tt,expiresIn:y().positive()}),"Failed to start Linear auth"),authConnectToken:async()=>({ok:false,code:"UNSUPPORTED",message:null}),authSaveOAuthClient:async()=>({ok:false,code:"UNSUPPORTED",message:null}),authDisconnect:a=>t(a,"/auth",{method:"DELETE"},d({removed:v().catch(false)}),"Failed to disconnect Linear").then(({removed:r})=>({removed:r})),authActivate:(a,r)=>t(a,"/auth/activate",{method:"POST",body:JSON.stringify({organizationId:r})},Qm,"Failed to switch Linear workspace"),list:(a,r)=>t(a,`/issues/list${Yq(r)}`,s,n(d({connected:g(true),issues:Rn(Zk),cursor:st,hasMore:v().catch(false)}).transform(({issues:l,cursor:u,hasMore:p})=>({connected:true,items:l.map(h=>eS(h,a)),cursor:u,hasMore:p}))),"Failed to load Linear issues"),refreshListReads:async a=>{await t(a,"/read-cache/refresh?scope=lists",{method:"POST"},oe(),"Failed to refresh Linear lists")},get:(a,r)=>t(a,`/issues/get?${new URLSearchParams({id:r}).toString()}`,s,o(a),"Failed to load Linear issue"),states:(a,r)=>t(a,`/issues/states?${new URLSearchParams({teamId:r}).toString()}`,s,n(d({connected:g(true),states:Rn(d({id:tt,name:tt,type:st,position:y().catch(0)}).transform(({id:l,name:u,type:p,position:h})=>({id:l,name:u,category:Jk(p),position:h})))})),"Failed to load Linear workflow states"),updateState:(a,r)=>t(a,"/issues/update",{method:"POST",body:JSON.stringify({id:r.id,stateId:r.stateId})},o(a),"Failed to update Linear issue"),mappingGet:a=>t(a,"/mapping",s,i,"Failed to load Linear mapping"),mappingSet:(a,r)=>t(a,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:r.defaultProjectPath,teamProjectPaths:r.containerProjectPaths})},i,"Failed to save Linear mapping"),sessionStatusPost:(a,r)=>t(a,"/session-status",{method:"POST",body:JSON.stringify({kind:r.kind,sessionId:r.sessionId,issueIdentifier:r.identifier,sessionOrigin:r.sessionOrigin})},Kk,"Failed to post Linear session status"),preferencesGet:a=>t(a,"/preferences",s,Kr,"Failed to load Linear preferences"),preferencesSet:(a,r)=>t(a,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:r.sessionComments})},Kr,"Failed to save Linear preferences")}},Qq=d({providers:k(oe())}),Zq=e=>{const t=e?.split(";")[0]?.trim().toLowerCase()??"";return t==="application/json"||t.endsWith("+json")};async function eG(e){const t=await e("/api/tracker/providers",{headers:{Accept:"application/json"}});if(t.status===404)return{kind:"legacy-linear"};if(!t.ok)throw await Hk(t,"Failed to load trackers");if(!Zq(t.headers.get("content-type")))return{kind:"legacy-linear"};const s=Qq.parse(await t.json().catch(()=>null)).providers,n=Rq.parse(s);if(s.length>0&&n.length===0)throw new Error("Trackers response contained no readable tracker");return{kind:"tracker",descriptors:n}}const Fl=(e,t)=>`/api/tracker/${encodeURIComponent(e)}${t}`,tG=({fetch:e=P,runtimeKey:t=F}={})=>{const s=Xq(e);let n=null;const o=()=>{const u=eG(e),p={runtimeKey:t(),request:u};return n=p,u.catch(()=>{n===p&&(n=null)}),u},i=async()=>(await((n?.runtimeKey===t()?n.request:null)??o())).kind==="legacy-linear",a=(u,p,h,m,w)=>Wk(e,Fl(u,p),h,m,w),r={method:"GET"},l=u=>{const p=new URLSearchParams,h=(w,b)=>{const S=b?.trim();S&&p.set(w,S)};h("query",u?.query),h("cursor",u?.cursor),h("state",u?.state),h("people",u?.people),h("priority",u?.priority),h("containerId",u?.containerId);const m=p.toString();return m?`?${m}`:""};return{async providers(){const u=await o();return u.kind==="legacy-linear"?[Yk]:u.descriptors},async authStatus(u){return await i()?s.authStatus(u):a(u,"/auth/status",r,Jm,"Failed to load tracker status")},async authStart(u,p,h){if(await i())return s.authStart(u,p);const m=h?.instance?{origin:p,instance:h.instance}:{origin:p};return a(u,"/auth/start",{method:"POST",body:JSON.stringify(m)},Vq,"Failed to start tracker sign-in")},async authConnectToken(u,p){if(await i())return s.authConnectToken(u,p);try{const h=await e(Fl(u,"/auth/token"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(p)});return await Ym(h)}catch{return{ok:false,code:"failed",message:null}}},async authSaveOAuthClient(u,p){if(await i())return s.authSaveOAuthClient(u,p);try{const h=await e(Fl(u,"/auth/oauth-client"),{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(p)});return await Ym(h)}catch{return{ok:false,code:"failed",message:null}}},async authDisconnect(u){return await i()?s.authDisconnect(u):a(u,"/auth",{method:"DELETE"},d({removed:v().catch(false)}),"Failed to disconnect tracker").then(({removed:p})=>({removed:p}))},async authActivate(u,p){return await i()?s.authActivate(u,p):a(u,"/auth/activate",{method:"POST",body:JSON.stringify({accountId:p})},Jm,"Failed to switch tracker account")},async list(u,p){return await i()?s.list(u,p):a(u,`/items/list${l(p)}`,r,Nq,"Failed to load tracker items")},async refreshListReads(u){if(await i())return s.refreshListReads(u);await a(u,"/read-cache/refresh?scope=lists",{method:"POST"},oe(),"Failed to refresh tracker lists")},async get(u,p){return await i()?s.get(u,p):a(u,`/items/get?${new URLSearchParams({id:p}).toString()}`,r,$m,"Failed to load tracker item")},async states(u,p){return await i()?s.states(u,p):a(u,`/states?${new URLSearchParams({containerId:p}).toString()}`,r,Uq,"Failed to load workflow states")},async updateState(u,p){return await i()?s.updateState(u,p):a(u,"/items/update",{method:"POST",body:JSON.stringify({id:p.id,stateId:p.stateId})},$m,"Failed to update tracker item")},async mappingGet(u){return await i()?s.mappingGet(u):a(u,"/mapping",r,Xm,"Failed to load project mapping")},async mappingSet(u,p){return await i()?s.mappingSet(u,p):a(u,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:p.defaultProjectPath,containerProjectPaths:p.containerProjectPaths})},Xm,"Failed to save project mapping")},async sessionStatusPost(u,p){return await i()?s.sessionStatusPost(u,p):a(u,"/session-status",{method:"POST",body:JSON.stringify({kind:p.kind,sessionId:p.sessionId,identifier:p.identifier,sessionOrigin:p.sessionOrigin})},Kk,"Failed to post session status")},async preferencesGet(u){return await i()?s.preferencesGet(u):a(u,"/preferences",r,Kr,"Failed to load tracker preferences")},async preferencesSet(u,p){return await i()?s.preferencesSet(u,p):a(u,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:p.sessionComments})},Kr,"Failed to save tracker preferences")}}},Us=async e=>await e.json().catch(()=>null),sG=d({identityConflict:v().catch(false)}),Zm=async(e,t)=>{const s=await P(e,{method:t,headers:{Accept:"application/json"}}),n=await s.json().catch(()=>null),o=sG.safeParse(n);if(!s.ok||!o.success)throw new Error(s.statusText||"Failed to read relay status");return o.data},nG=()=>({async listClients(){const e=await P("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load remote clients");return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){const t=await P("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),s=await Us(t);if(!t.ok||!s?.client||typeof s.token!="string")throw new Error(s?.error||t.statusText||"Failed to create remote client token");return s},async createPairingSession(e={}){const t=await P("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),s=await Us(t);if(!t.ok||typeof s?.pairing?.secret!="string"||!s?.server)throw new Error(s?.error||t.statusText||"Failed to create pairing session");return s},async listPendingPairings(){const e=await P("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pending pairings");return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){const e=await P("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pairing transports");return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable!==false}},async cancelPairing(e){const t=await P(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Us(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to cancel pairing");return{cancelled:s.cancelled===true}},async revokeClient(e){const t=await P(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Us(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to revoke remote client");return s},getRelayHostStatus:()=>Zm("/api/openchamber/relay/status","GET"),resetRelayIdentity:()=>Zm("/api/openchamber/relay/reset-identity","POST"),async purgeRevokedClients(){const e=await P("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),oG=(e={})=>{const t=e.urls??uu();return gC(t),{clipboard:CC(),themeFiles:TC(),runtime:{platform:"web",isDesktop:false,isVSCode:false,label:"web"},terminal:sV(),git:$W(),files:nq({getDirectory:()=>Tp.getState().currentDirectory}),settings:aq(),permissions:rq(),notifications:kq(),sourceControl:VW(),trackers:tG(),push:Sq(),clientAuth:nG()}},iG=3e3,ef=(e,t)=>{if(!e||!t)return false;try{return new URL(e).origin===new URL(t).origin}catch{return false}},aG=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__OPENCHAMBER_API_BASE_URL__),clientToken:e(window.__OPENCHAMBER_CLIENT_TOKEN__),localOrigin:e(window.__OPENCHAMBER_LOCAL_ORIGIN__),runtimeHeaders:window.__OPENCHAMBER_RUNTIME_HEADERS__,relayHostId:e(window.__OPENCHAMBER_RELAY_HOST_ID__),explicitRuntime:window.__OPENCHAMBER_EXPLICIT_RUNTIME__===true}};let lu=Promise.resolve();const MJ=()=>lu,FJ=()=>{const{apiBaseUrl:e,clientToken:t,localOrigin:s,runtimeHeaders:n,relayHostId:o,explicitRuntime:i}=aG(),a=Sf(),r=o||(a?.target==="remote"?a.hostId:""),l=Tf({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});bC({apiBaseUrl:e,runtimeKey:ef(e,s)?"local":r?`host:${r}`:null});const u=h=>{const m=h.trim(),w=window.__OPENCHAMBER_DESKTOP__?.invoke;!m||!w||w("desktop_set_window_runtime_key",{runtimeKey:m}).catch(()=>{})};u(F()),Qr(h=>u(h.runtimeKey)),Vf(t||null),Hf(n||null),et.reconnectToRuntimeBaseUrl(),tc(e||void 0).catch(()=>{}),s&&!ef(e,s)&&Object.keys(_o()).length>0&&Kf(s).catch(()=>{}),aw();const p=()=>o?dh(o,{reconnectActive:true}):i?Promise.resolve():dh();return lu=Promise.race([p().catch(()=>{}),new Promise(h=>{window.setTimeout(h,1e4)})]).then(()=>{et.reconnectToRuntimeBaseUrl()}),lu.then(()=>{window.setTimeout(()=>{aA().catch(()=>{})},iG)}),oG({urls:l})},tf="openchamber:chunk-import-reload",rG=250,cG=3e4,lG=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function tS(e){if(e instanceof Error)return`${e.name}
|
|
87
|
+
${A.documentElement.outerHTML}`;if(z.length>im)throw new Error("Extension document exceeds the size limit");return z},b=await u(i);if(b.type.split(";")[0]!=="text/html")throw new Error("Extension entry is not HTML");return w(await b.text(),i,[i.href])},yU=200,vU=/^image\/(?:png|jpeg|webp|gif)\b/,Ht=new Map,kU=(e,t)=>[os()||"same-origin",e,t].join("|"),SU=()=>{for(;Ht.size>yU;){const e=Ht.keys().next().value;if(typeof e!="string")return;const t=Ht.get(e);t?.url&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(t.url),Ht.delete(e)}},CU=(e,t,s)=>{const n=Ht.get(e);if(n?.url)return Promise.resolve(n.url);if(n?.promise)return n.promise;const o=P(t,{method:"GET",headers:{Accept:"image/*"},query:new URLSearchParams(s)}).then(async i=>{if(!i.ok||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;const a=await i.blob(),r=vU.test(a.type)?URL.createObjectURL(a):await fr(a);return Ht.set(e,{url:r}),SU(),r}).catch(()=>null).finally(()=>{const i=Ht.get(e);i?.promise===o&&!i.url&&Ht.delete(e)});return Ht.set(e,{promise:o}),o},TU=(e,t)=>{const s=yt.c(10);let n;s[0]!==e||s[1]!==t?(n=e?kU(e,t):null,s[0]=e,s[1]=t,s[2]=n):n=s[2];const o=n;let i;s[3]!==o?(i=()=>({url:o?Ht.get(o)?.url??null:null,failed:false}),s[3]=o,s[4]=i):i=s[4];const[a,r]=sn.useState(i);let l,u;return s[5]!==o||s[6]!==e||s[7]!==t?(l=()=>{const p=(w,b)=>r(S=>S.url===w&&S.failed===b?S:{url:w,failed:b});if(!o||!e){p(null,false);return}const h=Ht.get(o)?.url;if(h){p(h,false);return}let m=false;return p(null,false),CU(o,e,t).then(w=>{m||p(w,w===null)}),()=>{m=true}},u=[o,e,t],s[5]=o,s[6]=e,s[7]=t,s[8]=l,s[9]=u):(l=s[8],u=s[9]),sn.useEffect(l,u),a},AU=["image/png","image/jpeg","image/webp","image/svg+xml"],PU=1024*1024,Mv=T(AU),Fv=d({mime:Mv,updatedAt:y().int().positive()}),X4=()=>!Ne(),wp=e=>`/api/provider/${encodeURIComponent(e)}/logo`,RU=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["webp","image/webp"],["svg","image/svg+xml"]]),_v=e=>Mv.safeParse(e.type.trim().toLowerCase()).data??RU.get(e.name.toLowerCase().split(".").pop()??"")??null,Q4=e=>_v(e)?e.size<=0||e.size>PU?"size":null:"type",IU=(e,t)=>new Promise((s,n)=>{const o=new FileReader;o.onload=()=>{const i=c().safeParse(o.result);i.success?s(i.data.replace(/^data:[^;,]*;/i,`data:${t};`)):n(new Error("Could not read the file"))},o.onerror=()=>n(o.error??new Error("Could not read the file")),o.readAsDataURL(e)}),Nv=async e=>{const t=await e.json().catch(()=>null),s=d({error:c()}).safeParse(t).data?.error;return new Error(s??`HTTP ${e.status}`)},Z4=async(e,t)=>{const s=_v(t);if(!s)throw new Error("Logo must be PNG, JPEG, WebP or SVG");const n=await P(wp(e),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:await IU(t,s)})});if(!n.ok)throw await Nv(n);const o=d({logo:Fv}).safeParse(await n.json().catch(()=>null));if(!o.success)throw new Error("Unexpected response");return o.data.logo},eJ=async e=>{const t=await P(wp(e),{method:"DELETE",headers:{Accept:"application/json"}});if(!t.ok)throw await Nv(t)},tJ=(e,t,s)=>{const n=yt.c(6);let o;n[0]!==t||n[1]!==e?(o=t?wp(e):null,n[0]=t,n[1]=e,n[2]=o):o=n[2];const i=o;let a;return n[3]!==t||n[4]!==s?(a=t?new URLSearchParams(t.mime==="image/svg+xml"?{v:String(t.updatedAt),theme:s}:{v:String(t.updatedAt)}).toString():"",n[3]=t,n[4]=s,n[5]=a):a=n[5],TU(i,a)},xU=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const s=new TextEncoder().encode(t);let n="";for(const i of s)n+=String.fromCharCode(i);return`path_${typeof btoa=="function"?btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},sJ=e=>{if(!e.startsWith("path_"))return"";const t=e.slice(5);if(!t||!/^[A-Za-z0-9_-]+$/.test(t))return"";try{const s=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(s,n=>n.charCodeAt(0)))}catch{return""}},G=e=>t=>{const s=e.safeParse(t);return s.success?s.data:void 0},Bo=y().refine(Number.isFinite),ut=c().transform(e=>e.trim()),Fe=ut.pipe(c().min(1)),is=be(c(),oe()),O=G(v()),Be=G(c().min(1)),to=G(ut),wn=G(Fe),Kn=e=>G(c().max(e)),Jn=e=>G(ut.transform(t=>t.slice(0,e))),ue=e=>G(ut.pipe(T(e))),_s=G(Bo),Xa=(e,t)=>G(Bo.transform(s=>Math.max(e,Math.min(t,Math.round(s))))),yl=e=>G(Bo.transform(t=>Math.max(e,Math.round(t)))),EU=G(Bo.positive().transform(Math.floor)),OU=G(L([Ps(),Bo])),DU=G(L([Ps(),ut.transform(e=>e.length>0?e:null)])),MU=G(L([Ps(),ut])),bp=k(oe()).transform(e=>e.filter(t=>c().min(1).safeParse(t).success)),Yn=G(bp.transform(e=>Array.from(new Set(e.map(String))))),vl=G(bp.transform(e=>e.map(String))),FU=is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=k(oe()).safeParse(n);o.success&&(t[s]=o.data.filter(i=>c().safeParse(i).success).map(String))}return t}),kl=G(FU.pipe(be(c(),k(c())).refine(e=>Object.keys(e).length>0))),_U=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[s,n]of Object.entries(e)){const o=s.trim();o&&hU(n)&&(t[o]=n)}return t},NU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=Fv.safeParse(n);o&&i.success&&(t[o]=i.data)}return t})),LU=d({providerID:Fe,modelID:Fe}),Sl=e=>G(k(oe()).transform(t=>{const s=[],n=new Set;for(const o of t){const i=LU.safeParse(o);if(!i.success)continue;const a=`${i.data.providerID}/${i.data.modelID}`;if(!n.has(a)&&(n.add(a),s.push(i.data),s.length>=e))break}return s})),UU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){if(!s)continue;const o=bp.safeParse(n);if(!o.success)continue;const i=Array.from(new Set(o.data.map(String)));i.length>0&&(t[s]=i.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),jU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim();if(!o)continue;if(n===null){t[o]=null;continue}const i=Fe.safeParse(n);i.success&&(t[o]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),BU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=Fe.safeParse(n);!o||!i.success||(t[o]=i.data)}return t})),Qa={completion:{title:"Task Complete",message:"Your task has finished."},error:{title:"Error Occurred",message:"An error occurred while processing your task."},question:{title:"Input Needed",message:"Please provide input to continue."},subtask:{title:"Subtask Complete",message:"A subtask has finished."}},VU=d({title:c().catch(""),message:c().catch("")}),HU=G(is.transform(e=>{const t=a=>{const r=VU.safeParse(e[a]);return r.success?r.data:void 0},s=t("completion"),n=t("error"),o=t("question"),i=t("subtask");if(!(!s&&!n&&!o&&!i))return{completion:s??Qa.completion,error:n??Qa.error,question:o??Qa.question,subtask:i??Qa.subtask}}).pipe(Jr(e=>e!==void 0))),am=is.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,s])=>{const n=c().safeParse(s);return n.success?[[t,n.data]]:[]}))),WU=d({id:oe().transform(e=>String(e??"")),label:oe().transform(e=>String(e??"")),models:k(oe()).transform(e=>e.filter(t=>c().safeParse(t).success).map(String)).catch([]),order:y().catch(0)}),qU=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=is.safeParse(n);if(!o.success)continue;const i={},a=k(oe()).safeParse(o.data.customGroups);a.success&&(i.customGroups=a.data.flatMap(u=>{const p=WU.safeParse(u);return p.success?[p.data]:[]}));const r=am.safeParse(o.data.modelAssignments);r.success&&(i.modelAssignments=r.data);const l=am.safeParse(o.data.renamedGroups);l.success&&(i.renamedGroups=l.data),Object.keys(i).length>0&&(t[s]=i)}return t}).refine(e=>Object.keys(e).length>0)),GU=d({id:Fe,name:Fe,hostname:Fe.transform(e=>e.toLowerCase())}),zU=G(k(oe()).transform(e=>{const t=[],s=new Set,n=new Set;for(const o of e){const i=GU.safeParse(o);i.success&&(s.has(i.data.id)||n.has(i.data.hostname)||(s.add(i.data.id),n.add(i.data.hostname),t.push(i.data)))}return t})),$U=G(is.transform(e=>{const t={};for(const[s,n]of Object.entries(e)){const o=s.trim(),i=Fe.safeParse(n);!o||!i.success||(t[o]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),KU=d({id:Fe,label:Fe,source:Fe,subpath:ut.optional().catch(void 0),gitIdentityId:ut.optional().catch(void 0)}),JU=G(k(oe()).transform(e=>{const t=[],s=new Set;for(const n of e){const o=KU.safeParse(n);if(!o.success||s.has(o.data.id))continue;s.add(o.data.id);const i={id:o.data.id,label:o.data.label,source:o.data.source};o.data.subpath&&(i.subpath=o.data.subpath),o.data.gitIdentityId&&(i.gitIdentityId=o.data.gitIdentityId),t.push(i)}return t})),YU=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Cl=Bo.nonnegative(),XU=d({path:Fe,label:Fe.optional().catch(void 0),labelSource:T(["auto","manual"]).optional().catch(void 0),icon:Fe.optional().catch(void 0),iconImage:L([Ps(),d({mime:Fe,updatedAt:Cl.transform(Math.round).pipe(y().positive()),source:T(["custom","auto"])})]).optional().catch(void 0),color:Fe.optional().catch(void 0),iconBackground:L([Ps(),ut.pipe(c().regex(YU)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:Cl.optional().catch(void 0),lastOpenedAt:Cl.optional().catch(void 0),sidebarCollapsed:v().optional().catch(void 0),defaultModel:Fe.optional().catch(void 0),defaultAgent:Fe.optional().catch(void 0),defaultVariant:Fe.optional().catch(void 0)}),QU=G(k(oe()).transform(e=>{const t=[],s=new Set,n=new Set;for(const o of e){const i=XU.safeParse(o);if(!i.success)continue;const a=Oe(i.data.path);if(!a)continue;const r=xU(a);if(!r||s.has(r)||n.has(a))continue;s.add(r),n.add(a);const l={id:r,path:a};i.data.label&&(l.label=i.data.label),i.data.label&&i.data.labelSource&&(l.labelSource=i.data.labelSource),i.data.icon&&(l.icon=i.data.icon),i.data.iconImage!==void 0&&(l.iconImage=i.data.iconImage),i.data.color&&(l.color=i.data.color),i.data.iconBackground!==void 0&&(l.iconBackground=i.data.iconBackground),i.data.addedAt!==void 0&&(l.addedAt=i.data.addedAt),i.data.lastOpenedAt!==void 0&&(l.lastOpenedAt=i.data.lastOpenedAt),i.data.defaultModel&&(l.defaultModel=i.data.defaultModel),i.data.defaultAgent&&(l.defaultAgent=i.data.defaultAgent),i.data.defaultVariant&&(l.defaultVariant=i.data.defaultVariant),i.data.sidebarCollapsed!==void 0&&(l.sidebarCollapsed=i.data.sidebarCollapsed),t.push(l)}return t}).refine(e=>e.length>0)),ZU=T(["steer","queue"]),ej=(e,t)=>{const s=ZU.safeParse(e);if(s.success)return s.data;if(e==="immediate")return"steer";const n=v().safeParse(t.queueModeEnabled);if(n.success)return n.data?"queue":"steer"},tj=T(["default","wider","full"]),sj=(e,t)=>{const s=tj.safeParse(e);if(s.success)return s.data;const n=v().safeParse(t.wideChatLayoutEnabled);if(n.success)return n.data?"full":"default"},nj=ut.pipe(T(["collapsed","summary"])),oj=(e,t)=>{if(t.chatRenderMode==="sorted")return"collapsed";const s=nj.safeParse(e);return s.success?s.data:void 0},ij=G(ut.pipe(T(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),aj=G(ut.pipe(T(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),rj=G(ut.transform(e=>e.replace(/\s+/g," ").slice(0,64))),cj=e=>G(k(oe()).transform(t=>{const s=[];for(const n of t){const o=ut.transform(i=>i.toLowerCase()).safeParse(n);o.success&&e(o.data)&&!s.includes(o.data)&&s.push(o.data)}return s})),yp=e=>G(Jr(e)),Zi=(e,t)=>(s,n)=>{const o=e(s,n);return o===void 0?void 0:t(o)},f=e=>e,R=(e,t,s={})=>({read:()=>I.getState()[e],write:t,autoSave:s.autoSave??true}),kt=e=>t=>{I.setState({[e]:t})},rm=()=>globalThis.window?.__zustand_config_store__??null,$t=e=>({read:()=>rm()?.getState()[e],write:t=>{rm()?.setState({[e]:t})},autoSave:false}),ft=e=>({read:()=>Ut.getState()[e],write:t=>{Ut.setState({[e]:t})},autoSave:false}),lj=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],dj=yp(Xu),uj=yp(ex),pj=yp(tx),hj=G(c().refine(sy)),gj=G(y().refine(Yu)),mj=Zi(to,e=>ic(e,void 0)),fj=Zi(G(k(oe())),nO),wj=Zi(G(k(oe())),e=>kb(e)),bj=ue(["ask","attach","inline","inline-double-paste"]),yj=ue(["default","vim"]),vj=(e,t)=>{let s=e;const n=(o,i)=>{if(s.some(l=>l.type==="command"&&l.name===o))return;const a=s.findIndex(l=>l.type==="command"&&l.name===i),r=a>=0?a+1:s.length;s=[...s.slice(0,r),{type:"command",name:o},...s.slice(r)]};return t.draftStartersCraftGoalAdded!==true&&n("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==true&&n("schedule-task","craft-goal"),s},pa={themeId:f({scope:"profile",perSurface:true,parse:Be}),useSystemTheme:f({scope:"profile",perSurface:true,parse:O}),themeVariant:f({scope:"profile",derived:true,parse:ue(["light","dark"])}),lightThemeId:f({scope:"profile",perSurface:true,parse:Be}),darkThemeId:f({scope:"profile",perSurface:true,parse:Be}),locale:f({scope:"profile",parse:ue(rO),ui:{read:()=>Ur.getState().locale,write:e=>Ur.getState().setLocale(e),autoSave:false}}),lastDirectory:f({scope:"instance",adopt:"bootstrap-only",parse:Be}),homeDirectory:f({scope:"instance",parse:Be}),opencodeBinary:f({scope:"instance",parse:to}),serverUpdateChannel:f({scope:"instance",surfaces:["web"],parse:ue(["stable","canary"])}),projects:f({scope:"instance",parse:QU}),activeProjectId:f({scope:"instance",adopt:"bootstrap-only",parse:Be}),securityScopedBookmarks:f({scope:"instance",surfaces:["desktop"],parse:vl}),pinnedDirectories:f({scope:"instance",parse:Yn}),desktopLanAccessEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopKeepAwakeEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopMinimizeToTrayEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopUpdateChannel:f({scope:"instance",surfaces:["desktop"],parse:ue(["stable","canary"])}),desktopMacMenuBarEnabled:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopLinuxNativeFrame:f({scope:"instance",surfaces:["desktop"],parse:O}),desktopUiPassword:f({scope:"instance",secret:true,surfaces:["desktop"],parse:to}),hasDesktopUiPassword:f({scope:"instance",computed:true,surfaces:["desktop"],parse:O}),desktopLanAccessActive:f({scope:"instance",computed:true,surfaces:["desktop"],parse:O}),desktopLanAccessBlockedReason:f({scope:"instance",computed:true,surfaces:["desktop"],parse:to}),githubClientId:f({scope:"instance",parse:wn}),githubScopes:f({scope:"instance",parse:wn}),gitlabClientId:f({scope:"instance",parse:wn}),skillCatalogs:f({scope:"instance",parse:JU}),defaultGitIdentityId:f({scope:"instance",parse:to}),permissionAutoAccept:f({scope:"instance",parse:G(d({sessions:be(c().min(1),L([v(),T(["ask","safety","auto"])])).catch({}),revision:y().int().nonnegative().catch(0)}))}),permissionDefaultMode:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:G(T(["ask","safety","auto"])),ui:R("permissionDefaultMode",e=>I.getState().setPermissionDefaultMode(e))}),messageSearchEnabled:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:O,ui:R("messageSearchEnabled",e=>I.getState().setMessageSearchEnabled(e))}),messageSearchReasoningEnabled:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:O,ui:R("messageSearchReasoningEnabled",e=>I.getState().setMessageSearchReasoningEnabled(e))}),agentControlToolEnabled:f({scope:"instance",parse:O,ui:R("agentControlToolEnabled",e=>I.getState().setAgentControlToolEnabled(e))}),agentScheduleToolEnabled:f({scope:"instance",parse:O,ui:R("agentScheduleToolEnabled",e=>I.getState().setAgentScheduleToolEnabled(e))}),agentWebToolEnabled:f({scope:"instance",parse:O,ui:R("agentWebToolEnabled",e=>I.getState().setAgentWebToolEnabled(e))}),browserProvider:f({scope:"instance",parse:Be,ui:R("browserProvider",e=>I.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:f({scope:"instance",parse:O,ui:R("agentNotifyToolEnabled",e=>I.getState().setAgentNotifyToolEnabled(e))}),agentRenderToolEnabled:f({scope:"instance",parse:O,ui:R("agentRenderToolEnabled",e=>I.getState().setAgentRenderToolEnabled(e))}),agentUsageToolEnabled:f({scope:"instance",parse:O,ui:R("agentUsageToolEnabled",e=>I.getState().setAgentUsageToolEnabled(e))}),agentImageToolEnabled:f({scope:"instance",parse:O,ui:R("agentImageToolEnabled",e=>I.getState().setAgentImageToolEnabled(e))}),agentImageModel:f({scope:"instance",parse:Be,ui:R("agentImageModel",e=>I.getState().setAgentImageModel(e))}),agentSecretToolEnabled:f({scope:"instance",parse:O,ui:R("agentSecretToolEnabled",e=>I.getState().setAgentSecretToolEnabled(e))}),agentMemoryToolEnabled:f({scope:"instance",parse:O,ui:R("agentMemoryToolEnabled",e=>I.getState().setAgentMemoryToolEnabled(e))}),agentMemoryDreamingEnabled:f({scope:"instance",parse:O,ui:R("agentMemoryDreamingEnabled",e=>I.getState().setAgentMemoryDreamingEnabled(e))}),agentMemoryDreamingModel:f({scope:"instance",parse:G(c()),ui:R("agentMemoryDreamingModel",e=>I.getState().setAgentMemoryDreamingModel(e))}),agentMemoryDreamingVariant:f({scope:"instance",parse:G(c()),ui:R("agentMemoryDreamingVariant",e=>I.getState().setAgentMemoryDreamingVariant(e))}),agentKnowledgeToolEnabled:f({scope:"instance",parse:O,ui:R("agentKnowledgeToolEnabled",e=>I.getState().setAgentKnowledgeToolEnabled(e))}),agentWorkflowToolEnabled:f({scope:"instance",parse:O,ui:R("agentWorkflowToolEnabled",e=>I.getState().setAgentWorkflowToolEnabled(e))}),isolatedSpacesEnabled:f({scope:"instance",parse:O,ui:R("isolatedSpacesEnabled",e=>I.getState().setIsolatedSpacesEnabled(e))}),isolatedSpacesIdleStop:f({scope:"instance",parse:G(d({enabled:v(),hours:y().int().min(1).max(168)}).strict())}),isolatedSpacesSshHost:f({scope:"instance",parse:Jn(320)}),agentMemoryFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("agentMemoryFeatureAvailable",e=>I.getState().setAgentMemoryFeatureAvailable(e),{autoSave:false})}),agentWorkflowFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("agentWorkflowFeatureAvailable",e=>I.getState().setAgentWorkflowFeatureAvailable(e),{autoSave:false})}),overviewFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("overviewFeatureAvailable",e=>I.getState().setOverviewFeatureAvailable(e),{autoSave:false})}),routingFeatureAvailable:f({scope:"instance",computed:true,parse:O,ui:R("routingFeatureAvailable",e=>I.getState().setRoutingFeatureAvailable(e),{autoSave:false})}),openCodeUpdateToastDismissedVersion:f({scope:"instance",parse:Jn(128)}),autoDeleteEnabled:f({scope:"instance",parse:O,ui:R("autoDeleteEnabled",e=>I.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:f({scope:"instance",parse:Xa(1,365),ui:R("autoDeleteAfterDays",e=>I.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:f({scope:"instance",parse:O,ui:R("sessionRetentionOnlyArchived",e=>I.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionIncludeInWork:f({scope:"instance",parse:O,ui:R("sessionRetentionIncludeInWork",e=>I.getState().setSessionRetentionIncludeInWork(e))}),sessionRetentionAction:f({scope:"instance",parse:ue(["archive","delete"]),ui:R("sessionRetentionAction",e=>I.getState().setSessionRetentionAction(e))}),mergedWorktreeCleanupEnabled:f({scope:"instance",parse:O,ui:R("mergedWorktreeCleanupEnabled",e=>I.getState().setMergedWorktreeCleanupEnabled(e))}),worktreeArchiveOnDoneEnabled:f({scope:"instance",parse:O,ui:R("worktreeArchiveOnDoneEnabled",e=>I.getState().setWorktreeArchiveOnDoneEnabled(e))}),terminalShell:f({scope:"instance",parse:dj,ui:R("terminalShell",e=>I.getState().setTerminalShell(e))}),terminalLoginShells:f({scope:"instance",parse:cj(Xu),ui:R("terminalLoginShells",e=>I.getState().setTerminalLoginShells(e))}),openInAppId:f({scope:"instance",parse:wn}),dictationEnabled:f({scope:"profile",parse:O,ui:$t("dictationEnabled")}),dictationAutoSend:f({scope:"profile",parse:O,ui:$t("dictationAutoSend")}),sttProvider:f({scope:"instance",parse:ij,ui:$t("sttProvider")}),sttServerUrl:f({scope:"instance",parse:Jn(2048),ui:$t("sttServerUrl")}),sttEndpointPath:f({scope:"instance",parse:G(c().trim().max(1024)),ui:$t("sttEndpointPath")}),sttModel:f({scope:"instance",parse:Jn(256),ui:$t("sttModel")}),sttLocalModel:f({scope:"instance",parse:Jn(256),ui:$t("sttLocalModel")}),sttLanguage:f({scope:"profile",parse:Jn(64),ui:$t("sttLanguage")}),sttCorrectTranscript:f({scope:"profile",parse:O,ui:$t("sttCorrectTranscript")}),tunnelProvider:f({scope:"instance",parse:Zi(wn,e=>e.toLowerCase())}),tunnelMode:f({scope:"instance",parse:G(c().transform(e=>e.trim().toLowerCase()).pipe(T(["quick","managed-remote","managed-local","serve","funnel"])))}),tunnelHttpsPort:f({scope:"instance",parse:Xa(1,65535)}),tunnelBootstrapTtlMs:f({scope:"instance",parse:OU}),tunnelSessionTtlMs:f({scope:"instance",parse:_s}),managedLocalTunnelConfigPath:f({scope:"instance",parse:DU}),managedRemoteTunnelHostname:f({scope:"instance",parse:to}),managedRemoteTunnelToken:f({scope:"instance",secret:true,parse:MU}),hasManagedRemoteTunnelToken:f({scope:"instance",computed:true,parse:O}),managedRemoteTunnelPresets:f({scope:"instance",parse:zU}),managedRemoteTunnelSelectedPresetId:f({scope:"instance",parse:wn}),managedRemoteTunnelPresetTokens:f({scope:"instance",secret:true,parse:$U}),sidebarProjectDisplayMode:f({scope:"profile",parse:ue(["all","single"]),ui:ft("projectDisplayMode")}),sidebarViewMode:f({scope:"profile",perSurface:true,parse:ue(["projects","timeline"]),ui:ft("sidebarViewMode")}),sidebarListSessionGrouping:f({scope:"profile",perSurface:true,parse:ue(["project","time"]),ui:ft("listSessionGrouping")}),sidebarGrouping:f({scope:"profile",perSurface:true,parse:ue(["project","time"]),ui:ft("sidebarGrouping")}),sidebarKeepWorkInPlace:f({scope:"profile",perSurface:true,parse:O,ui:ft("keepWorkInPlace")}),sidebarKeepPinnedInPlace:f({scope:"profile",perSurface:true,parse:O,ui:ft("keepPinnedInPlace")}),sidebarSessionBatchSize:f({scope:"profile",parse:Xa(Nb,Lb),ui:ft("sessionBatchSize")}),sidebarProjectSortOrder:f({scope:"profile",parse:ue(["manual","a-z","z-a","date-added","recent"]),ui:ft("projectSortOrder")}),sidebarShowChatsSection:f({scope:"profile",perSurface:true,parse:O,ui:ft("showChatsSection")}),sidebarShowWorkSection:f({scope:"profile",perSurface:true,parse:O,ui:ft("showWorkSection")}),sidebarShowPinnedSection:f({scope:"profile",perSurface:true,parse:O,ui:ft("showPinnedSection")}),sidebarDetailedZoneRows:f({scope:"profile",perSurface:true,parse:O,ui:ft("detailedZoneRows")}),sidebarWorktreeNameByBranch:f({scope:"profile",parse:O,ui:ft("worktreeNameByBranch")}),sidebarSections:f({scope:"profile",parse:G(hd),ui:{read:()=>Ut.getState().sections,write:e=>Ut.getState().setSections(e),autoSave:false}}),sidebarPinLists:f({scope:"profile",parse:G(Vb),ui:{read:()=>Ut.getState().pinLists,write:e=>Ut.getState().setPinLists(e),autoSave:false}}),sidebarHiddenSections:f({scope:"profile",perSurface:true,parse:G(Hb),ui:{read:()=>Ut.getState().hiddenSections,write:e=>Ut.getState().setHiddenSections(e),autoSave:false}}),workStatusSectionOrder:f({scope:"profile",parse:Zi(vl,mo),ui:R("workStatusSectionOrder",(e,t)=>{const s=t.workStatusSectionOrderExplicit===true;I.setState({workStatusSectionOrder:mo(e,s),workStatusSectionOrderExplicit:s})})}),workStatusSectionOrderExplicit:f({scope:"profile",parse:O,ui:R("workStatusSectionOrderExplicit",e=>I.setState({workStatusSectionOrderExplicit:e}))}),workStatusPanelEnabled:f({scope:"profile",parse:O,ui:R("workStatusPanelEnabled",e=>I.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:f({scope:"profile",parse:wj,ui:{read:()=>I.getState().workStatusHiddenSections,write:(e,t)=>{const s=t.workStatusHiddenSectionsExplicit===true;I.setState({workStatusHiddenSections:kb(e,s),workStatusHiddenSectionsExplicit:s})},autoSave:true}}),workStatusHiddenSectionsExplicit:f({scope:"profile",parse:O,ui:R("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:f({scope:"profile",parse:O,ui:R("showReasoningTraces",e=>I.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:f({scope:"profile",perSurface:true,parse:O,ui:R("streamingAutoFollowEnabled",e=>I.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:f({scope:"profile",parse:O,ui:R("collapsibleThinkingBlocks",e=>I.getState().setCollapsibleThinkingBlocks(e))}),expandReasoningWhileStreaming:f({scope:"profile",parse:O,ui:R("expandReasoningWhileStreaming",e=>I.getState().setExpandReasoningWhileStreaming(e))}),showTextJustificationActivity:f({scope:"profile",parse:O}),chatRenderMode:f({scope:"profile",parse:ue(["sorted","live"])}),activityRenderMode:f({scope:"profile",parse:oj,ui:R("activityRenderMode",e=>I.getState().setActivityRenderMode(e))}),mermaidRenderingMode:f({scope:"profile",parse:ue(["svg","ascii"]),ui:R("mermaidRenderingMode",e=>I.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:f({scope:"profile",parse:ue(["markdown","plain"]),ui:R("userMessageRenderingMode",e=>I.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:f({scope:"profile",parse:O,ui:R("collapsibleUserMessages",e=>I.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:f({scope:"profile",perSurface:true,parse:O,ui:R("stickyUserHeader",e=>I.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:f({scope:"profile",perSurface:true,parse:O,ui:R("promptNavigatorEnabled",e=>I.getState().setPromptNavigatorEnabled(e))}),chatWidth:f({scope:"profile",perSurface:true,parse:sj,ui:R("chatWidth",e=>I.getState().setChatWidth(e))}),wideChatLayoutEnabled:f({scope:"profile",perSurface:true,parse:O}),showSplitAssistantMessageActions:f({scope:"profile",parse:O,ui:R("showSplitAssistantMessageActions",e=>I.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:f({scope:"profile",parse:O,ui:R("showToolFileIcons",e=>I.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:f({scope:"profile",parse:O,ui:R("codeBlockLineWrap",e=>I.getState().setCodeBlockLineWrap(e))}),tableCellWrap:f({scope:"profile",parse:O,ui:R("tableCellWrap",e=>I.getState().setTableCellWrap(e))}),copyMessagesAsPlainText:f({scope:"profile",parse:O,ui:R("copyMessagesAsPlainText",e=>I.getState().setCopyMessagesAsPlainText(e))}),selectionApprovalText:f({scope:"profile",parse:Kn(1e3),ui:R("selectionApprovalText",e=>I.getState().setSelectionApprovalText(e))}),showTurnChangedFiles:f({scope:"profile",parse:O,ui:R("showTurnChangedFiles",e=>I.getState().setShowTurnChangedFiles(e))}),toolJsonViewMode:f({scope:"profile",parse:ue(["summary","formatted","raw"]),ui:R("toolJsonViewMode",e=>I.getState().setToolJsonViewMode(e))}),timeFormatPreference:f({scope:"profile",parse:ue(["auto","12h","24h"]),ui:R("timeFormatPreference",e=>I.getState().setTimeFormatPreference(e))}),weekStartPreference:f({scope:"profile",parse:ue(["auto","sunday","monday"]),ui:R("weekStartPreference",e=>I.getState().setWeekStartPreference(e))}),messageStreamTransport:f({scope:"profile",parse:ue(["auto","ws","sse"]),ui:$t("settingsMessageStreamTransport")}),diffLayoutPreference:f({scope:"profile",parse:ue(["dynamic","inline","side-by-side"]),ui:R("diffLayoutPreference",e=>I.getState().setDiffLayoutPreference(e))}),diffWrapLines:f({scope:"profile",parse:O,ui:R("diffWrapLines",e=>I.getState().setDiffWrapLines(e))}),diffHideWhitespace:f({scope:"profile",parse:O,ui:R("diffHideWhitespace",e=>I.getState().setDiffHideWhitespace(e))}),gitChangesViewMode:f({scope:"profile",parse:ue(["flat","tree"]),ui:R("gitChangesViewMode",e=>I.getState().setGitChangesViewMode(e))}),gitmojiEnabled:f({scope:"profile",parse:O}),defaultFileViewerPreview:f({scope:"profile",parse:O}),directoryShowHidden:f({scope:"profile",parse:O,ui:{read:eO,write:e=>tO(e,{persist:false}),autoSave:false}}),filesViewShowGitignored:f({scope:"profile",parse:O,ui:{read:iO,write:e=>aO(e,{persist:false}),autoSave:false}}),fileEditorKeymap:f({scope:"profile",parse:yj,ui:R("fileEditorKeymap",e=>I.getState().setFileEditorKeymap(e))}),fileEditorVimMappings:f({scope:"profile",parse:Kn(1e4),ui:R("fileEditorVimMappings",e=>I.getState().setFileEditorVimMappings(e))}),autoSaveEnabled:f({scope:"profile",parse:O,ui:R("autoSaveEnabled",e=>I.getState().setAutoSaveEnabled(e))}),fileEditorWrapLines:f({scope:"profile",parse:O,ui:R("fileEditorWrapLines",e=>I.getState().setFileEditorWrapLines(e))}),confirmFileTreeMove:f({scope:"profile",parse:O,ui:R("confirmFileTreeMove",e=>I.getState().setConfirmFileTreeMove(e))}),fileTreeSide:f({scope:"profile",surfaces:["web","desktop"],parse:ue(["left","right"]),ui:R("fileTreeSide",e=>I.getState().setFileTreeSide(e))}),layoutAnimations:f({scope:"profile",surfaces:["web","desktop"],parse:O,ui:R("layoutAnimations",e=>I.getState().setLayoutAnimations(e))}),openLinksInBrowserPanel:f({scope:"profile",surfaces:["desktop"],parse:O,ui:R("openLinksInBrowserPanel",e=>I.getState().setOpenLinksInBrowserPanel(e))}),liveBrowserTabLimit:f({scope:"profile",surfaces:["desktop"],parse:Xa(hb,gb),ui:R("liveBrowserTabLimit",e=>I.getState().setLiveBrowserTabLimit(e))}),agentBrowserSharesLogins:f({scope:"profile",surfaces:["desktop"],parse:O,ui:R("agentBrowserSharesLogins",e=>I.getState().setAgentBrowserSharesLogins(e))}),openTrackerLinksOnBoard:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:O,ui:R("openTrackerLinksOnBoard",e=>I.getState().setOpenTrackerLinksOnBoard(e))}),terminalCloseOnExit:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:O,ui:R("terminalCloseOnExit",e=>I.getState().setTerminalCloseOnExit(e))}),terminalOpenOnProjectAction:f({scope:"profile",surfaces:["web","desktop"],parse:O,ui:R("terminalOpenOnProjectAction",e=>I.getState().setTerminalOpenOnProjectAction(e))}),autoCreateWorktree:f({scope:"profile",parse:O}),sessionTabsEnabled:f({scope:"profile",surfaces:["web","desktop","vscode"],parse:O,ui:R("sessionTabsEnabled",e=>I.getState().setSessionTabsEnabled(e))}),sessionTabsPerWorkspace:f({scope:"profile",surfaces:["web","desktop"],parse:O,ui:R("sessionTabsPerWorkspace",e=>I.getState().setSessionTabsPerWorkspace(e))}),allowPromptingSubagentSessions:f({scope:"profile",parse:O,ui:R("allowPromptingSubagentSessions",e=>I.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:f({scope:"profile",parse:O,ui:R("inputSpellcheckEnabled",e=>I.getState().setInputSpellcheckEnabled(e))}),enterToSend:f({scope:"profile",parse:O,ui:R("enterToSend",e=>I.getState().setEnterToSend(e))}),enterToSendConfigured:f({scope:"profile",parse:O,ui:R("enterToSendConfigured",e=>I.getState().setEnterToSendConfigured(e))}),mobileReturnKeySends:f({scope:"profile",parse:O,ui:R("mobileReturnKeySends",e=>I.getState().setMobileReturnKeySends(e))}),largeTextPasteBehavior:f({scope:"profile",parse:bj,ui:R("largeTextPasteBehavior",e=>I.getState().setLargeTextPasteBehavior(e))}),savePastedImagesAsFiles:f({scope:"profile",parse:O,ui:R("savePastedImagesAsFiles",e=>I.getState().setSavePastedImagesAsFiles(e))}),followUpBehavior:f({scope:"profile",parse:ej,ui:{read:()=>Ud.getState().followUpBehavior,write:e=>Ud.getState().setFollowUpBehavior(e),autoSave:false}}),queueModeEnabled:f({scope:"profile",parse:O}),inputHistoryScope:f({scope:"profile",parse:hj,ui:{read:()=>gi.getState().scope,write:e=>gi.getState().applyScope(e),autoSave:false}}),inputHistoryLimit:f({scope:"profile",parse:gj,ui:{read:()=>gi.getState().entryLimit,write:e=>gi.getState().applyEntryLimit(e),autoSave:false}}),draftStarters:f({scope:"profile",parse:fj,ui:{read:()=>I.getState().globalDraftStarters??void 0,write:(e,t)=>I.getState().setGlobalDraftStarters(vj(e,t)),autoSave:false}}),draftStartersVisible:f({scope:"profile",parse:O,ui:R("draftStartersVisible",e=>I.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:f({scope:"profile",parse:O}),draftStartersScheduleTaskAdded:f({scope:"profile",parse:O}),fontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("fontSize",e=>I.getState().setFontSize(e))}),chatFontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("chatFontSize",e=>I.getState().setChatFontSize(e))}),terminalFontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("terminalFontSize",e=>I.getState().setTerminalFontSize(e))}),editorFontSize:f({scope:"profile",perSurface:true,parse:_s,ui:R("editorFontSize",e=>I.getState().setEditorFontSize(e))}),uiFont:f({scope:"profile",parse:uj,ui:R("uiFont",e=>I.getState().setUiFont(e))}),monoFont:f({scope:"profile",parse:pj,ui:R("monoFont",e=>I.getState().setMonoFont(e))}),customUiFont:f({scope:"profile",parse:Kn(100),ui:R("customUiFont",e=>I.getState().setCustomUiFont(e))}),customMonoFont:f({scope:"profile",parse:Kn(100),ui:R("customMonoFont",e=>I.getState().setCustomMonoFont(e))}),uiFontWeight:f({scope:"profile",parse:ue(zI),ui:R("uiFontWeight",e=>I.getState().setUiFontWeight(e))}),padding:f({scope:"profile",perSurface:true,parse:_s,ui:R("padding",e=>I.getState().setPadding(e))}),cornerRadius:f({scope:"profile",perSurface:true,parse:_s,ui:R("cornerRadius",e=>I.getState().setCornerRadius(e))}),shortcutOverrides:f({scope:"profile",parse:BU,ui:R("shortcutOverrides",kt("shortcutOverrides"))}),defaultModel:f({scope:"profile",parse:Be}),defaultVariant:f({scope:"profile",parse:Be}),defaultAgent:f({scope:"profile",parse:Be}),smallModelUseDefault:f({scope:"profile",parse:O}),smallModelOverride:f({scope:"profile",parse:Be}),smallModelVariant:f({scope:"profile",parse:Be}),walkthroughModelOverride:f({scope:"profile",parse:Be}),walkthroughModelVariant:f({scope:"profile",parse:Be}),fallbackModel:f({scope:"profile",parse:Be}),fallbackVariant:f({scope:"profile",parse:Be}),accountSwitchProviders:f({scope:"profile",parse:Yn}),zenModel:f({scope:"profile",parse:wn}),favoriteModels:f({scope:"profile",parse:Sl(64),ui:R("favoriteModels",kt("favoriteModels"),{autoSave:false})}),hiddenModels:f({scope:"profile",parse:Sl(1024),ui:R("hiddenModels",kt("hiddenModels"),{autoSave:false})}),collapsedModelProviders:f({scope:"profile",parse:Yn,ui:R("collapsedModelProviders",kt("collapsedModelProviders"),{autoSave:false})}),customProviderIcons:f({scope:"profile",parse:_U,ui:R("customProviderIcons",kt("customProviderIcons"),{autoSave:false})}),customProviderLogos:f({scope:"profile",parse:NU,ui:R("customProviderLogos",kt("customProviderLogos"),{autoSave:false})}),recentModels:f({scope:"profile",parse:Sl(16),ui:R("recentModels",kt("recentModels"),{autoSave:false})}),lastSelectedModel:f({scope:"profile",parse:Be,ui:R("lastSelectedModel",kt("lastSelectedModel"))}),recentAgents:f({scope:"profile",parse:Yn,ui:R("recentAgents",kt("recentAgents"),{autoSave:false})}),favoriteAgents:f({scope:"profile",parse:Yn,ui:R("favoriteAgents",kt("favoriteAgents"),{autoSave:false})}),recentEfforts:f({scope:"profile",parse:UU,ui:R("recentEfforts",kt("recentEfforts"),{autoSave:false})}),lastUsedEfforts:f({scope:"profile",parse:jU,ui:R("lastUsedEfforts",kt("lastUsedEfforts"),{autoSave:false})}),providerOrder:f({scope:"profile",parse:Yn,ui:R("providerOrder",e=>I.getState().setProviderOrder(e))}),sessionRecapEnabled:f({scope:"profile",parse:O,ui:R("sessionRecapEnabled",e=>I.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:f({scope:"profile",parse:O,ui:R("sessionSuggestionEnabled",e=>I.getState().setSessionSuggestionEnabled(e))}),sessionWorkEnabled:f({scope:"profile",parse:O,ui:R("sessionWorkEnabled",e=>I.getState().setSessionWorkEnabled(e))}),sessionReviewOfferEnabled:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:O,ui:R("sessionReviewOfferEnabled",e=>I.getState().setSessionReviewOfferEnabled(e))}),sessionGoalEnabled:f({scope:"profile",parse:O,ui:R("sessionGoalEnabled",e=>I.getState().setSessionGoalEnabled(e))}),sessionGoalChecker:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:ue(["classifier","small-model"]),ui:R("sessionGoalChecker",e=>I.getState().setSessionGoalChecker(e))}),sessionGoalMaxAutoTurns:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:G(y().refine(sb)),ui:R("sessionGoalMaxAutoTurns",e=>I.getState().setSessionGoalMaxAutoTurns(e))}),sessionGoalDefaultBudgetEnabled:f({scope:"profile",parse:O,ui:R("sessionGoalDefaultBudgetEnabled",e=>I.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:f({scope:"profile",parse:EU,ui:R("sessionGoalDefaultBudget",e=>I.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:f({scope:"profile",parse:O,ui:R("summarizeLastMessage",e=>I.getState().setSummarizeLastMessage(e))}),summaryThreshold:f({scope:"profile",parse:yl(0),ui:R("summaryThreshold",e=>I.getState().setSummaryThreshold(e))}),summaryLength:f({scope:"profile",parse:yl(10),ui:R("summaryLength",e=>I.getState().setSummaryLength(e))}),maxLastMessageLength:f({scope:"profile",parse:yl(10),ui:R("maxLastMessageLength",e=>I.getState().setMaxLastMessageLength(e))}),showDeletionDialog:f({scope:"profile",parse:O,ui:R("showDeletionDialog",e=>I.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:f({scope:"profile",parse:O,ui:R("nativeNotificationsEnabled",e=>I.getState().setNativeNotificationsEnabled(e))}),notificationMode:f({scope:"profile",parse:ue(["always","hidden-only"]),ui:R("notificationMode",e=>I.getState().setNotificationMode(e))}),notifyOnSubtasks:f({scope:"profile",parse:O,ui:R("notifyOnSubtasks",e=>I.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:f({scope:"profile",parse:O,ui:R("notifyOnCompletion",e=>I.getState().setNotifyOnCompletion(e))}),notifyOnPullRequests:f({scope:"profile",parse:O,ui:R("notifyOnPullRequests",e=>I.getState().setNotifyOnPullRequests(e))}),notifyOnError:f({scope:"profile",parse:O,ui:R("notifyOnError",e=>I.getState().setNotifyOnError(e))}),notifyOnQuestion:f({scope:"profile",parse:O,ui:R("notifyOnQuestion",e=>I.getState().setNotifyOnQuestion(e))}),notificationTemplates:f({scope:"profile",parse:HU,ui:R("notificationTemplates",e=>I.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:f({scope:"profile",parse:O,ui:R("showOpenCodeUpdateNotifications",e=>I.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:f({scope:"profile",parse:O,ui:R("reportUsage",e=>I.getState().setReportUsage(e))}),usageDisplayMode:f({scope:"profile",parse:ue(["usage","remaining"])}),usageDropdownProviders:f({scope:"profile",parse:vl}),usageSelectedModels:f({scope:"profile",parse:kl}),usageCollapsedFamilies:f({scope:"profile",parse:kl}),usageExpandedFamilies:f({scope:"profile",parse:kl}),usageModelGroups:f({scope:"profile",parse:qU}),globalBehaviorPrompt:f({scope:"profile",parse:Kn(1024*1024)}),responseStyleEnabled:f({scope:"profile",parse:O}),responseStylePreset:f({scope:"profile",parse:ue(lj)}),responseStyleCustomInstructions:f({scope:"profile",parse:Kn(5e4)}),pwaAppName:f({scope:"instance",surfaces:["web"],parse:rj}),pwaOrientation:f({scope:"instance",surfaces:["web"],parse:ue(["system","portrait","landscape"])}),mobileKeyboardMode:f({scope:"device",surfaces:["mobile"],parse:mj,ui:R("mobileKeyboardMode",e=>I.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:f({scope:"device",surfaces:["desktop"],parse:aj,ui:R("desktopWindowControlsPosition",e=>I.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:f({scope:"device",surfaces:["desktop"],parse:ue(["classic","traffic-lights"]),ui:R("desktopWindowControlsStyle",e=>I.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:f({scope:"device",surfaces:["mobile","web"],parse:_s,ui:R("inputBarOffset",e=>I.getState().setInputBarOffset(e))})},kj=e=>Object.prototype.hasOwnProperty.call(pa,e),ha=Object.keys(pa).filter(kj),Lv=e=>pa[e].scope==="device",ga=e=>pa[e],Sj=e=>!pa[e].computed&&!Lv(e),Cj=be(c(),oe()),Tj=e=>{const t=Cj.safeParse(e);if(!t.success)return null;const s=t.data,n={};for(const o of ha){const a=ga(o).parse(s[o],s);a!==void 0&&Object.assign(n,{[o]:a})}return n},Aj=(e,t)=>e===t?true:e===void 0||t===void 0?false:JSON.stringify(e)===JSON.stringify(t),Pj=e=>{for(const t of ha){const s=ga(t);if(!s.ui)continue;const n=e[t];n!==void 0&&(Aj(s.ui.read(),n)||s.ui.write(n,e))}},Rj=ha.filter(e=>ga(e).ui?.autoSave===true),nJ=()=>{const e={};for(const t of Rj){const n=ga(t).ui?.read();n!==void 0&&Object.assign(e,{[t]:n})}return e},Ij=ha.filter(e=>{const t=ga(e);return t.scope!=="device"&&!t.secret&&!t.computed}),Uv=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},cm="openchamber.settingsMirror.v2.index",xj="openchamber.deviceSeeded.v1:",Ej=e=>`${xj}${encodeURIComponent(e)}`,Oj=(e,t)=>{const s=Ej(t);let n=false;try{n=localStorage.getItem(s)===null,n&&localStorage.setItem(s,String(Date.now()))}catch{n=false}if(n)return e;const o={};for(const i of ha)e[i]===void 0||Lv(i)||Object.assign(o,{[i]:e[i]});return o},Dj="openchamber.settingsMirror.v2:",Mj=5,jd=e=>`${Dj}${encodeURIComponent(e)}`,Ns=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},Fj=(e,t)=>{const s={};for(const i of Ij)e[i]!==void 0&&Object.assign(s,{[i]:e[i]});localStorage.setItem(jd(t),JSON.stringify(s));let n=[];try{const i=JSON.parse(localStorage.getItem(cm)??"[]");Array.isArray(i)&&(n=i.filter(a=>typeof a=="string"))}catch{n=[]}const o=[t,...n.filter(i=>i!==t)].slice(0,Mj);for(const i of n)o.includes(i)||localStorage.removeItem(jd(i));localStorage.setItem(cm,JSON.stringify(o))},_j=e=>{if(!(typeof window>"u")){if(Fj(e,F()),Ns("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),Uv(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(s=>s.sidebarCollapsed===true).map(s=>s.id).filter(s=>typeof s=="string"&&s.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"),Ns("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}else localStorage.removeItem("openchamber.pwaName");if(db(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion=="string"){const t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem("opencode-update-toast-dismissed-version",t):localStorage.removeItem("opencode-update-toast-dismissed-version")}else localStorage.removeItem("opencode-update-toast-dismissed-version");typeof e.dictationEnabled=="boolean"?localStorage.setItem("dictationEnabled",String(e.dictationEnabled)):localStorage.removeItem("dictationEnabled"),e.dictationAutoSend!==void 0?localStorage.setItem("dictationAutoSend",String(e.dictationAutoSend)):localStorage.removeItem("dictationAutoSend"),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),Ns("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),Ns("sttEndpointPath",e.sttEndpointPath??null),Ns("sttModel",typeof e.sttModel=="string"?e.sttModel:null),Ns("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),Ns("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null),Ns("sttCorrectTranscript",e.sttCorrectTranscript===void 0?null:String(e.sttCorrectTranscript))}},Bd=(e,t,s=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:s}}))};let Vd="idle",Za=null;const Hd=new Set,Nj=()=>Vd,Lj=e=>(Hd.add(e),()=>Hd.delete(e)),Uj=e=>{gc(),Bt(e)},Bt=e=>{Za&&(clearTimeout(Za),Za=null);const t=e==="saved"?"idle":e;t!==Vd&&(Vd=t,Hd.forEach(s=>s())),t==="error"&&(Za=setTimeout(()=>Bt("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},jv=()=>{const e=I.persist;if(e&&typeof e=="object")return e},Bv=()=>Mo()?.settings??null,Vv=()=>`/api/config/settings?${Db}=${lc()}`,jj=e=>{Pj(e)},Hr=e=>Tj(e);class Bj{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const s=this.mutations.at(-1),n=s?[...this.operations].some(o=>o.revision>=s.revision):true;s&&!n?(s.revision=this.revision,s.changes={...s.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const s={revision:t};return this.operations.add(s),s}reconcile(t,s){let n=t;for(const o of this.mutations)o.revision<=s.revision||(n={...n,...o.changes});return n}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const s=Math.min(...[...this.operations].map(({revision:n})=>n));this.mutations=this.mutations.filter(n=>n.revision>s)}reset(){this.mutations=[],this.operations.clear()}}let vp=0,Ys=null,Ro={},Wd=false;const Vj=()=>Wd,qd=e=>{Wd=true;try{jj(e)}finally{Wd=false}};let vn=null,qt=null,ss=null,lt=null,Oi=[],lm=false,Wr=0,wr=[];const wt=new Bj,Hj=2e3,Wj=200,kp=()=>({runtimeKey:F(),generation:vp}),hc=e=>Object.keys(e),Hv=(e,t)=>e===t?true:e===void 0||t===void 0?false:JSON.stringify(e)===JSON.stringify(t),br=e=>{Ro={...Ro,...e}},qj=e=>{const t={...Ro};for(const s of e)delete t[s];Ro=t},Gj=e=>{const t={};for(const s of hc(e))Hv(e[s],Ro[s])||Object.assign(t,{[s]:e[s]});return t},ea=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,Wv=e=>{let t=null;for(const s of wr)ea(s.context,e)&&(t={...t??{},...s.changes});return qt&&ss&&ea(ss,e)&&(t={...t??{},...qt}),t},dm=(e,t)=>{const s=Wv(t);return e&&s?{...e,...s}:e},_e=e=>e.generation===vp&&e.runtimeKey===F(),ii=()=>{qt&&(lt&&(clearTimeout(lt),lt=null),qr({keepalive:true}))},gc=()=>{if(!(lm||typeof window>"u")){lm=true,Xr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(lt&&clearTimeout(lt),qt&&qr())}),Qr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(vp+=1,wt.reset(),Wr=0,Ys=null,vn=null,Ro={},Bt("saved"))});try{window.addEventListener("pagehide",ii,{capture:true}),window.addEventListener("beforeunload",ii,{capture:true}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&ii()}),document.addEventListener("freeze",ii)),Mn()&&Ge(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||ii()})).catch(()=>{})}catch{}}},qv=async(e=kp())=>{if(gc(),Ys&&ea(Ys.context,e)&&Date.now()-Ys.at<Hj)return dm(Ys.value,e);if(vn&&ea(vn.context,e))return vn.promise;const t=wt.begin(),s=Wv(e),n=i=>{if(!_e(e)||!i)return null;const a=dm(wt.reconcile({...i,...s},t),e);Ys={value:a,at:Date.now(),context:e};const r={};for(const l of hc(i))Hv(i[l],a?.[l])&&Object.assign(r,{[l]:i[l]});return br(r),a},o={context:e,promise:(async()=>{const i=Bv();if(i)try{const a=await i.load();if(!_e(e))return null;const r=Hr(a.settings);return n(r)}catch(a){if(!_e(e))return null;console.warn("Failed to load shared settings from runtime settings API:",a)}if(!_e(e))return null;try{const a=await P(Vv(),{method:"GET",headers:{Accept:"application/json"}});if(!_e(e)||!a.ok)return null;const r=await a.json().catch(()=>null);if(!_e(e))return null;const l=Hr(r);return n(l)}catch(a){return _e(e)&&console.warn("Failed to load shared settings from server:",a),null}})()};return vn=o,o.promise.finally(()=>{wt.finish(t),vn===o&&(vn=null)}),o.promise},zj=async e=>{const t=e?.bootstrap!==false,s=e?.adoptTheme??t;if(typeof window>"u")return;gc();const n=kp(),o=wt.begin(),i=[jv(),Ut.persist],a=p=>!p?.hasHydrated||p.hasHydrated()||!p.onFinishHydration?Promise.resolve():new Promise(h=>{let m=false;const w=()=>{m||(m=true,h())},b=p.onFinishHydration(()=>{b?.(),w()});p.hasHydrated?.()&&w()}),r=()=>Promise.all(i.map(a)).then(()=>{}),l=p=>!qt||!ss||!_e(ss)?p:{...p,...qt},u=async p=>{if(!_e(n))return;let h=l(wt.reconcile(p,o));if(await r(),!!_e(n)){h=Oj(l(wt.reconcile(p,o)),n.runtimeKey);try{_j(h)}catch(m){console.warn("persistToLocalStorage failed:",m)}try{qd(h)}catch(m){console.warn("applyDesktopUiPreferences failed:",m)}Bd(h,t,s)}};try{const p=await qv(n);p&&_e(n)?await u(p):_e(n)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(p){_e(n)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",p)}finally{wt.finish(o)}};async function qr({keepalive:e=false}={}){let t=false;const s=qt,n=ss,o=Wr,i=Oi;qt=null,ss=null,Wr=0,lt=null,Oi=[];try{if(!s||!n||Object.keys(s).length===0||!_e(n)){t=true,Bt("saved");return}const a=wt.begin(o),r={context:n,changes:{...s}};wr.push(r),br(s);const l=()=>qj(hc(s));try{const u=Bv();if(u)try{const p=Hr(await u.save(s));if(!_e(n))return;if(p){br(p);const h=wt.reconcile(p,a);qd(h),Bd(h,false),Ys=null}p||l(),t=!!p,Bt(p?"saved":"error");return}catch(p){if(!_e(n))return;console.warn("Failed to update settings via runtime settings API:",p)}if(!_e(n))return;try{const p=await P(Vv(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s),keepalive:e});if(!_e(n))return;if(!p.ok){console.warn("Failed to update shared settings via API:",p.status,p.statusText),l(),Bt("error");return}const h=Hr(await p.json().catch(()=>null));if(!_e(n))return;if(h){br(h);const m=wt.reconcile(h,a);qd(m),Bd(m,false),t=true,Bt("saved"),Ys=null}else l(),Bt("error")}catch(p){_e(n)&&(console.warn("Failed to update shared settings via API:",p),l(),Bt("error"))}}finally{wr=wr.filter(u=>u!==r),wt.finish(a)}}finally{i.forEach(a=>a({ok:t}))}}const $j=()=>qv(),Zt=async e=>{if(typeof window>"u")return{ok:false};gc();const t=kp();ss&&!ea(ss,t)&&(lt&&clearTimeout(lt),qr());const s={};for(const a of hc(e))Sj(a)&&Object.assign(s,{[a]:e[a]});const n=wt.record(s),o=Gj({...qt??{},...s});if(Object.keys(o).length===0){qt=null,ss=null,lt&&(clearTimeout(lt),lt=null);const a=Oi;return Oi=[],a.forEach(r=>r({ok:true})),Bt("saved"),{ok:true}}qt=o,ss=t,Wr=n,Bt("saving"),lt&&clearTimeout(lt);const i=new Promise(a=>{Oi.push(a)});return lt=setTimeout(()=>{qr()},Wj),i},Kj=async()=>{if(typeof window>"u")return;const e=jv();try{const t=await fE();if(!t)return;const s=()=>mE(t);if(e?.hasHydrated?.()){s();return}if(s(),e?.onFinishHydration){const n=e.onFinishHydration(()=>{n?.(),s()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},oJ=Object.freeze(Object.defineProperty({__proto__:null,applyPersistedHomeDirectoryToWindow:Uv,getRuntimeSettingsMirrorStorageKey:jd,getSettingsSaveState:Nj,initializeAppearancePreferences:Kj,isApplyingServerSettings:Vj,loadDesktopSettings:$j,reportSettingsSaveState:Uj,subscribeToSettingsSaveState:Lj,syncDesktopSettings:zj,updateDesktopSettings:Zt},Symbol.toStringTag,{value:"Module"})),iJ="openchamber:chats",Tl=new Map,Gv=new Map,Gd=new Set,zv=(e,...t)=>[e.replace(/[\\/]+$/,""),...t].join("/");function $v(e){const t=Oe(e);return t?zv(t,".config","openchamber","chats"):null}const Jj=/(?:^|\/)\.\.?(?:\/|$)/;function oo(e,t){return(e===t||e.length>t.length&&e.charCodeAt(t.length)===47&&e.startsWith(t))&&!Jj.test(e)}function Kv(){return Gv.get(F())}function Yj(e){const t=Oe(e),s=Kv();return!t||!s?null:oo(t,s.configured)||oo(t,s.canonicalConfigured)?s.configured:oo(t,s.legacy)||oo(t,s.canonicalLegacy)?s.legacy:null}function Xj(e){return Yj(e)!==null}function aJ(e,t){if(Xj(e))return true;const s=Oe(e),n=$v(t);return!!(s&&n&&oo(s,n))}function Qj(){return Kv()?.configured??null}function rJ(e){return Gd.add(e),()=>Gd.delete(e)}async function ma(){const e=F(),t=Tl.get(e);if(t)return t;const s=et.getFilesystemHomeInfo().then(({home:n,chatsRoot:o,canonicalChatsRoot:i,canonicalLegacyChatsRoot:a})=>{const r=$v(n),l=Oe(o)??r;if(!r||!l)throw new Error("Unable to resolve chat directories");const u={configured:l,legacy:r,canonicalConfigured:Oe(i)??l,canonicalLegacy:Oe(a)??r};Gv.set(e,u);for(const p of Gd)p();return u}).catch(n=>{throw Tl.delete(e),n});return Tl.set(e,s),s}async function Zj(){await ma()}async function eB(){return(await ma()).configured}function cJ(){return Zj().catch(()=>{})}async function lJ(e=new Date){const t=F(),s=await ma();if(F()!==t)throw new Error("Runtime changed while preparing chat directory");const n=[e.getFullYear(),String(e.getMonth()+1).padStart(2,"0"),String(e.getDate()).padStart(2,"0")].join("-"),o=globalThis.crypto?.randomUUID?.()??`${e.getTime()}-${Math.random().toString(36).slice(2)}`,i=zv(s.configured,n,`session-${o}`);return await et.createDirectory(i),i}async function Jv(e,t,s){const n=Oe(e);if(!n)return;const o=[t.configured,t.legacy,t.canonicalConfigured,t.canonicalLegacy];if(o.includes(n)||!o.some(a=>oo(n,a)))return;const i=await s("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!i.ok&&i.status!==404)throw new Error(`Failed to delete chat directory (${i.status})`)}async function dJ(e){if(!Oe(e))return;const t=F(),s=await ma();if(F()!==t)throw new Error("Runtime changed while deleting chat directory");await Jv(e,s,P)}async function uJ(e){const t=await pw(e),s=await ma();if(F()!==e)throw new Error("Runtime changed while preparing chat cleanup");return async n=>{await t(async({fetch:o})=>{await Jv(n,s,o)})}}const tB=3e4,sB=40,nB=60,oB=(e,t,s,n,o,i,a)=>{const r=t.trim(),l=s.trim().toLowerCase();return JSON.stringify([e,r,l,n,o,i,a])},um=(e,t)=>{try{const s=JSON.parse(e);return Array.isArray(s)&&s[1]===t}catch{return false}},pm=new WeakMap,hm=(e,t)=>{if(!t){e.waiters=1/0;return}e.waiters+=1,t.addEventListener("abort",()=>{e.waiters-=1,e.waiters===0&&e.abandon()},{once:true})},iB=xt()(Do((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=nB,i){if(!s||s.trim().length===0)return[];const a=s.trim(),r=F(),l=typeof n=="string"?n.trim():"",u=!!i?.includeHidden,p=i?.respectGitignore??true,h=i?.type==="directory"?"directory":"file",m=oB(r,a,l,o,u,p,h),w=Date.now(),b=t().cache[m];if(b&&w-b.timestamp<tB)return b.files;const S=t().inFlight[m];if(S){const H=pm.get(S);return H&&hm(H,i?.signal),S}const C=h==="file"&&(u||!p)?Mo()?.files:void 0,x=C?t().searchFiles(a,l,o,{type:h}):et.searchFiles(l,{directory:a,limit:o,type:h});let A=false;const E=new AbortController,B=C?C.search({directory:a,query:l,maxResults:o,includeHidden:u,respectGitignore:p,signal:E.signal}).then(H=>H.map(z=>{const te=z.path.replace(/\\/g,"/"),se=z.preview?.[0]?z.preview[0].replace(/\\/g,"/"):te,Ve=se.split("/").filter(Boolean).pop()||te.split("/").filter(Boolean).pop()||"";return{name:Ve,path:te,relativePath:se,extension:Ve.includes(".")?Ve.split(".").pop()?.toLowerCase():void 0}})).catch(H=>(A=true,E.signal.aborted||console.warn("Supplemental file search failed; keeping indexed results:",H),[])):Promise.resolve([]),K=Promise.all([x,B]).then(([H,z])=>{if(z.length===0)return H;const te=new Set(H.map(se=>se.path.replace(/\\/g,"/")));return[...H,...z.filter(se=>te.has(se.path)?false:(te.add(se.path),true))].slice(0,o)}).then(H=>(A||e(z=>{if(z.inFlight[m]!==K)return z;const te={...z.cache,[m]:{files:H,timestamp:Date.now()}},se=z.cacheKeys.filter(Ve=>Ve!==m);for(se.push(m);se.length>sB;){const Ve=se.shift();Ve&&delete te[Ve]}return{cache:te,cacheKeys:se}}),H)).finally(j);function j(){e(H=>{if(H.inFlight[m]!==K)return H;const z={...H.inFlight};return delete z[m],{inFlight:z}})}if(e(H=>({inFlight:{...H.inFlight,[m]:K}})),C){const H={controller:E,waiters:0,abandon:()=>{E.abort(),j()}};pm.set(K,H),hm(H,i?.signal)}return K},invalidateDirectory(s){if(!s||s.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const n=s.trim();e(o=>{const i={...o.cache},a=o.cacheKeys.filter(u=>um(u,n)?(delete i[u],false):true),r=Object.entries(o.inFlight).filter(([u])=>!um(u,n)),l=Object.fromEntries(r);return{cache:i,cacheKeys:a,inFlight:l}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),aB=()=>{if(typeof window>"u")return false;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return false}},zd="openchamber_stream_perf",rB=()=>{if(typeof window>"u")return false;try{return window.localStorage.getItem(zd)==="1"}catch{return false}};let Yv=rB(),Xv=false;const Un=()=>Yv||Xv,Qv=()=>{Un()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},gm=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Zv=()=>{if(!Un()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},ek=e=>Array.from(e.entries()).map(([t,s])=>({metric:t,count:s.count,avg:s.count>0?Number((s.total/s.count).toFixed(3)):0,max:Number(s.max.toFixed(3)),total:Number(s.total.toFixed(3)),last:Number(s.last.toFixed(3))})).sort((t,s)=>s.total-t.total||s.count-t.count),Sp=(e,t)=>{const s=Zv();if(!s)return;const n=s.counters.get(e)??{count:0,total:0,max:0,last:0};n.count+=1,n.total+=t,n.max=Math.max(n.max,t),n.last=t,s.counters.set(e,n),s.lastUpdatedAt=Date.now()},cB=e=>{if(Yv=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(zd,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(zd),Qv()}catch{}},pJ=e=>{if(Xv=e,!(typeof window>"u")){if(e){Zv();return}Qv()}},lB=()=>{typeof window>"u"||(Un()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},dB=()=>{if(typeof window>"u")return{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!Un()||!e?{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:true,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:ek(e.counters)}},hJ=()=>{if(typeof window>"u")return{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!Un()||!e)return{enabled:false,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,s=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:true,startedAt:t,lastUpdatedAt:s,durationMs:t?Math.max(0,Date.now()-t):0,entries:ek(e.counters)}},gJ=(e,t=1)=>{Sp(e,t)},mJ=(e,t)=>{Sp(e,t)},fJ=e=>{!Un()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},wJ=(e,t)=>{if(!Un())return t();const s=gm();try{return t()}finally{Sp(e,gm()-s)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:cB,reset:lB,getSnapshot:dB});var uB={};const pB=e=>!e.isHomeReady&&(e.currentDirectory==="/"||e.currentDirectory===""),mm=(e,t)=>Bi()?t||"":!Ne()&&t||e,tk=async()=>{if(Ne()&&!Bi())return null;const e=F();try{const t=await eB();return F()!==e?null:(Bi()&&await et.createDirectory(t),t)}catch{return null}};let vs=null,$d=0,sk=true;const Tt=la(),fm=Tt.getItem("lastDirectory"),hB=typeof fm=="string"&&fm.length>0,Xn=e=>{try{iB.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Io=e=>Oe(e)??"",gB=(e,t)=>{const s=e.trim();return s.startsWith("~")?s==="~"?t||s:(s.startsWith("~/")||s.startsWith("~\\"))&&t?`${t}${s.slice(1)}`:s:s},yr=(e,t)=>{const s=gB(e,t);return Io(s)},mB=()=>{const e=Tt.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Io(e);return t.length>0?t:null},fB=()=>{const e=Tt.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Io(e);return t.length>0?t:null},wB=()=>{if(typeof process>"u")return null;const e=uB,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const n=Io(t);return n.length>0?n:null}const s=process?.cwd?.();if(typeof s=="string"&&s.trim().length>0){const n=Io(s);return n.length>0?n:null}return null},Cp=()=>{if(typeof window<"u"){if(vs)return vs;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return vs=t,Tt.setItem("homeDirectory",t),t;const s=mB();if(s&&!Ne())return vs=s,s}const e=wB();return e||"/"},fi=e=>{const t=Oe(e);return t&&t!=="/"?t:null},nk=async()=>{try{const s=await et.getFilesystemHome(),n=fi(s);if(n)return n}catch(s){console.warn("Failed to obtain filesystem home directory:",s)}if(!sk)return"/";try{const s=await et.getSystemInfo(),n=fi(s?.homeDirectory);if(n)return n}catch(s){console.warn("Failed to get home directory from system info:",s)}try{const s=await Df(),n=fi(s);if(n)return n}catch(s){console.warn("Failed to obtain desktop-integrated home directory:",s)}const e=Cp(),t=fi(e);return t||e},bB=()=>{if(!Ne())return null;const e=pu()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Io(e);return t.length>0?t:null},ta=bB()||Cp(),sa=(()=>{const e=fB();return e&&!Ne()?yr(e,ta):Ne()&&!Bi()?ta:""})();sa&&et.setDirectory(sa);const yB=!!(ta&&ta!=="/"&&sa),Tp=xt()(Do((e,t)=>({currentDirectory:sa,directoryHistory:[sa],historyIndex:0,homeDirectory:ta,hasPersistedDirectory:hB,isHomeReady:yB,isSwitchingDirectory:false,setDirectory:(s,n)=>{const o=vs||t().homeDirectory||Tt.getItem("homeDirectory"),i=yr(s,o);aB()&&console.log("[DirectoryStore] setDirectory called with path:",i),et.setDirectory(i),Xn(),e(a=>{const r=a.directoryHistory[a.historyIndex]===i,l=r?a.directoryHistory:[...a.directoryHistory.slice(0,a.historyIndex+1),i];return Tt.setItem("lastDirectory",i),Zt({lastDirectory:i}),{currentDirectory:i,directoryHistory:l,historyIndex:r?a.historyIndex:l.length-1,hasPersistedDirectory:true,isHomeReady:true,isSwitchingDirectory:false}})},goBack:()=>{const s=t();if(s.historyIndex>0){const n=s.historyIndex-1,o=s.directoryHistory[n];et.setDirectory(o),Xn(),Tt.setItem("lastDirectory",o),Zt({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:true,isHomeReady:true,isSwitchingDirectory:false})}},goForward:()=>{const s=t();if(s.historyIndex<s.directoryHistory.length-1){const n=s.historyIndex+1,o=s.directoryHistory[n];et.setDirectory(o),Xn(),Tt.setItem("lastDirectory",o),Zt({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:true,isHomeReady:true,isSwitchingDirectory:false})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=t(),o=vs||t().homeDirectory||Cp();if(s===o)return;const i=ZA(s);i&&n(i)},goToNoProjectDirectory:async()=>{const s=F(),n=t().currentDirectory,[o,i]=await Promise.all([vs||t().homeDirectory||nk(),tk()]);if(F()!==s||t().currentDirectory!==n)return;const a=mm(o,i);et.setDirectory(a),Xn(),Tt.removeItem("lastDirectory"),Zt({lastDirectory:""}),e(r=>{const l=r.directoryHistory[r.historyIndex]===a,u=l?r.directoryHistory:[...r.directoryHistory.slice(0,r.historyIndex+1),a];return{currentDirectory:a,directoryHistory:u,historyIndex:l?r.historyIndex:u.length-1,hasPersistedDirectory:false,isHomeReady:true,isSwitchingDirectory:false}})},synchronizeHomeDirectory:(s,n)=>{const o=t(),i=s;vs=i;const a=o.homeDirectory!==i,r=Tt.getItem("lastDirectory"),l=typeof r=="string"&&r.length>0,u=mm(i,n),p=pB(o)||!l&&(o.currentDirectory==="/"||o.currentDirectory===o.homeDirectory||o.currentDirectory===Qj()||!o.currentDirectory);if(!a&&!p){o.isHomeReady||e({isHomeReady:true});return}const h=typeof i=="string"&&i!==""&&i!=="/",m=o.currentDirectory?yr(o.currentDirectory,i):o.currentDirectory,w=o.directoryHistory.map(A=>yr(A,i)),b=w.some((A,E)=>A!==o.directoryHistory[E]),S=!!(m&&m!==o.currentDirectory),C=p&&(!Ne()||Bi())&&!n,x={homeDirectory:i,hasPersistedDirectory:l,isHomeReady:h&&!C};if(p?(x.currentDirectory=u,x.directoryHistory=[u],x.historyIndex=0,x.isSwitchingDirectory=false):(S||b)&&(x.currentDirectory=m,x.directoryHistory=w,x.historyIndex=Math.min(o.historyIndex,w.length-1),x.isSwitchingDirectory=false),e(()=>x),(p||S)&&h&&!C){const A=p?u:m;et.setDirectory(A),Xn(),p||(Tt.setItem("lastDirectory",A),Zt({lastDirectory:A}))}Zt({homeDirectory:i})},resetForRuntimeSwitch:()=>{et.setDirectory(void 0),Xn(),e({currentDirectory:"/",directoryHistory:["/"],historyIndex:0,homeDirectory:"/",hasPersistedDirectory:false,isHomeReady:false,isSwitchingDirectory:false})}}),{name:"directory-store"}));let Di=null;const Kd=()=>{const e=++$d,t=Promise.all([nk(),tk()]).then(([s,n])=>{if(e!==$d)return;const o=fi(s);o&&Tt.setItem("homeDirectory",o),Tp.getState().synchronizeHomeDirectory(s,n)}).finally(()=>{Di===t&&(Di=null)});return Di=t,t},bJ=async()=>{Di&&await Di,!Tp.getState().isHomeReady&&await Kd()};typeof window<"u"&&(Kd(),Qr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(sk=false),vs=null,$d+=1,queueMicrotask(()=>{Kd()})}));const vB=Z("type",[d({id:c(),type:g("open")}),d({id:c(),type:g("message"),data:c(),binary:v()}),d({id:c(),type:g("error")}),d({id:c(),type:g("close"),code:y().int(),reason:c()})]),kB=gS("RuntimeWebSocket"),SB=(e,t,s)=>{const n=new URL(e),o=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"||n.username||n.password?null:(n.protocol=n.protocol==="wss:"?"https:":"http:",n.origin===o.origin&&n.pathname.startsWith(o.pathname)?{...s}:null)},CB=e=>{const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let s="";for(let n=0;n<t.length;n+=8192)s+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(s)},TB=(e,t,s=[],n=kB)=>{if(new Set(s).size!==s.length||s.some(b=>!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(b)))throw new SyntaxError("Invalid WebSocket protocols");const o=crypto.randomUUID();let i=0,a=null,r=false,l=Promise.resolve(),u=0;const p=(b,S)=>{i!==3&&(i=3,a?.remove().catch(()=>{}),a=null,globalThis.window?.removeEventListener("pagehide",w),m.onclose?.({code:b,reason:S}))},h=()=>{i!==3&&(m.onerror?.(),p(1006,""),r&&n.close({id:o,code:1e3,reason:""}).catch(()=>{}))},m={get readyState(){return i},binaryType:"arraybuffer",onopen:null,onmessage:null,onerror:null,onclose:null,send(b){if(i===0)throw new DOMException("WebSocket is connecting","InvalidStateError");if(i!==1)return;const S=b instanceof ArrayBuffer||ArrayBuffer.isView(b),C=S?b.byteLength:new TextEncoder().encode(b).byteLength;if(u+=C,u>16*1024*1024){h();return}const x=S?CB(b):b;l=l.then(async()=>{i!==3&&await n.send({id:o,data:x,binary:S})}).catch(h).finally(()=>{u-=C})},close(b=1e3,S=""){if(b!==1e3&&(b<3e3||b>4999||!Number.isInteger(b)))throw new DOMException("Invalid close code","InvalidAccessError");if(new TextEncoder().encode(S).byteLength>123)throw new SyntaxError("Close reason is too long");if(!(i>=2)){if(i=2,!r){p(1e3,"");return}l=l.then(()=>n.close({id:o,code:b,reason:S})).catch(h)}}},w=()=>m.close();return globalThis.window?.addEventListener("pagehide",w),n.addListener("socketEvent",b=>{const S=vB.safeParse(b);if(!S.success||S.data.id!==o||i===3)return;const C=S.data;switch(C.type){case"open":if(i!==0)return;i=1,m.onopen?.();break;case"message":{if(i!==1)return;let x=C.data;if(C.binary)try{x=Uint8Array.from(atob(C.data),A=>A.charCodeAt(0)).buffer}catch{h();return}m.onmessage?.({data:x});break}case"error":h();break;case"close":p(C.code,C.reason);break}}).then(async b=>{if(i===3){await b.remove();return}a=b,r=true,l=n.open({id:o,url:e,headers:{...t},protocols:s}),await l}).catch(h),m},AB=(e,t)=>{const s=Fo();if(s)return s.openWebSocket(XS(e),t);const n=_o();if(Object.keys(n).length>0&&Mn()){const o=SB(e,Ss().api("/"),n);if(o)return TB(e,o,t)}return jC(new WebSocket(e))},ok=1,PB=2,RB=typeof DecompressionStream=="function",IB=e=>new Response(new Blob([new Uint8Array(e,1)]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer(),io=512*1024,Al=8*1024,xB=0,Qn=1,EB=15e3,xo=new TextEncoder,Ap=new TextDecoder,Pp=T(["interactive","command"]),ik=T(["running","exited","error"]),OB=T(["node","bun"]),Rp=Z("type",[d({type:g("terminal")}),d({type:g("project-action"),actionId:c(),executionId:c()})]),DB=d({sessionId:c(),cols:y(),rows:y(),status:ik,mode:Pp.optional(),purpose:Rp.optional()}),MB=d({sessionId:c(),cwd:c(),status:T(["running","exited"]),createdAt:y().nullable().optional().transform(e=>e??null),mode:Pp.optional(),purpose:Rp.optional()}),wm={mode:Pp.optional(),purpose:Rp.optional()},FB=Z("t",[d({t:g("hello")}),d({t:g("pong")}),d({t:g("error"),s:c().optional(),message:c().optional(),code:c().optional(),fatal:v().optional()}),d({t:g("snapshot"),s:c(),q:y().int().nonnegative().default(0),history:c().default(""),status:ik,cols:y().int().positive().optional(),rows:y().int().positive().optional(),exitCode:y().nullish().transform(e=>e??void 0),signal:y().nullable().optional(),runtime:OB.optional(),ptyBackend:c().optional(),...wm}),d({t:g("output"),s:c(),q:y().int().nonnegative(),d:c(),r:c().optional()}),d({t:g("exit"),s:c(),q:y().int().nonnegative(),exitCode:y().nullish().transform(e=>e??void 0),signal:y().nullable().optional()}),d({t:g("restarted"),s:c(),q:y().int().nonnegative(),history:c().default(""),...wm})]),_B=e=>{const t=xo.encode(JSON.stringify(e)),s=new Uint8Array(t.length+1);return s[0]=ok,s.set(t,1),s},NB=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):xo.encode(e);t[0]===ok&&(t=t.subarray(1));try{return FB.safeParse(JSON.parse(Ap.decode(t))).data??null}catch{return null}};class LB extends Error{code;constructor(t,s){super(t),this.name="TerminalRequestError",this.code=s}}const yJ=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,UB=d({error:c().optional(),code:c().optional()}),mc=async(e,t)=>{const s=UB.safeParse(await e.json().catch(()=>null)).data;return new LB(s?.error??t,s?.code??null)},jB=e=>{const t=xo.encode(e);if(t.byteLength<=io)return e;let s=t.byteLength-io;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;return Ap.decode(t.subarray(s))},Jd=e=>{for(let t=0;t<e.length;t+=1){const s=e.charCodeAt(t);if(s>=55296&&s<=56319){const n=e.charCodeAt(++t);if(n<56320||n>57343||Number.isNaN(n))return false}else if(s>=56320&&s<=57343)return false}return true},Yd=e=>{if(e.malformed!==null)return e.malformed;const t=new Uint8Array(e.byteLength);let s=0;for(const n of e.parts)t.set(n.bytes.subarray(n.start,n.end),s),s+=n.end-n.start;return Ap.decode(t)},Xd=(e,t)=>{if(t.length>=io){let n=t.length-io;for(;n<t.length&&(t[n]&192)===128;)n+=1;const o=t.slice(n);e.parts=[{bytes:o,start:0,end:o.length}],e.byteLength=o.length;return}const s=e.parts.at(-1);if(s&&s.bytes.length===Al&&s.end+t.length<=s.bytes.length)s.bytes.set(t,s.end),s.end+=t.length;else if(t.length<Al){const n=new Uint8Array(Al);n.set(t),e.parts.push({bytes:n,start:0,end:t.length})}else e.parts.push({bytes:t,start:0,end:t.length});for(e.byteLength+=t.length;e.byteLength>io;){const n=e.parts[0],o=e.byteLength-io,i=n.start+o;if(i>=n.end){e.byteLength-=n.end-n.start,e.parts.shift();continue}let a=i;for(;a<n.end&&(n.bytes[a]&192)===128;)a+=1;e.byteLength-=a-n.start,n.start=a,n.start===n.end&&e.parts.shift()}},BB=(e,t)=>{if(t){if(e.malformed!==null||!Jd(t)){const s=jB(Yd(e)+t);if(e.parts=[],e.byteLength=0,!Jd(s)){e.malformed=s;return}e.malformed=null,Xd(e,xo.encode(s));return}Xd(e,xo.encode(t))}},bm=e=>{const t={parts:[],byteLength:0,malformed:null};return Jd(e)?e&&Xd(t,xo.encode(e)):t.malformed=e,t},VB=d({sessions:k(oe())});class HB{constructor(t=ak(null)){this.dependencies=t}dependencies;socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=false;inflating=null;gunzipFailed=false;subscribe(t,s){this.cancelIdleClose();const n={handlers:s,lastSequence:-1},o=this.subscribers.get(t)??new Set,i=o.size===0;o.add(n),this.subscribers.set(t,o);const a=this.projections.get(t);a&&(n.lastSequence=a.sequence,s.onEvent({type:"snapshot",sequence:a.sequence,data:Yd(a.history),cols:a.cols,rows:a.rows,status:a.status,mode:a.mode,purpose:a.purpose,exitCode:a.exitCode,signal:a.signal,runtime:a.runtime,ptyBackend:a.ptyBackend}));const r=this.socket?.readyState===Qn;return this.ensureConnected().then(()=>{const l=this.subscribers.get(t);i&&r&&l===o&&l.size>0&&this.attach(t)}).catch(l=>{o.has(n)&&(s.onError?.(l,false),this.scheduleReconnect())}),()=>{const l=this.subscribers.get(t);if(l?.delete(n),l?.size===0&&(this.subscribers.delete(t),this.projections.delete(t),this.send({t:"detach",v:3,s:t})),this.subscribers.size===0){if(this.cancelReconnect(),this.failures=0,this.socket?.readyState===Qn){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,s){if(s&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s}))))throw new Error("Terminal connection is unavailable")}dispose(){this.disposed=true,this.generation+=1,this.opening=null,this.subscribers.clear(),this.projections.clear(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.cancelIdleClose(),this.wakeCleanup?.(),this.wakeCleanup=null,this.closeSocket()}forget(t){this.projections.delete(t)}noteResize(t,s,n){const o=this.projections.get(t);o&&this.projections.set(t,{...o,cols:s,rows:n})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===Qn)return;if(this.opening)return await this.opening,this.socket?.readyState===Qn?void 0:this.ensureConnected();const t=this.generation,s=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((n,o)=>{let i=false,a=false,r=false,l=null;const u=()=>t===this.generation&&!this.disposed&&l!==null&&this.socket===l,p=()=>{r||a||!u()||(r=true,this.dependencies.clearUrlAuthToken?.())},h=w=>{i||(i=true,clearTimeout(m),w?o(w):n())},m=setTimeout(()=>{p(),l?.close(),h(new Error("Terminal connection timed out"))},1e4);try{const w=this.dependencies.openSocket();l=w,w.binaryType="arraybuffer",this.socket=w,w.onopen=()=>{if(!u()){w.close(),h(new Error("Terminal runtime changed"));return}a=true,this.failures=0,this.send({t:"hello",v:3});for(const b of this.subscribers.keys())this.attach(b);this.startKeepalive(),h()},w.onmessage=b=>this.receive(w,b.data),w.onerror=()=>{const b=u();b&&p(),h(new Error("Terminal WebSocket failed")),b&&this.subscribers.size>0&&this.scheduleReconnect()},w.onclose=()=>{const b=u();b&&(this.stopKeepalive(),p()),this.socket===w&&(this.socket=null),h(new Error("Terminal WebSocket closed")),b&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(w){h(w instanceof Error?w:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=s;try{await s}finally{this.opening===s&&(this.opening=null)}}attach(t){this.send({t:"attach",v:3,s:t,...RB&&!this.gunzipFailed?{z:1}:{}})}receive(t,s){const n=s instanceof ArrayBuffer&&s.byteLength>1&&new Uint8Array(s,0,1)[0]===PB;if(!n&&!this.inflating){this.handleMessage(s);return}const o=(this.inflating??Promise.resolve()).then(()=>n?IB(s):s).then(i=>{this.socket===t&&this.handleMessage(i)}).catch(()=>{this.gunzipFailed=true,this.socket===t&&t.close()}).finally(()=>{this.inflating===o&&(this.inflating=null)});this.inflating=o}handleMessage(t){const s=NB(t);if(!s||s.t==="hello"||s.t==="pong")return;if(s.t==="error"){const i=new Error(s.message??"Terminal error");i.code=s.code;const a=s.s?[s.s]:[...this.subscribers.keys()];for(const r of a)for(const l of this.subscribers.get(r)??[])l.handlers.onError?.(i,s.fatal===true);return}if(!s.s)return;const n=this.subscribers.get(s.s);if(!n)return;if(s.t==="snapshot"){const i={sequence:s.q??0,history:bm(s.history??""),cols:s.cols,rows:s.rows,status:s.status,mode:s.mode,purpose:s.purpose,exitCode:s.exitCode,signal:s.signal??null,runtime:s.runtime,ptyBackend:s.ptyBackend};this.projections.set(s.s,i);const a=Yd(i.history);for(const r of n)r.lastSequence=i.sequence,r.handlers.onEvent({type:"snapshot",sequence:i.sequence,data:a,cols:i.cols,rows:i.rows,status:i.status,mode:i.mode,purpose:i.purpose,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend});return}const o=this.projections.get(s.s);o&&s.q>o.sequence&&(s.t==="output"?(BB(o.history,s.r??s.d),this.projections.set(s.s,{...o,sequence:s.q})):s.t==="exit"?this.projections.set(s.s,{...o,sequence:s.q,status:"exited",exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&this.projections.set(s.s,{...o,sequence:s.q,history:bm(s.history??""),status:"running",mode:s.mode??o.mode,purpose:s.purpose??o.purpose,exitCode:void 0,signal:null}));for(const i of n)s.q<=i.lastSequence||(i.lastSequence=s.q,s.t==="output"?i.handlers.onEvent({type:"data",sequence:s.q,data:s.d,replayData:s.r}):s.t==="exit"?i.handlers.onEvent({type:"exit",sequence:s.q,exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&i.handlers.onEvent({type:"snapshot",sequence:s.q,data:s.history??"",status:"running",mode:s.mode??o?.mode,purpose:s.purpose??o?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==Qn)return false;try{return this.socket.send(_B(t)),true}catch{return false}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const s=typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine?6e4:Math.min(500*2**Math.min(this.failures-1,10),8e3);for(const o of this.subscribers.values())for(const i of o)i.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const n=()=>{typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null,this.ensureConnected().catch(()=>this.scheduleReconnect()))};typeof window<"u"&&window.addEventListener("online",n),typeof document<"u"&&document.addEventListener("visibilitychange",n),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",n),typeof document<"u"&&document.removeEventListener("visibilitychange",n)},this.reconnectTimer=setTimeout(n,s)}scheduleIdleClose(){this.idleCloseTimer||this.disposed||(this.idleCloseTimer=setTimeout(()=>{this.idleCloseTimer=null,!(this.disposed||this.subscribers.size>0)&&(this.generation+=1,this.opening=null,this.closeSocket())},EB))}cancelIdleClose(){this.idleCloseTimer&&(clearTimeout(this.idleCloseTimer),this.idleCloseTimer=null)}startKeepalive(){this.stopKeepalive(),this.keepaliveTimer=setInterval(()=>this.send({t:"ping",v:3}),45e3)}stopKeepalive(){this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null}cancelReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null}closeSocket(){this.stopKeepalive();const t=this.socket;this.socket=null,t&&(t.readyState===xB||t.readyState===Qn)&&t.close()}}const WB="",Gr=new Map,qB=e=>e===null?"/api/terminal/ws":`/api/terminal/ws?directory=${encodeURIComponent(Qf(e))}`;function ak(e){return{refreshAuth:tc,openSocket:()=>AB(Ss().websocket(qB(e))),clearUrlAuthToken:ra}}function fa(e){const t=It(e),s=t??WB,n=Gr.get(s);if(n)return n;const o=new HB(ak(t));return Gr.set(s,o),o}async function GB(e){const t=await P("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),directory:e.cwd});if(!t.ok)throw await mc(t,"Failed to create terminal session");const s=await t.json().catch(()=>null),n=DB.safeParse(s).data;if(!n)throw new Error("Failed to create terminal session");return n}async function zB(e){const t=await P(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`,{directory:e});if(!t.ok)throw await mc(t,"Failed to list terminal sessions");const s=await t.json().catch(()=>null),n=VB.safeParse(s).data?.sessions;if(!Array.isArray(n))throw new Error("Failed to list terminal sessions");const o=[];for(const i of n){const a=MB.safeParse(i).data;a&&o.push(a)}return o}async function $B(e,t){e.length!==0&&await Vo("/api/terminal/touch","POST",{sessionIds:e},t)}async function KB(){const e=await P("/api/terminal/shells");if(!e.ok)throw await mc(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(s=>s&&typeof s=="object"&&Xu(s.id)&&typeof s.name=="string"&&typeof s.supportsLogin=="boolean"):[]}function JB(e,t,s,n){return fa(n).subscribe(e,{onEvent:t,onError:s})}async function YB(e,t,s){await fa(s).write(e,t)}async function Vo(e,t,s,n){const o={method:t,directory:n};s!==void 0&&(o.headers={"Content-Type":"application/json"},o.body=JSON.stringify(s));const i=await P(e,o);if(!i.ok)throw await mc(i,"Terminal command failed");return i}async function XB(e,t,s,n){await Vo(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:s},n),fa(n).noteResize(e,t,s)}async function QB(e,t,s){await Vo(`/api/terminal/${e}/appearance`,"POST",t,s)}async function ZB(e,t){await Vo(`/api/terminal/${e}`,"DELETE",void 0,t),fa(t).forget(e)}async function eV(e,t){return(await Vo(`/api/terminal/${e}/restart`,"POST",t,t.cwd)).json()}async function tV(e){const s=await(await Vo("/api/terminal/force-kill","POST",e,e.cwd)).json().catch(()=>null),n=fa(e.cwd);if(Array.isArray(s?.killedSessionIds))for(const o of s.killedSessionIds)typeof o=="string"&&n.forget(o);else e.sessionId&&n.forget(e.sessionId)}function vJ(){for(const e of Gr.values())e.dispose();Gr.clear()}const sV=()=>({async listShells(){return KB()},async listSessions(e){return zB(e)},async touchSessions(e,t){await $B(e,t)},async createSession(e){return GB(e)},connect(e,t,s){const n=JB(e,t.onEvent,t.onError,s);return{close:()=>n()}},async sendInput(e,t,s){await YB(e,t,s)},async resize(e){await XB(e.sessionId,e.cols,e.rows,e.directory)},async updateAppearance(e,t,s){await QB(e,t,s)},async close(e,t){await ZB(e,t)},async restartSession(e,t){return eV(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows,themeMode:t.themeMode,terminalBackground:t.terminalBackground,terminalForeground:t.terminalForeground,shell:t.shell,loginShell:t.loginShell})},async forceKill(e){await tV(e)}});class Ip extends Error{code;status;constructor(t,s,n){super(s),this.name="GitNetworkOperationRequestError",this.code=t,this.status=n}}class xp extends Error{code;status;remoteName;constructor(t,s,n,o){super(s),this.name="GitWorktreeRequestError",this.code=t,this.status=n,this.remoteName=o}}class nV extends Error{provider;constructor(t,s){super(t),this.name="SourceControlInstanceOtherProviderError",this.provider=s}}class oV extends Error{reason;alias;constructor(t,s,n){super(t),this.name="SourceControlInstanceAliasError",this.reason=s,this.alias=n}}const iV=c().trim().min(1).max(200),Mi=c().trim().min(1).max(512),er=c().trim().max(512).nullable().optional(),aV=d({provider:Ks,instance:Mi,accountId:Mi}).strict(),rV=T(["account","ssh","system","anonymous"]),Eo=d({id:iV,name:Mi,userName:Mi,userEmail:Mi,account:aV.nullable().optional(),transport:rV.optional(),sshCredentialId:er,signCommits:v().optional(),signingKey:er,color:er,icon:er}).strict().superRefine((e,t)=>{e.transport==="account"&&!e.account&&t.addIssue({code:"custom",path:["account"],message:"An account transport requires an account"}),e.transport==="ssh"&&!e.sshCredentialId?.trim()&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"An SSH transport requires a managed key"}),e.transport!=="ssh"&&e.sshCredentialId&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"Only an SSH transport names a managed key"})}),kJ=e=>e?.transport??"system",cV=k(Eo).max(256).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Git identity profile IDs must be unique"),rk=d({userName:c().max(512).nullable(),userEmail:c().max(512).nullable()}).strict(),lV=d({success:v(),profile:Eo.nullable()}).strict(),SJ=e=>!!e.userName&&!!e.userEmail&&(e.transport==="account"&&!!e.account||e.transport==="anonymous"||e.transport==="system"||e.transport===void 0||e.transport==="ssh"&&!!e.sshCredentialId),Qd=new Set,dV=e=>(Qd.add(e),()=>{Qd.delete(e)}),ck=e=>{for(const t of Qd)t(e)},Zd=new Set,uV=(e,t)=>JSON.stringify([t,Oe(e)]);function CJ(e){return Zd.add(e),()=>{Zd.delete(e)}}function pV(e,t){const s=uV(e,t);for(const n of Zd)n(s)}class hV extends Error{reason;constructor(t,s){super(t),this.name="GitPathUnavailableError",this.reason=s}}const gV=d({error:c(),code:T(["path_not_found","nested_repository","untracked_directory"])}),Ep=d({headCommit:c().nullable(),indexCommit:c().nullable(),worktreeCommit:c().nullable(),hasTrackedChanges:v(),hasUntrackedFiles:v(),hasConflict:v()}),Op="GIT_REPOSITORY_UNREADABLE";class lk extends Error{code=Op;constructor(t){super(t),this.name="GitRepositoryUnreadableError"}}const M="/api/git",mV=d({original:c(),modified:c()}),dk=d({diff:c()}),fV=d({files:k(d({path:c(),status:c(),previousPath:c().optional(),revision:c().optional()}))}),wV=d({error:c()}),bV=d({error:c(),code:g(Op)}),yV=d({files:k(d({path:c(),previousPath:c().optional(),changeType:c(),insertions:y(),deletions:y(),isBinary:v()}))}),ym=d({hash:c(),date:c(),message:c(),refs:c(),body:c(),author_name:c(),author_email:c(),filesChanged:y(),insertions:y(),deletions:y(),parents:k(c())}),vV=d({all:k(ym),latest:ym.nullable(),total:y()}),kV=d({diff:c(),submodule:Ep.nullable().default(null)}),SV=d({diffs:k(L([d({path:c(),diff:c(),submodule:Ep.nullable().default(null)}),d({path:c(),error:c(),code:T(["path_not_found","nested_repository","untracked_directory"]).nullable()})]))}),CV=d({original:c(),modified:c(),path:c(),isBinary:v().optional(),submodule:Ep.nullable().default(null)});async function Dp(e,t){const s=await e.json().catch(()=>null),n=d({code:g("not_repository"),error:c()}).safeParse(s);if(e.status===409&&n.success)return new Error(n.data.error);const o=gV.safeParse(s);return o.success&&(e.status===404||e.status===422)?new hV(o.data.error,o.data.code):new Error(`${t}: ${e.statusText}`)}async function wa(e,t){const s=wV.safeParse(await e.json().catch(()=>null));return new Error(s.success?s.data.error:`${t}: ${e.statusText}`)}const uk=1200,pk=5e3,na=new Map,ao=new Map,hk=new Map,zr=new Map,tr=new Map,TV=256,AV=900*1e3,PV=3600*1e3,ba=8192,RV=/^[A-Za-z0-9_-]{1,200}$/,eu=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i,IV=/^[A-Za-z0-9_-]{43}$/,xV=/^SHA256:[A-Za-z0-9+/]{43}=?$/,as=e=>c().trim().min(1).max(e),gk=c().regex(RV),fc=c().regex(IV),Hs=as(1024),Mp=as(4096),Ee=as(512),mk=c().min(1).max(4096).refine(e=>e.trim()===e&&!Array.from(e).some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)&&e!==".."&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")&&!/^[A-Za-z]:\//.test(e),"Checkout path must be repository-relative"),vm=c().max(4096).refine(e=>{if(!e)return true;try{const t=new URL(e);return!t.username&&!t.password&&!t.search&&!t.hash}catch{return e.includes("://")?false:!/[?#]/.test(e)}},"Git remote display URLs must not contain credentials, query parameters, or fragments"),EV=k(d({name:Ee,fetchUrl:vm,pushUrl:vm}).strict()).max(256),OV=d({selectionId:gk,provenanceRevision:y().int().safe().positive(),sourceSha:c().regex(eu),expiresInMs:y().int().safe().positive().max(900*1e3)}).strict(),DV=d({remote:d({name:Ee,endpoint:d({displayUrl:Mp,fingerprint:fc}).strict()}).strict(),transportMode:g("managed"),classification:T(["contributor-fork","own-fork","bound-repository","other"])}).strict(),MV=Z("kind",[d({kind:g("ordinary")}).strict(),d({kind:g("contributor"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,provenanceRevision:y().int().safe().positive(),candidates:k(DV).max(128)}).strict()]),FV=d({state:g("awaiting-trust"),digest:fc,actions:k(d({kind:T(["post-checkout-hook","project-start-command","setup-command"]),label:c().max(65536)}).strict()).max(3)}).strict(),Vt=new Map,_V=e=>{if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&t[1].split("/").every(s=>s&&s!=="."&&s!==".."))}try{const t=new URL(e),s=decodeURIComponent(t.pathname);return(t.protocol==="https:"||t.protocol==="ssh:")&&!t.username&&!t.password&&!t.search&&!t.hash&&!!(t.hostname&&t.pathname&&t.pathname!=="/")&&!/[\0-\x20\x7f\\]/.test(s)&&s.split("/").slice(1).every(n=>n&&n!=="."&&n!=="..")}catch{return false}},ro=d({displayUrl:Mp.refine(_V),fingerprint:fc}).strict(),NV=d({displayName:as(1024),fingerprint:fc}).strict(),LV=d({id:Ee,platform:T(["web","desktop","vscode"]),label:as(512).optional()}).strict(),UV=Z("kind",[d({kind:g("provider"),provider:Ee,instance:Mp,accountId:Ee,login:Ee.optional()}).strict(),d({kind:g("ssh-key"),fingerprint:c().regex(xV)}).strict()]),Pl=Z("mode",[d({mode:g("anonymous"),verification:d({status:g("anonymous")}).strict()}).strict(),d({mode:g("managed"),verification:d({status:g("verified"),method:T(["credential","git-identity"])}).strict(),actor:UV.optional()}).strict(),d({mode:g("system"),verification:d({status:g("unverified"),reason:g("system-credentials")}).strict()}).strict()]),jV=L([Pl,d({fetch:Pl,push:Pl}).strict()]),vr=d({name:Ee,endpoint:ro}).strict(),Rl={repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,sourceRef:Hs,destinationRef:Hs},BV=Z("operation",[d({operation:g("push"),...Rl,forceWithLease:d({expectedRemoteSha:c().regex(eu)}).strict().optional(),configureUpstream:v().optional()}).strict(),Z("fetchScope",[d({operation:g("fetch"),fetchScope:g("ref").optional(),...Rl}).strict(),d({operation:g("fetch"),fetchScope:g("remote"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,force:v()}).strict()]),d({operation:g("pull"),...Rl}).strict(),d({operation:g("delete-remote-branch"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,destinationRef:Hs}).strict(),d({operation:g("checkout-hydration"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,remote:vr,requirements:k(d({kind:T(["submodule","lfs"]),path:mk,endpoint:ro}).strict()).max(256)}).strict(),d({operation:g("sync"),repositoryId:Ee,bindingRevision:y().int().safe().nonnegative(),configRevision:Ee,fetch:d({name:Ee,endpoint:ro,sourceRef:Hs,destinationRef:Hs}).strict(),pull:d({destinationRef:Hs}).strict(),push:d({name:Ee,endpoint:ro,sourceRef:Hs,destinationRef:Hs,forceWithLease:d({expectedRemoteSha:c().regex(eu)}).strict().optional()}).strict()}).strict(),d({operation:g("clone"),remote:ro,destination:NV}).strict()]),VV=T(["validated","authenticated","transferred","updated-local-repository","checked-out","cleaned-up"]),wc=T(["INVALID_REQUEST","NOT_FOUND","STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","REMOTE_URL_USERINFO","AUTHENTICATION_REQUIRED","DESTINATION_SELECTION_REQUIRED","CONTRIBUTOR_MANAGED_TRANSPORT_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","CONFLICT","CANCELLED","TIMEOUT","OUTCOME_UNKNOWN","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","PATH_LENGTH_LIMIT","BRANCH_NAME_CONFLICT","UNKNOWN"]),ai=e=>d({code:T(e),message:as(ba)}).strict(),HV=d({step:T(["fetch","pull","push"]),status:T(["succeeded","skipped","conflicted","failed","cancelled"]),error:d({code:wc,message:as(ba)}).strict().optional()}).strict(),fk=T(["succeeded","authorization-required","invalid","client-missing","failed","cancelled","not-needed"]),WV=["cancelled","invalid","client-missing","authorization-required","failed"],km=d({path:mk,status:fk,endpoint:ro.optional(),error:d({code:wc,message:as(ba)}).strict().optional()}).strict().superRefine((e,t)=>{(e.status!=="succeeded"&&e.status!=="not-needed")!==(e.error!==void 0)&&t.addIssue({code:"custom",message:"Git hydration status and error do not match"})}),wk=d({status:fk,submodules:k(km).max(256),lfs:k(km).max(256)}).strict().superRefine((e,t)=>{const s=[...e.submodules,...e.lfs].map(o=>o.status);let n="succeeded";!s.length||s.every(o=>o==="not-needed")?n="not-needed":n=WV.find(o=>s.includes(o))??"succeeded",e.status!==n&&t.addIssue({code:"custom",message:"Git hydration summary does not match its results"})}),qV=d({status:T(["pending","ready","failed"]),phase:T(["directory-created","git-ready","setup-ready"]).optional(),error:as(ba).nullable(),errorCode:wc.optional(),updatedAt:y().int().safe().nonnegative(),hydration:wk.optional()}).strict().superRefine((e,t)=>{e.status!=="failed"&&(e.errorCode||e.hydration)&&t.addIssue({code:"custom",message:"Only failed worktree bootstrap status may include failure details"})}),Fp=d({error:as(ba),code:wc}).strict(),Ls={operationId:gk,runtimeIdentity:LV,transport:jV,target:BV,completedSteps:k(VV),stepResults:k(HV).length(3).optional(),hydration:wk.optional()},GV=Z("state",[d({...Ls,state:g("planned")}).strict(),d({...Ls,state:g("running")}).strict(),d({...Ls,state:g("succeeded")}).strict(),d({...Ls,state:g("partial"),error:ai(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),d({...Ls,state:g("failed"),error:ai(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),d({...Ls,state:g("cancelled"),error:ai(["CANCELLED","TIMEOUT"])}).strict(),d({...Ls,state:g("outcome-unknown"),error:ai(["OUTCOME_UNKNOWN"])}).strict(),d({...Ls,state:g("conflicted"),error:ai(["STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","CONFLICT"])}).strict()]).superRefine((e,t)=>{e.target.operation==="clone"&&e.state==="partial"&&!e.completedSteps.includes("checked-out")&&t.addIssue({code:"custom",message:"Partial clone must retain a completed checkout"});const s=e.target.operation==="sync",n=e.state!=="planned"&&e.state!=="running";s&&n&&e.stepResults===void 0&&t.addIssue({code:"custom",message:"Sync operation result is missing step results"});for(const o of e.stepResults??[])(o.status!=="succeeded"&&o.status!=="skipped")!==(o.error!==void 0)&&t.addIssue({code:"custom",message:"Git sync step status and error do not match"});!s&&e.stepResults!==void 0&&t.addIssue({code:"custom",message:"Non-sync operation contains sync step results"}),e.state==="succeeded"&&e.hydration&&e.hydration.status!=="succeeded"&&e.hydration.status!=="not-needed"&&t.addIssue({code:"custom",message:"Successful Git operation contains incomplete hydration"}),s!=="fetch"in e.transport&&t.addIssue({code:"custom",message:"Git operation transport does not match its target"})}),bk=e=>e.trim(),ya=(e,t)=>JSON.stringify([e,bk(t)]),bc=(e,t,s)=>JSON.stringify([e,bk(t),s??"full"]),oa=(e,t)=>hk.get(ya(e,t))??0,_p=(e,t)=>{const s=ya(e,t);hk.set(s,oa(e,t)+1);for(const n of[void 0,"light"]){const o=bc(e,t,n);na.delete(o),ao.delete(o)}},zV=(e,t,s)=>JSON.stringify([e,t,s]),Np=(e=Date.now())=>{for(const[t,s]of Vt){const n=s.terminalState?PV:AV;s.observedAt<=e-n&&Vt.delete(t)}for(;Vt.size>TV;){let t=null;for(const[s,n]of Vt)n.terminalState&&(!t||n.observedAt<t.observedAt)&&(t={key:s,observedAt:n.observedAt});if(!t)for(const[s,n]of Vt)(!t||n.observedAt<t.observedAt)&&(t={key:s,observedAt:n.observedAt});if(!t)return;Vt.delete(t.key)}},tu=(e,t,s)=>{Np();for(const[n,o]of Vt)if(o.runtimeKey===e&&o.operationId===t&&(!s||o.runtimeIdentity.id===s))return{key:n,value:o};return null},$V=(e,t)=>{let s=null;for(const[n,o]of Vt)if(o.runtimeKey===e&&o.operationId===t){if(s)return;s=n}s&&Vt.delete(s)},KV=(e,t)=>{Np();const s=Date.now();for(const n of Vt.values())n.runtimeKey===e&&n.operationId===t&&!n.terminalState&&(n.observedAt=s)},es=(e,t)=>JSON.stringify(e)===JSON.stringify(t),JV=e=>JSON.stringify(e,(t,s)=>{if(t==="forceWithLease")return;if(t!=="displayUrl")return s;const n=c().safeParse(s);if(!n.success||n.data.includes("://"))return s;const o=n.data.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/);return o?`${o[1]}:${o[2]}`:n.data}),YV=e=>{const t=e.trim();try{const s=new URL(t);return s.username="",s.password="",s.hostname=s.hostname.toLowerCase(),s.search="",s.hash="",s.toString().replace(/\/$/,"")}catch{const s=t.match(/^([^@/:\s]+)@([^/:\s]+):(.+)$/);return s?`${s[1]}@${s[2].toLowerCase()}:${s[3].replace(/[?#].*$/,"")}`:t.replace(/[?#].*$/,"")}},XV=(e,t)=>{if(t.target.operation!==e.operation)throw new Error("Malformed Git network operation plan response");if(e.operation==="sync"){if(!("fetch"in t.transport)||t.transport.fetch.mode!==e.fetch.transportMode||t.transport.push.mode!==e.push.transportMode)throw new Error("Malformed Git network operation plan response");const o={...e.push.remote,sourceRef:e.push.sourceRef,destinationRef:e.push.destinationRef,forceWithLease:e.push.forceWithLease},i={operation:"sync",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,fetch:{...e.fetch.remote,sourceRef:e.fetch.sourceRef,destinationRef:e.fetch.destinationRef},pull:e.pull,push:o};if(!es(t.target,i))throw new Error("Malformed Git network operation plan response");return}if("fetch"in t.transport)throw new Error("Malformed Git network operation plan response");if(e.operation==="checkout-hydration"){const o=t.target;if(o.operation!=="checkout-hydration"||!es({repositoryId:o.repositoryId,bindingRevision:o.bindingRevision,configRevision:o.configRevision,remote:o.remote},{repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote}))throw new Error("Malformed Git network operation plan response");return}if(t.transport.mode!==e.transportMode)throw new Error("Malformed Git network operation plan response");if(e.operation==="clone"){const o=t.target;if(o.operation!=="clone")throw new Error("Malformed Git network operation plan response");const i=e.destinationPath.trim().split(/[\\/]/).filter(Boolean).at(-1);if(o.remote.displayUrl!==YV(e.remoteUrl)||o.destination.displayName!==i)throw new Error("Malformed Git network operation plan response");return}if(e.operation==="delete-remote-branch"){if(!es(t.target,{operation:"delete-remote-branch",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,destinationRef:e.destinationRef}))throw new Error("Malformed Git network operation plan response");return}if(e.operation==="fetch"&&e.fetchScope==="remote"){const o=t.target;if(o.operation!=="fetch"||o.fetchScope!=="remote"||!es(o,{operation:"fetch",fetchScope:"remote",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,force:o.force}))throw new Error("Malformed Git network operation plan response");return}const s={repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,sourceRef:e.sourceRef,destinationRef:e.destinationRef},n=e.operation==="fetch"?{operation:"fetch",fetchScope:e.fetchScope,...s}:{operation:e.operation,...s};if(e.operation==="push"&&e.forceWithLease&&Object.assign(n,{forceWithLease:e.forceWithLease}),e.operation==="push"&&e.configureUpstream&&Object.assign(n,{configureUpstream:true}),!es(t.target,n))throw new Error("Malformed Git network operation plan response")},QV=e=>e.target.operation==="clone"?false:e.state==="succeeded"?true:e.completedSteps.includes("transferred")||e.completedSteps.includes("updated-local-repository"),su=(e,t,s=false)=>"fetch"in e||"fetch"in t?"fetch"in e&&"fetch"in t&&su(e.fetch,t.fetch,s)&&su(e.push,t.push,s):e.mode===t.mode&&es(e.verification,t.verification)&&(e.mode!=="managed"||t.mode==="managed"&&(!e.actor||s&&!t.actor||es(e.actor,t.actor)));dV(e=>{_p(F(),e),zr.delete(ya(F(),e))});const Ho=e=>{ck(e)},De=async(e,t)=>{const s=await t.json();return Ho(e),s};function _(e,t,s){const n={...s};return t&&(n.directory=t),Ss().api(e,n)}const ZV=15,Sm=200,e1=e=>e==="worktrees"?`${M}/project-worktrees`:`${M}/projects`,t1=(e,t)=>JSON.stringify(e==="status"||e==="root"?{directories:t,fields:[e]}:{directories:t}),s1=(e,t)=>`${e}\0${It(t)??""}`,Fi=new Map,Cm=async e=>{const t=Fi.get(e);if(Fi.delete(e),!t)return;if(t.runtimeKey!==F()){const r=new Error("Runtime changed before project repository batch was sent");for(const l of t.waiters.values())for(const u of l)u.reject(r);return}const s=[...t.waiters.keys()],n=new Map;for(const r of s)n.set(r,oa(t.runtimeKey,r));const o=e1(t.field),i=new Map,a=[];for(let r=0;r<s.length;r+=Sm)a.push(s.slice(r,r+Sm));await Promise.all(a.map(async r=>{try{const l=await P(_(o,r[0]),{method:"POST",headers:{"Content-Type":"application/json"},body:t1(t.field,r)});if(!l.ok)throw new Error(`Failed to read project repositories: ${l.statusText}`);const u=await l.json();for(const p of u?.projects??[])i.set(p.directory,p)}catch(l){const u=l instanceof Error?l.message:"Failed to read project repositories";for(const p of r)i.set(p,{directory:p,error:u})}}));for(const[r,l]of i)typeof l.isGitRepository=="boolean"&&zr.set(ya(t.runtimeKey,r),{value:l.isGitRepository,expiresAt:Date.now()+pk}),l.status&&oa(t.runtimeKey,r)===n.get(r)&&na.set(bc(t.runtimeKey,r,void 0),{value:l.status,expiresAt:Date.now()+uk});for(const[r,l]of t.waiters){const u=i.get(r)??null;for(const p of l)u?u.error?p.reject(u.code===Op?new lk(u.error):new Error(u.error)):u.errors?.includes(t.field)?p.reject(new Error(`Failed to read project ${t.field}`)):p.resolve(u):p.reject(new Error("Project repository read missing from batch response"))}},yc=(e,t)=>{const s=F(),n=s1(t,e),o=Fi.get(n);o&&o.runtimeKey!==s&&Cm(n);let i=Fi.get(n);i||(i={runtimeKey:s,field:t,waiters:new Map,timer:null},Fi.set(n,i));const a=i;return new Promise((r,l)=>{const u=a.waiters.get(e)??[];u.push({resolve:r,reject:l}),a.waiters.set(e,u),a.timer===null&&(a.timer=setTimeout(()=>{Cm(n)},ZV))})};async function n1(e){const t=F(),s=Date.now(),n=e.filter(o=>{const i=bc(t,o,void 0),a=na.get(i);return!(a&&a.expiresAt>s)&&!ao.has(i)});await Promise.allSettled(n.map(o=>yc(o,"status")))}async function o1(e){const t=ya(F(),e),s=Date.now(),n=zr.get(t);if(n&&n.expiresAt>s)return n.value;const o=tr.get(t);if(o)return o;const i=(async()=>{const r=(await yc(e,"repo")).isGitRepository===true;return zr.set(t,{value:r,expiresAt:Date.now()+pk}),r})();tr.set(t,i);try{return await i}finally{tr.get(t)===i&&tr.delete(t)}}class i1 extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function TJ(e){const t=await P("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new i1;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const s=await t.json();if(!Array.isArray(s?.repositories))throw new Error("Unexpected git directories response");return s.repositories.map(n=>Oe(n?.path??null)).filter(n=>n!==null)}async function a1(e,t){const s=t?.mode,n=F();t?.fresh&&_p(n,e);const o=bc(n,e,s),i=Date.now(),a=na.get(o);if(a&&a.expiresAt>i)return a.value;const r=ao.get(o);if(r)return r;const l=(async()=>{const u=oa(n,e),p=await P(_(`${M}/status`,e,s?{mode:s}:void 0));if(!p.ok){const m=bV.safeParse(await p.json().catch(()=>null));throw m.success?new lk(m.data.error):new Error(`Failed to get git status: ${p.statusText}`)}const h=await p.json();return oa(n,e)===u&&na.set(o,{value:h,expiresAt:Date.now()+uk}),h})();ao.set(o,l);try{return await l}finally{ao.get(o)===l&&ao.delete(o)}}async function AJ(e){const t=await yc(e,"root");return{root:t.root?t.root:e}}async function PJ(e){const t=await P(_(`${M}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve the repository folder: ${t.statusText}`);const s=await t.json().catch(()=>({}));if(s.prefix===void 0||s.prefix===null)throw new Error("The server did not report the repository folder");return s.prefix}async function RJ(e){const t=await P(_(`${M}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const s=await t.json().catch(()=>({}));return{root:typeof s.root=="string"&&s.root?s.root:e}}async function IJ(e,t){const s=await P(_(`${M}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!s.ok)throw new Error(`Failed to get git commit summaries: ${s.statusText}`);const n=await s.json().catch(()=>({}));return{commits:Array.isArray(n.commits)?n.commits.map(o=>({sha:typeof o.sha=="string"?o.sha:"",short:typeof o.short=="string"?o.short:"",subject:typeof o.subject=="string"?o.subject:""})).filter(o=>o.sha&&o.short):[]}}async function r1(e,t){const{path:s,staged:n,contextLines:o,previousPath:i}=t;if(!s)throw new Error("path is required to fetch git diff");const a=await P(_(`${M}/diff`,e,{path:s,staged:n?"true":void 0,context:o,previousPath:i||void 0}));if(!a.ok)throw await Dp(a,"Failed to get git diff");return kV.parse(await a.json())}const Tm=1e3;async function c1(e,t){const{paths:s,staged:n,contextLines:o}=t,i=[];for(let a=0;a<s.length;a+=Tm){const r=await P(_(`${M}/diffs`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s.slice(a,a+Tm),staged:n===true,context:o})});if(!r.ok)throw await Dp(r,"Failed to get git diffs");for(const l of SV.parse(await r.json()).diffs)i.push("diff"in l?{path:l.path,ok:true,diff:{diff:l.diff,submodule:l.submodule}}:{path:l.path,ok:false,error:l.error,reason:l.code})}return i}async function l1(e,t){const{base:s,head:n,path:o,contextLines:i,includeWorkingTree:a,previousPath:r}=t;if(!s||!n)throw new Error("base and head are required to fetch git range diff");const l=await P(_(`${M}/range-diff`,e,{base:s,head:n,path:o||void 0,context:i,includeWorkingTree:a,previousPath:r||void 0}));if(!l.ok)throw await wa(l,"Failed to get git range diff");return dk.parse(await l.json())}async function d1(e,t){const s=await P(_(`${M}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!s.ok)throw await wa(s,"Failed to get commit diff");return dk.parse(await s.json())}async function u1(e,t){const{base:s,head:n,includeWorkingTree:o}=t;if(!s||!n)throw new Error("base and head are required to fetch git range files");const i=await P(_(`${M}/range-files`,e,{base:s,head:n,includeWorkingTree:o}));if(!i.ok)throw await wa(i,"Failed to get git range files");return fV.parse(await i.json()).files}async function p1(e,t){if(!t)throw new Error("branch is required to get branch base");const s=await P(_(`${M}/branch-base`,e,{branch:t}));if(!s.ok)throw new Error(`Failed to get branch base: ${s.statusText}`);return s.json()}async function h1(e,t){const{path:s,staged:n,previousPath:o}=t;if(!s)throw new Error("path is required to fetch git file diff");const i=await P(_(`${M}/file-diff`,e,{path:s,staged:n?"true":void 0,previousPath:o||void 0}));if(!i.ok)throw await Dp(i,"Failed to get git file diff");return CV.parse(await i.json())}async function g1(e,t,s){if(!t)throw new Error("path is required to revert git changes");const n=await P(_(`${M}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:s?.scope})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to revert git changes")}Ho(e)}async function m1(e,t){await yk(e,[t])}async function yk(e,t){const s=t.map(o=>o.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to stage git changes");const n=await P(_(`${M}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to stage git changes")}Ho(e)}async function f1(e,t){await vk(e,[t])}async function vk(e,t){const s=t.map(o=>o.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to unstage git changes");const n=await P(_(`${M}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to unstage git changes")}Ho(e)}async function w1(e,t,s){await Lp(e,t,s,"stage")}async function b1(e,t,s){await Lp(e,t,s,"unstage")}async function y1(e,t,s){await Lp(e,t,s,"discard")}async function Lp(e,t,s,n){if(!t)throw new Error("path is required to apply a git hunk");if(typeof s!="string"||!s.trim())throw new Error("patch is required to apply a git hunk");const o=await P(_(`${M}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:s,action:n})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to apply git hunk")}Ho(e)}async function v1(e){if(!e)return false;const t=await P(_(`${M}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function k1(e,t){const s=await P(_(`${M}/branches`,e,t?.remote?{remote:t.remote}:void 0));if(!s.ok)throw new Error(`Failed to get branches: ${s.statusText}`);return s.json()}async function S1(e,t){const s=await P(_(`${M}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!s.ok)throw new Error(`Failed to get branch push status: ${s.statusText}`);return s.json()}async function C1(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const s=await P(_(`${M}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to delete branch")}return De(e,s)}async function T1(e,t){const s=t?.remote?.trim();if(!s)throw new Error("remote is required to remove a remote");const n=await P(_(`${M}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to remove remote")}return De(e,n)}async function A1(e,t,s){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const n={files:t};s?.zenModel&&(n.zenModel=s.zenModel),s?.providerId&&(n.providerId=s.providerId),s?.modelId&&(n.modelId=s.modelId);const o=await P(_(`${M}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){const l=await o.json().catch(()=>({error:o.statusText}));console.error("[git-generation][browser] http error",{status:o.status,statusText:o.statusText,error:l});const u=typeof l?.traceId=="string"&&l.traceId?` (traceId: ${l.traceId})`:"";throw new Error(`${l.error||"Failed to generate commit message"}${u}`)}const i=await o.json();if(!i?.message||typeof i.message!="object")throw new Error("Malformed commit generation response");const a=typeof i.message.subject=="string"&&i.message.subject.trim().length>0?i.message.subject.trim():"",r=Array.isArray(i.message.highlights)?i.message.highlights.filter(l=>typeof l=="string"&&l.trim().length>0).map(l=>l.trim()):[];return{message:{subject:a,highlights:r}}}async function P1(e,t){const{base:s,head:n,context:o,zenModel:i,providerId:a,modelId:r}=t;if(!s||!n)throw new Error("base and head are required");const l={base:s,head:n};o?.trim()&&(l.context=o.trim()),i&&(l.zenModel=i),a&&(l.providerId=a),r&&(l.modelId=r);const u=await P(_(`${M}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok){const w=await u.json().catch(()=>({error:u.statusText}));throw new Error(w.error||"Failed to generate PR description")}const p=await u.json().catch(()=>null),h=typeof p?.title=="string"?p.title:"",m=typeof p?.body=="string"?p.body:"";if(!h&&!m)throw new Error("Malformed PR description response");return{title:h,body:m}}async function Am(e){return(await yc(e,"worktrees")).worktrees??[]}async function Pm(e,t){const s=await P(_(`${M}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to validate worktree")}return s.json()}async function R1(e){const t=await P(_(`${M}/worktrees/bootstrap-status`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to get worktree bootstrap status")}return qV.parse(await t.json())}async function I1(e,t){const s=await P(_(`${M}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to preview worktree")}return s.json()}async function Rm(e,t){const s=await P(_(`${M}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const n=d({error:c().optional(),code:c().optional(),remoteName:c().optional()}).strict().parse(await s.json().catch(()=>({error:s.statusText})));throw new xp(n.code||"UNKNOWN",n.error||"Failed to create worktree",s.status,n.remoteName)}return s.json()}async function Im(e,t){const s=await P(_(`${M}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});return s.ok||await kk(s,"Failed to delete worktree"),s.json()}async function x1(e,t){const s=await P(_(`${M}/worktrees/teardown`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return s.ok||await kk(s,"Failed to tear down worktree"),s.json()}const kk=async(e,t)=>{const s=d({error:c().optional(),code:c().optional()}).catch({}).parse(await e.json().catch(()=>null)),n=s.error||e.statusText||t;throw s.code?new xp(s.code,n,e.status):new Error(n)},E1=d({title:c(),branch:c()});async function O1(e,t,s="user"){const n=await P(_(`${M}/worktrees/title`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t,by:s})}),o=await n.json().catch(()=>null);if(!n.ok){const a=d({error:c()}).safeParse(o).data?.error;throw new Error(a||"Failed to rename the task")}const i=E1.safeParse(o);if(!i.success)throw new Error("Malformed task title response");return i.data}const D1=d({pinned:v(),branch:c()});async function M1(e,t,s=null){const n=await P(_(`${M}/worktrees/pin`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s?{pinned:t,list:s}:{pinned:t})}),o=await n.json().catch(()=>null);if(!n.ok){const a=d({error:c()}).safeParse(o).data?.error;throw new Error(a||"Failed to pin the task")}const i=D1.safeParse(o);if(!i.success)throw new Error("Malformed pin response");return i.data}const Sk=d({id:c().min(1),ref:c().min(1),commit:c().min(1),head:c(),path:c().min(1),branch:c(),branchExists:v(),title:c(),archivedAt:y(),sessionIds:k(c())}),vc=async(e,t,s,n,o)=>{const i=await P(_(`${M}/worktrees/archives${e}`,t),{...s,headers:s.body?{"Content-Type":"application/json"}:void 0});if(!i.ok){const a=d({error:c().optional(),code:c().optional()}).catch({}).parse(await i.json().catch(()=>null)),r=a.error||i.statusText||o;throw a.code?new xp(a.code,r,i.status):new Error(r)}return n.parse(await i.json())},F1=(e,t)=>vc("",e,{method:"POST",body:JSON.stringify(t)},Sk,"Failed to archive worktree"),_1=async e=>(await vc("",e,{method:"GET"},d({archives:k(Sk)}),"Failed to list worktree archives")).archives,N1=(e,t)=>vc("/restore",e,{method:"POST",body:JSON.stringify({id:t})},d({id:c(),conflicts:v()}),"Failed to restore worktree archive"),L1=(e,t)=>vc("",e,{method:"DELETE",body:JSON.stringify(t)},d({id:c(),branchDeleted:v()}),"Failed to delete worktree archive"),U1=d({ref:c(),commit:c().min(1),head:c().min(1)});async function j1(e,t){const s=await P(_(`${M}/worktrees/snapshot`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to snapshot worktree")}return U1.parse(await s.json())}async function B1(e,t,s={}){const n=await P(_(`${M}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:s.addAll??false,files:s.files,stageFiles:s.stageFiles})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create commit")}return De(e,n)}async function V1(e,t={}){const s=F(),n=await P(_(`${M}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to push")}const o=await De(e,n);return o.success&&pV(e,s),o}async function H1(e,t={}){const s=await P(_(`${M}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to pull")}return De(e,s)}async function W1(e,t={}){const s=await P(_(`${M}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to fetch")}return De(e,s)}const Ck=async(e,t,s)=>{const n=await P(e,t);if(!n.ok){const o=Fp.parse(await n.json());throw o.code==="NOT_FOUND"&&s&&$V(s.runtimeKey,s.operationId),new Ip(o.code,o.error,n.status)}return GV.parse(await n.json())},q1=(e,t,s)=>{if(s.operationId!==e)throw new Error("Malformed Git network operation response");const n=tu(t,e,s.runtimeIdentity.id);if(!n&&tu(t,e))throw new Error("Malformed Git network operation response");if(n){const o=n.value.transport,i=s.state!=="planned"&&s.state!=="running",a=es(n.value.target,s.target)||i&&JV(n.value.target)===JSON.stringify(s.target);if(!es(n.value.runtimeIdentity,s.runtimeIdentity)||!a||!su(o,s.transport,i))throw new Error("Malformed Git network operation response");if(n.value.terminalState&&(s.state==="planned"||s.state==="running"||s.state!==n.value.terminalState))throw new Error("Malformed Git network operation response");es(o,s.transport)===false&&(n.value.transport=s.transport),s.state!=="planned"&&s.state!=="running"?n.value.terminalState||(QV(s)&&(_p(n.value.runtimeKey,n.value.directory),n.value.runtimeKey===F()&&ck(n.value.directory)),n.value.terminalState=s.state,n.value.observedAt=Date.now()):n.value.observedAt=Date.now()}if(F()!==t)throw new Error("Git network operation response belongs to a stale runtime");return s};async function G1(e){const t=F(),s=await Ck(`${M}/network-operations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(s.state!=="planned")throw new Error("Malformed Git network operation plan response");if(F()!==t)throw new Error("Git network operation response belongs to a stale runtime");XV(e,s);const n=zV(t,s.runtimeIdentity.id,s.operationId);if(tu(t,s.operationId,s.runtimeIdentity.id)?.value.terminalState)throw new Error("Malformed Git network operation plan response");return Vt.set(n,{operationId:s.operationId,runtimeKey:t,directory:e.operation==="clone"?e.destinationPath:e.directory,runtimeIdentity:s.runtimeIdentity,transport:s.transport,target:s.target,observedAt:Date.now()}),Np(),s}async function z1(e){const t=await P(`${M}/contributor-destinations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const s=Fp.parse(await t.json());throw new Ip(s.code,s.error,t.status)}return OV.parse(await t.json())}async function $1(e){const t=F(),s=await P(_(`${M}/contributor-destinations`,e));if(!s.ok){const o=Fp.parse(await s.json());throw new Ip(o.code,o.error,s.status)}const n=MV.parse(await s.json());if(F()!==t)throw new Error("Contributor destinations belong to a stale runtime");return n}async function K1(e){const t=await P(_(`${M}/worktrees/checkout-trust`,e));if(!t.ok)throw new Error((await t.json()).error||"Failed to inspect checkout actions");return FV.parse(await t.json())}async function J1(e,t,s){const n=await P(_(`${M}/worktrees/checkout-trust`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({digest:t,decision:s})});if(!n.ok)throw new Error((await n.json()).error||"Failed to apply checkout trust decision");return d({state:c().min(1)}).passthrough().parse(await n.json())}const Up=async(e,t)=>{const s=F();KV(s,e);const n=t?`/${t}`:"",o=t?{method:"POST"}:void 0,i=await Ck(`${M}/network-operations/${encodeURIComponent(e)}${n}`,o,{runtimeKey:s,operationId:e});return q1(e,s,i)};async function Y1(e){return Up(e,"execute")}async function X1(e){return Up(e)}async function Q1(e){return Up(e,"cancel")}async function Z1(e){const t=await P(_(`${M}/stashes`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to list stashes")}return t.json()}async function eH(e,t){const s=await P(_(`${M}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to count stash files")}return s.json()}async function Tk(e,t={}){const s=await P(_(`${M}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to stash changes")}return De(e,s)}const jp=async(e,t,s)=>{const n=await P(_(`${M}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||`Failed to ${t}`)}return De(e,n)},tH=(e,t)=>jp(e,"stash/apply",t),Ak=(e,t)=>jp(e,"stash/pop",t),sH=(e,t)=>jp(e,"stash/drop",t);async function nH(e,t){const s=await P(_(`${M}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to checkout branch")}return De(e,s)}async function oH(e,t,s){const n=await P(_(`${M}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create branch")}return De(e,n)}async function iH(e,t,s){const n=await P(_(`${M}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:s})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to rename branch")}return De(e,n)}async function aH(e,t={}){const s=await P(_(`${M}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(`Failed to get git log: ${n.error||s.statusText}`)}return vV.parse(await s.json())}const rH=d({sha:c().regex(/^[0-9a-f]{40}$/),changeId:c().regex(/^I[0-9a-f]{40}$/)});async function cH(e,t){const s=await P(_(`${M}/change-id`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedHead:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to add a Change-Id")}return Ho(e),rH.parse(await s.json())}async function lH(e,t){const s=await P(_(`${M}/commit-files`,e,{hash:t}));if(!s.ok)throw await wa(s,"Failed to get commit files");return yV.parse(await s.json())}async function xJ(e,t){const{base:s,head:n,path:o,previousPath:i,includeWorkingTree:a}=t,r=await P(_(`${M}/range-file-versions`,e,{base:s,head:n,path:o,previousPath:i,includeWorkingTree:a?"true":void 0}));if(!r.ok)throw await wa(r,"Failed to read file versions");return mV.parse(await r.json())}async function dH(e,t,s,n,o){const i=await P(_(`${M}/commit-file-diff`,e,{hash:t,path:s,binary:n?"true":void 0,previousPath:o}));if(!i.ok)throw new Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function uH(){const e=await P(_(`${M}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return cV.parse(await e.json())}async function pH(e){const t=Eo.parse(e),s=await P(_(`${M}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to create git identity")}return Eo.parse(await s.json())}async function hH(e,t){const s=Eo.parse(t);if(s.id!==e)throw new Error("Git identity profile ID does not match the update target");const n=await P(_(`${M}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to update git identity")}return Eo.parse(await n.json())}async function gH(e){const t=await P(_(`${M}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to delete git identity")}}async function mH(e){if(!e)return null;const t=await P(_(`${M}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const s=await t.json();return s?rk.parse(s):null}async function fH(e){if(!e)return false;const t=await P(_(`${M}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===true}async function wH(){const e=await P(_(`${M}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();if(!t)return null;const s=rk.parse(t);return s.userName||s.userEmail?s:null}async function bH(e,t){const s=await P(_(`${M}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to set git identity")}return lV.parse(await s.json())}async function yH(e){const t=await P(_(`${M}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return EV.parse(await t.json())}async function vH(e,t){const s=await P(_(`${M}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to rebase")}return De(e,s)}async function kH(e){const t=await P(_(`${M}/rebase/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort rebase")}return De(e,t)}async function SH(e,t){const s=await P(_(`${M}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to merge")}return De(e,s)}async function CH(e,t){const s=await P(_(`${M}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to checkout commit")}return De(e,s)}async function TH(e,t){const s=await P(_(`${M}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to cherry-pick")}return De(e,s)}async function AH(e,t){const s=await P(_(`${M}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const n=await s.json().catch(()=>({error:s.statusText}));throw new Error(n.error||"Failed to revert commit")}return De(e,s)}async function PH(e,t,s,n){const o=await P(_(`${M}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:s,force:n})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to reset")}return De(e,o)}async function RH(e){const t=await P(_(`${M}/merge/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort merge")}return De(e,t)}async function IH(e){const t=await P(_(`${M}/rebase/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue rebase")}return De(e,t)}async function xH(e){const t=await P(_(`${M}/merge/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue merge")}return De(e,t)}async function EH(e,t){return await Tk(e,{message:t?.message}),{success:true}}async function OH(e){return await Ak(e,{ref:"stash@{0}"}),{success:true}}async function DH(e){const t=await P(_(`${M}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function MH(e,t){const s=await P(`${M}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!s.ok)throw new Error(`Failed to validate worktree directory: ${s.statusText}`);return s.json()}async function FH(e){const t=await P(`${M}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const _H=/^[a-z][a-z0-9-]{0,31}$/,$r=e=>Object.prototype.toString.call(e)==="[object String]"&&_H.test(e),xm="ext-",Pk=e=>$r(e)&&e.startsWith(xm)&&$r(e.slice(xm.length)),Rk=(e,t,s)=>{if(typeof s!="string"||!s.startsWith(`${t}#`))return false;const n=s.slice(t.length+1);return Pk(e)?n.length>0&&n.length<=256:/^\d+$/.test(n)},NH=e=>Object.prototype.toString.call(e)==="[object String]"&&/^[\x20-\x39\x3b-\x7e]{1,256}$/.test(e)&&e.trim()===e,Ik=e=>e!==null&&Object.prototype.toString.call(e)==="[object Object]"&&Object.getPrototypeOf(e)===Object.prototype,LH=e=>Object.prototype.toString.call(e)==="[object String]",Ct=e=>LH(e)&&e.length>0,Em=(e,t=512)=>Ct(e)&&e.length<=t&&e.trim()===e&&!/[\0\r\n]/.test(e),UH=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/,jH=e=>{const t=e.toLowerCase();return t==="localhost"||t==="::1"||t==="[::1]"||UH.test(t)},BH=e=>{if(!e.instance.includes("://"))return/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(e.instance);try{const t=new URL(e.instance),s=jH(t.hostname);return t.origin===e.instance&&!t.username&&!t.password&&["","/"].includes(t.pathname)&&!t.search&&!t.hash&&(t.protocol==="https:"||t.protocol==="http:"&&s)}catch{return false}},bs=(e,t,s=[])=>Ik(e)&&t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>t.includes(n)||s.includes(n)),Om=e=>{let t;try{t=decodeURIComponent(e)}catch{return false}const s=t.replace(/^\/+|\/+$/g,"");return!!(s&&!/[\0\r\n]/.test(s)&&!s.split("/").some(n=>!n||n==="."||n===".."))},VH=e=>{if(!Ct(e)||e.trim()!==e||e.length>4096||/[\0\r\n]/.test(e))return false;if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&Om(`/${t[1]}`))}try{const t=new URL(e);return["http:","https:","ssh:"].includes(t.protocol)&&!!t.hostname&&(!t.username||t.protocol==="ssh:")&&!t.password&&!t.search&&!t.hash&&Om(t.pathname)}catch{return false}},nu=e=>bs(e,["displayUrl","fingerprint"])&&VH(e.displayUrl)&&Ct(e.fingerprint)&&e.fingerprint.length<=128&&/^[A-Za-z0-9_-]+$/.test(e.fingerprint),sr=nu,Dm=e=>["managed","system","anonymous"].includes(e.mode)&&(e.mode==="managed"?Ct(e.credentialId):!Object.hasOwn(e,"credentialId")),HH=e=>Ik(e)&&Object.hasOwn(e,"status")&&(e.status==="unavailable"&&bs(e,["status"])||e.status==="available"&&(bs(e,["status","transport","fingerprint"])&&e.transport==="ssh"&&/^SHA256:[A-Za-z0-9+/]{43}=?$/.test(e.fingerprint)||bs(e,["status","transport","provider","instance","source","username","providerUserId"])&&e.transport==="https"&&$r(e.provider)&&["oauth","pat","cli"].includes(e.source)&&Em(e.instance,2048)&&NH(e.username)&&Em(e.providerUserId)&&BH(e)&&Rk(e.provider,e.instance,e.providerUserId))),Il=(e,t)=>new Set(e.map(t)).size===e.length,ri=()=>Object.assign(new Error("Source control binding storage is invalid"),{code:"INVALID_SOURCE_CONTROL_BINDINGS"}),WH=(e,t=false)=>{if(!bs(e,["repositoryId","revision","state","configRevision","providers","remotes"],["auxiliary"])||!Ct(e.repositoryId)||!Number.isSafeInteger(e.revision)||e.revision<1||!Ct(e.configRevision)||!["bound","needs-attention"].includes(e.state)||!Array.isArray(e.providers)||!Array.isArray(e.remotes)||!Array.isArray(e.auxiliary))throw ri();for(const s of e.providers)if(!bs(s,["provider","instance","accountId","primaryRemote","readiness","endpoint"],["repository"])||!$r(s.provider)||!Ct(s.instance)||!Ct(s.accountId)||!Ct(s.primaryRemote)||s.repository!==void 0&&(!bs(s.repository,["owner","name"])||!Ct(s.repository.owner)||!Ct(s.repository.name))||!["ready","confirmation-required","account-unavailable","config-changed"].includes(s.readiness)||!(s.endpoint===null&&s.readiness!=="ready"||sr(s.endpoint)))throw ri();for(const s of e.remotes)if(!bs(s,["name","fetch","push","mode","readiness"],["credentialId",...t&&s.mode==="managed"?["presentation"]:[],...t?["inherited"]:[]])||!Ct(s.name)||!sr(s.fetch)||!sr(s.push)||!Dm(s)||s.presentation!==void 0&&!HH(s.presentation)||s.inherited!==void 0&&(s.inherited!==true||s.readiness!=="ready")||s.mode==="anonymous"&&!s.fetch.displayUrl.startsWith("https://")||!["ready","confirmation-required","config-changed"].includes(s.readiness))throw ri();for(const s of e.auxiliary??[])if(!bs(s,["kind","endpoint","mode","readiness"],["credentialId"])||!["submodule","lfs"].includes(s.kind)||!sr(s.endpoint)||!Dm(s)||s.mode==="anonymous"&&!s.endpoint.displayUrl.startsWith("https://")||!["ready","confirmation-required"].includes(s.readiness))throw ri();if((e.auxiliary?.length??0)>256||!Il(e.remotes,s=>s.name)||!Il(e.providers,s=>`${s.provider}\0${s.instance}\0${s.primaryRemote}`)||!Il(e.auxiliary??[],s=>`${s.kind}\0${s.endpoint.fingerprint}`))throw ri()},qH=e=>[...e.providers,...e.remotes,...e.auxiliary].some(t=>t.readiness!=="ready")?"needs-attention":"bound",GH=e=>(WH(e,true),structuredClone(e)),zH=(e,t)=>{const s=new Map(t.remotes.map(a=>[a.name,a])),n=e.providers.map(a=>a.readiness==="ready"&&a.endpoint?.fingerprint!==s.get(a.primaryRemote)?.fetch.fingerprint?{...a,readiness:"config-changed"}:a),o=e.remotes.map(a=>{const r=s.get(a.name);return a.readiness==="ready"&&(!r||a.fetch.fingerprint!==r.fetch.fingerprint||a.push.fingerprint!==r.push.fingerprint)?{...a,readiness:"config-changed"}:a}),i={...e,providers:n,remotes:o};return i.state=qH(i),i},Mm={referenceSearch:false,referenceDetail:false,listStatuses:false,referencesAcross:false,startThread:false,authorCanReview:false,projectUploads:false,issueCloseReason:false,changeRequestTemplates:[],changeRequestPatch:false},xk=[{id:"github",label:"GitHub",order:0,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:true,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"github",filledSprite:"github-fill"},repository:{nestedNamespaces:false},instances:{format:"host",defaultInstance:"github.com",defaultInstances:["github.com"],multiple:true,allowLoopbackHttp:false,allowPort:false,reserved:["github.com"],placeholder:"https://github.example.com",legacyFlow:{instance:"github.com",kind:"github-com-device"}},auth:{methods:["device","pat","cli"],cliName:"gh",cliTransport:true,token:{scopes:["repo","read:org","workflow","read:user","user:email"],createPath:"/settings/tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:false},{id:"token",kind:"personal-access-token",secret:true}]},urls:{changeRequest:["/{owner}/{repo}/pull/{number}"],issue:["/{owner}/{repo}/issues/{number}"],commit:["/{owner}/{repo}/commit/{sha}"],user:["/{user}"]},features:{...Mm,referenceSearch:true,referenceDetail:true,listStatuses:true,referencesAcross:true,issueCloseReason:true,changeRequestPatch:true}},{id:"gitlab",label:"GitLab",order:1,terminology:{changeRequest:"mergeRequest",changeRequestPrefix:"!",issuePrefix:"#",sharedNumberSpace:false,abbreviation:"MR",promptNoun:"merge request",ci:"pipeline"},icon:{sprite:"gitlab"},repository:{nestedNamespaces:true},instances:{format:"origin",defaultInstance:"https://gitlab.com",defaultInstances:["https://gitlab.com"],multiple:true,allowLoopbackHttp:true,allowPort:true,reserved:[],placeholder:"https://gitlab.example.com"},auth:{methods:["device","pat","cli"],cliName:"glab",cliTransport:false,token:{scopes:["api"],createPath:"/-/user_settings/personal_access_tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:false},{id:"token",kind:"personal-access-token",secret:true}]},urls:{changeRequest:["/{namespace+}/{repo}/-/merge_requests/{number}"],issue:["/{namespace+}/{repo}/-/issues/{number}","/{namespace+}/{repo}/-/work_items/{number}"],commit:["/{namespace+}/{repo}/-/commit/{sha}"],user:["/{user}"]},features:{...Mm,startThread:true,authorCanReview:true,projectUploads:true,changeRequestPatch:true,changeRequestTemplates:[".gitlab/merge_request_templates/Default.md"]}}],Wo=(e,t)=>`/api/source-control/${e.provider}${t}`,$H=d({providers:k(oe())}),KH=d({error:c()}),JH=async e=>{const t=await e("/api/source-control/providers",{headers:{Accept:"application/json"}});if(t.status===404)return _d.parse(xk);const s=await t.json().catch(()=>null);if(!t.ok){const i=KH.safeParse(s);throw new Error(i.success&&i.data.error||t.statusText||"Failed to load source control providers")}const n=$H.parse(s).providers,o=_d.parse(n);if(n.length>0&&o.length===0)throw new Error("Source control providers response contained no readable provider");return o},Ek=d({state:T(["success","failure","pending","unknown"]),total:y(),success:y(),failure:y(),pending:y(),inProgress:y().optional(),queued:y().optional(),startedAt:c().optional()}),xl={number:y(),title:c(),url:c(),body:c(),bodyTruncated:v(),createdAt:c().nullable(),updatedAt:c().nullable(),author:d({login:c(),avatarUrl:c().optional()}).nullable(),labels:k(d({name:c(),color:c().optional()})),commentCount:y(),sourceRepo:d({owner:c(),repo:c(),source:c()})},Ok=Z("kind",[d({kind:g("issue"),...xl,state:T(["open","completed","not_planned"])}),d({kind:g("pull"),...xl,state:T(["open","closed","merged"]),draft:v(),head:c(),base:c(),headSha:c(),headRepo:d({owner:c(),repo:c(),url:c(),cloneUrl:c().optional(),sshUrl:c().optional()}).nullable()}),d({kind:g("discussion"),...xl,state:T(["open","resolved","outdated","duplicate"]),answered:v().nullable(),upvotes:y(),locked:v(),category:d({name:c(),emoji:c().nullable(),answerable:v()})})]),YH=Z("connected",[d({connected:g(false)}),d({connected:g(true),repo:d({owner:c(),repo:c(),url:c()}).nullable(),items:k(Ok),cursor:c().nullable(),hasMore:v(),total:y()})]),Fm={author:d({login:c(),avatarUrl:c().optional()}).nullable(),body:c(),createdAt:c().nullable(),url:c(),path:c().nullable(),line:y().nullable(),review:T(["approved","changes_requested","commented","dismissed"]).nullable(),excerpt:d({startLine:y().int().positive(),lines:k(c()).max(200)}).optional().catch(void 0)},XH=Z("connected",[d({connected:g(false)}),d({connected:g(true),detail:d({number:y(),comments:k(d({...Fm,thread:d({id:c().min(1),resolved:v(),canResolve:v(),canReply:v(),replies:k(d(Fm))}).optional(),answer:d({chosen:v(),canChange:v()}).optional()})),commentTotal:y(),pull:d({reviewDecision:T(["approved","changes_requested","review_required"]).nullable(),reviewers:k(d({id:c(),login:c(),avatarUrl:c().optional()})).default([]),checks:Ek.nullable().optional(),additions:y(),deletions:y(),changedFiles:y(),commits:k(d({sha:c(),headline:c(),author:d({login:c(),avatarUrl:c().optional()}).nullable(),authorName:c().nullable(),committedAt:c().nullable(),url:c().nullable()})).default([]),commitTotal:y().nullable().default(null),stack:d({number:y().nullable(),base:c(),layers:k(d({number:y(),title:c(),url:c(),state:T(["open","closed","merged"]),draft:v(),head:c()}))}).nullable().optional().catch(void 0)}).nullable(),discussion:d({canComment:v(),canClose:v(),canReopen:v()}).optional()}).nullable()})]),QH=Sa({items:k(Ok.and(d({directory:c().min(1)}))),cursor:c().nullable(),hasMore:v(),total:y().int().nonnegative(),repositories:k(L([Sa({directory:c().min(1),status:g("included"),repo:Sa({owner:c(),repo:c(),url:c(),host:c().optional()})}),Sa({directory:c().min(1),status:T(["no-repo","disconnected","invalid-context","error"])})]))}),ZH=Z("connected",[d({connected:g(false)}),d({connected:g(true),statuses:k(d({owner:c(),repo:c(),number:y(),checks:Ek.nullable(),mergeable:v().nullable(),mergeableState:c().nullable()}))})]),eW=d({error:c()}),kc=e=>{const t=new URLSearchParams({directory:e.directory,instance:e.instance,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},va=async(e,t,s)=>{const n=await e.json().catch(()=>null);if(!e.ok){const o=eW.safeParse(n);throw new Error(o.success&&o.data.error||e.statusText||s)}return t.parse(n)},tW=async(e,t,s)=>{const n=kc(t);n.set("kind",s.kind),s.state&&n.set("state",s.state),s.people&&n.set("people",s.people),s.query?.trim()&&n.set("query",s.query.trim()),s.cursor&&n.set("cursor",s.cursor);const o=await e(Wo(t,"/references"),{query:n,headers:{Accept:"application/json"}}),i=await va(o,YH,"Failed to load issues and pull requests");return i.connected?{...i,items:i.items.map(a=>({...a,provider:t.provider}))}:i},sW=async(e,t,s)=>{const n=kc(t);n.set("owner",s.owner),n.set("repo",s.repo),n.set("number",String(s.number)),s.kind==="discussion"&&n.set("kind","discussion");const o=s.host?.trim();o&&o!=="github.com"&&n.set("host",o);const i=await e(Wo(t,"/references/detail"),{query:n,headers:{Accept:"application/json"}});return va(i,XH,"Failed to load issue or pull request detail")},_m=d({login:c(),avatarUrl:c().optional()}).nullable(),Nm=T(["old","new"]),nW=Z("connected",[d({connected:g(false)}),d({connected:g(true),viewerIsAuthor:v(),headSha:c(),draft:d({id:c(),body:c(),comments:k(d({id:c(),path:c(),side:Nm,line:y().int().nullable(),startLine:y().int().nullable(),body:c(),author:_m}))}).nullable(),threads:k(d({id:c(),path:c(),side:Nm,line:y().int().nullable(),startLine:y().int().nullable(),resolved:v(),canReply:v(),canResolve:v(),comments:k(d({id:c(),body:c(),createdAt:c(),url:c(),author:_m}))})),truncated:v()})]),oW=async(e,t,s)=>{const n=kc(t);n.set("owner",s.owner),n.set("repo",s.repo),n.set("number",String(s.number));const o=await e(Wo(t,"/pr/review/state"),{query:n,headers:{Accept:"application/json"}});return va(o,nW,"Failed to load the review")},iW=async(e,t,s)=>{const[n]=t;if(!n||t.some(a=>a.provider!==n.provider))throw new Error("A search across repositories needs contexts of one provider");const o=await e(Wo(n,"/references/across"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({contexts:t,...s,query:s.query?.trim()})}),i=await va(o,QH,"Failed to load issues and pull requests");return{...i,items:i.items.map(a=>({...a,provider:n.provider}))}},aW=async(e,t,s)=>{const n=kc(t);n.set("pulls",s.map(i=>{const a=i.host?.trim().toLowerCase();return`${i.owner}/${i.repo}#${i.number}${a&&a!=="github.com"?`@${a}`:""}`}).join(","));const o=await e(Wo(t,"/references/status"),{query:n,headers:{Accept:"application/json"}});return va(o,ZH,"Failed to load pull request statuses")};class ks extends Error{constructor(t,s){super(t),this.code=s}code}const Sc=new Map,Dk=e=>{for(const t of e)Sc.set(t.id,{format:t.instances.format,label:t.label,pathStyle:t.repository.pathStyle==="path"})},Bp=(e,t)=>Q(t)&&(t.trim().length>0||t===""&&Sc.get(e.provider)?.pathStyle!==false);Dk(xk);const ia=e=>Sc.get(e.provider)?.label??e.provider,rW=e=>{const t=e.instance.trim();let s;try{s=new URL(t.includes("://")?t:`https://${t}`)}catch{throw new Error(`Invalid source control instance: ${e.instance}`)}const n=["localhost","127.0.0.1","::1","[::1]"].includes(s.hostname.toLowerCase());if(s.username||s.password||s.search||s.hash||s.pathname&&s.pathname!=="/"||s.protocol!=="https:"&&!(s.protocol==="http:"&&n))throw new Error(`Invalid ${ia(e)} instance: ${e.instance}`);return{provider:e.provider,instance:s.origin}},cW=e=>{const t=e.instance.trim().toLowerCase().replace(/\.$/,"");let s=t;if(t.includes("://"))try{const n=new URL(t);if(n.protocol!=="https:"||n.username||n.password||n.port||n.search||n.hash||n.pathname&&n.pathname!=="/")throw new Error(`Invalid ${ia(e)} instance: ${e.instance}`);s=n.hostname.toLowerCase().replace(/\.$/,"")}catch{throw new Error(`Invalid ${ia(e)} instance: ${e.instance}`)}return{provider:e.provider,instance:s}},$=e=>{const t=(Sc.get(e.provider)?.format??"origin")==="host"?cW(e):rW(e),s=e.instanceSshUrl?.trim()?{...t,instanceSshUrl:e.instanceSshUrl.trim()}:t,n=Array.isArray(e.instanceAliases)?e.instanceAliases.filter(D):[];return n.length?{...s,instanceAliases:n}:s},Mk=e=>{if(!e||!Q(e.repositoryId)||!e.repositoryId||!Q(e.configRevision)||!e.configRevision||Object.prototype.toString.call(e.bare)!=="[object Boolean]"||!Array.isArray(e.remotes))throw new Error("Source control response contained an invalid repository context");const t=e.remotes.map(s=>{if(!s||!Q(s.name)||!s.name||!nu(s.fetch)||!nu(s.push))throw new Error("Source control response contained an invalid repository remote");return{name:s.name,fetch:{displayUrl:s.fetch.displayUrl,fingerprint:s.fetch.fingerprint},push:{displayUrl:s.push.displayUrl,fingerprint:s.push.fingerprint}}});return{repositoryId:e.repositoryId,configRevision:e.configRevision,bare:e.bare,remotes:t}},wo=e=>{const t=Mk(e.repository);if(!Number.isInteger(e.revision)||e.revision<0)throw new Error("Source control response contained an invalid binding revision");if(e.binding===null)return{status:"missing",repository:t,revision:e.revision,binding:null};const s=GH(e.binding);if(!s||s.repositoryId!==t.repositoryId||s.revision!==e.revision||!Q(s.configRevision)||!Array.isArray(s.providers)||!Array.isArray(s.auxiliary)||s.state!=="bound"&&s.state!=="needs-attention")throw new Error("Source control response contained an invalid repository binding");const n=zH({...s,providers:s.providers.map(o=>({...o,...$(o)}))},t);return{status:n.state,repository:t,revision:e.revision,binding:n}},Lm=async(e,t,s)=>{const n=await e(t,{query:new URLSearchParams({directory:s}),headers:{Accept:"application/json"}}),o=await n.json();if(!n.ok)throw new ks(o.error||n.statusText||"Source control repository request failed",o.code);return o},lW=async(e,t=P)=>{const s=await t("/api/source-control/binding/transport",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new ks(n.error||"Git transport configuration failed",n.code);return{status:"configured",binding:wo(n)}},dW=async(e,t=P)=>{const s=await t("/api/source-control/binding/transport/remove",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new ks(n.error||"Git transport removal failed",n.code);return{status:"removed",binding:wo(n)}},uW=async(e,t=P)=>{const s=await t("/api/source-control/binding/auxiliary",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),n=await s.json();if(!s.ok)throw new ks(n.error||"Git auxiliary transport configuration failed",n.code);return{status:"configured",binding:wo(n)}},Xe=async(e,t,s,n={},o)=>{const i=$(t),a=await e(Wo(i,s),{...n,query:new URLSearchParams([["instance",i.instance],...o?Array.from(o.entries()):[]]),headers:{Accept:"application/json",...n.headers}}),r=await a.json();if(!a.ok){const l=r?.error||a.statusText||"Source control request failed";throw r?.code==="SOURCE_CONTROL_INSTANCE_OTHER_PROVIDER"&&D(r.provider)?new nV(l,r.provider):new ks(l,r?.code)}return r},us=e=>{const t=new URLSearchParams({directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},pW=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!D(t)))throw new Error("Source control response contained invalid incomplete projects");return[...e]}},de=(e,t,s,n)=>Xe(e,t,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),Wt=(e,t)=>{const s=Object.keys(e);return s.length===t.length&&s.every(n=>t.includes(n))};function ke(e,t,s){const n=e.target;if(!D(e.directory)||!D(e.repositoryId)||!D(e.accountId)||!Nk(e.bindingRevision)||!D(e.primaryRemote)||!D(e.idempotencyKey)||!n||!Bp(t,n.project?.owner)||!D(n.project?.name)||s==="create"&&("number"in n||"headSha"in n)||s==="create"&&(!D(n.head)||!D(n.base))||s==="existing"&&!Gt(n.number)||n.number!==void 0&&!Gt(n.number)||n.head!==void 0&&!D(n.head)||n.base!==void 0&&!D(n.base)||n.headSha!==void 0&&!D(n.headSha))throw new Error("Source control mutation context is invalid");const o={...t,directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:e.bindingRevision,primaryRemote:e.primaryRemote,idempotencyKey:e.idempotencyKey};if(s==="create"){if(!D(n.head)||!D(n.base))throw new Error("Source control mutation context is invalid");return{...o,target:{project:{owner:n.project.owner,name:n.project.name},head:n.head,base:n.base}}}if(!Gt(n.number))throw new Error("Source control mutation context is invalid");const i={project:{owner:n.project.owner,name:n.project.name},number:n.number};return n.head!==void 0&&(i.head=n.head),n.base!==void 0&&(i.base=n.base),n.headSha!==void 0&&(i.headSha=n.headSha),{...o,target:i}}const hW=(e,t)=>e.repositoryId===t.repositoryId&&e.bindingRevision===t.bindingRevision&&e.primaryRemote===t.primaryRemote&&e.project.owner===t.target.project.owner&&e.project.name===t.target.project.name&&(t.target.number===void 0||e.number===t.target.number)&&(t.target.head===void 0||e.head===t.target.head)&&(t.target.base===void 0||e.base===t.target.base)&&(t.target.headSha===void 0||e.headSha===t.target.headSha),Se=(e,t,s,n)=>{const o=e?.actor,i=e?.target,a=i?.project;if(!e||!Wt(e,["status","actor","target","replayed","result"])||e.status!=="succeeded"||!Re(e.replayed)||!o||!Wt(o,["provider","instance","providerAccountId"])||o.provider!==s.provider||o.instance!==s.instance||!D(o.providerAccountId)||!Rk(s.provider,s.instance,o.providerAccountId)||!i||!Wt(i,["repositoryId","bindingRevision","primaryRemote","project",...["number","head","base","headSha"].filter(l=>i[l]!==void 0)])||!D(i.repositoryId)||!Nk(i.bindingRevision)||!D(i.primaryRemote)||!a||!Wt(a,["id","owner","name"])||!D(a.id)||!Bp(s,a.owner)||!D(a.name)||i.number!==void 0&&!Gt(i.number)||i.head!==void 0&&!D(i.head)||i.base!==void 0&&!D(i.base)||i.headSha!==void 0&&!D(i.headSha)||!hW(i,t)||!e.result||Object.prototype.toString.call(e.result)!=="[object Object]")throw new Error("Source control response contained an invalid mutation receipt");const r={repositoryId:i.repositoryId,bindingRevision:i.bindingRevision,primaryRemote:i.primaryRemote,project:{id:a.id,owner:a.owner,name:a.name}};return i.number!==void 0&&(r.number=i.number),i.head!==void 0&&(r.head=i.head),i.base!==void 0&&(r.base=i.base),i.headSha!==void 0&&(r.headSha=i.headSha),{status:"succeeded",actor:{...s,providerAccountId:o.providerAccountId},target:r,replayed:e.replayed,result:n(e.result)}},Ye=e=>{if(!Wt(e,[]))throw new Error("Source control response contained an invalid mutation result");return{}},gW=["queued","merging","auto-merge","cancelled"],mW=e=>gW.find(t=>t===e)??null,fW=e=>{if(!Wt(e,e.stacked===void 0?[]:["stacked"])||e.stacked!==void 0&&!Re(e.stacked))throw new Error("Source control response contained an invalid create result");return e.stacked===void 0?{}:{stacked:e.stacked}},wW=e=>{const t=["merged",...e.message===void 0?[]:["message"],...e.outcome===void 0?[]:["outcome"]],s=e.outcome===void 0?void 0:mW(e.outcome);if(!Wt(e,t)||!Re(e.merged)||e.message!==void 0&&!Q(e.message)||s===null)throw new Error("Source control response contained an invalid merge result");const n={merged:e.merged};return e.message!==void 0&&(n.message=e.message),s!==void 0&&(n.outcome=s),n},bW=e=>{if(!Wt(e,["commented"])||!Re(e.commented))throw new Error("Source control response contained an invalid review result");return{commented:e.commented}},Um=async(e,t,s,n)=>{const o=$(t),i=us(t);i.set("owner",s.owner),i.set("repo",s.repo);const a=await Xe(e,o,n,{},i);if(a.connected!==true)throw new Error(`${ia(o)} is not connected`);if(!Array.isArray(a.items))throw new Error("Source control response contained an invalid list");return a.items},yW=e=>e.map(t=>{if(!D(t.name)||t.color!==void 0&&!Q(t.color))throw new Error("Source control response contained an invalid label");return t.color?{name:t.name,color:t.color}:{name:t.name}}),vW=e=>e.map(t=>{if(!D(t.id)||!D(t.login)||t.avatarUrl!==void 0&&!xs(t.avatarUrl))throw new Error("Source control response contained an invalid user");return t.avatarUrl?{id:t.id,login:t.login,avatarUrl:t.avatarUrl}:{id:t.id,login:t.login}}),El=e=>{if(!Wt(e,["state"])||e.state!=="open"&&e.state!=="closed")throw new Error("Source control response contained an invalid state result");return{state:e.state}},kW=e=>{if(!Wt(e,["ready"])||!Re(e.ready))throw new Error("Source control response contained an invalid ready result");return{ready:e.ready}},SW=e=>{if(!Wt(e,["draft"])||!Re(e.draft))throw new Error("Source control response contained an invalid draft result");return{draft:e.draft}},bt=(e,t)=>{const s=e?.username||e?.login,n=Pk(t.provider)?typeof e?.id=="string"&&e.id.length>0&&e.id.length<=256||Gt(e?.id):e&&As(e.id);if(!e||!n||!D(s)||!NW(e,t)||e.avatarUrl!==void 0&&!xs(e.avatarUrl)||e.name!==void 0&&!Q(e.name)||e.email!==void 0&&!Q(e.email))throw new Error("Source control response contained an invalid user");const o={...t,id:String(e.id),username:s};return e.avatarUrl&&(o.avatarUrl=e.avatarUrl),e.name&&(o.name=e.name),e.email&&(o.email=e.email),o},Oo=(e,t)=>{if(!e||!As(e.id)||!Bp(t,e.owner)||!D(e.name)||!xs(e.url)||!Pt(e,t)||e.cloneUrl!==void 0&&!D(e.cloneUrl)||e.sshUrl!==void 0&&!D(e.sshUrl)||e.defaultBranch!==void 0&&!D(e.defaultBranch)||e.defaultBranchSha!==void 0&&e.defaultBranchSha!==null&&!D(e.defaultBranchSha)||e.remoteName!==void 0&&e.remoteName!==null&&!D(e.remoteName))throw new Error("Source control response contained an invalid project");const s={...t,id:String(e.id),owner:e.owner,name:e.name,url:e.url};return e.cloneUrl&&(s.cloneUrl=e.cloneUrl),e.sshUrl&&(s.sshUrl=e.sshUrl),e.defaultBranch&&(s.defaultBranch=e.defaultBranch),e.defaultBranchSha!==void 0&&(s.defaultBranchSha=e.defaultBranchSha),e.remoteName!==void 0&&(s.remoteName=e.remoteName),s},Fk=(e,t)=>{if(e==null)return null;if(!e.summary)throw new Error("Source control response contained an invalid CI summary");if(jW(e.summary),e.runs!==void 0){if(!Array.isArray(e.runs)||e.runs.some(s=>!s||!As(s.id)||!D(s.name)||!Pt(s,t)||s.detailsUrl!==void 0&&!xs(s.detailsUrl)))throw new Error("Source control response contained invalid CI runs");for(const s of e.runs){if(s.startedAt!==void 0&&!D(s.startedAt)||s.completedAt!==void 0&&!D(s.completedAt)||s.status!==void 0&&!D(s.status)||s.conclusion!==void 0&&s.conclusion!==null&&!Q(s.conclusion))throw new Error("Source control response contained invalid CI run fields");if(s.application!==void 0&&(Object.prototype.toString.call(s.application)!=="[object Object]"||s.application.name!==void 0&&!Q(s.application.name)||s.application.slug!==void 0&&!Q(s.application.slug)))throw new Error("Source control response contained an invalid CI application");if(s.job!==void 0&&(Object.prototype.toString.call(s.job)!=="[object Object]"||s.job.runId!==void 0&&!As(s.job.runId)||s.job.jobId!==void 0&&!As(s.job.jobId)||s.job.url!==void 0&&!xs(s.job.url)||s.job.name!==void 0&&!Q(s.job.name)||s.job.workflowName!==void 0&&!Q(s.job.workflowName)||s.job.conclusion!==void 0&&s.job.conclusion!==null&&!Q(s.job.conclusion)))throw new Error("Source control response contained an invalid CI job");if(s.job?.steps!==void 0&&(!Array.isArray(s.job.steps)||s.job.steps.some(n=>!n||!D(n.name)||n.status!==void 0&&!Q(n.status)||n.conclusion!==void 0&&n.conclusion!==null&&!Q(n.conclusion)||n.number!==void 0&&(!Number.isInteger(n.number)||n.number<0)||n.startedAt!==void 0&&!D(n.startedAt)||n.completedAt!==void 0&&!D(n.completedAt))))throw new Error("Source control response contained invalid CI steps");if(s.output!==void 0&&(Object.prototype.toString.call(s.output)!=="[object Object]"||s.output.title!==void 0&&!Q(s.output.title)||s.output.summary!==void 0&&!Q(s.output.summary)||s.output.text!==void 0&&!Q(s.output.text)))throw new Error("Source control response contained invalid CI output");if(s.annotations!==void 0&&(!Array.isArray(s.annotations)||s.annotations.some(n=>!n||!D(n.message)||n.path!==void 0&&!Q(n.path)||n.startLine!==void 0&&(!Number.isInteger(n.startLine)||n.startLine<0)||n.endLine!==void 0&&(!Number.isInteger(n.endLine)||n.endLine<0)||n.level!==void 0&&!Q(n.level)||n.title!==void 0&&!Q(n.title)||n.rawDetails!==void 0&&!Q(n.rawDetails))))throw new Error("Source control response contained invalid CI annotations")}}return{summary:{state:e.summary.state,total:e.summary.total,success:e.summary.success,failure:e.summary.failure,pending:e.summary.pending,inProgress:e.summary.inProgress,queued:e.summary.queued,startedAt:e.summary.startedAt},runs:e.runs?.map(s=>({...t,id:String(s.id),name:s.name,status:s.status,conclusion:s.conclusion,startedAt:s.startedAt,completedAt:s.completedAt,detailsUrl:s.detailsUrl,application:s.application,job:s.job,output:s.output,annotations:s.annotations}))}},ou=(e,t)=>{if(!e||!As(e.id)||!Number.isInteger(e.number)||e.number<1||!D(e.title)||!xs(e.url)||!["open","closed","merged"].includes(e.state)||!Re(e.draft)||!D(e.base)||!D(e.head)||!Pt(e,t)||e.body!==void 0&&!Q(e.body)||e.headSha!==void 0&&!D(e.headSha)||e.author!==void 0&&e.author!==null&&!Pt(e.author,t)||e.createdAt!==void 0&&!D(e.createdAt)||e.updatedAt!==void 0&&!D(e.updatedAt)||e.headLabel!==void 0&&!D(e.headLabel)||e.mergeable!==void 0&&e.mergeable!==null&&!Re(e.mergeable)||e.mergeableState!==void 0&&e.mergeableState!==null&&!Q(e.mergeableState)||e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(n=>!n||!D(n.name)||n.color!==void 0&&!Q(n.color)))||e.workInProgress!==void 0&&!Re(e.workInProgress)||e.private!==void 0&&!Re(e.private)||e.topic!==void 0&&!Q(e.topic)||e.hashtags!==void 0&&(!Array.isArray(e.hashtags)||e.hashtags.some(n=>!D(n)))||e.revisionNumber!==void 0&&!Gt(e.revisionNumber))throw new Error("Source control response contained an invalid change request");const s={...t,id:String(e.id),number:e.number,project:Oo(e.project,t),title:e.title,url:e.url,state:e.state,draft:e.draft,base:e.base,head:e.head};return e.body!==void 0&&(s.body=e.body),e.headSha&&(s.headSha=e.headSha),e.author!==void 0&&e.author!==null&&(s.author=bt(e.author,t)),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),e.headLabel&&(s.headLabel=e.headLabel),e.headProject!==void 0&&e.headProject!==null&&(s.headProject=Oo(e.headProject,t)),e.mergeable!==void 0&&(s.mergeable=e.mergeable),e.mergeableState!==void 0&&(s.mergeableState=e.mergeableState),e.labels!==void 0&&(s.labels=e.labels.map(n=>({name:n.name,color:n.color}))),e.workInProgress!==void 0&&(s.workInProgress=e.workInProgress),e.private!==void 0&&(s.private=e.private),e.topic&&(s.topic=e.topic),e.hashtags!==void 0&&(s.hashtags=[...e.hashtags]),e.revisionNumber!==void 0&&(s.revisionNumber=e.revisionNumber),s},jm=(e,t)=>{if(!e||!As(e.id)||!Number.isInteger(e.number)||e.number<1||!D(e.title)||!xs(e.url)||e.state!=="open"&&e.state!=="closed"||!Pt(e,t)||e.body!==void 0&&!Q(e.body)||e.author!==void 0&&e.author!==null&&!Pt(e.author,t)||e.createdAt!==void 0&&!D(e.createdAt)||e.updatedAt!==void 0&&!D(e.updatedAt))throw new Error("Source control response contained an invalid issue");if(e.assignees!==void 0&&(!Array.isArray(e.assignees)||e.assignees.some(n=>!Pt(n,t))))throw new Error("Source control response contained invalid issue assignees");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(n=>!n||!D(n.name)||n.color!==void 0&&!Q(n.color))))throw new Error("Source control response contained invalid issue labels");const s={...t,id:String(e.id),number:e.number,project:Oo(e.project,t),title:e.title,url:e.url,state:e.state};return e.body!==void 0&&(s.body=e.body),e.author!==void 0&&(s.author=e.author?bt(e.author,t):null),e.assignees!==void 0&&(s.assignees=e.assignees.map(n=>bt(n,t))),e.labels!==void 0&&(s.labels=e.labels.map(n=>({name:n.name,color:n.color}))),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),s},CW=e=>{if(!e||!D(e.sha)||!Q(e.headline)||e.authorName!==null&&!Q(e.authorName)||e.committedAt!==null&&!D(e.committedAt)||e.url!==null&&!xs(e.url))throw new Error("Source control response contained an invalid commit");return{sha:e.sha,headline:e.headline,authorName:e.authorName,committedAt:e.committedAt,url:e.url}},TW=["open","closed","merged"],AW=e=>{if(!e||!D(e.base)||!Array.isArray(e.layers)||e.number!==null&&!Number.isSafeInteger(e.number))throw new Error("Source control response contained an invalid merge request chain");return{number:e.number,base:e.base,layers:e.layers.map(t=>{const s=TW.find(n=>n===t?.state);if(!t||!Number.isSafeInteger(t.number)||!Q(t.title)||!xs(t.url)||!s||!Re(t.draft)||!D(t.head))throw new Error("Source control response contained an invalid merge request chain");return{number:t.number,title:t.title,url:t.url,state:s,draft:t.draft,head:t.head}})}},_k=e=>{try{return AW(e)}catch{return}},PW=(e,t)=>{if(!e||e.state!=="approved"&&e.state!=="changes_requested"||!D(e.url)||e.createdAt!==null&&!D(e.createdAt))throw new Error("Source control response contained an invalid review verdict");const s={state:e.state,url:e.url,createdAt:e.createdAt};return e.author&&(s.author=bt(e.author,t)),s},RW=["approved","rejected","recommended","disliked","neutral"],IW=["satisfied","unsatisfied","overridden","not-applicable","error","forced"],xW=["rework","trivial-rebase","merge-first-parent-update","no-code-change","no-change"],_i=e=>Cc(e)&&Number.isInteger(e)&&e>=-10&&e<=10,EW=(e,t)=>{if(!e||!_i(e.value)||e.revision!==void 0&&!Gt(e.revision))throw new Error("Source control response contained an invalid vote");const s={user:bt(e.user,t),value:e.value};return e.revision!==void 0&&(s.revision=e.revision),s},OW=(e,t)=>{const s=RW.find(n=>n===e?.status);if(!e||!D(e.name)||!s||!_i(e.defaultValue)||!Re(e.blocking)||!Array.isArray(e.values)||e.values.some(n=>!n||!_i(n.value)||!Q(n.description))||!Array.isArray(e.permitted)||e.permitted.some(n=>!_i(n))||!Array.isArray(e.votes))throw new Error("Source control response contained an invalid vote label");return{name:e.name,values:e.values.map(n=>({value:n.value,description:n.description})),defaultValue:e.defaultValue,permitted:[...e.permitted],blocking:e.blocking,status:s,votes:e.votes.map(n=>EW(n,t))}},DW=e=>{const t=IW.find(n=>n===e?.status);if(!e||!D(e.name)||!t||e.description!==void 0&&!Q(e.description))throw new Error("Source control response contained an invalid submit requirement");const s={name:e.name,status:t};return e.description&&(s.description=e.description),s},MW=(e,t)=>{const s=e?.kind===void 0?void 0:xW.find(o=>o===e.kind);if(!e||!Gt(e.number)||!D(e.sha)||!D(e.ref)||e.createdAt!==null&&!D(e.createdAt)||e.kind!==void 0&&!s)throw new Error("Source control response contained an invalid revision");const n={number:e.number,sha:e.sha,createdAt:e.createdAt,ref:e.ref};return e.uploader&&(n.uploader=bt(e.uploader,t)),s&&(n.kind=s),n},FW=e=>{if(!e||!D(e.sha)||e.changeId!==null&&!D(e.changeId)||e.uploadedAs!==null&&!Gt(e.uploadedAs))throw new Error("Source control response contained an invalid local revision");return{sha:e.sha,changeId:e.changeId,uploadedAs:e.uploadedAs}},_W=(e,t)=>{if(e?.revision!==void 0&&!Gt(e.revision))throw new Error("Source control response contained an invalid review comment");const s={...iu(e,t),path:e.path,line:e.line,position:e.position};return e.revision!==void 0&&(s.revision=e.revision),s},iu=(e,t)=>{if(!e||!As(e.id)||!D(e.url)||!Q(e.body)||!Pt(e,t)||e.author!==void 0&&e.author!==null&&!Pt(e.author,t)||e.createdAt!==void 0&&!D(e.createdAt)||e.updatedAt!==void 0&&!D(e.updatedAt))throw new Error("Source control response contained an invalid comment");const s=e.thread;if(s!==void 0&&(!s||!As(s.id)||!Re(s.resolved)||!Re(s.resolvable)||!Re(s.first)||s.canResolve!==void 0&&!Re(s.canResolve)||s.canReply!==void 0&&!Re(s.canReply)))throw new Error("Source control response contained an invalid comment thread");const n={...t,id:String(e.id),url:e.url,body:e.body};return s&&(n.thread={id:String(s.id),resolved:s.resolved,resolvable:s.resolvable,first:s.first},s.canResolve!==void 0&&(n.thread.canResolve=s.canResolve),s.canReply!==void 0&&(n.thread.canReply=s.canReply)),e.author&&(n.author=bt(e.author,t)),e.createdAt&&(n.createdAt=e.createdAt),e.updatedAt&&(n.updatedAt=e.updatedAt),n},Q=e=>Object.prototype.toString.call(e)==="[object String]",Re=e=>Object.prototype.toString.call(e)==="[object Boolean]",Cc=e=>Object.prototype.toString.call(e)==="[object Number]",D=e=>Q(e)&&e.trim().length>0,Gt=e=>Cc(e)&&Number.isSafeInteger(e)&&e>=1,Nk=e=>Cc(e)&&Number.isSafeInteger(e)&&e>=0,As=e=>D(e)||Number.isFinite(e),xs=e=>{if(!D(e))return false;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"}catch{return false}},Pt=(e,t)=>e?.provider===t.provider&&e.instance===t.instance,NW=(e,t)=>e.provider===void 0&&e.instance===void 0?true:Pt(e,t),LW=(e,t)=>{if(!Cc(e)||!Number.isInteger(e)||e<1||!Re(t))throw new Error("Source control response contained invalid pagination");return{page:e,hasMore:t}},Bm=(e,t)=>{const s={items:t,...LW(e.page,e.hasMore)},n=pW(e.incompleteProjectIds);return n?.length&&(s.incompleteProjectIds=n),s},UW=e=>{if(!e||!Array.isArray(e.branches)||e.branches.some(t=>!D(t)))throw new Error("Source control response contained invalid branches");return[...e.branches]},jW=e=>{if(!["success","failure","pending","unknown"].includes(e.state)||!Number.isInteger(e.total)||e.total<0||!Number.isInteger(e.success)||e.success<0||!Number.isInteger(e.failure)||e.failure<0||!Number.isInteger(e.pending)||e.pending<0||e.inProgress!==void 0&&(!Number.isInteger(e.inProgress)||e.inProgress<0)||e.queued!==void 0&&(!Number.isInteger(e.queued)||e.queued<0)||e.startedAt!==void 0&&!D(e.startedAt))throw new Error("Source control response contained an invalid CI summary")},BW=(e,t,s)=>{if(!e||!Pt(e.identity,t)||!D(e.branch)||e.branch!==s||e.project===void 0||e.changeRequest===void 0||e.fetchedAt!==void 0&&(!Number.isFinite(e.fetchedAt)||e.fetchedAt<0)||e.canMerge!==void 0&&!Re(e.canMerge)||e.defaultBranch!==void 0&&e.defaultBranch!==null&&!D(e.defaultBranch)||e.resolvedRemoteName!==void 0&&e.resolvedRemoteName!==null&&!D(e.resolvedRemoteName))throw new Error("Source control response contained an invalid change request status");const n={identity:t,project:e.project===null?null:Oo(e.project,t),branch:e.branch,changeRequest:e.changeRequest===null?null:ou(e.changeRequest,t)};if(e.ci!==void 0&&(n.ci=Fk(e.ci,t)),e.canMerge!==void 0&&(n.canMerge=e.canMerge),e.defaultBranch!==void 0&&(n.defaultBranch=e.defaultBranch),e.resolvedRemoteName!==void 0&&(n.resolvedRemoteName=e.resolvedRemoteName),e.fetchedAt!==void 0&&(n.fetchedAt=e.fetchedAt),e.localRevision!==void 0&&(n.localRevision=FW(e.localRevision)),e.stack===null)n.stack=null;else if(e.stack!==void 0){const o=_k(e.stack);o&&(n.stack=o)}return n},Ol=(e,t)=>(e??[]).map(s=>{if(!D(s.id)||s.id!==s.credentialId||!Gt(s.credentialRevision)||!D(s.providerUserId)||!["available","unavailable"].includes(s.providerUserStatus)||!Re(s.current)||!["oauth","pat","cli"].includes(s.source)||!["valid","invalid"].includes(s.status))throw new Error("Source control response contained an invalid auth credential");return{id:s.id,credentialId:s.credentialId,credentialRevision:s.credentialRevision,providerUserId:s.providerUserId,providerUserStatus:s.providerUserStatus,user:bt(s.user,t),scope:s.scope,current:s.current,source:s.source,status:s.status}}),Dl=(e,t)=>{if(!e.connected){if(!e.status){const s={...t,status:"disconnected",connected:false};return e.cli&&(s.cli={available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?bt(e.cli.user,t):void 0}),s.accounts=Ol(e.accounts,t),s}return{...e,...t,connected:false,accounts:Ol(e.accounts,t)}}return{...t,status:"connected",connected:true,user:bt(e.user,t),scope:e.scope,accounts:Ol(e.accounts,t),cli:e.cli?{available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?bt(e.cli.user,t):void 0}:void 0}},VW=(e={})=>{const t=e.fetch??P;return{repositoryContext:async s=>Mk(await Lm(t,"/api/source-control/repository-context",s)),repositoryBinding:async s=>wo(await Lm(t,"/api/source-control/binding",s)),resetRepositoryBinding:async s=>{const n=await t("/api/source-control/binding/reset",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),o=await n.json();if(!n.ok)throw new ks(o.error||n.statusText||"Source control binding reset failed",o.code);return wo(o)},repositoryProviderBindingMutate:async s=>{const n=await t("/api/source-control/binding/provider",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),o=await n.json();if(!n.ok)throw new ks(o.error||n.statusText||"Source control binding request failed",o.code);return wo(o)},providers:async()=>{const s=await JH(t);return Dk(s),s},authInstances:async()=>{const s=await t("/api/source-control/instances",{headers:{Accept:"application/json"}}),n=await s.json();if(!s.ok)throw new Error(n.error||s.statusText||"Failed to list source control instances");return n.instances.map($)},capabilities:async s=>{const n=await Xe(t,s,"/capabilities");return{identity:$(n.identity),authentication:n.authentication,authenticationMethods:n.authenticationMethods,multipleAccounts:n.multipleAccounts,projects:n.projects,issues:n.issues,changeRequests:n.changeRequests,draftChangeRequests:n.draftChangeRequests,draftConversion:n.draftConversion===true,mergeChangeRequests:n.mergeChangeRequests,mergeMethods:n.mergeMethods?[...n.mergeMethods]:void 0,ci:n.ci}},authStatus:async s=>{const n=$(s);return Dl(await Xe(t,n,"/auth/status"),n)},authStart:async s=>{const n=await Xe(t,s,"/auth/start",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),o={flowId:n.flowId,userCode:n.userCode,verificationUri:n.verificationUri,expiresIn:n.expiresIn,interval:n.interval};return n.verificationUriComplete&&(o.verificationUriComplete=n.verificationUriComplete),n.scope&&(o.scope=n.scope),o},authComplete:async(s,n)=>{let o;try{o=await de(t,s,"/auth/complete",{flowId:n})}catch(a){if(a instanceof ks&&a.code==="SOURCE_CONTROL_OAUTH_FLOW_UNAVAILABLE")return{status:"error",code:"expired",message:a.message};throw a}if(o.connected){const a={status:"connected",user:bt(o.user,$(s))};return o.scope&&(a.scope=o.scope),a}if(o.status==="authorization_pending"||o.status==="slow_down"){const a={status:"pending"};return o.status==="slow_down"&&(a.slowDown=true),a}let i="provider-error";return o.status==="access_denied"?i="access-denied":o.status==="expired_token"&&(i="expired"),{status:"error",code:i,message:o.error||o.status||`${ia(s)} authentication failed`}},authSetToken:async(s,n,o)=>{const i=$(s);return await de(t,i,"/auth/token",o?.username?{token:n,username:o.username}:{token:n}),Dl(await Xe(t,i,"/auth/status"),i)},authSetSshUrl:async(s,n)=>{const o=$(s),i=await de(t,o,"/auth/ssh-url",{sshUrl:n});if(i.sshUrl!==null&&!D(i.sshUrl))throw new Error("Source control response contained an invalid SSH URL");return{sshUrl:i.sshUrl??null}},setInstanceAliases:async(s,n)=>{const o=$(s),i=await t("/api/source-control/instances/aliases",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({provider:o.provider,instance:o.instance,aliases:n})}),a=await i.json();if(!i.ok){const r=a.error||i.statusText||"Failed to save instance aliases";throw(a.code==="INVALID_INSTANCE_ALIAS"||a.code==="INSTANCE_ALIAS_TAKEN")&&D(a.alias)?new oV(r,a.code==="INSTANCE_ALIAS_TAKEN"?"taken":"invalid",a.alias):new ks(r,a.code)}if(!Array.isArray(a.aliases)||!a.aliases.every(D))throw new Error("Source control response contained invalid instance aliases");return{aliases:[...a.aliases]}},authDisconnect:async(s,n)=>{if(!D(n)||n.trim()!==n)throw new Error("Source control credential accountId is required");const o=new URLSearchParams({accountId:n}),i=await Xe(t,s,"/auth",{method:"DELETE"},o);if(!Re(i.removed))throw new Error("Source control response contained an invalid account removal result");return{removed:i.removed}},authActivate:async(s,n)=>{const o=$(s);return Dl(await de(t,o,"/auth/activate",{accountId:n}),o)},authSetCliDisabled:async(s,n)=>{const o=$(s);return{disabled:!!(await de(t,o,"/auth/cli",{disabled:n})).disabled}},changeRequestStatus:async(s,n,o)=>{const i=$(s),a=us(s);a.set("branch",n),o?.force&&a.set("force","true");const r=await Xe(t,i,"/pr/status",{},a);return BW(r,i,n)},changeRequestCreate:async s=>{const n=$(s),i={...ke(s,n,"create"),title:s.title};s.body!==void 0&&(i.body=s.body),s.draft!==void 0&&(i.draft=s.draft),s.remote&&(i.remote=s.remote),s.headRemote&&(i.headRemote=s.headRemote);const a=await de(t,n,"/pr/create",i);return Se(a,s,n,fW)},changeRequestUpdate:async s=>{const n=$(s),o={...ke(s,n,"existing"),title:s.title};s.body!==void 0&&(o.body=s.body);const i=await de(t,n,"/pr/update",o);return Se(i,s,n,Ye)},changeRequestMerge:async s=>{const n=$(s),o=await de(t,n,"/pr/merge",{...ke(s,n,"existing"),method:s.method,cancel:s.cancel});return Se(o,s,n,wW)},changeRequestReady:async s=>{const n=$(s),o=await de(t,n,"/pr/ready",ke(s,n,"existing"));return Se(o,s,n,kW)},changeRequestDraft:async s=>{const n=$(s),o=await de(t,n,"/pr/draft",ke(s,n,"existing"));return Se(o,s,n,SW)},changeRequestComment:async s=>{const n=$(s),o=await de(t,n,"/pr/comment",{...ke(s,n,"existing"),body:s.body});return Se(o,s,n,Ye)},changeRequestStartThread:async s=>{const n=$(s),o=await de(t,n,"/pr/thread/start",{...ke(s,n,"existing"),body:s.body});return Se(o,s,n,Ye)},changeRequestReplyToThread:async s=>{const n=$(s),o=await de(t,n,"/pr/thread/reply",{...ke(s,n,"existing"),threadId:s.threadId,body:s.body});return Se(o,s,n,Ye)},changeRequestResolveThread:async s=>{const n=$(s),o=await de(t,n,"/pr/thread/resolve",{...ke(s,n,"existing"),threadId:s.threadId,resolved:s.resolved});return Se(o,s,n,Ye)},changeRequestReview:async s=>{const n=$(s),o=ke(s,n,"existing");let i;if(s.votes!==void 0){const r=Object.entries(s.votes);if(s.verdict!==void 0||r.length===0&&s.publishDrafts!==true||r.some(([l,u])=>!D(l)||!_i(u)))throw new Error("Source control review input is invalid");i={...o,votes:Object.fromEntries(r),publishDrafts:s.publishDrafts}}else i={...o,verdict:s.verdict};s.body!==void 0&&(i.body=s.body);const a=await de(t,n,"/pr/review",i);return Se(a,s,n,bW)},changeRequestReviewState:(s,n)=>oW(t,s,n),changeRequestReviewComment:async s=>{const n=$(s),o=s.line===void 0?{path:s.path}:{path:s.path,side:s.side,line:s.line,startLine:s.startLine},i=await de(t,n,"/pr/review/comment",{...ke(s,n,"existing"),...o,body:s.body});return Se(i,s,n,Ye)},changeRequestReviewCommentUpdate:async s=>{const n=$(s),o=await de(t,n,"/pr/review/comment/update",{...ke(s,n,"existing"),commentId:s.commentId,body:s.body});return Se(o,s,n,Ye)},changeRequestReviewCommentDelete:async s=>{const n=$(s),o=await de(t,n,"/pr/review/comment/delete",{...ke(s,n,"existing"),commentId:s.commentId});return Se(o,s,n,Ye)},changeRequestReviewDiscard:async s=>{const n=$(s),o=await de(t,n,"/pr/review/discard",ke(s,n,"existing"));return Se(o,s,n,Ye)},changeRequestSetState:async s=>{const n=$(s),o=await de(t,n,"/pr/state",{...ke(s,n,"existing"),state:s.state});return Se(o,s,n,El)},issueSetState:async s=>{const n=$(s),o=await de(t,n,"/issues/state",{...ke(s,n,"existing"),state:s.state});return Se(o,s,n,El)},changeRequestSetLabels:async s=>{const n=$(s),o=await de(t,n,"/pr/labels",{...ke(s,n,"existing"),labels:s.labels});return Se(o,s,n,Ye)},issueSetLabels:async s=>{const n=$(s),o=await de(t,n,"/issues/labels",{...ke(s,n,"existing"),labels:s.labels});return Se(o,s,n,Ye)},changeRequestSetReviewers:async s=>{const n=$(s),o=await de(t,n,"/pr/reviewers",{...ke(s,n,"existing"),reviewers:s.reviewers});return Se(o,s,n,Ye)},refreshProviderReads:async(s,n)=>{const o="item"in n?new URLSearchParams({scope:"item",owner:n.item.owner,repo:n.item.repo,number:String(n.item.number)}):new URLSearchParams({scope:"lists"});await Xe(t,s,"/read-cache/refresh",{method:"POST"},o)},referenceLabels:async(s,n)=>yW(await Um(t,s,n,"/references/labels")),referenceReviewers:async(s,n)=>vW(await Um(t,s,n,"/references/reviewers")),issueComment:async s=>{const n=$(s),o=await de(t,n,"/issues/comment",{...ke(s,n,"existing"),body:s.body});return Se(o,s,n,Ye)},discussionComment:async s=>{const n=$(s),o={...ke(s,n,"existing"),body:s.body};s.replyTo&&(o.replyTo=s.replyTo);const i=await de(t,n,"/discussions/comment",o);return Se(i,s,n,Ye)},discussionSetState:async s=>{const n=$(s),o=ke(s,n,"existing"),i=await de(t,n,"/discussions/state",s.state==="closed"?{...o,state:"closed",reason:s.reason}:{...o,state:"open"});return Se(i,s,n,El)},discussionSetAnswer:async s=>{const n=$(s),o=await de(t,n,"/discussions/answer",{...ke(s,n,"existing"),commentId:s.commentId,answer:s.answer});return Se(o,s,n,Ye)},discussionSetLabels:async s=>{const n=$(s),o=await de(t,n,"/discussions/labels",{...ke(s,n,"existing"),labels:s.labels});return Se(o,s,n,Ye)},changeRequestsList:async(s,n)=>{const o=$(s),i=us(s);i.set("page",String(n?.page??1)),n?.query&&i.set("query",n.query),n?.state&&i.set("state",n.state),n?.people&&i.set("people",n.people);const a=await Xe(t,o,"/pulls/list",{},i);if(!a||!Array.isArray(a.items))throw new Error("Source control response contained invalid change requests");return Bm(a,a.items.map(r=>ou(r,o)))},changeRequestContext:async(s,n,o)=>{const i=$(s),a=us(s);a.set("number",String(n)),o?.includeDiff&&a.set("diff","1"),o?.includeCIDetails&&a.set("checkDetails","1"),o?.includeTimeline&&a.set("timeline","1"),o?.revision&&a.set("revision",o.revision),o?.project&&(a.set("owner",o.project.owner),a.set("repo",o.project.name));const r=await Xe(t,i,"/pulls/context",{},a),l={identity:i,project:r.project?Oo(r.project,i):null,changeRequest:r.changeRequest?ou(r.changeRequest,i):null,issueComments:r.issueComments.map(u=>iu(u,i)),reviewComments:r.reviewComments.map(u=>_W(u,i)),files:r.files.map(u=>({...u})),diff:r.diff,ci:Fk(r.ci,i),fetchedAt:r.fetchedAt};if(r.commits&&(l.commits=r.commits.map(CW),l.commitsComplete=r.commitsComplete!==false,l.verdicts=(r.verdicts??[]).map(u=>PW(u,i)),r.reviewers&&(l.reviewers=r.reviewers.map(u=>bt(u,i)))),r.stack===null)l.stack=null;else if(r.stack!==void 0){const u=_k(r.stack);u&&(l.stack=u)}if(r.voteLabels!==void 0){if(!Array.isArray(r.voteLabels))throw new Error("Source control response contained invalid vote labels");l.voteLabels=r.voteLabels.map(u=>OW(u,i))}if(r.submitRequirements!==void 0){if(!Array.isArray(r.submitRequirements))throw new Error("Source control response contained invalid submit requirements");l.submitRequirements=r.submitRequirements.map(DW)}if(r.revisions!==void 0){if(!Array.isArray(r.revisions))throw new Error("Source control response contained invalid revisions");l.revisions=r.revisions.map(u=>MW(u,i))}return l},issuesList:async(s,n)=>{const o=$(s),i=us(s);i.set("page",String(n?.page??1)),n?.query&&i.set("query",n.query),n?.state&&i.set("state",n.state),n?.people&&i.set("people",n.people);const a=await Xe(t,o,"/issues/list",{},i);if(!a||!Array.isArray(a.items))throw new Error("Source control response contained invalid issues");return Bm(a,a.items.map(r=>jm(r,o)))},issueGet:async(s,n,o)=>{const i=$(s),a=us(s);a.set("number",String(n)),o&&(a.set("owner",o.owner),a.set("repo",o.name));const r=await Xe(t,i,"/issues/get",{},a);return r===null?null:jm(r,i)},issueComments:async(s,n,o)=>{const i=$(s),a=us(s);a.set("number",String(n)),o&&(a.set("owner",o.owner),a.set("repo",o.name));const r=await Xe(t,i,"/issues/comments",{},a);if(!Array.isArray(r))throw new Error("Source control response contained invalid comments");return r.map(l=>iu(l,i))},projectUpstream:async s=>{const n=$(s),o=us(s),i=await Xe(t,n,"/repo/upstream",{},o);if(!i||!Pt(i.identity,n)||!Re(i.isFork)||i.upstream!==null&&i.upstream===void 0||i.isFork!==!!i.upstream)throw new Error("Source control response contained an invalid upstream");return{identity:n,isFork:i.isFork,upstream:i.upstream?Oo(i.upstream,n):null}},projectBranches:async(s,n,o)=>{const i=$(s),a=us(s);a.set("owner",n),a.set("repo",o);const r=await Xe(t,i,"/repo/branches",{},a);return UW(r)},references:(s,n)=>tW(t,s,n),referencesAcross:(s,n)=>iW(t,s,n),referenceDetail:(s,n)=>sW(t,s,n),changeRequestListStatuses:(s,n)=>aW(t,s,n)}},HW=d({status:g("unsupported"),reason:g("host-setup-required")}).strict(),Lk=c().regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/),au=d({credentialId:c().regex(/^ocgit:v1:ssh:[A-Za-z0-9_-]{1,267}$/),label:g("SSH"),fingerprint:Lk,capability:L([d({status:g("ready")}).strict(),d({status:g("unavailable"),reason:T(["unreadable","encrypted-or-unverifiable","fingerprint-mismatch"])}).strict()])}).strict(),WW=au.extend({capability:d({status:g("ready")}).strict()}),Vm=c().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),qW=L([d({candidateId:c().regex(/^[A-Za-z0-9_-]{1,200}$/),label:Vm,fingerprint:Lk,capability:d({status:g("ready")}).strict()}).strict(),d({label:Vm,capability:d({status:g("unavailable"),reason:T(["unreadable","encrypted-or-unverifiable","insecure-permissions"])}).strict()}).strict()]),GW=L([HW,d({status:g("available"),credentials:k(au).max(256)}).strict(),d({status:g("discovered"),candidates:k(qW).max(128),truncated:v()}).strict(),d({status:g("imported"),credentials:k(au).max(256),selectedCredential:WW}).strict(),d({status:g("rejected"),reason:T(["candidate-expired","candidate-changed","fingerprint-mismatch","candidate-unavailable","inventory-full"])}).strict()]),zW=async(e,t=P)=>{const s=await t("/api/git/managed-ssh-credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw new Error("Managed SSH inventory request failed");const n=GW.parse(await s.json());if(n.status==="imported"&&!n.credentials.some(o=>o.credentialId===n.selectedCredential.credentialId&&o.fingerprint===n.selectedCredential.fingerprint&&o.capability.status==="ready"))throw new Error("Managed SSH import response is inconsistent");return n},$W=()=>({managedSshCredentials:zW,configureTransportBinding:lW,removeTransportBinding:dW,configureAuxiliaryBinding:uW,checkIsGitRepository:o1,getGitStatus:a1,prefetchProjectStatuses:n1,getGitDiff:r1,getGitDiffs:c1,getGitFileDiff:h1,getGitRangeDiff:l1,getGitRangeFiles:u1,getBranchBase:p1,revertGitFile:g1,stageGitFile:m1,stageGitFiles:yk,unstageGitFile:f1,unstageGitFiles:vk,stageGitHunk:w1,unstageGitHunk:b1,revertGitHunk:y1,isLinkedWorktree:v1,getGitBranches:k1,getGitUnpushedBranchCounts:S1,deleteGitBranch:C1,removeRemote:T1,generateCommitMessage:A1,generatePullRequestDescription:P1,listGitWorktrees:Am,validateGitWorktree:Pm,createGitWorktree:Rm,deleteGitWorktree:Im,validateWorktreeDirectory:MH,canonicalizeWorktreeState:FH,createGitCommit(e,t,s){return B1(e,t,s)},gitPush:V1,gitPull:H1,gitFetch:W1,planNetworkOperation:G1,issueContributorDestination:z1,listContributorDestinations:$1,inspectCheckoutTrust:K1,decideCheckoutTrust:J1,executeNetworkOperation:Y1,getNetworkOperation:X1,cancelNetworkOperation:Q1,listGitStashes:Z1,countGitStashFiles:eH,stashGitChanges:Tk,applyGitStash:tH,popGitStash:Ak,dropGitStash:sH,checkoutBranch:nH,createBranch:oH,renameBranch:iH,getGitLog(e,t){return aH(e,t)},addChangeIdToHead:cH,getCommitFiles:lH,getCommitFileDiff:dH,getGitCommitDiff:d1,getCurrentGitIdentity:mH,hasLocalIdentity:fH,setGitIdentity:bH,getGitIdentities:uH,createGitIdentity:pH,updateGitIdentity:hH,deleteGitIdentity:gH,getGlobalGitIdentity:wH,getRemotes:yH,rebase:vH,abortRebase:kH,continueRebase:IH,merge:SH,abortMerge:RH,continueMerge:xH,checkoutCommit:CH,cherryPick:TH,revertCommit:AH,resetToCommit:PH,stash:EH,stashPop:OH,getConflictDetails:DH,worktree:{list:Am,validate:Pm,bootstrapStatus:R1,preview:I1,create:Rm,remove:Im,teardown:x1,setTitle:O1,setPinned:M1,snapshot:j1,archive:F1,listArchives:_1,restoreArchive:N1,deleteArchive:L1}});let Hm=null;const KW=()=>window.Capacitor,JW=e=>e.getPlatform?.()!=="android"||!e.registerPlugin?null:(Hm??=e.registerPlugin("FileShare"),Hm),YW=async e=>{const t=new Uint8Array(await e.arrayBuffer());let s="";for(let n=0;n<t.length;n+=32768)s+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(s)},XW=async e=>{const t=KW(),s=t?JW(t):null;if(s){await s.share({fileName:e.name,mimeType:e.type||"application/octet-stream",data:await YW(e)});return}if(!navigator.canShare?.({files:[e]}))throw new Error("File sharing is unavailable in this mobile runtime");await navigator.share({files:[e]})},Ae=e=>e.replace(/\\/g,"/"),QW=(e,t)=>et.searchFiles(e,t),ZW=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Lt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:Ae(t?.directory||t?.path||e),entries:t.entries.filter(n=>!!(n&&typeof n.name=="string"&&typeof n.path=="string")).map(n=>({name:n.name,path:Ae(n.path),isDirectory:!!n.isDirectory}))}},St=(e,t,s)=>{const n=e?.(),o=It(s),i=t||(o!==null&&It(n)!==o?Qf(o):n);return i?{"x-opencode-directory":i}:void 0},eq=d({matches:k(d({path:c(),relativePath:c(),line:y().int().positive(),column:y().int().positive(),text:c(),ranges:k(kr([y().int().nonnegative(),y().int().nonnegative()])),cutStart:v()})),stopped:T(["limit","deadline"]).nullable()}),tq=d({error:c().optional(),reason:c().optional()}),sq=d({files:k(d({path:c(),relativePath:c()}))}),nq=({getDirectory:e,searchFiles:t=QW})=>({async listDirectory(s,n){const o=Ae(s),i=new URLSearchParams;o&&i.set("path",o),n?.respectGitignore&&i.set("respectGitignore","true");const a=await P("/api/fs/list",{query:i,headers:St(e,void 0,o)});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Lt(l.error||"Failed to list directory",{reason:ki(l.reason),status:a.status})}const r=await a.json();return ZW(o,r)},async search(s){const n=Ae(s.directory),o=!!s.includeHidden,i=s.respectGitignore!==false;if(o||!i){const r=new URLSearchParams;r.set("query",s.query),n&&r.set("directory",n),typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)&&r.set("limit",String(s.maxResults)),o&&r.set("includeHidden","true"),i||r.set("respectGitignore","false");const l=await P("/api/fs/search",{query:r,signal:s.signal,headers:St(e,n)});if(!l.ok){const p=await l.json().catch(()=>({error:l.statusText}));throw new Error(p.error||"Failed to search files")}const u=sq.safeParse(await l.json().catch(()=>null));if(!u.success)throw new Lt("File search returned an invalid response",{reason:"invalid-response"});return u.data.files.map(p=>({path:Ae(p.path),preview:[Ae(p.relativePath)]}))}return(await t(s.query,{directory:n,limit:typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)?s.maxResults:void 0,type:"file"})).map(r=>({path:Ae(r.path),preview:[Ae(r.relativePath)]}))},async searchContents(s){const n=Ae(s.directory),o=new URLSearchParams({query:s.query,regex:s.regex?"true":"false"});s.limit!==void 0&&o.set("limit",String(s.limit)),s.includeHidden&&o.set("includeHidden","true"),s.respectGitignore===false&&o.set("respectGitignore","false");const i=await P("/api/fs/find-in-files",{query:o,cache:"no-store",signal:s.signal,headers:St(e,n)});if(i.ok){const l=eq.safeParse(await i.json().catch(()=>null));if(!l.success)throw new Lt("Content search returned an invalid response",{reason:"invalid-response"});return{status:"ok",matches:l.data.matches.map(u=>({...u,path:Ae(u.path)})),stopped:l.data.stopped}}const a=tq.safeParse(await i.json().catch(()=>null)),r=a.success?a.data.reason:void 0;if(i.status===501&&r==="search-unavailable")return{status:"unavailable"};if(i.status===400&&r==="invalid-pattern")return{status:"invalid-pattern",message:a.success&&a.data.error?a.data.error:"Invalid regular expression"};throw new Lt(a.success&&a.data.error||i.statusText||"Failed to search file contents",{status:i.status})},async createDirectory(s){const n=Ae(s),o=await P("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,n)},body:JSON.stringify({path:n})});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to create directory")}const i=await o.json();return{success:!!i?.success,path:typeof i?.path=="string"?Ae(i.path):n}},async statFile(s,n){const o=Ae(s),i=new URLSearchParams({path:o});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant);const a=await P("/api/fs/stat",{query:i,signal:AbortSignal.timeout(3e4),headers:St(e,n?.directory,o)});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Error(l.error||"Failed to stat file")}const r=await a.json().catch(()=>({}));return{path:typeof r.path=="string"?Ae(r.path):o,isFile:!!r.isFile,size:typeof r.size=="number"?r.size:0,mtimeMs:typeof r.mtimeMs=="number"?r.mtimeMs:void 0}},async readFile(s,n){const o=Ae(s),i=new URLSearchParams({path:o});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&i.set("optional","true");const a=await P("/api/fs/read",{query:i,signal:AbortSignal.timeout(3e4),cache:n?.optional||n?.fresh?"no-store":"default",headers:St(e,n?.directory,o)});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Error(l.error||"Failed to read file")}return{content:await a.text(),path:o}},async writeFile(s,n){const o=Ae(s),i=await P("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,o)},body:JSON.stringify({path:o,content:n})});if(!i.ok){const r=await i.json().catch(()=>({error:i.statusText}));throw new Error(r.error||"Failed to write file")}const a=await i.json().catch(()=>({}));return{success:!!a.success,path:typeof a.path=="string"?Ae(a.path):o}},async uploadFile(s,n,o){const i=Ae(s),a=await P("/api/fs/upload",{method:"POST",query:{path:i,overwrite:o?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...St(e,o?.directory,i)},body:n});if(!a.ok){const l=await a.json().catch(()=>({error:a.statusText}));throw new Lt(l.error||"Failed to upload file",{reason:ki(l.reason),status:a.status,maxBytes:l.maxBytes})}const r=await a.json().catch(()=>({}));return{success:!!r.success,path:r.path?Ae(r.path):i}},async delete(s){const n=Ae(s),o=await P("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,n)},body:JSON.stringify({path:n})});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to delete file")}return{success:!!(await o.json().catch(()=>({}))).success}},async rename(s,n){const o=await P("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,s)},body:JSON.stringify({oldPath:s,newPath:n})});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Lt(a.error||"Failed to rename file",{reason:ki(a.reason),status:o.status})}const i=await o.json().catch(()=>({}));return{success:!!i.success,path:i.path?Ae(i.path):n}},async revealPath(s){const n=await P("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...St(e,void 0,s)},body:JSON.stringify({path:Ae(s)})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(s,n){const o=Ae(s),i=new URLSearchParams({path:o,download:"true"});n?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&i.set("outsideFileGrant",n.outsideFileGrant);const a=await P("/api/fs/raw",{query:i,headers:St(e,n?.directory,o)});if(!a.ok)throw new Error(`Download failed (${a.status})`);const r=await a.blob(),l=o.split("/").pop()||"file";if(window.Capacitor?.isNativePlatform?.()===true){await XW(new File([r],l,{type:r.type||"application/octet-stream"}));return}const p=URL.createObjectURL(r),h=document.createElement("a");h.href=p,h.download=l,document.body.appendChild(h),h.click(),document.body.removeChild(h),setTimeout(()=>URL.revokeObjectURL(p),100)}}),oq="/api/config/settings",Wm=()=>`${oq}?${Db}=${lc()}`,iq="/api/config/reload",qm=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},aq=()=>({async load(){const e=await P(Wm(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:qm(await e.json()),source:"web"}},async save(e){const t=await P(Wm(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to save settings")}return qm(await t.json())},async restartOpenCode(){const e=await P(iq,{method:"POST"});if(!e.ok){const t=await e.json().catch(()=>({error:e.statusText}));throw new Error(t.error||"Failed to restart OpenCode")}return{restarted:true}}}),rq=()=>({async requestDirectoryAccess(e){return{success:true,path:e.path}},async startAccessingDirectory(e){return{success:true}},async stopAccessingDirectory(e){return{success:true}}}),cq=d({type:g("openchamber:notification-navigation"),url:c().url(),expiresAt:y().finite()});let Ni=null;function Uk(e){if(!Ni)return false;try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin&&t.pathname===window.location.pathname&&Ni(t)}catch{return false}}function EJ(e){Ni=e;const t="serviceWorker"in navigator?navigator.serviceWorker:null,s=n=>{const o=cq.safeParse(n.data),i=n.ports[0];if(!(!o.success||!i))try{const a=n.origin===window.location.origin&&Date.now()<o.data.expiresAt&&Uk(o.data.url);i.postMessage(a)}catch{i.postMessage(false)}finally{i.close()}};return t?.addEventListener("message",s),()=>{t?.removeEventListener("message",s),Ni===e&&(Ni=null)}}const lq=1500,ru=5e3,dq="openchamber-notification-claim:",Li=new Map,uq=()=>typeof document>"u"?true:document.visibilityState==="visible"&&document.hasFocus(),pq=e=>{if(typeof e!="string")return null;const t=e.trim();return t?`/?session=${encodeURIComponent(t)}`:null},jk=e=>{const t=typeof e?.sessionId=="string"?e.sessionId.trim():"";if(!t)return;const s=pq(t);if(s)return{url:s,sessionId:t}},Bk=(e,t)=>{const s={body:e?.body,tag:e?.tag};return t&&(s.data=t),s},hq=e=>{try{if(typeof window>"u"||(typeof window.focus=="function"&&window.focus(),!e)||`${window.location.pathname}${window.location.search}`===e.url||Uk(e.url))return;window.location.assign(e.url)}catch{}},gq=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.trim()).join("|")},mq=e=>{for(const[t,s]of Li)e-s>ru&&Li.delete(t)},fq=e=>{const t=gq(e);if(!t)return true;const s=Date.now();mq(s);const n=Li.get(t)??0;if(s-n<ru)return false;try{if(typeof window<"u"&&window.localStorage){const o=`${dq}${t}`,i=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(i)&&s-i<ru)return Li.set(t,i),false;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(s))}}catch{}return Li.set(t,s),true},Vk=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(s=>{setTimeout(()=>s(null),lq)})])??e}catch{return e}},wq=async e=>{const t=await Vk();if(!t||typeof t.showNotification!="function")return false;try{const s=jk(e);return await t.showNotification(e?.title??"OpenChamber",Bk(e,s)),true}catch(s){return console.warn("Failed to send notification via service worker",s),false}},bq=async()=>{const e=await Vk();if(!e||!("pushManager"in e)||!e.pushManager)return false;try{return!!await e.pushManager.getSubscription()}catch{return false}},yq=async e=>{if(e?.requireHidden&&typeof document<"u"&&document.hasFocus())return true;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",e),false;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),false;if(!uq()&&await bq()||!fq(e))return true;try{if(await wq(e))return true;const t=jk(e),s=new Notification(e?.title??"OpenChamber",Bk(e,t));return s.onclick=n=>{n.preventDefault(),hq(t),s.close()},true}catch(t){return console.warn("Failed to send notification",t),false}},vq=async e=>{if(typeof window>"u")return false;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return false;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,runtimeKey:e?.runtimeKey,requireHidden:e?.requireHidden,showWhenFocused:e?.showWhenFocused}}),true}catch(s){return console.warn("Failed to send native notification (desktop)",s),false}},kq=()=>({async notifyAgentCompletion(e){return await vq(e)||await yq(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?true:typeof Notification<"u"?Notification.permission==="granted":false}),Zn=async(e,t)=>{try{const s=await P(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return s.ok?await s.json():null}catch{return null}},Sq=()=>({async getVapidPublicKey(){return Zn("/api/push/vapid-public-key")},async subscribe(e){return Zn("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return Zn("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return Zn("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:true})},async registerApnsToken(e){return Zn("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return Zn("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),Cq=new Set(kv),Tq=c().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!Cq.has(e),{message:"Reserved tracker id"}),Aq=e=>{try{return new RegExp(e),true}catch{return false}},Gm=c().min(1).max(2048).refine(Aq),Kt=v().catch(false),Pq=d({id:Tq,name:c().min(1).max(64),authMethods:k(c()).transform(e=>e.filter(t=>t==="oauth"||t==="token")),capabilities:d({multipleAccounts:Kt,stateUpdate:Kt,children:Kt,labels:Kt,priority:Kt,filters:d({people:Kt,priority:Kt}).catch({people:false,priority:false}),projectMapping:Kt,sessionComments:Kt,hostAccess:Kt}),stateFilters:k(c().min(1).max(32)).max(32),urlPatterns:k(d({host:c().min(1).max(256),path:Gm,query:d({name:c().min(1).max(64)}).optional().catch(void 0)}).nullable().catch(null)).max(8).transform(e=>e.filter(t=>t!==null)),identifierPattern:Gm}),Rq=k(Pq.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const n of e)!n||t.has(n.id)||(t.add(n.id),s.push(n));return s}),zm=new Map,OJ=e=>{const t=zm.get(e);if(t)return t;const s={id:e,name:e,authMethods:[],capabilities:{multipleAccounts:false,stateUpdate:false,children:false,labels:false,priority:false,filters:{people:false,priority:false},projectMapping:false,sessionComments:false,hostAccess:false},stateFilters:["open","all"],urlPatterns:[],identifierPattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$"};return zm.set(e,s),s},Iq=d({error:c()}),Hk=async(e,t)=>{const s=Iq.safeParse(await e.json().catch(()=>null));return new Error(s.success&&s.data.error.trim()||e.statusText||t)};async function Wk(e,t,s,n,o){const i=new Headers({Accept:"application/json"});s.body!==void 0&&i.set("Content-Type","application/json");const a=await e(t,{method:s.method,body:s.body,headers:i});if(!a.ok)throw await Hk(a,o);const r=n.safeParse(await a.json().catch(()=>null));if(!r.success)throw new Error(`${o}: unreadable answer`);return r.data}const Ze=c().trim().min(1),Rt=c().trim().nullish().catch(null).transform(e=>e||null),qk=T(["triage","backlog","todo","in-progress","done","canceled"]),xq=T(["none","urgent","high","medium","low"]),nn=e=>k(oe()).catch([]).transform(t=>t.flatMap(s=>{const n=e.safeParse(s);return n.success?[n.data]:[]})),Vp=d({name:Rt,avatarUrl:Rt}).nullish().catch(null).transform(e=>e&&(e.name||e.avatarUrl)?e:null),Eq=c().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null}),Oq=d({id:Rt,name:c().trim().catch(""),category:qk.nullable().catch(null)}).nullish().catch(null).transform(e=>e??null),Dq=d({total:y().int().positive(),done:y(),more:v().catch(false)}).nullish().catch(null).transform(e=>e?{...e,done:Math.min(Math.max(e.done,0),e.total)}:null),Gk={provider:Ze,id:Ze,identifier:Ze,title:Ze,url:Ze,state:Oq,priority:xq.nullish().catch(null),assignee:Vp.optional(),container:d({id:Ze,key:Rt,name:Ze}).nullish().catch(null),updatedAt:Rt.optional()},zk=d(Gk),$k=d({...Gk,labels:nn(d({id:Ze,name:Ze,color:Eq})).optional(),parent:zk.nullish().catch(null),progress:Dq.optional()}),Mq=$k,Fq=d({id:Ze,body:c().catch(""),createdAt:Rt,author:Vp}),_q=$k.extend({description:c().nullish().catch(null).transform(e=>e??null),comments:nn(Fq),children:nn(zk),childrenMore:v().catch(false)}),qo=d({connected:g(false)}).transform(()=>({connected:false})),Nq=L([qo,d({connected:g(true),items:nn(Mq),cursor:Rt,hasMore:v().catch(false)})]),$m=L([qo,d({connected:g(true),item:_q.nullish().catch(null).transform(e=>e??null)})]),Lq=d({id:Ze,name:Ze,category:qk.nullable().catch(null),position:y().catch(0)}),Uq=L([qo,d({connected:g(true),states:nn(Lq)})]),Ml=d({id:Ze,name:Rt,user:Vp.optional(),current:v().catch(false),authorizedAt:y().nullish().catch(null),status:T(["valid","invalid"]).optional().catch(void 0),invalidReason:c().trim().min(1).max(256).optional().catch(void 0),method:T(["oauth","token"]).optional().catch(void 0)}),Km=d({instance:c().trim().min(1).max(2048).nullable().catch(null),instances:L([d({kind:g("fixed"),origin:c().trim().min(1).max(2048)}),d({kind:g("user"),label:c().trim().min(1).max(64),placeholder:c().trim().min(1).max(256).optional()})]),hasClient:v().catch(false),redirectUri:c().trim().min(1).max(2048).nullable().catch(null)}),Jm=L([d({connected:g(false),accounts:nn(Ml).optional(),connect:Km.optional().catch(void 0)}),d({connected:g(true),account:Ml.nullish().catch(null),accounts:nn(Ml),connect:Km.optional().catch(void 0)})]),jq=["UNSUPPORTED","INSTANCE_REQUIRED","INSTANCE_MISMATCH","UNSUPPORTED_INSTANCE","TOKEN_REQUIRED","TOKEN_REFUSED","USERNAME_REQUIRED","USERNAME_INVALID","CLIENT_MISSING","CONNECT_SUPERSEDED","TRACKER_UNAVAILABLE"],Bq=d({error:c().optional(),code:c().optional()}),Ym=async e=>{if(e.ok)return{ok:true};const t=Bq.safeParse(await e.json().catch(()=>null));if(!t.success)return{ok:false,code:"failed",message:null};const s=T(jq).safeParse(t.data.code);return{ok:false,code:s.success?s.data:"failed",message:t.data.error?.trim()||null}},Vq=d({authorizationUrl:Ze,expiresIn:y().positive()}),Xm=L([qo,d({connected:g(true),defaultProjectPath:Rt,containers:nn(d({id:Ze,key:Rt,name:Ze,projectPath:Rt}))})]),Kr=d({sessionComments:v()}),Kk=L([qo,d({connected:g(true),posted:g(true),commentId:Rt}),d({connected:g(true),posted:g(false),skipped:T(["already-posted","issue-not-found","not-started","disabled","origin-not-public"])})]),Hq=new Map([["triage","triage"],["backlog","backlog"],["unstarted","todo"],["started","in-progress"],["completed","done"],["canceled","canceled"],["duplicate","canceled"]]),Jk=e=>e?Hq.get(e)??null:null,Wq=new Map([["linear","linear"]]),DJ=e=>Wq.get(e)??"tracker",Yk={id:"linear",name:"Linear",authMethods:["oauth"],capabilities:{multipleAccounts:true,stateUpdate:true,children:true,labels:true,priority:true,filters:{people:true,priority:true},projectMapping:true,sessionComments:true,hostAccess:true},stateFilters:["open","all","backlog","todo","in-progress","inReview","done","canceled","duplicate"],urlPatterns:[{host:"linear.app",path:"^/[^/]+/issue/([A-Za-z][A-Za-z0-9]*-\\d+)(?:/|$)"}],identifierPattern:"^[A-Za-z][A-Za-z0-9]*-\\d+$"},qq=["none","urgent","high","medium","low"],Gq=new Map([["in-progress","started"],["done","completed"]]),tt=c().trim().min(1),st=c().trim().nullish().catch(null).transform(e=>e||null),Rn=e=>k(oe()).catch([]).transform(t=>t.flatMap(s=>{const n=e.safeParse(s);return n.success?[n.data]:[]})),Tc=d({name:st,displayName:st,avatarUrl:st}).nullish().catch(null).transform(e=>{const t=e?.displayName||e?.name||null,s=e?.avatarUrl??null;return t||s?{name:t,avatarUrl:s}:null}),zq=d({id:st,name:st,type:st}).nullish().catch(null).transform(e=>e&&(e.id||e.name||e.type)?{id:e.id,name:e.name??"",category:Jk(e.type)}:null),Xk={id:tt,identifier:tt,title:tt,url:tt,state:zq,assignee:Tc,team:d({id:tt,key:st,name:tt}).nullish().catch(null),priority:y().int().nullish().catch(null),updatedAt:st},cu=(e,t)=>({provider:t,id:e.id,identifier:e.identifier,title:e.title,url:e.url,state:e.state,priority:e.priority!=null?qq[e.priority]??null:null,assignee:e.assignee,container:e.team?{id:e.team.id,key:e.team.key,name:e.team.name}:null,updatedAt:e.updatedAt}),Qk=d(Xk),Zk=d({...Xk,labels:Rn(d({id:tt,name:tt,color:c().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null})})),parent:Qk.nullish().catch(null),subIssueProgress:d({total:y().int().positive(),done:y(),more:v().catch(false)}).nullish().catch(null)}),eS=(e,t)=>({...cu(e,t),labels:e.labels,parent:e.parent?cu(e.parent,t):null,progress:e.subIssueProgress?{...e.subIssueProgress,done:Math.min(Math.max(e.subIssueProgress.done,0),e.subIssueProgress.total)}:null}),$q=Zk.extend({description:c().nullish().catch(null),comments:Rn(d({id:tt,body:c().catch(""),createdAt:st,user:Tc})),subIssues:Rn(Qk),subIssuesMore:v().catch(false)}),Kq=(e,t)=>({...eS(e,t),description:e.description??null,comments:e.comments.map(s=>({id:s.id,body:s.body,createdAt:s.createdAt,author:s.user})),children:e.subIssues.map(s=>cu(s,t)),childrenMore:e.subIssuesMore}),Jq=d({id:tt,name:st,current:v().catch(false),user:Tc,authorizedAt:y().nullish().catch(null)}),Qm=d({connected:v(),user:Tc,organization:d({id:tt,name:st}).nullish().catch(null),workspaces:Rn(Jq)}).transform(e=>{if(!e.connected)return{connected:false};const t=[...e.workspaces];return t.length===0&&e.organization&&t.push({id:e.organization.id,name:e.organization.name,user:e.user,current:true,authorizedAt:null}),{connected:true,account:t.find(s=>s.current)??null,accounts:t}}),Yq=e=>{const t=new URLSearchParams,s=(i,a)=>{const r=a?.trim();r&&t.set(i,r)},n=e?.state?.trim();s("query",e?.query),s("cursor",e?.cursor),s("status",n?Gq.get(n)??n:void 0),s("assignee",e?.people),s("teamId",e?.containerId),s("priority",e?.priority);const o=t.toString();return o?`?${o}`:""},Xq=e=>{const t=async(a,r,l,u,p)=>{if(a!==Yk.id)throw new Error(`Unknown tracker: ${a}`);return Wk(e,`/api/linear${r}`,l,u,p)},s={method:"GET"},n=a=>L([qo,a]),o=a=>n(d({connected:g(true),issue:$q.nullish().catch(null)}).transform(({issue:r})=>({connected:true,item:r?Kq(r,a):null}))),i=n(d({connected:g(true),defaultProjectPath:st,teams:Rn(d({id:tt,key:st,name:tt,projectPath:st}))}).transform(({defaultProjectPath:a,teams:r})=>({connected:true,defaultProjectPath:a,containers:r})));return{authStatus:a=>t(a,"/auth/status",s,Qm,"Failed to load Linear status"),authStart:(a,r)=>t(a,"/auth/start",{method:"POST",body:JSON.stringify({origin:r})},d({authorizationUrl:tt,expiresIn:y().positive()}),"Failed to start Linear auth"),authConnectToken:async()=>({ok:false,code:"UNSUPPORTED",message:null}),authSaveOAuthClient:async()=>({ok:false,code:"UNSUPPORTED",message:null}),authDisconnect:a=>t(a,"/auth",{method:"DELETE"},d({removed:v().catch(false)}),"Failed to disconnect Linear").then(({removed:r})=>({removed:r})),authActivate:(a,r)=>t(a,"/auth/activate",{method:"POST",body:JSON.stringify({organizationId:r})},Qm,"Failed to switch Linear workspace"),list:(a,r)=>t(a,`/issues/list${Yq(r)}`,s,n(d({connected:g(true),issues:Rn(Zk),cursor:st,hasMore:v().catch(false)}).transform(({issues:l,cursor:u,hasMore:p})=>({connected:true,items:l.map(h=>eS(h,a)),cursor:u,hasMore:p}))),"Failed to load Linear issues"),refreshListReads:async a=>{await t(a,"/read-cache/refresh?scope=lists",{method:"POST"},oe(),"Failed to refresh Linear lists")},get:(a,r)=>t(a,`/issues/get?${new URLSearchParams({id:r}).toString()}`,s,o(a),"Failed to load Linear issue"),states:(a,r)=>t(a,`/issues/states?${new URLSearchParams({teamId:r}).toString()}`,s,n(d({connected:g(true),states:Rn(d({id:tt,name:tt,type:st,position:y().catch(0)}).transform(({id:l,name:u,type:p,position:h})=>({id:l,name:u,category:Jk(p),position:h})))})),"Failed to load Linear workflow states"),updateState:(a,r)=>t(a,"/issues/update",{method:"POST",body:JSON.stringify({id:r.id,stateId:r.stateId})},o(a),"Failed to update Linear issue"),mappingGet:a=>t(a,"/mapping",s,i,"Failed to load Linear mapping"),mappingSet:(a,r)=>t(a,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:r.defaultProjectPath,teamProjectPaths:r.containerProjectPaths})},i,"Failed to save Linear mapping"),sessionStatusPost:(a,r)=>t(a,"/session-status",{method:"POST",body:JSON.stringify({kind:r.kind,sessionId:r.sessionId,issueIdentifier:r.identifier,sessionOrigin:r.sessionOrigin})},Kk,"Failed to post Linear session status"),preferencesGet:a=>t(a,"/preferences",s,Kr,"Failed to load Linear preferences"),preferencesSet:(a,r)=>t(a,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:r.sessionComments})},Kr,"Failed to save Linear preferences")}},Qq=d({providers:k(oe())}),Zq=e=>{const t=e?.split(";")[0]?.trim().toLowerCase()??"";return t==="application/json"||t.endsWith("+json")};async function eG(e){const t=await e("/api/tracker/providers",{headers:{Accept:"application/json"}});if(t.status===404)return{kind:"legacy-linear"};if(!t.ok)throw await Hk(t,"Failed to load trackers");if(!Zq(t.headers.get("content-type")))return{kind:"legacy-linear"};const s=Qq.parse(await t.json().catch(()=>null)).providers,n=Rq.parse(s);if(s.length>0&&n.length===0)throw new Error("Trackers response contained no readable tracker");return{kind:"tracker",descriptors:n}}const Fl=(e,t)=>`/api/tracker/${encodeURIComponent(e)}${t}`,tG=({fetch:e=P,runtimeKey:t=F}={})=>{const s=Xq(e);let n=null;const o=()=>{const u=eG(e),p={runtimeKey:t(),request:u};return n=p,u.catch(()=>{n===p&&(n=null)}),u},i=async()=>(await((n?.runtimeKey===t()?n.request:null)??o())).kind==="legacy-linear",a=(u,p,h,m,w)=>Wk(e,Fl(u,p),h,m,w),r={method:"GET"},l=u=>{const p=new URLSearchParams,h=(w,b)=>{const S=b?.trim();S&&p.set(w,S)};h("query",u?.query),h("cursor",u?.cursor),h("state",u?.state),h("people",u?.people),h("priority",u?.priority),h("containerId",u?.containerId);const m=p.toString();return m?`?${m}`:""};return{async providers(){const u=await o();return u.kind==="legacy-linear"?[Yk]:u.descriptors},async authStatus(u){return await i()?s.authStatus(u):a(u,"/auth/status",r,Jm,"Failed to load tracker status")},async authStart(u,p,h){if(await i())return s.authStart(u,p);const m=h?.instance?{origin:p,instance:h.instance}:{origin:p};return a(u,"/auth/start",{method:"POST",body:JSON.stringify(m)},Vq,"Failed to start tracker sign-in")},async authConnectToken(u,p){if(await i())return s.authConnectToken(u,p);try{const h=await e(Fl(u,"/auth/token"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(p)});return await Ym(h)}catch{return{ok:false,code:"failed",message:null}}},async authSaveOAuthClient(u,p){if(await i())return s.authSaveOAuthClient(u,p);try{const h=await e(Fl(u,"/auth/oauth-client"),{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(p)});return await Ym(h)}catch{return{ok:false,code:"failed",message:null}}},async authDisconnect(u){return await i()?s.authDisconnect(u):a(u,"/auth",{method:"DELETE"},d({removed:v().catch(false)}),"Failed to disconnect tracker").then(({removed:p})=>({removed:p}))},async authActivate(u,p){return await i()?s.authActivate(u,p):a(u,"/auth/activate",{method:"POST",body:JSON.stringify({accountId:p})},Jm,"Failed to switch tracker account")},async list(u,p){return await i()?s.list(u,p):a(u,`/items/list${l(p)}`,r,Nq,"Failed to load tracker items")},async refreshListReads(u){if(await i())return s.refreshListReads(u);await a(u,"/read-cache/refresh?scope=lists",{method:"POST"},oe(),"Failed to refresh tracker lists")},async get(u,p){return await i()?s.get(u,p):a(u,`/items/get?${new URLSearchParams({id:p}).toString()}`,r,$m,"Failed to load tracker item")},async states(u,p){return await i()?s.states(u,p):a(u,`/states?${new URLSearchParams({containerId:p}).toString()}`,r,Uq,"Failed to load workflow states")},async updateState(u,p){return await i()?s.updateState(u,p):a(u,"/items/update",{method:"POST",body:JSON.stringify({id:p.id,stateId:p.stateId})},$m,"Failed to update tracker item")},async mappingGet(u){return await i()?s.mappingGet(u):a(u,"/mapping",r,Xm,"Failed to load project mapping")},async mappingSet(u,p){return await i()?s.mappingSet(u,p):a(u,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:p.defaultProjectPath,containerProjectPaths:p.containerProjectPaths})},Xm,"Failed to save project mapping")},async sessionStatusPost(u,p){return await i()?s.sessionStatusPost(u,p):a(u,"/session-status",{method:"POST",body:JSON.stringify({kind:p.kind,sessionId:p.sessionId,identifier:p.identifier,sessionOrigin:p.sessionOrigin})},Kk,"Failed to post session status")},async preferencesGet(u){return await i()?s.preferencesGet(u):a(u,"/preferences",r,Kr,"Failed to load tracker preferences")},async preferencesSet(u,p){return await i()?s.preferencesSet(u,p):a(u,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:p.sessionComments})},Kr,"Failed to save tracker preferences")}}},Us=async e=>await e.json().catch(()=>null),sG=d({identityConflict:v().catch(false)}),Zm=async(e,t)=>{const s=await P(e,{method:t,headers:{Accept:"application/json"}}),n=await s.json().catch(()=>null),o=sG.safeParse(n);if(!s.ok||!o.success)throw new Error(s.statusText||"Failed to read relay status");return o.data},nG=()=>({async listClients(){const e=await P("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load remote clients");return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){const t=await P("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),s=await Us(t);if(!t.ok||!s?.client||typeof s.token!="string")throw new Error(s?.error||t.statusText||"Failed to create remote client token");return s},async createPairingSession(e={}){const t=await P("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),s=await Us(t);if(!t.ok||typeof s?.pairing?.secret!="string"||!s?.server)throw new Error(s?.error||t.statusText||"Failed to create pairing session");return s},async listPendingPairings(){const e=await P("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pending pairings");return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){const e=await P("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pairing transports");return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable!==false}},async cancelPairing(e){const t=await P(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Us(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to cancel pairing");return{cancelled:s.cancelled===true}},async revokeClient(e){const t=await P(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Us(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to revoke remote client");return s},getRelayHostStatus:()=>Zm("/api/openchamber/relay/status","GET"),resetRelayIdentity:()=>Zm("/api/openchamber/relay/reset-identity","POST"),async purgeRevokedClients(){const e=await P("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Us(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),oG=(e={})=>{const t=e.urls??uu();return gC(t),{clipboard:CC(),themeFiles:TC(),runtime:{platform:"web",isDesktop:false,isVSCode:false,label:"web"},terminal:sV(),git:$W(),files:nq({getDirectory:()=>Tp.getState().currentDirectory}),settings:aq(),permissions:rq(),notifications:kq(),sourceControl:VW(),trackers:tG(),push:Sq(),clientAuth:nG()}},iG=3e3,ef=(e,t)=>{if(!e||!t)return false;try{return new URL(e).origin===new URL(t).origin}catch{return false}},aG=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__OPENCHAMBER_API_BASE_URL__),clientToken:e(window.__OPENCHAMBER_CLIENT_TOKEN__),localOrigin:e(window.__OPENCHAMBER_LOCAL_ORIGIN__),runtimeHeaders:window.__OPENCHAMBER_RUNTIME_HEADERS__,relayHostId:e(window.__OPENCHAMBER_RELAY_HOST_ID__),explicitRuntime:window.__OPENCHAMBER_EXPLICIT_RUNTIME__===true}};let lu=Promise.resolve();const MJ=()=>lu,FJ=()=>{const{apiBaseUrl:e,clientToken:t,localOrigin:s,runtimeHeaders:n,relayHostId:o,explicitRuntime:i}=aG(),a=Sf(),r=o||(a?.target==="remote"?a.hostId:""),l=Tf({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});bC({apiBaseUrl:e,runtimeKey:ef(e,s)?"local":r?`host:${r}`:null});const u=h=>{const m=h.trim(),w=window.__OPENCHAMBER_DESKTOP__?.invoke;!m||!w||w("desktop_set_window_runtime_key",{runtimeKey:m}).catch(()=>{})};u(F()),Qr(h=>u(h.runtimeKey)),Vf(t||null),Hf(n||null),et.reconnectToRuntimeBaseUrl(),tc(e||void 0).catch(()=>{}),s&&!ef(e,s)&&Object.keys(_o()).length>0&&Kf(s).catch(()=>{}),aw();const p=()=>o?dh(o,{reconnectActive:true}):i?Promise.resolve():dh();return lu=Promise.race([p().catch(()=>{}),new Promise(h=>{window.setTimeout(h,1e4)})]).then(()=>{et.reconnectToRuntimeBaseUrl()}),lu.then(()=>{window.setTimeout(()=>{aA().catch(()=>{})},iG)}),oG({urls:l})},tf="openchamber:chunk-import-reload",rG=250,cG=3e4,lG=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function tS(e){if(e instanceof Error)return`${e.name}
|
|
88
88
|
${e.message}
|
|
89
|
-
${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function sf(e){const t=tS(e);return lG.some(s=>s.test(t))}function dG(e){return`2.7.
|
|
89
|
+
${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function sf(e){const t=tS(e);return lG.some(s=>s.test(t))}function dG(e){return`2.7.3-canary.20261115.21:${tS(e).slice(0,500)}`}function uG(e){if(typeof window>"u"||Ne())return;const t=Date.now(),s=dG(e);let n=null;try{const i=window.sessionStorage.getItem(tf);if(i)try{n=JSON.parse(i)}catch{n=null}}catch{return}const o=typeof n?.timestamp=="number"?n.timestamp:0;if(!(n?.signature===s&&t-o<cG)){try{window.sessionStorage.setItem(tf,JSON.stringify({signature:s,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function pG(e,t={}){const s=t.retries??1;let n;for(let o=0;o<=s;o+=1)try{return await e()}catch(i){if(n=i,!sf(i)||o>=s)break;await new Promise(a=>setTimeout(a,rG*(o+1)))}throw sf(n)&&uG(n),n}const _J=e=>dS.lazy(()=>pG(e));export{gz as $,I2 as A,DE as B,OE as C,EE as D,ME as E,xE as F,IE as G,LE as H,UE as I,sJ as J,Lb as K,Nb as L,Zt as M,dB as N,hJ as O,lB as P,L$ as Q,_$ as R,Vc as S,FJ as T,pG as U,F$ as V,F as W,s$ as X,z2 as Y,Gc as Z,Ie as _,Kj as a,$e as a$,D4 as a0,E4 as a1,W4 as a2,CJ as a3,uV as a4,iJ as a5,Qr as a6,mA as a7,Rw as a8,V4 as a9,it as aA,nz as aB,dr as aC,xG as aD,EG as aE,OG as aF,mb as aG,Sn as aH,Gx as aI,bz as aJ,KK as aK,pA as aL,Xj as aM,G2 as aN,Dn as aO,PG as aP,XG as aQ,qi as aR,Dz as aS,sc as aT,VT as aU,pz as aV,Oz as aW,$j as aX,sz as aY,az as aZ,cw as a_,ra as aa,tc as ab,I4 as ac,AB as ad,Ss as ae,c2 as af,RM as ag,AP as ah,xu as ai,Zc as aj,X$ as ak,T2 as al,A2 as am,MJ as an,Qw as ao,x4 as ap,dp as aq,R2 as ar,R0 as as,l2 as at,r4 as au,bF as av,iB as aw,vt as ax,ie as ay,MG as az,at as b,Wu as b$,Fz as b0,_z as b1,Yg as b2,hV as b3,O4 as b4,V0 as b5,SJ as b6,kJ as b7,J2 as b8,Xr as b9,Cz as bA,mu as bB,hs as bC,Sz as bD,yu as bE,MT as bF,Ez as bG,F2 as bH,Fr as bI,d2 as bJ,u2 as bK,Hu as bL,Mo as bM,mC as bN,ko as bO,kz as bP,fb as bQ,p2 as bR,x$ as bS,aJ as bT,f2 as bU,fz as bV,lr as bW,gJ as bX,M4 as bY,bR as bZ,_J as b_,oz as ba,OC as bb,GF as bc,Ln as bd,SE as be,W2 as bf,aO as bg,xy as bh,C4 as bi,os as bj,_2 as bk,wz as bl,Wz as bm,JK as bn,YK as bo,oE as bp,qC as bq,$K as br,ac as bs,Mf as bt,la as bu,Mn as bv,AT as bw,ql as bx,BC as by,Fo as bz,C$ as c,hz as c$,dt as c0,Tn as c1,Vx as c2,m2 as c3,Xx as c4,dd as c5,wb as c6,QK as c7,XK as c8,Uu as c9,eA as cA,Nt as cB,U$ as cC,rC as cD,Sf as cE,CG as cF,pJ as cG,GK as cH,TG as cI,ZG as cJ,AG as cK,RG as cL,IG as cM,LG as cN,UG as cO,TE as cP,JR as cQ,LK as cR,Dh as cS,V$ as cT,UK as cU,pI as cV,WT as cW,NT as cX,Iz as cY,xz as cZ,KT as c_,It as ca,ab as cb,Kl as cc,M$ as cd,ur as ce,ZK as cf,e2 as cg,s2 as ch,zK as ci,n2 as cj,Ax as ck,t2 as cl,o2 as cm,r2 as cn,a2 as co,i2 as cp,En as cq,g2 as cr,yJ as cs,rc as ct,QG as cu,Oa as cv,uo as cw,GI as cx,ez as cy,dh as cz,v$ as d,dz as d$,Uj as d0,Q4 as d1,Dv as d2,X4 as d3,Z4 as d4,eJ as d5,YG as d6,oV as d7,nV as d8,kR as d9,WG as dA,qG as dB,GG as dC,zG as dD,_G as dE,jG as dF,$G as dG,NG as dH,BG as dI,KG as dJ,VG as dK,HG as dL,UI as dM,jI as dN,Ud as dO,gi as dP,Yu as dQ,KD as dR,$D as dS,C2 as dT,tO as dU,Xu as dV,gb as dW,hb as dX,FG as dY,uz as dZ,lz as d_,o4 as da,Of as db,iz as dc,tz as dd,qK as de,lb as df,KI as dg,QI as dh,JI as di,ZI as dj,zI as dk,cg as dl,ic as dm,Xz as dn,e$ as dp,n$ as dq,a$ as dr,t$ as ds,Qz as dt,Zz as du,zA as dv,GA as dw,N$ as dx,w$ as dy,b$ as dz,u$ as e,sd as e$,B4 as e0,Lj as e1,Nj as e2,EJ as e3,l4 as e4,ZF as e5,dy as e6,ry as e7,_E as e8,NE as e9,rt as eA,ix as eB,XI as eC,Ip as eD,Xt as eE,vJ as eF,q2 as eG,$2 as eH,rO as eI,hu as eJ,pu as eK,wn as eL,xU as eM,aB as eN,TA as eO,I$ as eP,eB as eQ,Jz as eR,uA as eS,j$ as eT,jK as eU,yR as eV,vR as eW,qz as eX,z$ as eY,q$ as eZ,Da as e_,$E as ea,js as eb,AE as ec,Yj as ed,ZT as ee,QT as ef,Uz as eg,Xs as eh,eP as ei,wx as ej,lc as ek,E$ as el,z4 as em,fJ as en,P$ as eo,h$ as ep,D2 as eq,zz as er,Kz as es,Bi as et,O2 as eu,E2 as ev,wC as ew,Qf as ex,Cx as ey,_o as ez,T$ as f,l1 as f$,MR as f0,sC as f1,Wc as f2,B$ as f3,NR as f4,xR as f5,IK as f6,xK as f7,VR as f8,H0 as f9,o1 as fA,k1 as fB,a1 as fC,x1 as fD,j1 as fE,Im as fF,Rm as fG,Pm as fH,Am as fI,L1 as fJ,N1 as fK,_1 as fL,F1 as fM,AJ as fN,MH as fO,PJ as fP,gH as fQ,hH as fR,pH as fS,wH as fT,uH as fU,yk as fV,m1 as fW,vk as fX,f1 as fY,u1 as fZ,lH as f_,Ks as fa,E0 as fb,H$ as fc,ck as fd,eK as fe,$$ as ff,bK as fg,ZA as fh,Rd as fi,DJ as fj,Ld as fk,ds as fl,iM as fm,ae as fn,nC as fo,oC as fp,uh as fq,$4 as fr,dJ as fs,go as ft,Oh as fu,Zj as fv,Qj as fw,S$ as fx,R1 as fy,nO as fz,l$ as g,tA as g$,d1 as g0,dH as g1,xJ as g2,r1 as g3,S1 as g4,aH as g5,tH as g6,CH as g7,TH as g8,eH as g9,Tq as gA,Jk as gB,uU as gC,K4 as gD,iP as gE,Wl as gF,JG as gG,AK as gH,O$ as gI,rP as gJ,D$ as gK,aP as gL,lJ as gM,pB as gN,uJ as gO,R$ as gP,SK as gQ,BK as gR,rb as gS,vz as gT,bE as gU,nJ as gV,Vj as gW,Rj as gX,P2 as gY,jz as gZ,Bz as g_,oH as ga,sH as gb,p1 as gc,DH as gd,IJ as ge,Z1 as gf,SH as gg,Ak as gh,vH as gi,PH as gj,RJ as gk,AH as gl,M1 as gm,O1 as gn,Tk as go,DG as gp,UR as gq,Mh as gr,ZR as gs,QR as gt,oI as gu,Au as gv,MA as gw,Pz as gx,kK as gy,cJ as gz,A$ as h,_K as h$,iA as h0,Mz as h1,Hz as h2,Vz as h3,Lz as h4,Nz as h5,HT as h6,dA as h7,bJ as h8,Rz as h9,Lt as hA,m4 as hB,h2 as hC,Fa as hD,tK as hE,vF as hF,t4 as hG,Br as hH,s4 as hI,Cd as hJ,e4 as hK,XW as hL,Ow as hM,PK as hN,wK as hO,Z$ as hP,GP as hQ,gK as hR,uK as hS,dK as hT,oK as hU,CK as hV,rK as hW,cK as hX,RK as hY,DK as hZ,MK as h_,pV as ha,c4 as hb,TU as hc,tJ as hd,J4 as he,dV as hf,TJ as hg,i1 as hh,lk as hi,HI as hj,K$ as hk,rJ as hl,T0 as hm,A0 as hn,C0 as ho,Rq as hp,OJ as hq,Q$ as hr,Y$ as hs,Fu as ht,ot as hu,U4 as hv,H4 as hw,dc as hx,a4 as hy,j4 as hz,GD as i,F4 as i$,hK as i0,TK as i1,lK as i2,pK as i3,td as i4,yK as i5,vK as i6,UP as i7,mJ as i8,FK as i9,wM as iA,Id as iB,PM as iC,pF as iD,py as iE,dF as iF,lF as iG,uF as iH,xd as iI,wg as iJ,_M as iK,gF as iL,fF as iM,hF as iN,aN as iO,zM as iP,jM as iQ,Ey as iR,C_ as iS,S_ as iT,d4 as iU,Tz as iV,Y4 as iW,f4 as iX,hM as iY,pM as iZ,N4 as i_,z0 as ia,G0 as ib,mz as ic,xw as id,sp as ie,UF as ig,Z2 as ih,Q2 as ii,Va as ij,i4 as ik,k_ as il,kF as im,uy as io,LM as ip,MM as iq,OM as ir,mF as is,d_ as it,l_ as iu,c_ as iv,cy as iw,ly as ix,xM as iy,fM as iz,P as j,DN as j$,_4 as j0,L4 as j1,J$ as j2,RP as j3,q as j4,Vw as j5,mK as j6,G$ as j7,YP as j8,YI as j9,r$ as jA,i$ as jB,o$ as jC,oP as jD,c$ as jE,xF as jF,EF as jG,Ay as jH,TF as jI,MF as jJ,by as jK,WF as jL,LF as jM,S4 as jN,b4 as jO,w4 as jP,p4 as jQ,v4 as jR,y4 as jS,Ng as jT,iL as jU,T4 as jV,A4 as jW,RN as jX,xN as jY,IN as jZ,ON as j_,oR as ja,aR as jb,ZP as jc,QP as jd,pc as je,K2 as jf,mt as jg,X0 as jh,Az as ji,N2 as jj,U2 as jk,H2 as jl,j2 as jm,L2 as jn,B2 as jo,zb as jp,V2 as jq,q4 as jr,G4 as js,DC as jt,y$ as ju,k$ as jv,f$ as jw,m$ as jx,g$ as jy,p$ as jz,or as k,n4 as k0,R4 as k1,KN as k2,JN as k3,k4,g4 as k5,h4 as k6,iV as k7,Eo as k8,rk as k9,EM as kA,S2 as kB,VK as kC,NK as kD,Gz as kE,$z as kF,yz as kG,Yt as kH,xp as kI,WK as kJ,HK as kK,Y2 as kL,oJ as kM,cV as ka,rz as kb,cz as kc,cM as kd,X2 as ke,pp as kf,OK as kg,EK as kh,eR as ki,sK as kj,nK as kk,wJ as kl,aK as km,iK as kn,fK as ko,_0 as kp,Hx as kq,b2 as kr,y2 as ks,k2 as kt,$x as ku,w2 as kv,v2 as kw,W$ as kx,P4 as ky,u4 as kz,Tp as l,Ne as m,Oe as n,d$ as o,Yz as p,zD as q,nP as r,zj as s,Ur as t,I as u,et as v,Ut as w,x2 as x,FE as y,M2 as z};
|