@openchamber/web 2.7.0 → 2.7.1-canary.20261108.12
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-Bbu8cDW8.js → AboutDialog-uNKjHvzl.js} +1 -1
- package/dist/assets/{AboutLogo-sAyRFbrm.js → AboutLogo-BhyG0ENm.js} +1 -1
- package/dist/assets/{ArchiveView-DvLmQllR.js → ArchiveView-Jt6Qj8Ry.js} +1 -1
- package/dist/assets/{ChangeRequestDiffUnavailable-Ctc-P6zi.js → ChangeRequestDiffUnavailable-CNIWdYRx.js} +1 -1
- package/dist/assets/{ChangedPathLabel-CQOXgkIF.js → ChangedPathLabel-CCsE-8p4.js} +1 -1
- package/dist/assets/{CommandPalette-DHk0MqYi.js → CommandPalette-DrsFSbmk.js} +1 -1
- package/dist/assets/{DiffView-DPpu52DA.js → DiffView-DwaJOPUe.js} +1 -1
- package/dist/assets/{FilesView-CPrroDyU.js → FilesView-Hvxe_KqA.js} +4 -4
- package/dist/assets/{GitView-wWoZ95Yt.js → GitView-ZI_EafL9.js} +1 -1
- package/dist/assets/{GuestSurfacePane-BsMH8QjU.js → GuestSurfacePane-Ds8luSO0.js} +1 -1
- package/dist/assets/{HelpDialog-BZtzVj6Z.js → HelpDialog-DtZKoPZE.js} +1 -1
- package/dist/assets/{IntegrationsCatalogView-DJAOTlcc.js → IntegrationsCatalogView-DgdYlI3Z.js} +1 -1
- package/dist/assets/{JsonTreeView-BXv2HzlC.js → JsonTreeView-zAv-pn0X.js} +1 -1
- package/dist/assets/{MarkdownDiffPreview-CseaChSt.js → MarkdownDiffPreview-Bf9-WPy9.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CyXOMsMS.js → MarkdownRendererImpl-w7LnAwp_.js} +4 -4
- package/dist/assets/{MemoryDebugPanel-xYvjTjLG.js → MemoryDebugPanel-ylQytlyw.js} +1 -1
- package/dist/assets/{NoteEditor-Bbrtl8rq.js → NoteEditor-0HEW8KrY.js} +1 -1
- package/dist/assets/{OfficeDocumentDiff-DXsfJnFq.js → OfficeDocumentDiff-BFr4rAHy.js} +1 -1
- package/dist/assets/{OnboardingScreen-DuWvo16v.js → OnboardingScreen-Bpj6hpDe.js} +1 -1
- package/dist/assets/{OpenCodeStatusDialog-9WRgjgWL.js → OpenCodeStatusDialog-CX3oxFSb.js} +1 -1
- package/dist/assets/{OverviewView-BzA9rGEs.js → OverviewView-UfIFJ3mf.js} +1 -1
- package/dist/assets/{PatchDiff-DVcyjZVm.js → PatchDiff-DC4ydsOW.js} +1 -1
- package/dist/assets/{PlanView-BGdba90K.js → PlanView-CgoTn3HJ.js} +1 -1
- package/dist/assets/{ProjectActionsDialog-ByPMdwFG.js → ProjectActionsDialog-B16N4lqs.js} +1 -1
- package/dist/assets/{ReplyCommand-pviKPDT8.js → ReplyCommand-CnDNvFmd.js} +1 -1
- package/dist/assets/{ReplyUiBlock-D7HPBgmq.js → ReplyUiBlock-BsOTgv8M.js} +1 -1
- package/dist/assets/{ReviewCards-CU1YHZkQ.js → ReviewCards-BkpTYy_a.js} +1 -1
- package/dist/assets/{RunOverview-uFEfusCK.js → RunOverview-DsffX3fI.js} +1 -1
- package/dist/assets/{ScheduledTasksDialog-J8i_b433.js → ScheduledTasksDialog-DgrAfpeX.js} +1 -1
- package/dist/assets/{SettingsView-CaUgulkI.js → SettingsView-B804XZvl.js} +1 -1
- package/dist/assets/{SettingsWindow-BVEVntuV.js → SettingsWindow-k5FSMAzV.js} +1 -1
- package/dist/assets/{SidebarSectionsManager-CIXOcE0-.js → SidebarSectionsManager-DH61-mRe.js} +1 -1
- package/dist/assets/{SourceBoardView-BW1OSOo1.js → SourceBoardView-BvGoSNer.js} +1 -1
- package/dist/assets/{SpaceAccessDialog-6GhzlMD8.js → SpaceAccessDialog-DHNqUzKD.js} +1 -1
- package/dist/assets/{SpaceApplyDialog-zB4jAExK.js → SpaceApplyDialog-DEOTeEjy.js} +1 -1
- package/dist/assets/{SpaceRow-C6QD41XF.js → SpaceRow-CBva6ofM.js} +1 -1
- package/dist/assets/{SpaceSetupOutput-6GuKiRed.js → SpaceSetupOutput-C4NhRkjl.js} +1 -1
- package/dist/assets/{SpacesView-BgncMV45.js → SpacesView-BGevrpQp.js} +1 -1
- package/dist/assets/{SubmoduleDiffSummary-BwVdGw0c.js → SubmoduleDiffSummary-Bebhaz7n.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CC9hcX2C.js → ToolOutputDialog-B1gU22Tz.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-D15Ja459.js → ToolPartDiffPreview-CVy_zn_m.js} +1 -1
- package/dist/assets/{UiBlock-pyLxOJr6.js → UiBlock-C11qZK5T.js} +2 -2
- package/dist/assets/{UsageStatsView-CMf29PeL.js → UsageStatsView-CNm8WPSk.js} +1 -1
- package/dist/assets/{WalkthroughView-DeuNxpZ7.js → WalkthroughView-Bbwyk6rg.js} +1 -1
- package/dist/assets/{WorktreesView-jHcQwWBH.js → WorktreesView-BGIfERNs.js} +1 -1
- package/dist/assets/{appThemeRegistry-BwyM6n38.js → appThemeRegistry-DYzVI9tX.js} +1 -1
- package/dist/assets/{ar-DnPStsLU.js → ar-CT3AuXVj.js} +1 -1
- package/dist/assets/{codeHighlight-C7ZRQ5-2.js → codeHighlight-BcDjh6yS.js} +1 -1
- package/dist/assets/{columnWidthMemory-Cbfh5HD5.js → columnWidthMemory-BA6h4J11.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DVynfSBh.js → computeVirtualFileMetrics-DVfKKHny.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-CKnYjgFC.js → contextFileOpenGuard-BC79wuu1.js} +1 -1
- package/dist/assets/{date-time-qS8d5iiz.js → date-time-DhfjtTnp.js} +1 -1
- package/dist/assets/{de-SUU4F7Nt.js → de-BdVTH897.js} +1 -1
- package/dist/assets/{documentClient-B0iRikhq.js → documentClient-JcxJ7vyh.js} +2 -2
- package/dist/assets/{documentExport-Cf0gMwM0.js → documentExport-C830mU4N.js} +1 -1
- package/dist/assets/{documentHost-cOykm7qf.js → documentHost-DKm0U_q_.js} +1 -1
- package/dist/assets/{es-BWlkhnKy.js → es-BFk4dosu.js} +1 -1
- package/dist/assets/{fileContentPoller-CKcqqhzG.js → fileContentPoller-BmcApnk-.js} +1 -1
- package/dist/assets/{flexokiTheme-deI9tWCZ.js → flexokiTheme-BMYGLHbL.js} +1 -1
- package/dist/assets/{fr-DN3Tx1EV.js → fr-CeExWqT9.js} +1 -1
- package/dist/assets/{he-B-7jIB_R.js → he-C_O5IfNH.js} +1 -1
- package/dist/assets/{highlights-B2Re-VTM.js → highlights-CIuWBj_n.js} +1 -1
- package/dist/assets/{index-D5Ed7hon.js → index-bD6u6GDm.js} +1 -1
- package/dist/assets/{initializeSharedPreferences-D5FLPdpI.js → initializeSharedPreferences-BcnhlF3e.js} +1 -1
- package/dist/assets/{install-sOrZWWGd.js → install-CSoRI5iX.js} +1 -1
- package/dist/assets/{install-request-C-zhz88k.js → install-request-EHX4ORhb.js} +1 -1
- package/dist/assets/{isDiffPlainText-DpcjRlB-.js → isDiffPlainText-saKoOWJx.js} +1 -1
- package/dist/assets/{isFilePlainText-DJ_bXU7C.js → isFilePlainText-DOjSDWo3.js} +1 -1
- package/dist/assets/{ja-DE4Yf-rX.js → ja-BlUqUBMY.js} +1 -1
- package/dist/assets/{katex.min-g52ii4Gs.js → katex.min-Bs5OLoA1.js} +4 -4
- package/dist/assets/{ko-CETaCyB8.js → ko-CGv47dWq.js} +1 -1
- package/dist/assets/{main-QRYvDkRZ.js → main-064y5MQB.js} +4 -4
- package/dist/assets/{main-89VT8Kff.js → main-D8yzv2tL.js} +2 -2
- package/dist/assets/{miniChat-CgHPqY7Z.js → miniChat-X7g2IHQj.js} +2 -2
- package/dist/assets/{mobile-BQrjPA_e.js → mobile-B5efB3tI.js} +2 -2
- package/dist/assets/{moveWorkspacePath-C4_JgpNC.js → moveWorkspacePath-BaEfuU4S.js} +1 -1
- package/dist/assets/{nl-CL94_9kf.js → nl-CavtTtNf.js} +1 -1
- package/dist/assets/{officeDocument-COfYG-XF.js → officeDocument-CQScRmC1.js} +1 -1
- package/dist/assets/{parseDiffFromFile-CD1h9Yf5.js → parseDiffFromFile-By5H8w4y.js} +1 -1
- package/dist/assets/{pierreDiffTint-Cg024Eeg.js → pierreDiffTint-CVm_qZm-.js} +1 -1
- package/dist/assets/{pl-Bk1GuZBm.js → pl-BQZVI44N.js} +1 -1
- package/dist/assets/{pt-BR-Bfrsw-GS.js → pt-BR-iqkU-MRA.js} +1 -1
- package/dist/assets/{relocateRestoredSession-C79EVzC-.js → relocateRestoredSession-CsK2RUM_.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-lMVP5gEt.js → renderElectronMiniChatApp-DzVezwky.js} +2 -2
- package/dist/assets/{renderMarkdownForExport-DTutihQz.js → renderMarkdownForExport-BM19JOji.js} +1 -1
- package/dist/assets/{renderMobileApp-CmYW0oos.js → renderMobileApp-CiTrtu6R.js} +3 -3
- package/dist/assets/{resolveLanguages-lTTkQHer.js → resolveLanguages-DQXSOQcc.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-BJm_77m2.js → runtimeEndpointReset-DiTyBUwe.js} +5 -5
- package/dist/assets/{scheduledTasksApi-CKPLiwD-.js → scheduledTasksApi-Z7dc8sXS.js} +1 -1
- package/dist/assets/{shiki-CQYsk6Az.js → shiki-DW-V1SDr.js} +1 -1
- package/dist/assets/{space-apply-BT-PjBF5.js → space-apply-8YUOtYvk.js} +1 -1
- package/dist/assets/{space-close-C1Qs6EK6.js → space-close-D7zK_obq.js} +1 -1
- package/dist/assets/{spaceNetwork-C14OnxrT.js → spaceNetwork-XStNVwJo.js} +1 -1
- package/dist/assets/{stream-tokenizer-xdyY_PEd.js → stream-tokenizer-BfPOSMyw.js} +1 -1
- package/dist/assets/{textMateThemeFromAppTheme-CRhUx8P-.js → textMateThemeFromAppTheme-CVOJt2hL.js} +1 -1
- package/dist/assets/{tr-Cgg3eQb7.js → tr-CYfLfxAg.js} +1 -1
- package/dist/assets/{uk-zPAKOL1d.js → uk-Bm__l5YX.js} +1 -1
- package/dist/assets/{useAppFontEffects-D9nf8G19.js → useAppFontEffects-3RimJo4B.js} +15 -15
- package/dist/assets/{useBranchPullRequestRequest-CaGsp4wW.js → useBranchPullRequestRequest-CMvepZei.js} +1 -1
- package/dist/assets/{useCallableModelProviders-B1YBs2FN.js → useCallableModelProviders-DpMos2Hl.js} +1 -1
- package/dist/assets/{useDiffFindSurface-DiINVOLu.js → useDiffFindSurface-Dy5ZvPrH.js} +1 -1
- package/dist/assets/{useGitCleanLine-BK-o3SG6.js → useGitCleanLine-COG7MPwc.js} +1 -1
- package/dist/assets/{useInlineCommentController-CzeMiLCm.js → useInlineCommentController-_L6_JHZ6.js} +1 -1
- package/dist/assets/{useMarkdownLocalAssets-wPn7MXUN.js → useMarkdownLocalAssets-CH5Ekvbl.js} +1 -1
- package/dist/assets/{useRootScrollLock-BvsNFl90.js → useRootScrollLock-DdknBCBa.js} +2 -2
- package/dist/assets/{useWalkthroughReview-CEo_4ZLc.js → useWalkthroughReview-Bi8eB9_G.js} +1 -1
- package/dist/assets/{useWholeFileComment-BexRzYws.js → useWholeFileComment-CqHAJ2YU.js} +1 -1
- package/dist/assets/{useWorktreeArchiveActions-DaRx6tMV.js → useWorktreeArchiveActions-D1kaQEP9.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-z3n6zAAT.js → vendor-codemirror-language-data-DRsX0PKK.js} +2 -2
- package/dist/assets/{zh-CN-BPcuR4-K.js → zh-CN-Db0Y0Ij-.js} +1 -1
- package/dist/assets/{zh-TW-CmPAjna9.js → zh-TW-CuzqmROB.js} +1 -1
- package/dist/index.html +2 -2
- package/dist/mini-chat.html +2 -2
- package/dist/mobile.html +2 -2
- package/package.json +3 -3
|
@@ -1,5 +1,5 @@
|
|
|
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/zh-CN-
|
|
2
|
-
import{_ as qe}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as vt,d as dn,p as zi,a as uw}from"./vendor-zustand-C9tWdk0j.js";import{o as g,s as p,n as v,l as k,e as T,c as z,h as ve,_ as I,u as J,a as kt,j as ci,f as ee,i as mw,k as jo,p as li,q as Wu,v as Ui}from"./vendor-zod--raI7LhK.js";import{e as Hu,C as lp}from"./vendor-opencode-client-CeybcDBQ.js";import{f as Mt,R as Qa,r as hw}from"./vendor-react--VO_rL_p.js";import{F as Gu}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as fw}from"./vendor-streamdown-BbSYZ3NF.js";import{u as bw}from"./vendor-unified-1CQKw2_w.js";import{c as ww}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as kw}from"./vendor-capacitor-core-B4EWRrHz.js";const Hn=1,yw=g({type:k("relay-retire"),code:v().int(),reason:p().catch("")}),vw=e=>{try{const t=yw.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},Cw="openchamber-relay-v1",_u=1,Ku=12,Gn=1+Ku,di=64*1024,pi=5,Oo=128,Zu=0,Ju=1,$a=4,Sw=1+$a,jc=di-pi-Sw,xw="x-openchamber-tunnel-accept-encoding",Pw="x-openchamber-tunnel-content-encoding",se={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},Tw=new Set(Object.values(se)),zw=e=>Tw.has(e),Ns={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},cs=globalThis.crypto.subtle,Qu={name:"ECDH",namedCurve:"P-256"},$u=16,Ar=32,Aw=16,Oc=4,Yu=8;class Fs extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Rw=()=>cs.generateKey(Qu,!0,["deriveBits"]),Iw=async e=>{const t=await cs.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},jw=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 cs.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Qu,!0,[])}catch{throw new Fs("invalid ECDH public key JWK")}},Ow=()=>{const e=new Uint8Array($u);return globalThis.crypto.getRandomValues(e),e},Dw=async(e,t,s)=>{if(s.length!==$u)throw new Fs("invalid handshake nonce length");const a=await cs.deriveBits({name:"ECDH",public:t},e,256),n=await cs.importKey("raw",a,"HKDF",!1,["deriveBits"]),i=new Uint8Array(await cs.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(Cw)},n,Ar*2*8)),o=(r,c)=>cs.importKey("raw",r,{name:"AES-GCM"},!1,c);return{clientToHost:await o(i.slice(0,Ar),["encrypt","decrypt"]),hostToClient:await o(i.slice(Ar),["encrypt","decrypt"])}},Fw=(e,t,s)=>{for(let a=Yu-1;a>=0;a-=1)e[t+a]=Number(s&0xffn),s>>=8n},Bw=(e,t)=>{let s=0n;for(let a=0;a<Yu;a+=1)s=s<<8n|BigInt(e[t+a]);return s},Nw=e=>{const t=new Uint8Array(Oc);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(a){if(a.length>di)throw new Fs("plaintext frame exceeds maximum size");s+=1n;const n=new Uint8Array(Ku);n.set(t,0),Fw(n,Oc,s);const i=new Uint8Array(await cs.encrypt({name:"AES-GCM",iv:n},e,a)),o=new Uint8Array(Gn+i.length);return o[0]=_u,o.set(n,1),o.set(i,Gn),o}}},Mw=e=>{let t=0n;return{async decrypt(s){if(s.length<Gn+Aw)throw new Fs("encrypted frame too short");if(s[0]!==_u)throw new Fs("unsupported encrypted frame version");const a=s.slice(1,Gn),n=Bw(a,Oc);if(n<=t)throw new Fs("frame counter regression");let i;try{i=await cs.decrypt({name:"AES-GCM",iv:a},e,s.slice(Gn))}catch{throw new Fs("frame decryption failed")}return t=n,new Uint8Array(i)}}},Wi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ew=e=>{let t="";for(let s=0;s<e.length;s+=3){const a=e[s],n=s+1<e.length?e[s+1]:void 0,i=s+2<e.length?e[s+2]:void 0;t+=Wi[a>>2],t+=Wi[(a&3)<<4|(n??0)>>4],n!==void 0&&(t+=Wi[(n&15)<<2|(i??0)>>6]),i!==void 0&&(t+=Wi[i&63])}return t},dp=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!==Hn)return null;const a=s.batch===!0,n=s.flowControl===!0;return s.t==="ready"?{t:"ready",v:Hn,batch:a,flowControl:n}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:Hn,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:a,flowControl:n}:null},Lw=e=>({type:"fail",closeCode:Ns.ChannelFailure,reason:e}),qw=async(e,t={})=>{const s=t.batch!==!1,a=await jw(e),n=await Rw(),i=Ow(),o={t:"hello",v:Hn,clientPubJwk:await Iw(n.publicKey),nonce:Ew(i)};s&&(o.batch=!0),t.flowControl!==!1&&(o.flowControl=!0);let r=!1;return{helloText:JSON.stringify(o),get established(){return r},async handleText(c){if(r)return dp(c)?.t==="ready"?{type:"ignore"}:Lw("plaintext frame on established channel");const l=dp(c);if(l?.t!=="ready")return{type:"ignore"};const d=await Dw(n.privateKey,a,i);return r=!0,{type:"established",batch:s&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:Nw(d.clientToHost),decryptor:Mw(d.hostToClient)}}}}},Xu=4294967295,Vw=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 Ve extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const zt=(e,t,s,a=!1)=>{if(!Number.isInteger(t)||t<0||t>Xu)throw new Ve("invalid stream id");if(s.length>jc)throw new Ve("tunnel payload exceeds maximum size");const n=new Uint8Array(pi+s.length);return n[0]=a?e|Oo:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(s,pi),n},Uw=e=>{if(e.length<pi)throw new Ve("tunnel frame too short");const t=e[0],s=(t&Oo)!==0,a=t&~Oo;if(!zw(a))throw new Ve(`unknown tunnel frame type ${a}`);const n=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:a,streamId:n,payload:e.slice(pi),hasMoreFragments:s}},Ww=new TextEncoder,Hw=new TextDecoder,Hi=e=>Ww.encode(JSON.stringify(e)),Gi=(e,t)=>{let s;try{s=JSON.parse(Hw.decode(e))}catch{throw new Ve("malformed JSON tunnel payload")}if(!t(s))throw new Ve("unexpected JSON tunnel payload shape");return s},em=(e,t=jc)=>{if(t<=0||t>jc)throw new Ve("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let a=0;a<e.length;a+=t)s.push(e.slice(a,a+t));return s},pp=(e,t,s)=>{const a=em(s);return a.map((n,i)=>zt(e,t,n,i<a.length-1))},Gw=(e=16*1024*1024)=>{const t=new Map;return{push(s){const a=`${s.streamId}:${s.frameType}`,n=t.get(a);if(!s.hasMoreFragments&&!n)return s.payload;const i=n?.chunks??[],o=(n?.totalBytes??0)+s.payload.length;if(o>e)throw t.delete(a),new Ve("fragmented message exceeds maximum size");if(i.push(s.payload),s.hasMoreFragments)return t.set(a,{chunks:i,totalBytes:o}),null;t.delete(a);const r=new Uint8Array(o);let c=0;for(const l of i)r.set(l,c),c+=l.length;return r},dropStream(s){for(const a of t.keys())a.startsWith(`${s}:`)&&t.delete(a)}}},_w=e=>{if(e.length===0)throw new Ve("cannot encode an empty frame batch");if(e.length===1){const n=e[0],i=new Uint8Array(1+n.length);if(i[0]=Zu,i.set(n,1),i.length>di)throw new Ve("frame batch exceeds maximum plaintext size");return i}let t=1;for(const n of e)t+=$a+n.length;if(t>di)throw new Ve("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=Ju;let a=1;for(const n of e)s[a]=n.length>>>24&255,s[a+1]=n.length>>>16&255,s[a+2]=n.length>>>8&255,s[a+3]=n.length&255,a+=$a,s.set(n,a),a+=n.length;return s},Kw=e=>{if(e.length<1)throw new Ve("empty batch plaintext");const t=e[0];if(t===Zu)return[e.slice(1)];if(t!==Ju)throw new Ve(`unknown batch container tag ${t}`);const s=[];let a=1;for(;a<e.length;){if(a+$a>e.length)throw new Ve("truncated batch frame length");const n=(e[a]<<24|e[a+1]<<16|e[a+2]<<8|e[a+3])>>>0;if(a+=$a,a+n>e.length)throw new Ve("truncated batch frame body");s.push(e.slice(a,a+n)),a+=n}if(s.length===0)throw new Ve("empty frame batch");return s},Zw=new Set([se.HttpBody,se.WsText,se.WsBinary]),tm=150,Jw=24*1024,Qw=32,$w=e=>{const t=e.windowMs??tm,s=e.maxBatchBytes??Jw,a=e.maxBatchFrames??Qw,n=e.now??(()=>Date.now()),i=e.setTimer??((w,y)=>setTimeout(w,y)),o=e.clearTimer??(w=>clearTimeout(w));let r=[],c=0,l=null,d=0,u=!1;const m=()=>{l!==null&&(o(l),l=null)},f=()=>{if(m(),r.length===0)return;const w=r;r=[],c=0,d=n(),e.sendBatch(_w(w))};return{enqueue:w=>{if(u)return;const y=w[0]&~Oo;if(!Zw.has(y)){r.push(w),f();return}const A=n();if(r.length===0&&A-d>=t){r.push(w),f();return}const x=$a+w.length;if(r.length>0&&1+c+x>di&&f(),r.push(w),c+=x,c>=s||r.length>=a){f();return}l===null&&(l=i(f,t))},flush:f,dispose(){u=!0,m(),r=[],c=0}}},Yw=()=>{let e=1;return{next(){if(e>Xu)throw new Ve("stream id space exhausted");const t=e;return e+=2,t}}},Xo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xw=e=>Xo(e)&&Object.values(e).every(t=>typeof t=="string"),ek=e=>Xo(e)&&typeof e.status=="number"&&Xw(e.headers),gp=e=>Xo(e)&&typeof e.reason=="string",tk=e=>Xo(e)&&typeof e.code=="number"&&typeof e.reason=="string",sm=/^[a-z][a-z\d+.-]*:\/\//i,Kl="http://tunnel.invalid",sk=e=>{try{const t=sm.test(e)?new URL(e):new URL(e,Kl);return`${t.pathname}${t.search}`}catch{return e}},_i=e=>({async*[Symbol.asyncIterator](){yield e}}),ak=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:a}=await t.read();if(s)return;a&&(yield a)}}finally{t.releaseLock()}}}),nk=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},ik=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:ak(e)};if(typeof e=="string")return{body:_i(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:_i(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:_i(nk(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,a=new Uint8Array(await t.arrayBuffer());return{body:_i(a),contentType:s}},ok=async(e,t)=>{let s;const a=new Headers;let n="GET",i=null,o;e instanceof Request?(s=e.url,n=e.method,e.headers.forEach((u,m)=>a.set(m,u)),o=e.signal,i=e.body):s=e.toString(),t&&(t.method&&(n=t.method),t.headers&&new Headers(t.headers).forEach((u,m)=>a.set(m,u)),t.body!==void 0&&(i=t.body),t.signal&&(o=t.signal));const r=sm.test(s)?new URL(s):new URL(s,Kl),{body:c,contentType:l}=await ik(i);l&&!a.has("content-type")&&a.set("content-type",l);const d={};return a.forEach((u,m)=>{d[m]=u}),{method:n.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:d,body:c,signal:o}},am="__openchamberAmbiguousTransport",nm=new WeakSet,rk=e=>(nm.add(e),e),ck=e=>nm.has(e),Dc=e=>(Object.defineProperty(e,am,{value:!0,enumerable:!1,configurable:!0}),e),lk=e=>!e||typeof e!="object"?!1:e[am]===!0,dk=["local","remote",null],pk=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function im(e){if(!e||typeof e!="object")return{valid:!1};const t=e,s=t.localAvailable===!1?{localAvailable:!1}:{},a=t.target,n=t.status;if(a!==null&&(typeof a!="string"||!dk.includes(a)))return{valid:!1};if(typeof n!="string"||!pk.includes(n))return{valid:!1};if(a==="remote"||a==="local"){if(n==="ok"&&a==="local"){const i={target:"local",status:"ok",...s},o=p().min(1).safeParse(t.sshStartupFallbackHostId);return o.success&&(i.sshStartupFallbackHostId=o.data),{valid:!0,outcome:i}}if(n==="ok"&&a==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(n==="unreachable")return a==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(n==="incompatible"||n==="wrong-service")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url,...s}};if(n==="missing")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(a===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...s}};if(n==="missing")return{valid:!1}}return{valid:!1}}function AM(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===!1?{localAvailable:!1}:{};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 RM(e){return!e.isDesktopShell||e.bootOutcomeKnown}function IM(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function om(){if(gk()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=im(t);return s.valid?s.outcome:null}function gk(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":im(e).valid?"valid":"malformed"}const Do=/^[a-z][a-z\d+.-]*:\/\//i,uk=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Fo=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),mk=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Fo(e)},hk=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Fo(e)},fk=()=>Object.keys(un()).length>0,bk=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Fc=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},wk=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Fc({searchParams:s},t);const a=s.toString();return a?e.includes("?")?`${e}&${a}`:`${e}?${a}`:e},up=(e,t,s)=>{if(Do.test(t)){const o=new URL(t);return Fc(o,s),o.toString()}const a=uk(t);if(!e)return wk(a,s);const n=new URL(e),i=new URL(`${n.origin}${n.pathname.replace(/\/+$/,"")}${a}`);return Fc(i,s),i.toString()},Ki=(e,t=ay())=>{if(!t)return e;const s=Do.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),Do.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},rm=(e,t)=>{const s=Do.test(e)?new URL(e):new URL(e,bk(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},mp=(e,t,s)=>{if(!fk())return null;const a=hk();if(!a)return null;try{const n=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${a}/`);n.searchParams.set("url",t);const i=ny(a);return i&&n.searchParams.set("oc_url_token",i),e==="ws"?(n.protocol=n.protocol==="https:"?"wss:":"ws:",rm(n.toString(),s)):n.toString()}catch{return null}},Zl=(e={})=>{const t=Fo(e.apiBaseUrl),s=Fo(e.realtimeBaseUrl),a=()=>t||mk(),n=()=>s||a(),i=(r,c)=>up(a(),r,c),o=(r,c)=>up(n(),r,c);return{api:i,authenticatedAsset:(r,c)=>Ki(i(r,c)),assetWithUrlToken:(r,c,l)=>Ki(i(r,l),c),auth:i,health:r=>i("/health",r),rawFile:(r,c)=>i("/api/fs/raw",{path:r,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(r,c)=>{const l=Ki(o(r,c));return mp("sse",l,e)||l},websocket:(r,c)=>{const l=rm(Ki(o(r,c)),e);return mp("ws",l,e)||l}}};let Bo=Zl();const ds=()=>Bo,kk=e=>{Bo=e},cm=e=>(Bo=Zl(e),Bo),Bc="openchamber:runtime-endpoint-changed",Nc="openchamber:runtime-endpoint-will-change";let Ya="",gi="",Mc=0,Ec=null;const Rr=(e,t,s)=>{try{e[t]=s}catch{}},Jl=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"}`}},yk="mobile-disconnected",vk="url:default",Lc=e=>e===""||e===vk||e===yk,lm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},dm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},pm=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},us=()=>Ya||lm(),Ck=()=>{if(Ec!==null)return Ec;const e=us();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let Ir="",hp=null,fp,bp;const wp=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(gi)return gi;const e=wp("__OPENCHAMBER_API_BASE_URL__"),t=wp("__OPENCHAMBER_LOCAL_ORIGIN__");if(hp===Ya&&fp===e&&bp===t)return Ir;const s=us();return Ir=pm(s,dm())?"local":Jl(s),hp=Ya,fp=e,bp=t,Ir},gm=()=>{const e=Mc,t=D();return()=>e===Mc&&t===D()},Sk=(e={})=>{if(Ya||gi)return;const t=e.apiBaseUrl?.trim()||lm(),s=globalThis.window?.location?.origin??"",a=/^https?:\/\//.test(s)?s:"";if(!t&&!a)return;const n=dm(),i=n&&(!t||pm(t,n));Ya=t,gi=e.runtimeKey?.trim()||(i?"local":Jl(t||a))},qc=e=>{const t=e.apiBaseUrl.trim(),s=us(),a=D(),n=e.runtimeKey?.trim()||Jl(t),i=e.sshForwarded??(t===s&&n===a&&Ck()),o={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:n,previousRuntimeKey:a};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Nc,{detail:o})),Ya=t,gi=n,n!==a&&(Mc+=1),Ec=i,typeof window<"u"){const r=window;Rr(r,"__OPENCHAMBER_API_BASE_URL__",t),Rr(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Rr(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}cm({apiBaseUrl:t,realtimeBaseUrl:t}),Am(e.requestHeaders||null),zm(e.clientToken||null),e.relay?Qk(e.relay):$k(),nr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bc,{detail:o}))},er=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Nc,t),()=>window.removeEventListener(Nc,t)},tr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Bc,t),()=>window.removeEventListener(Bc,t)};let Vc=null;const jM=e=>{Vc=e},pn=()=>Vc||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Ql=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,ui=()=>{const e=Ql();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():!1},um=(e=Ql())=>!!e,xk=e=>e==="stable"||e==="canary",Pk=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,OM=e=>{const t=Pk.exec(e??"");if(!t)return null;const[,s,a,n,i,o]=t;return{release:s,builtOn:new Date(Date.UTC(Number(a),Number(n)-1,Number(i))),build:o?Number(o):null}},Tk=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),DM=(e,t,s)=>{const a=Tk(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${a} #${e.build}`:a},mm=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,ms=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,ua=()=>mm()?.runtime==="electron",hm=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},zk="right",FM=()=>{if(!ua())return!1;const e=hm();return e==="linux"?mm()?.nativeFrame!==!0:e==="win32"},BM=e=>e==="left"?"left":zk,NM=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],tt=()=>typeof ms()?.invoke=="function",gt=()=>ua()&&tt(),Ak=()=>{const e=ms()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>p().parse(await t()),writeText:async a=>{k(!0).parse(await s(a))}}}},Rk=()=>{if(ms()?.pickThemeFile)return{async pick(){const e=ms()?.pickThemeFile;return e?{status:"picked",file:g({name:p(),size:v().nonnegative(),text:p()}).nullable().parse(await e())}:{status:"unsupported"}}}},Y=async(e,t)=>{const s=ms();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},MM=e=>{hm()!=="darwin"||!gt()||Y("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},EM=()=>({apiBaseUrl:us(),clientToken:td(),runtimeKey:D()}),LM=async()=>{if(!Ye()||!Se())return!1;const e=us();try{const t=T().safeParse(await Y("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===us()}catch{return!1}},qM=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},VM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},fm=e=>xk(e?.channel)?e.channel:null,UM=async()=>{if(!gt()||!Se())return null;try{return fm(await Y("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},WM=async e=>{if(!gt()||!Se())return null;try{return fm(await Y("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},HM=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},GM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},_M=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},KM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},Ik=g({supported:T(),enabled:T(),combo:p().nullable(),storedCombo:p().nullable(),active:T(),heightFraction:v(),error:k("unsupported-combo").optional()}),sr=async(e,t,s)=>{if(!gt()||!Se())return null;try{const a=Ik.safeParse(await Y(e,t));return a.success?a.data:null}catch(a){return console.warn(s,a),null}},ZM=()=>sr("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),JM=e=>sr("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),QM=e=>sr("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),$M=e=>sr("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),YM=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},XM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},kp=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}}},jr=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}}},jk=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Pn=e=>{const t=jk(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Se=()=>{if(typeof window>"u"||!Ye())return!1;if(D()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=jr(e),s=jr(us());if(!s&&t&&om()?.target==="local")return!0;if(t&&s){if(t.origin===s.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&o===r&&Pn(t.hostname)&&Pn(s.hostname)}const a=jr(window.location.origin);if(t&&a){if(t.origin===a.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=a.port||(a.protocol==="https:"?"443":"80");return t.protocol===a.protocol&&o===r&&Pn(t.hostname)&&Pn(a.hostname)}const n=kp(e),i=kp(window.location.origin)||window.location.origin;return n&&i&&n===i?!0:!!(a&&Pn(a.hostname))},Ye=()=>typeof window>"u"?!1:ua(),eE=async()=>{if(!Ye())return null;const e=g({visible:T()}).safeParse(await Y("desktop_get_current_window_state"));return e.success?e.data.visible:null},tE=async()=>{if(!Ye())return!1;try{return!!await Y("desktop_focus_window")}catch{return!1}},sE=(e,t,s=null)=>!t||t===D()||!gt()?!1:(Y("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(n=>{console.warn("[desktop] failed to open host session",n)}),!0),bm=()=>Ye()&&tt()&&Se(),Ok=z(g({sessionId:p().min(1),messageId:p().min(1).optional(),runtimeKey:p().min(1).optional(),requireKnownSession:T().optional()})),aE=async()=>{if(!Ye())return[];try{const e=z(p()).safeParse(await Y("desktop_take_pending_extension_installs"));return e.success?e.data:[]}catch{return[]}},nE=async()=>{if(!Ye()||!Se())return[];try{const e=Ok.safeParse(await Y("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===!0})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},Dk=z(ve("type",[g({type:k("pairing"),link:p().min(1)}),g({type:k("host"),hostId:p().min(1)})])),iE=async()=>{if(!Ye())return[];try{const e=Dk.safeParse(await Y("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},Fk=p().min(1),oE=e=>{if(!bm())return null;try{const t=Fk.safeParse(ms()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},rE=async()=>{if(!Ye())return!1;try{return await Y("desktop_start_window_drag"),!0}catch{return!1}},Oe=()=>um()?!0:pn()?.runtime?.isVSCode===!0,cE=()=>{const t=pn()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Oe()},lE=(e,t=Ye())=>e==="web"&&!t,wm=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},dE=async e=>{if(bm())try{const t=await ms()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},Bk=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),pE=async e=>{if(tt()&&Se())try{const t=await ms()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!Bk(t))return{success:!1,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:!0,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},gE=async e=>({success:!0}),uE=async e=>({success:!0}),mE=async()=>tt()?await Y("desktop_check_for_updates"):null,hE=async e=>{if(!tt())return!1;const t=ms();let s=null,a=0,n;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",i=>{const o=i?.payload;if(!o||typeof o!="object")return;const r=o,c=typeof r.event=="string"?r.event:null,l=r.data&&typeof r.data=="object"?r.data:null;if(c==="Started"){a=0,n=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:a,total:n});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(a=d),typeof u=="number"&&(n=u),e({downloaded:a,total:n});return}c==="Finished"&&e({downloaded:a,total:n})})),await Y("desktop_download_and_install_update"),!0}catch(i){throw i instanceof Error?i:new Error(String(i))}finally{if(s)try{const i=s();i instanceof Promise&&await i}catch{}}},fE=async()=>tt()?(await Y("desktop_restart"),!0):!1,bE=async()=>{if(!tt())return!1;try{return await Y("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},wE=async()=>{if(!tt()||!Se())return null;try{const e=await Y("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}},Nk=async(e,t)=>{if(!tt()||!Se())return!1;const s=e?.trim();if(!s)return!1;try{return await Y("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(a){return console.warn("Failed to open path",a),!1}},kE=async e=>{if(!tt()||!Se())return!1;const t=e?.trim();if(!t)return!1;try{return await Y("desktop_reveal_path",{path:t}),!0}catch{return Nk(t)}},yE=async(e,t)=>{if(!tt()||!Se())return null;const s=e?.trim();if(!s)return null;try{const a=await Y("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof a=="string"&&a.trim().length>0?a:null}catch(a){return console.warn("Failed to save markdown file",a),null}},vE=async(e,t,s)=>{if(!tt()||!Se())return!1;const a=e?.trim(),n=t?.trim(),i=s?.trim();if(!a||!n||!i)return!1;try{return await Y("desktop_open_in_app",{projectPath:a,appId:n,appName:i}),!0}catch(o){return console.warn("Failed to open project in app",o),!1}},CE=async(e,t,s)=>{if(!tt()||!Se())return!1;const a=e?.trim(),n=t?.trim(),i=s?.trim();if(!a||!n||!i)return!1;try{return await Y("desktop_open_file_in_app",{filePath:a,appId:n,appName:i}),!0}catch(o){return console.warn("Failed to open file in app",o),!1}},SE=async(e,t)=>{if(!tt()||!Se())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=Array.isArray(e)?e.filter(a=>typeof a=="string"):[];if(s.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const a=await Y("desktop_get_installed_apps",{apps:s,force:t===!0?!0:void 0});if(!a||typeof a!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=a;return n.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(n.apps)?{apps:n.apps.filter(o=>o&&typeof o=="object").map(o=>{const r=o;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(o=>o.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(a){return console.warn("Failed to fetch installed apps",a),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},xE=()=>navigator.platform.toLowerCase().startsWith("linux"),ma=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",PE=()=>typeof window>"u"||!ma()?!1:km()==="ios"&&Mk(),Mk=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},km=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Oe()?"vscode":Ye()?"desktop":"web"},Ek="2.7.0",Zi=new Uint8Array(0),Lk=typeof DecompressionStream=="function",qk=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")),ym=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,Vk=new TextEncoder,Uk=new TextDecoder,xt=e=>e instanceof Error?e:new Error(String(e)),Ji=()=>new DOMException("The operation was aborted.","AbortError"),Wk=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(ym(s))},close(s,a){e.close(s,a)},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},Hk=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(ym(s))},close(s,a){e.close(s,a)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const a=s.data;(typeof a=="string"||a instanceof ArrayBuffer)&&t.onmessage?.({data:a})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},Gk=e=>e?.state==="error"&&e.closeCode===Ns.LimitExceeded,yp=0,Or=1,vp=2,Cp=3,_k=new Set([Ns.AuthFailed,Ns.DuplicateClient,Ns.LimitExceeded]),Kk={[Ns.AuthFailed]:"relay authentication failed",[Ns.DuplicateClient]:"relay connection replaced by another client",[Ns.LimitExceeded]:"relay connection limit reached"},Dr=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},$l=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,a=e.pingIntervalMs??3e4,n=e.pingTimeoutMs??15e3,i=e.batchWindowMs??tm,o=e.batch!==!1,r=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(N=>Wk(new WebSocket(N)));let u=!1,m=null,f={state:"idle"};const b=new Set;let w=null,y=null,A=null,x=0,M=0,Q=null,he=[],L=!1;const U=N=>{if(!(f.state===N.state&&f.lastError===N.lastError&&f.terminal===N.terminal&&f.closeCode===N.closeCode)){f=N;for(const ce of b)try{ce(f)}catch{}}},Z=N=>{const ce=he;he=[];for(const W of ce)W.reject(N)},ot=N=>{const ce=he;he=[];for(const W of ce)W.resolve(N)},de=(N,ce)=>{N.dead=!0;const W=Array.from(N.streams.values());N.streams.clear();for(const _ of W)try{_.fail(ce)}catch{}},st=()=>{Q!==null&&(clearTimeout(Q),Q=null)},vn=()=>{if(!u){if(Q!==null){if(Dr())return;st(),Ct(),ya();return}Dr()||Vs()}},Vs=()=>{u||m===null||(Ct(),m=null,ya())},G=()=>{typeof document<"u"&&document.visibilityState==="visible"&&vn()},rt=()=>{L||typeof window>"u"||(L=!0,window.addEventListener("online",vn),typeof document<"u"&&document.addEventListener("visibilitychange",G))},Ct=()=>{!L||typeof window>"u"||(L=!1,window.removeEventListener("online",vn),typeof document<"u"&&document.removeEventListener("visibilitychange",G))},Cn=()=>{if(u||Q!==null)return;const N=Math.max(0,M-1),ce=r*2**Math.min(N,10),W=Dr()?l:c,_=Math.min(W,ce);rt(),Q=setTimeout(()=>{Q=null,Ct(),ya()},_)},xr=()=>{const N=new URL(e.relayUrl);return N.searchParams.set("v",String(Hn)),N.searchParams.set("role","client"),N.searchParams.set("serverId",e.serverId),N.searchParams.set("appId","openchamber"),N.searchParams.set("appVersion",Ek),N.searchParams.set("platform",km()),e.grant&&N.searchParams.set("grant",e.grant),N.toString()},ya=async()=>{if(u)return;st(),x+=1;const N=x;U({state:M>0?"reconnecting":"connecting",lastError:f.lastError});let ce;try{ce=await qw(e.hostEncPubJwk,{batch:o,flowControl:e.flowControl})}catch(ge){if(N!==x||u)return;cp(N,xt(ge),!0);return}if(N!==x||u)return;let W;try{W=d(xr())}catch(ge){cp(N,xt(ge));return}y=W;let _=!1,$=null,pe=null,ct=null,Me=null,te=Promise.resolve(),ae=null,Re=null,es=!1,De=!1,Fe=0,Ee=0,Le=null,ts=null,Ce=Date.now();const ws=()=>{Le!==null&&(clearTimeout(Le),Le=null),$!==null&&(clearInterval($),$=null),pe!==null&&(clearTimeout(pe),pe=null),ct!==null&&(clearInterval(ct),ct=null),Me!==null&&(clearTimeout(Me),Me=null),ts!==null&&(ts.dispose(),ts=null)};A=ws;function ue(ge,xe=!1,me=null){if(!(_||N!==x)){_=!0,me!==null&&(m=ge),ws(),ae&&(w=null,de(ae,new Error(`relay tunnel reset: ${ge.message}`))),Z(ge);try{W.close()}catch{}if(y===W&&(y=null),!u){if(M+=1,me!==null){rt(),U({state:"error",lastError:ge.message,terminal:!0,closeCode:me});return}U({state:xe?"error":"reconnecting",lastError:ge.message}),Cn()}}}const Sn=()=>{try{W.send(ce.helloText)}catch{}},Us=(ge,xe,me)=>{Re=ge,es=xe,De=me,$!==null&&(clearInterval($),$=null),pe!==null&&(clearTimeout(pe),pe=null);const lt=new Map,We=Yw(),St=Gw();let Ws=Promise.resolve();const ks=xn=>{Ws=Ws.then(async()=>{if(Hs.dead)return;const gw=await ge.encryptor.encrypt(xn);Hs.dead||W.send(gw)}).catch(()=>{ue(new Error("relay encrypt/send failed"))})},zr=xe?$w({windowMs:i,sendBatch:ks}):null;ts=zr;const Hs={streams:lt,assembler:St,nextStreamId:()=>We.next(),dead:!1,send(xn){Hs.dead||(zr?zr.enqueue(xn):ks(xn))}};ae=Hs,w=Hs,M=0,Ce=Date.now(),U({state:"connected"}),ot(Hs),ct=setInterval(()=>{Date.now()-Ce<a||(Hs.send(zt(se.Ping,0,Zi)),Me===null&&(Me=setTimeout(()=>{Me=null,ue(new Error("relay keepalive timeout"))},n)))},a)},Vi=()=>{Le!==null&&clearTimeout(Le),Le=null,!(!ae||ae.dead||Fe===Ee)&&(Ee=Fe,ae.send(zt(se.DeliveryAck,0,Vw(Fe))))},Tr=(ge,xe)=>{let me;try{me=Uw(xe)}catch(St){ue(xt(St));return}if(me.frameType===se.DeliveryAck){ue(new Error("unexpected downstream delivery acknowledgement"));return}if(De&&me.streamId!==0&&(Fe+=xe.length,Le===null&&(Le=setTimeout(Vi,10))),Ce=Date.now(),Me!==null&&(clearTimeout(Me),Me=null),me.frameType===se.Ping){ge.send(zt(se.Pong,me.streamId,Zi));return}if(me.frameType===se.Pong)return;let lt=me.payload;if(me.frameType===se.WsText||me.frameType===se.WsBinary){let St;try{St=ge.assembler.push(me)}catch(Ws){ue(xt(Ws));return}if(St===null)return;lt=St}else if(me.hasMoreFragments){ue(new Error("unexpected fragmented tunnel frame"));return}const We=ge.streams.get(me.streamId);We&&We.handleFrame(me.frameType,lt)};W.onopen=()=>{_||N!==x||(Sn(),$=setInterval(Sn,t))};const va=ge=>{const xe=_k.has(ge);ue(new Error(Kk[ge]??`relay socket closed (code ${ge})`),xe,xe?ge:null)};W.onmessage=ge=>{if(_||N!==x)return;const xe=ge.data;if(typeof xe=="string"){const lt=vw(xe);if(lt){va(lt.code);return}te=te.then(async()=>{if(_||N!==x)return;const We=await ce.handleText(xe);if(We.type==="established"){if(Re)return;Us(We.channel,We.batch,We.flowControl)}else We.type==="fail"&&ue(new Error(`relay handshake failed: ${We.reason}`))}).catch(We=>{ue(xt(We))});return}const me=xe instanceof ArrayBuffer?new Uint8Array(xe):xe instanceof Uint8Array?xe:null;me&&(te=te.then(async()=>{if(_||N!==x)return;const lt=ae,We=Re;if(!lt||!We){ue(new Error("encrypted frame before handshake completed"));return}let St;try{St=await We.decryptor.decrypt(me)}catch(ks){ue(xt(ks));return}let Ws;try{Ws=es?Kw(St):[St]}catch(ks){ue(xt(ks));return}for(const ks of Ws){if(_||N!==x||lt.dead)return;Tr(lt,ks)}De&&Fe-Ee>=16*1024&&Vi()}).catch(lt=>{ue(xt(lt))}))},W.onclose=ge=>va(ge.code),W.onerror=()=>{},pe=setTimeout(()=>{pe=null,ue(new Error("relay handshake timeout"),!0)},s);function cp(ge,xe,me=!1){ge!==x||u||(Z(xe),M+=1,U({state:me?"error":"reconnecting",lastError:xe.message}),Cn())}},Xt=N=>u?Promise.reject(new Error("relay tunnel closed")):N?.aborted?Promise.reject(Ji()):m?Promise.reject(m):w&&!w.dead?Promise.resolve(w):new Promise((ce,W)=>{let _=null;const $={resolve(pe){_&&N&&N.removeEventListener("abort",_),ce(pe)},reject(pe){_&&N&&N.removeEventListener("abort",_),W(pe)}};N&&(_=()=>{he=he.filter(pe=>pe!==$),W(Ji())},N.addEventListener("abort",_,{once:!0})),he.push($)}),Pr=async(N,ce)=>{const W=await ok(N,ce),_=W.signal;if(_?.aborted)throw Ji();const $=await Xt(_),pe=$.nextStreamId();return await new Promise((ct,Me)=>{let te=!1,ae=!1,Re=null,es=null;const De=()=>{$.streams.delete(pe),$.assembler.dropStream(pe),es&&_&&_.removeEventListener("abort",es)},Fe=Ce=>{if(!ae){if(ae=!0,De(),!te){Me(Ce);return}try{Re?.error(Ce)}catch{}}},Ee=Ce=>{$.dead||$.send(zt(se.StreamAbort,pe,Hi({reason:Ce})))},Le=Ce=>Dc(new Error(Ce));es=()=>{Ee("aborted"),Fe(Ji())},$.streams.set(pe,{handleFrame(Ce,ws){if(Ce===se.HttpResponse){if(te||ae)return;let ue;try{ue=Gi(ws,ek)}catch(va){Ee("malformed response head"),Fe(Le(xt(va).message));return}const Sn=ue.status===204||ue.status===205||ue.status===304;let Us=null;Sn||(Us=new ReadableStream({start(va){Re=va},cancel(){ae||(ae=!0,De(),Ee("response body cancelled"))}})),te=!0;const{[Pw]:Vi,...Tr}=ue.headers;Us&&Vi==="gzip"&&(Us=qk(Us)),ct(new Response(Us,{status:ue.status,headers:Tr})),Sn&&(ae=!0,De());return}if(Ce===se.HttpBody){if(!te||ae)return;try{Re?.enqueue(ws)}catch{}return}if(Ce===se.StreamEnd){if(ae)return;if(!te){Fe(Le("tunnel stream ended before response head"));return}ae=!0,De();try{Re?.close()}catch{}return}if(Ce===se.StreamAbort){let ue="stream aborted by host";try{ue=Gi(ws,gp).reason}catch{}Fe(Le(ue))}},fail(Ce){Fe(Le(Ce.message))}}),_&&_.addEventListener("abort",es,{once:!0});const ts={method:W.method,path:W.path,query:W.query,headers:Lk?{...W.headers,[xw]:"gzip"}:W.headers,hasBody:W.body!==null};$.send(zt(se.HttpRequest,pe,Hi(ts))),(async()=>{try{let Ce=!1;if(W.body)for await(const ws of W.body){if(ae||$.dead)return;for(const ue of em(ws))$.send(zt(se.HttpBody,pe,ue)),Ce=!0}!ae&&!$.dead&&(W.body&&!Ce&&$.send(zt(se.HttpBody,pe,Zi)),$.send(zt(se.StreamEnd,pe,Zi)))}catch(Ce){Ee("request body failed"),Fe(Le(xt(Ce).message))}})()})},lw=N=>{const ce=N.indexOf("?");return ce===-1?{path:N,query:""}:{path:N.slice(0,ce),query:N.slice(ce+1)}},dw=(N,ce)=>{let W=yp,_=null,$=0,pe=!1;const ct={get readyState(){return W},onopen:null,onmessage:null,onerror:null,onclose:null,send(te){if(W!==Or||!_||_.dead)throw new Error("relay tunnel socket is not open");if(typeof te=="string"){for(const Re of pp(se.WsText,$,Vk.encode(te)))_.send(Re);return}const ae=te instanceof ArrayBuffer?new Uint8Array(te.slice(0)):(()=>{const Re=new Uint8Array(te.byteLength);return Re.set(new Uint8Array(te.buffer,te.byteOffset,te.byteLength)),Re})();for(const Re of pp(se.WsBinary,$,ae))_.send(Re)},close(te=1e3,ae=""){W===Cp||W===vp||(W===Or&&_&&!_.dead&&(W=vp,_.send(zt(se.WsClose,$,Hi({code:te,reason:ae})))),Me(te,ae))}},Me=(te,ae,Re=!1)=>{if(!pe){if(pe=!0,_&&(_.streams.delete($),_.assembler.dropStream($)),W=Cp,Re)try{ct.onerror?.()}catch{}try{ct.onclose?.({code:te,reason:ae})}catch{}}};return(async()=>{let te;try{te=await Xt()}catch(De){Me(1006,xt(De).message,!0);return}if(pe)return;_=te,$=te.nextStreamId(),te.streams.set($,{handleFrame(De,Fe){if(De===se.WsOpened){if(W===yp){W=Or;try{ct.onopen?.()}catch{}}return}if(De===se.WsText){try{ct.onmessage?.({data:Uk.decode(Fe)})}catch{}return}if(De===se.WsBinary){const Ee=new ArrayBuffer(Fe.byteLength);new Uint8Array(Ee).set(Fe);try{ct.onmessage?.({data:Ee})}catch{}return}if(De===se.WsClose){let Ee=1e3,Le="";try{const ts=Gi(Fe,tk);Ee=ts.code,Le=ts.reason}catch{}Me(Ee,Le);return}if(De===se.StreamAbort){let Ee="stream aborted";try{Ee=Gi(Fe,gp).reason}catch{}Me(1006,Ee,!0)}},fail(De){Me(1012,De.message,!0)}});const{path:ae,query:Re}=lw(N),es=ce&&ce.length>0?{path:ae,query:Re,protocols:ce}:{path:ae,query:Re};te.send(zt(se.WsOpen,$,Hi(es)))})(),ct},pw=()=>{if(u)return;u=!0,x+=1,st(),Ct(),A?.(),A=null;const N=w;w=null;const ce=new Error("relay tunnel closed");N&&de(N,ce),Z(ce);try{y?.close()}catch{}y=null,U({state:"idle"})};return ya(),{fetch:Pr,openWebSocket:dw,getStatus:()=>f,subscribeStatus(N){return b.add(N),()=>{b.delete(N)}},retry:Vs,close:pw}};let Qt=null,Kt=null;const Uc=new Set;let Fr=null;const Yl=e=>{Fr?.(),Fr=null,Qt=e,e&&(Fr=e.subscribeStatus(t=>{for(const s of Uc)s(t)}))},TE=e=>(Uc.add(e),()=>{Uc.delete(e)}),Zk=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),gn=()=>Qt,zE=()=>!Qt||!Kt?null:{relayUrl:Kt.relayUrl,serverId:Kt.serverId,hostEncPubJwk:{...Kt.hostEncPubJwk}},Jk=()=>Qt!==null,Qk=e=>{if(Qt&&Kt&&Zk(Kt,e))return Qt;Qt?.close(),Kt=e;const t=$l(e);return Yl(t),t},AE=(e,t)=>{if(Qt===t){Kt=e;return}Qt?.close(),Kt=e,Yl(t)},$k=()=>{Qt?.close(),Yl(null),Kt=null};let vm=()=>null,Cm="",No={},Xa="",mi=0,Xs=null,Ua="",hi=0,da="",ea=null,zs="",wo=0,ko=0;const Xl=1e4,Yk=e=>e.toLowerCase()==="authorization",Sm=e=>{const t={};for(const[s,a]of Object.entries(e||{})){const n=s.trim(),i=a.trim();n&&i&&!Yk(n)&&(t[n]=i)}return t},Xk=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?!1:s.every(([a,n])=>t[a]===n)},ar=e=>typeof e!="string"?"":e.trim(),ey=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return ar(e)},ty=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},xm=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():ty();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},ed=e=>{try{return new URL(e).origin}catch{return""}},Pm=()=>{Ua="",hi=0,da="",ea=null,zs="",wo+=1},Ai=()=>{Xa="",mi=0,Pm()},Tm=()=>{ko+=1,Xs=null,Ai(),sd()},zm=e=>{const t=ar(e);Cm=t,Tm(),vm=()=>t?{type:"bearer",token:t}:null},Am=e=>{const t=Sm(e);Xk(No,t)||(No=t,Tm())},un=()=>{if(Object.keys(No).length>0)return No;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Sm(e):{}},td=()=>Cm||ey(),sy=(e,t)=>{const s=ar(e);if(!s||typeof t!="number"||!Number.isFinite(t)){Ai();return}Xa=s,mi=t},Rm=()=>!Xa||mi<=Date.now()+Xl?(Ai(),""):Xa,Im=e=>{const t=ed(e);return!t||da!==t?"":!Ua||hi<=Date.now()+Xl?(Ua="",hi=0,da="",""):Ua},ay=()=>{const e=Rm();return!e&&(td()||typeof window<"u")&&nr().catch(()=>{}),e},ny=e=>{const t=e?Im(e):"";return!t&&e&&typeof window<"u"&&Fm(e).catch(()=>{}),t},jm=async()=>{const e=await vm(),t=e?.type==="bearer"?ar(e.token):td();return t?{type:"bearer",token:t}:null},iy=g({token:p(),expiresAt:v(),expiresIn:v().optional()}),Om=async(e,t)=>{const s=await jm(),a=new Headers;for(const[u,m]of Object.entries(un()))a.set(u,m);s?.type==="bearer"&&a.set("Authorization",`Bearer ${s.token}`);const n=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",i=gn(),o=i?await i.fetch(n,{method:"POST",headers:a}):await fetch(xm(e,n),{method:"POST",headers:a,credentials:"include"});if(!o.ok)throw new Error(`Failed to mint runtime URL auth token (${o.status})`);const r=iy.safeParse(await o.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:c,expiresAt:l,expiresIn:d}=r.data;return{token:c.trim(),expiresAt:d===void 0?l:Date.now()+d}},RE=async e=>{const t=await Om(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Dm=e=>{if(Xs)return Xs;const t=ko,a=(async()=>{let n;try{n=await Om(e)}catch(i){throw t===ko&&Ai(),i}if(t!==ko)throw new Error("Runtime URL auth token response is stale");if(sy(n.token,n.expiresAt),!Xa)throw new Error("Runtime URL auth token response was invalid");return Xa})().finally(()=>{Xs===a&&(Xs=null)});return Xs=a,Xs},oy=e=>{const t=ed(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(ea&&zs===t)return ea;const s=wo,n=(async()=>{const i=await fetch(xm(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!i.ok)throw s===wo&&t===zs&&(Ua="",hi=0,da=""),new Error(`Failed to mint local runtime URL auth token (${i.status})`);const o=await i.json().catch(()=>null),r=typeof o?.token=="string"?o.token.trim():"",c=typeof o?.expiresAt=="number"?o.expiresAt:0;if(!r||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(s!==wo||t!==zs)throw new Error("Local runtime URL auth token response is stale");return Ua=r,hi=c,da=t,r})().finally(()=>{ea===n&&(ea=null,zs="")});return ea=n,zs=t,ea},nr=async e=>{const t=Rm();return t||Dm(e)},Fm=async e=>{const t=ed(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=Im(t);return s||((da&&da!==t||zs&&zs!==t)&&Pm(),oy(t))};let Na=0,_n=null,ry=null;const cy=5e3,Bm=()=>{_n!==null&&(clearTimeout(_n),_n=null)},sd=()=>{if(Bm(),Na<=0||typeof window>"u")return;const e=mi-Xl-cy,t=mi>0?Math.max(0,e-Date.now()):0;_n=setTimeout(()=>{_n=null,!(Na<=0)&&Dm(ry).catch(()=>{}).finally(()=>{sd()})},t)},IE=e=>{Na+=1,sd();let t=!1;return()=>{t||(t=!0,Na=Math.max(0,Na-1),Na===0&&Bm())}},Nm=async e=>{const t=new Headers(e);for(const[a,n]of Object.entries(un()))t.has(a)||t.set(a,n);if(t.has("Authorization"))return t;const s=await jm();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},en=vt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),jE=e=>new Promise(t=>{if(e.aborted||en.getState().state==="ok"){t();return}const s=()=>{a(),e.removeEventListener("abort",s),t()},a=en.subscribe(n=>{n.state==="ok"&&s()});e.addEventListener("abort",s,{once:!0})}),ly=15e3,dy=5*6e4;let Wc=0,Br=!1;const py=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),gy=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!py(t)},Mm=async()=>{if(!Br){Br=!0;try{const{runtimeFetch:e}=await qe(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>Iy);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){en.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:a}=en.getState();s==="expired"&&a()}}catch{}finally{Br=!1}}},uy=(e,t)=>{if(t!==401||en.getState().state==="expired"||!gy(e))return;const s=Date.now();s-Wc<ly||(Wc=s,Mm())};let Sp=!1;const OE=()=>{if(Sp)return;Sp=!0;let e=Date.now();const t=()=>{if(en.getState().state!=="ok")return;const s=Date.now();s-e<dy||(e=s,Wc=s,Mm())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},my=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,yt=e=>{if(!e)return null;const t=my.exec(e);return t?t[1]:null},Hc=e=>yt(e)!==null,hy=()=>um()||pn()?.runtime?.isVSCode===!0,fy=e=>!e||hy()||!Hc(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},Em=e=>`/spaces/${e}`,pa=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",by=()=>typeof window>"u"?"":window.location.origin||"",ad=e=>{if(typeof window>"u")return!1;const t=by();if(t&&e.origin===t)return!0;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return!1}},nd=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),wy=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),as=(e,t)=>{try{wy(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},id=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},ky=e=>{if(!e)return!1;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!0;return!1},yy=(e,t,s)=>{const a=fy(s);if(a===null||ky(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const n=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...n,...Object.entries(a)]}},vy=()=>{const e=ds().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$/,"")}`},Cy=e=>{try{const t=vy();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const a=s.pathname.replace(/\/+$/,"");return a?e.pathname!==a&&!e.pathname.startsWith(`${a}/`)?null:e.pathname.slice(a.length)||"/":e.pathname}catch{return null}},yo=e=>{const t=Cy(e);return t!==null&&pa(t)},Nr=e=>{if(pa(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ad(t)&&pa(t.pathname)}catch{return!1}},Sy=(e,t)=>{try{const s=new URL(e);if(!ad(s))return e;const a=Ms(`${s.pathname}${s.search}`,t);return!nd(a)&&(s.protocol==="http:"||s.protocol==="https:")?(id(s,t),s.toString()):s.hash?`${a}${s.hash}`:a}catch{return e}},Ms=(e,t)=>e==="/health"?ds().health(t):e.startsWith("/auth/")||e==="/auth"?ds().auth(e,t):pa(e)?ds().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Sy(e,t):e,Lm=e=>{const t=e instanceof Request?e.url:e.toString();if(!nd(t))return pa(t);try{return yo(new URL(t))}catch{return!1}},qm=(e,t)=>Object.keys(un()).length>0&&ma()&&Lm(e)?{...t,redirect:"error"}:t,Vm=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},xy=(e,t)=>!Vm(t),Mo=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 a=!1,n=!1;for(const[i,o]of t)xy(i,o)?(s.push([i,encodeURIComponent(o)]),a=!0,i.toLowerCase()==="x-opencode-directory"&&(n=!0)):s.push([i,o]);return n&&s.push(["x-opencode-directory-encoding","uri"]),a?s:void 0},ns=async(e,t,s=!0)=>{const a=new Headers(Mo(e)??e);return t&&new Headers(Mo(t)??t).forEach((n,i)=>a.set(i,n)),s?Nm(a):a},Py=(e,t)=>{if(!t)return e;const s=new URL(e,Kl);return id(s,t),`${s.pathname}${s.search}`},Um=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!nd(s))return pa(s)?Py(s,t):null;try{const a=new URL(s);return!ad(a)||!pa(a.pathname)?null:(id(a,t),`${a.pathname}${a.search}`)}catch{return null}},Ty=async(e,t,s)=>{const a=gn();if(!a)return null;const n=Um(e,s);if(n===null)return null;const i=e instanceof Request?e.headers:void 0,o=await ns(i,t.headers,!0);return e instanceof Request?a.fetch(e,{...t,headers:o}):a.fetch(n,{...t,headers:o})},zy=(e,t)=>{if(typeof e=="string")return Ms(e,t);if(e instanceof URL)return Ms(e.toString(),t);const s=Ms(e.url,t);return s===e.url?e:new Request(s,e)},Ay=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Qi=new Map,Ry=(e,t,s,a)=>s||e!=="GET"||t.includes("/event")||!Ay.test(t)?null:`GET ${t}\0${a.get("x-opencode-directory")??""}`,C=async(e,t={})=>{const{query:s,directory:a,...n}=t,i=e,o=yy(i,n,a),r=gn(),c=r?Um(i,s):null;let l,d,u,m;if(r&&c!==null){const x=i instanceof Request?i.headers:void 0,M=await ns(x,o.headers,!0);l=i instanceof Request?()=>r.fetch(i,{...o,headers:M}):()=>r.fetch(c,{...o,headers:M}),m=M,d=c,u=String(o.method??(i instanceof Request?i.method:"GET")).toUpperCase()}else{const x=zy(i,s),M=x instanceof Request?x.headers:void 0,Q=await ns(M,o.headers,Lm(x)),he=x instanceof Request?x.url:x instanceof URL?x.toString():String(x);as(he,Q);const L=qm(x,{...o,headers:Q});l=x instanceof Request?()=>fetch(new Request(x,L)):()=>fetch(x,L),m=Q,d=he,u=String(o.method??(x instanceof Request?x.method:"GET")).toUpperCase()}const f=l;l=()=>f().then(x=>(uy(d,x.status),x));const b=o.signal!=null||i instanceof Request,w=Ry(u,d,b,m);if(!w)return l();const y=Qi.get(w);if(y)return y.then(x=>x.clone());const A=l();return Qi.set(w,A),A.then(()=>Qi.delete(w),()=>Qi.delete(w)),A.then(x=>x.clone())};let xp=!1,Wm=null;const Hm=(e,t)=>(Wm??globalThis.fetch.bind(globalThis))(e,t),Gm=()=>{if(xp||typeof window>"u")return;xp=!0;const e=window.fetch.bind(window);Wm=e;const t=(s,a)=>e(s,qm(s,a));window.fetch=async(s,a)=>{const n=await Ty(s,a??{});if(n)return n;if(typeof s=="string"){if(!Nr(s)){try{const r=new URL(s);if(yo(r)){const c=await ns(void 0,a?.headers);return as(r.toString(),c),t(s,{...a,headers:c})}}catch{}return t(s,a)}const i=await ns(void 0,a?.headers),o=Ms(s);return as(o,i),t(o,{...a,headers:i})}if(s instanceof URL){const i=s.toString();if(!Nr(i)){if(yo(s)){const c=await ns(void 0,a?.headers);return as(s.toString(),c),t(s,{...a,headers:c})}return t(s,a)}const o=await ns(void 0,a?.headers),r=Ms(i);return as(r,o),t(r,{...a,headers:o})}if(s instanceof Request){if(!Nr(s.url)){try{const c=new URL(s.url);if(yo(c)){const l=await ns(s.headers,a?.headers);return as(c.toString(),l),t(new Request(s,{...a,headers:l}))}}catch{}return t(s,a)}const i=await ns(s.headers,a?.headers),o=Ms(s.url);as(o,i);const r=o===s.url?s:new Request(o,s);return t(new Request(r,{...a,headers:i}))}return t(s,a)}},Iy=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:as,buildRuntimeFetchUrl:Ms,fetchBypassingRuntimeBridge:Hm,installRuntimeFetchBridge:Gm,isLatin1Safe:Vm,runtimeFetch:C,sanitizeHeadersForBrowser:Mo},Symbol.toStringTag,{value:"Module"})),Wa=16384,Eo=globalThis,jy=e=>{if(Eo.Buffer)return Eo.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let a=0;a<t.length;a+=32768)s+=String.fromCharCode(...t.slice(a,a+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},_m=e=>{try{if(Eo.Buffer)return Eo.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),a=new Uint8Array(s.length);for(let n=0;n<s.length;n+=1)a[n]=s.charCodeAt(n);return new TextDecoder().decode(a)}catch{return null}},Oy=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}},Dy=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}},Pp=e=>typeof e=="string"&&e.length>0,Fy=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Pp(t.x)||!Pp(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},By=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ny=e=>{if(!e||typeof e!="object")return null;const t=e,s=By(t.priority);if(t.type==="lan"||t.type==="tunnel"){const a=Oy(t.url);return a?s===void 0?{type:t.type,url:a}:{type:t.type,url:a,priority:s}:null}if(t.type==="relay"){const a=Dy(t.relayUrl);if(!a)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const i=Fy(t.hostEncPubJwk);if(!i)return null;const o=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:a,serverId:n,hostEncPubJwk:i,...o?{grant:o}:{},...s===void 0?{}:{priority:s}}}return null},od=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():"",a=typeof t.secret=="string"?t.secret.trim():"";if(!s||!a)return null;const n=Array.isArray(t.candidates)?t.candidates.map(Ny).filter(c=>!!c):[];if(n.length===0)return null;const i=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(i){const c=Date.parse(i);if(!Number.isFinite(c)||c<=Date.now())return null}const o=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:a,...o?{label:o}:{},...r?{fingerprint:r}:{},...i?{expiresAt:i}:{},candidates:n}},DE=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}),FE=e=>{const t=od(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",jy(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},My=e=>{const t=e.trim();if(!t||t.length>Wa)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const a=s.searchParams.get("p")||"";if(!a||a.length>Wa)return null;const n=_m(a);return!n||n.length>Wa?null:od(JSON.parse(n))}catch{return null}},BE=e=>{const t=e.trim();if(!t||t.length>Wa)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let a=null,n=null;for(const o of t.slice(s+1).split("&")){const r=o.indexOf("=");if(r===-1)continue;const c=o.slice(0,r),l=o.slice(r+1);c==="v"?a=l:c==="p"&&(n=l)}if(a!=="2"||!n||n.length>Wa)return null;const i=_m(n);if(!i||i.length>Wa)return null;try{return od(JSON.parse(i))}catch{return null}},tn=e=>typeof e=="object"&&e!==null,Ey=e=>e.trim().toLowerCase()==="authorization",Ly=e=>{if(!tn(e))return;const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),i=typeof a=="string"?a.trim():"";!n||!i||/[\r\n:]/.test(n)||/[\r\n]/.test(i)||Ey(n)||(t[n]=i)}return Object.keys(t).length>0?t:void 0},qy=e=>`relay://${e}`,Vy=e=>{if(!tn(e))return null;const t=Ke(e,"relayUrl")||Ke(e,"relay_url"),s=Ke(e,"serverId")||Ke(e,"server_id"),a=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!tn(a)?null:{relayUrl:t,serverId:s,hostEncPubJwk:a}},Uy=()=>{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"},Tp=15e3,NE=async(e,t)=>{const s=My(e);if(!s)throw new Error("invalid-connect-link");const a=await Ky().catch(()=>""),n={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:Uy(),...a?{dedupeKey:`desktop:${a}`}:{}})},i=async y=>{if(!y.ok)return null;const A=await y.json().catch(()=>null);return(typeof A?.clientToken=="string"?A.clientToken.trim():"")||null};let o=null;const r=[...s.candidates].sort((y,A)=>(y.type==="relay"?1:0)-(A.type==="relay"?1:0));for(const y of r){if(y.type==="relay"){const x=$l({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const M=await i(await x.fetch("/api/client-auth/pairing/redeem",{...n,signal:AbortSignal.timeout(Tp)}));if(M){o={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:M};break}}catch{}finally{x.close()}continue}const A=Ue(y.url);if(A)try{const x=await i(await fetch(`${A}/api/client-auth/pairing/redeem`,{...n,signal:AbortSignal.timeout(Tp)}));if(x){o={directUrl:A,token:x};break}}catch{}}if(!o)throw new Error("pairing-redeem-failed");const c=s.candidates.find(y=>y.type==="relay"),l=o.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),d=s.candidates.filter(y=>y.type!=="relay").map(y=>Ue(y.url)).find(y=>!!y),u=o.directUrl||d,m=u||(l?qy(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");const f=t.find(y=>l?y.relay?.serverId===l.serverId:!y.relay&&Ue(y.apiUrl||y.url)===m),b=f?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),w={...f||{},id:b,label:s.label||f?.label||Km(m),url:m,apiUrl:u,clientToken:o.token,...l?{relay:l}:{}};return{hostId:b,hosts:f?t.map(y=>y.id===b?w:y):[w,...t]}},Wy=/^(t|.*(?:token|auth|secret|api).*)$/i,Ue=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}},ME=e=>{const t=Ue(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"}},Km=e=>{const t=Ue(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const a=Array.from(new Set(Array.from(s.searchParams.keys())));for(const n of a)Wy.test(n)&&s.searchParams.set(n,"[REDACTED]");return s.toString()}catch{return t}},$i=(e,t)=>{const s=Ue(e),a=Ue(t);if(!s||!a)return!1;try{const n=new URL(s),i=new URL(a);if(n.origin!==i.origin||i.search&&n.search!==i.search)return!1;const o=i.pathname.length>1?i.pathname.replace(/\/+$/,""):i.pathname,r=n.pathname.length>1?n.pathname.replace(/\/+$/,""):n.pathname;return o==="/"?!0:r===o||r.startsWith(`${o}/`)}catch{return!1}},Ke=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},zp=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},Hy=e=>{if(!tn(e))return null;const t=Ke(e,"id"),s=Ke(e,"label"),a=Ke(e,"url"),n=Ke(e,"apiUrl")||Ke(e,"api_url"),i=Ke(e,"clientToken")||Ke(e,"client_token"),o=Ly(e.requestHeaders),r=Vy(e.relay);if(!t||!s||!a)return null;const c={id:t,label:s,url:a,...n?{apiUrl:n}:{},...i?{clientToken:i}:{},...o?{requestHeaders:o}:{},...r?{relay:r}:{}};return e.sshForwarded===!0&&(c.sshForwarded=!0),c},Ha=e=>Ue(e.apiUrl||e.url)||e.apiUrl||e.url,bs=()=>tt()?(e,t)=>Y(e,t):null,fi=async()=>{const e=bs();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!tn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const s=t.hosts,a=Array.isArray(s)?s.map(Hy).filter(r=>!!r):[],n=Ke(t,"defaultHostId")||Ke(t,"default_host_id")||Ke(t,"defaultHostID"),i=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,o=Ke(t,"localOrigin")||Ke(t,"local_origin");return{hosts:a,defaultHostId:n,initialHostChoiceCompleted:i,localOrigin:o}},Gy=async e=>{const t=bs();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})},_y=async()=>{const e=bs();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},EE=async()=>{const e=bs();return e?await e("desktop_switch_to_local").catch(()=>!1)===!0:!1},Ky=async()=>{const e=bs();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Zy=8e3,Jy=15e3,Qy=400,$y=async(e,t,s,a)=>{const n=new AbortController,i=window.setTimeout(()=>n.abort(),s);try{return await e.fetch(t,{...a,signal:n.signal})}finally{window.clearTimeout(i)}},Ap=async(e,t,s,a)=>{for(;;){const n=s-Date.now();if(n<=0)throw new Error("relay probe deadline exceeded");try{return await $y(e,t,Math.min(Zy,n),a)}catch(i){if(e.getStatus().state==="error"||Date.now()>=s)throw i;await new Promise(o=>window.setTimeout(o,Qy))}}},Yy=async(e,t)=>{const s=$l({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),a=Date.now(),n=a+Jy;let i=!1;try{if(!(await Ap(s,"/health",n)).ok)return{status:"unreachable",latencyMs:0};const r=new Headers({Accept:"application/json"});for(const[d,u]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&r.set(d,u);const c=t?.clientToken?.trim();c&&r.set("Authorization",`Bearer ${c}`);const l=await Ap(s,"/auth/session",n,{headers:r});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-a)}:l.ok?(i=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-a),...i?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:Gk(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{i||s.close()}},ir=async(e,t)=>{const s=bs();if(!s)return{status:"unreachable",latencyMs:0};const a=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!tn(a))return{status:"unreachable",latencyMs:0};const n=a.status,i=n==="ok"||n==="auth"||n==="update-recommended"||n==="incompatible"||n==="wrong-service"||n==="unreachable"?n:"unreachable",o=zp(a,"latencyMs")??zp(a,"latency_ms")??0;return{status:i,latencyMs:o}},Xy=ve("status",[g({status:k("started")}),g({status:k("auth")}),g({status:k("failed"),error:p().nullable()})]),LE=async e=>{const t=bs();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),a=Xy.safeParse(s);return a.success?a.data:{status:"failed",error:null}},ev=600*1e3,tv=3e3,qE=async(e,{maxWaitMs:t=ev,intervalMs:s=tv,readHosts:a=fi,probe:n=ir}={})=>{const i=Date.now()+t;for(;Date.now()<i;){await new Promise(c=>setTimeout(c,Math.min(s,Math.max(0,i-Date.now()))));const o=(await a()).hosts.find(c=>c.id===e);if(!o)return"timeout";const r=await n(Ha(o),{clientToken:o.clientToken,requestHeaders:o.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},VE=async(e,t)=>{const s=bs();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},UE=async e=>{const t=bs();t&&await t("desktop_new_window_for_host",{hostId:e})},Bs="local",sv=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",av=(e,t)=>t?[{id:Bs,label:"Local",url:t},...e]:e,nv=e=>e.id===Bs?"local":`host:${e.id}`,WE=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(m=>m.id===Bs)?.url||sv(),a=us(),n=Ue(s)||s,i=Ue(t)||t,o=D(),r=e.find(m=>m.relay&&nv(m)===o);if(r)return{id:r.id,label:r.label,url:r.url};if(a&&$i(a,s))return{id:Bs,label:"Local",url:n};const c=e.find(m=>a?$i(a,Ha(m)):!1);if(c)return{id:c.id,label:c.label,url:Ue(Ha(c))||Ha(c)};if(t&&$i(t,s))return{id:Bs,label:"Local",url:n};const l=e.find(m=>t?$i(t,m.url):!1);if(l)return{id:l.id,label:l.label,url:Ue(l.url)||l.url};const d=t.startsWith("openchamber-ui://");if(d&&s&&!a)return{id:Bs,label:"Local",url:n};const u=a?Ue(a)||a:d?"":i;return{id:"custom",label:Km(u||"Instance"),url:u}},Lo=new Map;let Zm=0;const Kn=new Map,Ga=new Set;let Gc=0,Jm={byHostId:{},isProbing:!1};const _c=new Set,qo=()=>{Jm={byHostId:Object.fromEntries(Lo),isProbing:Gc>0};for(const e of _c)try{e()}catch{}},HE=e=>(_c.add(e),()=>{_c.delete(e)}),GE=()=>Jm,Qm=(e,t)=>{Lo.set(e,t),qo()},_E=(e,t)=>{Kn.set(e,++Zm),Ga.delete(e),Qm(e,t)},KE=e=>Ga.has(e),iv=e=>{const t=new Set([Bs,...e]);let s=!1;for(const a of Array.from(Lo.keys()))t.has(a)||(Lo.delete(a),Kn.delete(a),Ga.delete(a),s=!0);s&&qo()},ov=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",rv=async()=>ua()?_y().catch(()=>""):"",cv=async(e,t)=>{const s=e.id===Bs?t:e.clientToken||"",a=async()=>{const o=await Yy(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:o.status,latencyMs:o.latencyMs};return o.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return a();const n=Ue(ua()?Ha(e):e.url);if(!n)return{status:"unreachable",latencyMs:0};const i=await ir(n,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(ov(i.status)&&e.relay){const o=await a();if(o.status==="ok"||o.status==="relay-limit")return o}return{status:i.status,latencyMs:i.latencyMs}},lv=async e=>{if(!Ye())return;const t=++Zm;for(const s of e)Kn.set(s.id,t),Ga.add(s.id);Gc+=1,qo();try{const s=await rv();await Promise.all(e.map(async a=>{const n=await cv(a,s);Kn.get(a.id)===t&&(Ga.delete(a.id),Qm(a.id,n))}))}finally{for(const s of e)Kn.get(s.id)===t&&Ga.delete(s.id);Gc-=1,qo()}};let Rp=!1;const dv=async()=>{if(Rp||!Ye())return;Rp=!0;const e=await fi().catch(()=>null);e&&(iv(e.hosts.map(t=>t.id)),await lv(av(e.hosts,e.localOrigin)))},pv=5e3,gv=1500;let Mr=!1;const Er=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}},uv=async e=>{if(!ua()||Mr)return;const t=`host:${e}`;if(D()===t){Mr=!0;try{const s=await fi().catch(()=>null),a=s?.hosts.find(b=>b.id===e);if(!s||!a?.relay)return;const n=a.apiUrl?Ue(a.apiUrl):null;if(n&&n.startsWith("https://"))return;const i=await C("/api/client-auth/connection/candidates").catch(()=>null);if(!i?.ok)return;const o=await i.json().catch(()=>null);if(!o||o.serverId!==a.relay.serverId)return;const r=Array.isArray(o.candidates)?o.candidates:[],c=[];for(const b of r){if(!b||typeof b!="object")continue;const w=b;if(w.type!=="lan"||typeof w.url!="string")continue;const y=Ue(w.url);y&&!c.includes(y)&&c.push(y)}if(c.length===0)return;const l=n&&c.includes(n)?n:c[0],d=Er(l);d&&d!==Er(n)&&await Gy({hosts:s.hosts.map(b=>b.id===e?{...b,apiUrl:l}:b),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const m=(await fi().catch(()=>null))?.hosts.find(b=>b.id===e)??null;if(!m||!d||Er(m.apiUrl)!==d)return;const f=await ir(l,{clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,expectedServerId:a.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(f.status==="unreachable"||f.status==="wrong-service"||f.status==="incompatible"||D()!==t)return;qc({apiBaseUrl:l,clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,runtimeKey:t})}finally{Mr=!1}}},mv=e=>{typeof window>"u"||window.setTimeout(()=>{uv(e).catch(()=>{})},pv)},Ip=async(e,t)=>{if(!ua())return;const s=await fi().catch(()=>null);if(!s)return;const a=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!a)return;const n=s.hosts.find(m=>m.id===a);if(!n?.relay)return;const i=`host:${n.id}`;if(D()===i&&!t?.reconnectActive)return;const o=m=>{qc({apiBaseUrl:m,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:i})},r=()=>{qc({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:n.clientToken||null,runtimeKey:i,relay:n.relay??void 0}),mv(n.id)},c=n.apiUrl?Ue(Ha(n)):null;if(!c){r();return}const l=m=>m.status!=="unreachable"&&m.status!=="wrong-service"&&m.status!=="incompatible",d=ir(c,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),u=await Promise.race([d,new Promise(m=>setTimeout(()=>m(null),gv))]);if(u){if(l(u)){o(c);return}r();return}r(),d.then(m=>{l(m)&&D()===i&&o(c)})};class jp 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 hv=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class jt 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 fv=e=>e instanceof jt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),Zn=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"}},bv=g({message:p()}),ZE=e=>{if(fv(e)&&e.reason==="not-found")return!0;const t=bv.safeParse(e),a=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return a.includes("file not found")||a.includes("enoent")||a.includes("no such file")||a.includes("does not exist")},Gs=new Map;let Lr;async function Op(e){const t=ds().api("/api").replace(/\/api\/?$/,""),s=gn(),a=await Nm();if(D()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(i,o)=>{const r=i instanceof Request?i.url:String(i),c=r.startsWith("/")?`${t}${r}`:r,l=new Headers(i instanceof Request?i.headers:void 0);return new Headers(Mo(o?.headers)??o?.headers).forEach((d,u)=>l.set(u,d)),a.forEach((d,u)=>l.set(u,d)),s?s.fetch(i,{...o,headers:l}):(as(c,l),Hm(i instanceof Request?new Request(c,i):c,{...o,headers:l}))},baseUrl:t}}async function $m(e){const t=!!us()&&!gn(),s=await Op(e);return async a=>{let n=!1;const i=async()=>{if(!n){n=!0;try{const r=D()===e;if(!t&&!r)return;await a(r?await Op(e):s),Gs.get(e)?.delete(i),Gs.get(e)?.size===0&&Gs.delete(e),Gs.size===0&&(Lr?.(),Lr=void 0)}catch{}finally{n=!1}}},o=Gs.get(e)??new Set;o.add(i),Gs.set(e,o),Lr??=tr(({runtimeKey:r})=>{for(const c of Gs.get(r)??[])c()}),await i()}}const Vo=()=>({active:0,waiters:[],activeSessionWaiters:[]});let As=Vo(),oa=Vo();const wv=3,Dp=2;er(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[As,oa];As=Vo(),oa=Vo();for(const a of s){for(const n of[...a.activeSessionWaiters,...a.waiters])n(!1);a.activeSessionWaiters.length=0,a.waiters.length=0}});const Fp=()=>{for(;As.active+oa.active<wv;){const e=oa.active<Dp&&oa.waiters.length>0?oa:As.active<Dp&&(As.activeSessionWaiters.length>0||As.waiters.length>0)?As:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(!0)}};async function Ym(e,t,s){const a=gm();if(await new Promise(i=>{s==="active-session"?e.activeSessionWaiters.push(i):e.waiters.push(i),Fp()}))try{if(!a())return;const i=await t();return a()?i:void 0}finally{e.active-=1,Fp()}}const kv=(e,t="normal")=>Ym(As,e,t),JE=e=>Ym(oa,e,"normal"),Xm="/api/opencode/trust",yv="opencode_trust_required",vv=g({kind:I(["plugin","package","mcp","lsp","formatter","shell","config"]),source:p(),name:p(),detail:p()}),Cv=g({directory:p(),trusted:T(),fingerprint:p().nullable(),items:z(vv)}),Sv=g({code:k(yv),directory:p()});let ca=null;const Kc=new Set,Nn=new Map,bi=new Set;let Zc=Promise.resolve(),Rs=0;const qr=()=>{for(const e of Kc)e()},QE=()=>ca,$E=e=>(Kc.add(e),()=>{Kc.delete(e)}),YE=e=>ca?ca.settle(e):Promise.resolve("skipped");er(()=>{Rs+=1,ca?.settle("skip"),Nn.clear(),bi.clear(),Zc=Promise.resolve()});const xv=()=>{bi.clear()},Pv=async e=>{if(e.status!==403)return null;try{const t=Sv.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},eh=async e=>Cv.parse(await e.json()),Vr=async e=>{const t=await C(Xm,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return eh(t)},Tv=async e=>{const t=await C(Xm,{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 eh(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},zv=(e,t)=>new Promise(s=>{const a=n=>{if(t!==Rs){s(!1);return}ca={directory:n.directory,items:n.items,settle:async i=>{if(i==="skip")return bi.add(`${n.directory}
|
|
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/zh-CN-Db0Y0Ij-.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-zustand-C9tWdk0j.js","assets/vendor-zod--raI7LhK.js","assets/vendor-opencode-client-CeybcDBQ.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/vendor-streamdown-BbSYZ3NF.js","assets/vendor-markdown-BTUqNk6W.js","assets/vendor-mdast-util-from-markdown-CZHjOE75.js","assets/vendor-micromark-util-decode-numeric-character-reference-CNs1qBpV.js","assets/vendor-micromark-util-decode-string-fHsnqYdj.js","assets/vendor-decode-named-character-reference-C3-224fz.js","assets/vendor-micromark-util-normalize-identifier-C9ANKk3v.js","assets/vendor-micromark-AWM-NZXP.js","assets/vendor-micromark-util-combine-extensions-d8XJZrgA.js","assets/vendor-micromark-util-chunked-DrRIdSP-.js","assets/vendor-micromark-factory-space-PzSHLgmq.js","assets/vendor-micromark-util-character-CW3Cu1MS.js","assets/vendor-micromark-core-commonmark-kzTLNXAm.js","assets/vendor-micromark-util-classify-character-tcLuZZwM.js","assets/vendor-micromark-util-resolve-all-PQCKh0dx.js","assets/vendor-micromark-util-subtokenize-BF1Jf29a.js","assets/vendor-micromark-factory-destination-Sj0xfi0V.js","assets/vendor-micromark-factory-label-amyP0HdC.js","assets/vendor-micromark-factory-title-khnLkZK6.js","assets/vendor-micromark-factory-whitespace-eIB00uTl.js","assets/vendor-micromark-util-html-tag-name-DbKNfynz.js","assets/vendor-unist-util-stringify-position-Ch_qCilz.js","assets/vendor-mdast-util-to-string-C_aolqmU.js","assets/vendor-unist-util-visit-DhPeCsfG.js","assets/vendor-unist-util-visit-parents-DlviEg7Z.js","assets/vendor-unist-util-is-BPZGFiMU.js","assets/vendor-hast-util-raw-DvvLJg15.js","assets/vendor-ungap-structured-clone--gfxRhYI.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-parse5-DwmzEj2o.js","assets/vendor-entities-wUUgTZDW.js","assets/vendor-web-namespaces-bsVAaBS1.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-unist-util-position-60F3QETU.js","assets/vendor-hast-util-from-parse5-Ba3T6RJI.js","assets/vendor-devlop-0Dp3JUBc.js","assets/vendor-property-information-Boo8Xpef.js","assets/vendor-hastscript-BrPNioaz.js","assets/vendor-comma-separated-tokens-CRUGqg4f.js","assets/vendor-space-separated-tokens-D7QSIrTI.js","assets/vendor-hast-util-parse-selector-TXfch5wI.js","assets/vendor-vfile-location-LfEFwJ2h.js","assets/vendor-hast-util-to-parse5-BoysVIPW.js","assets/vendor-hast-util-sanitize-2aGO5ay8.js","assets/vendor-micromark-extension-gfm-CsfPlnlB.js","assets/vendor-micromark-extension-gfm-autolink-literal-BYug7onl.js","assets/vendor-micromark-extension-gfm-footnote-OFl1FCH2.js","assets/vendor-micromark-extension-gfm-strikethrough-CyFiuwBf.js","assets/vendor-micromark-extension-gfm-table-dgw4LfUw.js","assets/vendor-micromark-extension-gfm-task-list-item-Dnadzr9U.js","assets/vendor-mdast-util-gfm-CroMDYLM.js","assets/vendor-mdast-util-gfm-autolink-literal-CTruMtvI.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-mdast-util-find-and-replace-DB9iC-bx.js","assets/vendor-escape-string-regexp-BaJN9MlJ.js","assets/vendor-mdast-util-gfm-footnote-C-csI7OF.js","assets/vendor-mdast-util-gfm-strikethrough-BcskTdio.js","assets/vendor-mdast-util-gfm-table-DhPwQIyj.js","assets/vendor-markdown-table-DvhhVmnL.js","assets/vendor-mdast-util-to-markdown-Cl3qaiyc.js","assets/vendor-longest-streak-CtXnX3Xp.js","assets/vendor-mdast-util-phrasing-4oVbNLC3.js","assets/vendor-mdast-util-gfm-task-list-item-DMU5mK_M.js","assets/vendor-mdast-util-to-hast-CWnLaQSO.js","assets/vendor-micromark-util-sanitize-uri-BbwQ7CLk.js","assets/vendor-trim-lines-D8znQY54.js","assets/vendor-micromark-extension-cjk-friendly-BzZDGrF5.js","assets/vendor-micromark-extension-cjk-friendly-util-D5lVNoxW.js","assets/vendor-get-east-asian-width-CPhS2cOv.js","assets/vendor-micromark-util-symbol-JJPacVTp.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-BZ3pe_qd.js","assets/vendor-micromark-extension-cjk-friendly-gfm-strikethrough-CqW-Ep4M.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-BdPDQFO7.js","assets/vendor-hast-util-from-html-isomorphic-B0Kn01s9.js","assets/vendor-hast-util-from-dom-DeNf9aYW.js","assets/vendor-katex-DBqql0K7.js","assets/vendor-hast-util-to-text-0GXLnBvt.js","assets/vendor-hast-util-is-element-CuOmiqQi.js","assets/vendor-unist-util-find-after-CMaZmLxc.js","assets/vendor-micromark-extension-math-BRFoDziv.js","assets/vendor-mdast-util-math-wB-IJCL0.js","assets/vendor-remend-r8cP_t-e.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-marked-DN3zOnEe.js","assets/vendor-hast-util-to-jsx-runtime-Bq6JeJCx.js","assets/vendor-style-to-js-CI2G4dgu.js","assets/vendor-style-to-object-BAv4SQXc.js","assets/vendor-inline-style-parser-BlqBsVO4.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-estree-util-is-identifier-name-BgBfM8ME.js","assets/vendor-vfile-message-DqhD22jI.js","assets/vendor-unified-1CQKw2_w.js","assets/vendor-bail-FqpXQuLt.js","assets/vendor-extend-B94qxKr5.js","assets/vendor-is-plain-obj-C1gvLhAf.js","assets/vendor-trough-B_b8ryxu.js","assets/vendor-vfile-BCWrK60u.js","assets/vendor-html-url-attributes-D46m5wfe.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/fr-CeExWqT9.js","assets/nl-CavtTtNf.js","assets/zh-TW-CuzqmROB.js","assets/es-BFk4dosu.js","assets/pt-BR-iqkU-MRA.js","assets/uk-Bm__l5YX.js","assets/ko-CGv47dWq.js","assets/pl-BQZVI44N.js","assets/de-BdVTH897.js","assets/ja-BlUqUBMY.js","assets/tr-CYfLfxAg.js","assets/ar-CT3AuXVj.js","assets/he-C_O5IfNH.js","assets/vendor-capacitor-app-BrDJj9I_.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as qe}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as vt,d as dn,p as zi,a as uw}from"./vendor-zustand-C9tWdk0j.js";import{o as g,s as p,n as v,l as k,e as T,c as z,h as ve,_ as I,u as J,a as kt,j as ci,f as ee,i as mw,k as jo,p as li,q as Wu,v as Ui}from"./vendor-zod--raI7LhK.js";import{e as Hu,C as lp}from"./vendor-opencode-client-CeybcDBQ.js";import{f as Mt,R as Qa,r as hw}from"./vendor-react--VO_rL_p.js";import{F as Gu}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as fw}from"./vendor-streamdown-BbSYZ3NF.js";import{u as bw}from"./vendor-unified-1CQKw2_w.js";import{c as ww}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as kw}from"./vendor-capacitor-core-B4EWRrHz.js";const Hn=1,yw=g({type:k("relay-retire"),code:v().int(),reason:p().catch("")}),vw=e=>{try{const t=yw.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},Cw="openchamber-relay-v1",_u=1,Ku=12,Gn=1+Ku,di=64*1024,pi=5,Oo=128,Zu=0,Ju=1,$a=4,Sw=1+$a,jc=di-pi-Sw,xw="x-openchamber-tunnel-accept-encoding",Pw="x-openchamber-tunnel-content-encoding",se={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},Tw=new Set(Object.values(se)),zw=e=>Tw.has(e),Ns={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},cs=globalThis.crypto.subtle,Qu={name:"ECDH",namedCurve:"P-256"},$u=16,Ar=32,Aw=16,Oc=4,Yu=8;class Fs extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Rw=()=>cs.generateKey(Qu,!0,["deriveBits"]),Iw=async e=>{const t=await cs.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},jw=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 cs.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Qu,!0,[])}catch{throw new Fs("invalid ECDH public key JWK")}},Ow=()=>{const e=new Uint8Array($u);return globalThis.crypto.getRandomValues(e),e},Dw=async(e,t,s)=>{if(s.length!==$u)throw new Fs("invalid handshake nonce length");const a=await cs.deriveBits({name:"ECDH",public:t},e,256),n=await cs.importKey("raw",a,"HKDF",!1,["deriveBits"]),i=new Uint8Array(await cs.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(Cw)},n,Ar*2*8)),o=(r,c)=>cs.importKey("raw",r,{name:"AES-GCM"},!1,c);return{clientToHost:await o(i.slice(0,Ar),["encrypt","decrypt"]),hostToClient:await o(i.slice(Ar),["encrypt","decrypt"])}},Fw=(e,t,s)=>{for(let a=Yu-1;a>=0;a-=1)e[t+a]=Number(s&0xffn),s>>=8n},Bw=(e,t)=>{let s=0n;for(let a=0;a<Yu;a+=1)s=s<<8n|BigInt(e[t+a]);return s},Nw=e=>{const t=new Uint8Array(Oc);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(a){if(a.length>di)throw new Fs("plaintext frame exceeds maximum size");s+=1n;const n=new Uint8Array(Ku);n.set(t,0),Fw(n,Oc,s);const i=new Uint8Array(await cs.encrypt({name:"AES-GCM",iv:n},e,a)),o=new Uint8Array(Gn+i.length);return o[0]=_u,o.set(n,1),o.set(i,Gn),o}}},Mw=e=>{let t=0n;return{async decrypt(s){if(s.length<Gn+Aw)throw new Fs("encrypted frame too short");if(s[0]!==_u)throw new Fs("unsupported encrypted frame version");const a=s.slice(1,Gn),n=Bw(a,Oc);if(n<=t)throw new Fs("frame counter regression");let i;try{i=await cs.decrypt({name:"AES-GCM",iv:a},e,s.slice(Gn))}catch{throw new Fs("frame decryption failed")}return t=n,new Uint8Array(i)}}},Wi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ew=e=>{let t="";for(let s=0;s<e.length;s+=3){const a=e[s],n=s+1<e.length?e[s+1]:void 0,i=s+2<e.length?e[s+2]:void 0;t+=Wi[a>>2],t+=Wi[(a&3)<<4|(n??0)>>4],n!==void 0&&(t+=Wi[(n&15)<<2|(i??0)>>6]),i!==void 0&&(t+=Wi[i&63])}return t},dp=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!==Hn)return null;const a=s.batch===!0,n=s.flowControl===!0;return s.t==="ready"?{t:"ready",v:Hn,batch:a,flowControl:n}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:Hn,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:a,flowControl:n}:null},Lw=e=>({type:"fail",closeCode:Ns.ChannelFailure,reason:e}),qw=async(e,t={})=>{const s=t.batch!==!1,a=await jw(e),n=await Rw(),i=Ow(),o={t:"hello",v:Hn,clientPubJwk:await Iw(n.publicKey),nonce:Ew(i)};s&&(o.batch=!0),t.flowControl!==!1&&(o.flowControl=!0);let r=!1;return{helloText:JSON.stringify(o),get established(){return r},async handleText(c){if(r)return dp(c)?.t==="ready"?{type:"ignore"}:Lw("plaintext frame on established channel");const l=dp(c);if(l?.t!=="ready")return{type:"ignore"};const d=await Dw(n.privateKey,a,i);return r=!0,{type:"established",batch:s&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:Nw(d.clientToHost),decryptor:Mw(d.hostToClient)}}}}},Xu=4294967295,Vw=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 Ve extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const zt=(e,t,s,a=!1)=>{if(!Number.isInteger(t)||t<0||t>Xu)throw new Ve("invalid stream id");if(s.length>jc)throw new Ve("tunnel payload exceeds maximum size");const n=new Uint8Array(pi+s.length);return n[0]=a?e|Oo:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(s,pi),n},Uw=e=>{if(e.length<pi)throw new Ve("tunnel frame too short");const t=e[0],s=(t&Oo)!==0,a=t&~Oo;if(!zw(a))throw new Ve(`unknown tunnel frame type ${a}`);const n=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:a,streamId:n,payload:e.slice(pi),hasMoreFragments:s}},Ww=new TextEncoder,Hw=new TextDecoder,Hi=e=>Ww.encode(JSON.stringify(e)),Gi=(e,t)=>{let s;try{s=JSON.parse(Hw.decode(e))}catch{throw new Ve("malformed JSON tunnel payload")}if(!t(s))throw new Ve("unexpected JSON tunnel payload shape");return s},em=(e,t=jc)=>{if(t<=0||t>jc)throw new Ve("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let a=0;a<e.length;a+=t)s.push(e.slice(a,a+t));return s},pp=(e,t,s)=>{const a=em(s);return a.map((n,i)=>zt(e,t,n,i<a.length-1))},Gw=(e=16*1024*1024)=>{const t=new Map;return{push(s){const a=`${s.streamId}:${s.frameType}`,n=t.get(a);if(!s.hasMoreFragments&&!n)return s.payload;const i=n?.chunks??[],o=(n?.totalBytes??0)+s.payload.length;if(o>e)throw t.delete(a),new Ve("fragmented message exceeds maximum size");if(i.push(s.payload),s.hasMoreFragments)return t.set(a,{chunks:i,totalBytes:o}),null;t.delete(a);const r=new Uint8Array(o);let c=0;for(const l of i)r.set(l,c),c+=l.length;return r},dropStream(s){for(const a of t.keys())a.startsWith(`${s}:`)&&t.delete(a)}}},_w=e=>{if(e.length===0)throw new Ve("cannot encode an empty frame batch");if(e.length===1){const n=e[0],i=new Uint8Array(1+n.length);if(i[0]=Zu,i.set(n,1),i.length>di)throw new Ve("frame batch exceeds maximum plaintext size");return i}let t=1;for(const n of e)t+=$a+n.length;if(t>di)throw new Ve("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=Ju;let a=1;for(const n of e)s[a]=n.length>>>24&255,s[a+1]=n.length>>>16&255,s[a+2]=n.length>>>8&255,s[a+3]=n.length&255,a+=$a,s.set(n,a),a+=n.length;return s},Kw=e=>{if(e.length<1)throw new Ve("empty batch plaintext");const t=e[0];if(t===Zu)return[e.slice(1)];if(t!==Ju)throw new Ve(`unknown batch container tag ${t}`);const s=[];let a=1;for(;a<e.length;){if(a+$a>e.length)throw new Ve("truncated batch frame length");const n=(e[a]<<24|e[a+1]<<16|e[a+2]<<8|e[a+3])>>>0;if(a+=$a,a+n>e.length)throw new Ve("truncated batch frame body");s.push(e.slice(a,a+n)),a+=n}if(s.length===0)throw new Ve("empty frame batch");return s},Zw=new Set([se.HttpBody,se.WsText,se.WsBinary]),tm=150,Jw=24*1024,Qw=32,$w=e=>{const t=e.windowMs??tm,s=e.maxBatchBytes??Jw,a=e.maxBatchFrames??Qw,n=e.now??(()=>Date.now()),i=e.setTimer??((w,y)=>setTimeout(w,y)),o=e.clearTimer??(w=>clearTimeout(w));let r=[],c=0,l=null,d=0,u=!1;const m=()=>{l!==null&&(o(l),l=null)},f=()=>{if(m(),r.length===0)return;const w=r;r=[],c=0,d=n(),e.sendBatch(_w(w))};return{enqueue:w=>{if(u)return;const y=w[0]&~Oo;if(!Zw.has(y)){r.push(w),f();return}const A=n();if(r.length===0&&A-d>=t){r.push(w),f();return}const x=$a+w.length;if(r.length>0&&1+c+x>di&&f(),r.push(w),c+=x,c>=s||r.length>=a){f();return}l===null&&(l=i(f,t))},flush:f,dispose(){u=!0,m(),r=[],c=0}}},Yw=()=>{let e=1;return{next(){if(e>Xu)throw new Ve("stream id space exhausted");const t=e;return e+=2,t}}},Xo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xw=e=>Xo(e)&&Object.values(e).every(t=>typeof t=="string"),ek=e=>Xo(e)&&typeof e.status=="number"&&Xw(e.headers),gp=e=>Xo(e)&&typeof e.reason=="string",tk=e=>Xo(e)&&typeof e.code=="number"&&typeof e.reason=="string",sm=/^[a-z][a-z\d+.-]*:\/\//i,Kl="http://tunnel.invalid",sk=e=>{try{const t=sm.test(e)?new URL(e):new URL(e,Kl);return`${t.pathname}${t.search}`}catch{return e}},_i=e=>({async*[Symbol.asyncIterator](){yield e}}),ak=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:a}=await t.read();if(s)return;a&&(yield a)}}finally{t.releaseLock()}}}),nk=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},ik=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:ak(e)};if(typeof e=="string")return{body:_i(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:_i(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:_i(nk(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,a=new Uint8Array(await t.arrayBuffer());return{body:_i(a),contentType:s}},ok=async(e,t)=>{let s;const a=new Headers;let n="GET",i=null,o;e instanceof Request?(s=e.url,n=e.method,e.headers.forEach((u,m)=>a.set(m,u)),o=e.signal,i=e.body):s=e.toString(),t&&(t.method&&(n=t.method),t.headers&&new Headers(t.headers).forEach((u,m)=>a.set(m,u)),t.body!==void 0&&(i=t.body),t.signal&&(o=t.signal));const r=sm.test(s)?new URL(s):new URL(s,Kl),{body:c,contentType:l}=await ik(i);l&&!a.has("content-type")&&a.set("content-type",l);const d={};return a.forEach((u,m)=>{d[m]=u}),{method:n.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:d,body:c,signal:o}},am="__openchamberAmbiguousTransport",nm=new WeakSet,rk=e=>(nm.add(e),e),ck=e=>nm.has(e),Dc=e=>(Object.defineProperty(e,am,{value:!0,enumerable:!1,configurable:!0}),e),lk=e=>!e||typeof e!="object"?!1:e[am]===!0,dk=["local","remote",null],pk=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function im(e){if(!e||typeof e!="object")return{valid:!1};const t=e,s=t.localAvailable===!1?{localAvailable:!1}:{},a=t.target,n=t.status;if(a!==null&&(typeof a!="string"||!dk.includes(a)))return{valid:!1};if(typeof n!="string"||!pk.includes(n))return{valid:!1};if(a==="remote"||a==="local"){if(n==="ok"&&a==="local"){const i={target:"local",status:"ok",...s},o=p().min(1).safeParse(t.sshStartupFallbackHostId);return o.success&&(i.sshStartupFallbackHostId=o.data),{valid:!0,outcome:i}}if(n==="ok"&&a==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(n==="unreachable")return a==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(n==="incompatible"||n==="wrong-service")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url,...s}};if(n==="missing")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(a===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...s}};if(n==="missing")return{valid:!1}}return{valid:!1}}function AM(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===!1?{localAvailable:!1}:{};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 RM(e){return!e.isDesktopShell||e.bootOutcomeKnown}function IM(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function om(){if(gk()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=im(t);return s.valid?s.outcome:null}function gk(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":im(e).valid?"valid":"malformed"}const Do=/^[a-z][a-z\d+.-]*:\/\//i,uk=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Fo=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),mk=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Fo(e)},hk=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Fo(e)},fk=()=>Object.keys(un()).length>0,bk=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Fc=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},wk=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Fc({searchParams:s},t);const a=s.toString();return a?e.includes("?")?`${e}&${a}`:`${e}?${a}`:e},up=(e,t,s)=>{if(Do.test(t)){const o=new URL(t);return Fc(o,s),o.toString()}const a=uk(t);if(!e)return wk(a,s);const n=new URL(e),i=new URL(`${n.origin}${n.pathname.replace(/\/+$/,"")}${a}`);return Fc(i,s),i.toString()},Ki=(e,t=ay())=>{if(!t)return e;const s=Do.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),Do.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},rm=(e,t)=>{const s=Do.test(e)?new URL(e):new URL(e,bk(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},mp=(e,t,s)=>{if(!fk())return null;const a=hk();if(!a)return null;try{const n=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${a}/`);n.searchParams.set("url",t);const i=ny(a);return i&&n.searchParams.set("oc_url_token",i),e==="ws"?(n.protocol=n.protocol==="https:"?"wss:":"ws:",rm(n.toString(),s)):n.toString()}catch{return null}},Zl=(e={})=>{const t=Fo(e.apiBaseUrl),s=Fo(e.realtimeBaseUrl),a=()=>t||mk(),n=()=>s||a(),i=(r,c)=>up(a(),r,c),o=(r,c)=>up(n(),r,c);return{api:i,authenticatedAsset:(r,c)=>Ki(i(r,c)),assetWithUrlToken:(r,c,l)=>Ki(i(r,l),c),auth:i,health:r=>i("/health",r),rawFile:(r,c)=>i("/api/fs/raw",{path:r,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(r,c)=>{const l=Ki(o(r,c));return mp("sse",l,e)||l},websocket:(r,c)=>{const l=rm(Ki(o(r,c)),e);return mp("ws",l,e)||l}}};let Bo=Zl();const ds=()=>Bo,kk=e=>{Bo=e},cm=e=>(Bo=Zl(e),Bo),Bc="openchamber:runtime-endpoint-changed",Nc="openchamber:runtime-endpoint-will-change";let Ya="",gi="",Mc=0,Ec=null;const Rr=(e,t,s)=>{try{e[t]=s}catch{}},Jl=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"}`}},yk="mobile-disconnected",vk="url:default",Lc=e=>e===""||e===vk||e===yk,lm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},dm=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},pm=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},us=()=>Ya||lm(),Ck=()=>{if(Ec!==null)return Ec;const e=us();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let Ir="",hp=null,fp,bp;const wp=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},D=()=>{if(gi)return gi;const e=wp("__OPENCHAMBER_API_BASE_URL__"),t=wp("__OPENCHAMBER_LOCAL_ORIGIN__");if(hp===Ya&&fp===e&&bp===t)return Ir;const s=us();return Ir=pm(s,dm())?"local":Jl(s),hp=Ya,fp=e,bp=t,Ir},gm=()=>{const e=Mc,t=D();return()=>e===Mc&&t===D()},Sk=(e={})=>{if(Ya||gi)return;const t=e.apiBaseUrl?.trim()||lm(),s=globalThis.window?.location?.origin??"",a=/^https?:\/\//.test(s)?s:"";if(!t&&!a)return;const n=dm(),i=n&&(!t||pm(t,n));Ya=t,gi=e.runtimeKey?.trim()||(i?"local":Jl(t||a))},qc=e=>{const t=e.apiBaseUrl.trim(),s=us(),a=D(),n=e.runtimeKey?.trim()||Jl(t),i=e.sshForwarded??(t===s&&n===a&&Ck()),o={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:n,previousRuntimeKey:a};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Nc,{detail:o})),Ya=t,gi=n,n!==a&&(Mc+=1),Ec=i,typeof window<"u"){const r=window;Rr(r,"__OPENCHAMBER_API_BASE_URL__",t),Rr(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Rr(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}cm({apiBaseUrl:t,realtimeBaseUrl:t}),Am(e.requestHeaders||null),zm(e.clientToken||null),e.relay?Qk(e.relay):$k(),nr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Bc,{detail:o}))},er=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Nc,t),()=>window.removeEventListener(Nc,t)},tr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Bc,t),()=>window.removeEventListener(Bc,t)};let Vc=null;const jM=e=>{Vc=e},pn=()=>Vc||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Ql=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,ui=()=>{const e=Ql();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():!1},um=(e=Ql())=>!!e,xk=e=>e==="stable"||e==="canary",Pk=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,OM=e=>{const t=Pk.exec(e??"");if(!t)return null;const[,s,a,n,i,o]=t;return{release:s,builtOn:new Date(Date.UTC(Number(a),Number(n)-1,Number(i))),build:o?Number(o):null}},Tk=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),DM=(e,t,s)=>{const a=Tk(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${a} #${e.build}`:a},mm=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,ms=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,ua=()=>mm()?.runtime==="electron",hm=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},zk="right",FM=()=>{if(!ua())return!1;const e=hm();return e==="linux"?mm()?.nativeFrame!==!0:e==="win32"},BM=e=>e==="left"?"left":zk,NM=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],tt=()=>typeof ms()?.invoke=="function",gt=()=>ua()&&tt(),Ak=()=>{const e=ms()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>p().parse(await t()),writeText:async a=>{k(!0).parse(await s(a))}}}},Rk=()=>{if(ms()?.pickThemeFile)return{async pick(){const e=ms()?.pickThemeFile;return e?{status:"picked",file:g({name:p(),size:v().nonnegative(),text:p()}).nullable().parse(await e())}:{status:"unsupported"}}}},Y=async(e,t)=>{const s=ms();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},MM=e=>{hm()!=="darwin"||!gt()||Y("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},EM=()=>({apiBaseUrl:us(),clientToken:td(),runtimeKey:D()}),LM=async()=>{if(!Ye()||!Se())return!1;const e=us();try{const t=T().safeParse(await Y("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===us()}catch{return!1}},qM=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},VM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},fm=e=>xk(e?.channel)?e.channel:null,UM=async()=>{if(!gt()||!Se())return null;try{return fm(await Y("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},WM=async e=>{if(!gt()||!Se())return null;try{return fm(await Y("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},HM=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},GM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},_M=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},KM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},Ik=g({supported:T(),enabled:T(),combo:p().nullable(),storedCombo:p().nullable(),active:T(),heightFraction:v(),error:k("unsupported-combo").optional()}),sr=async(e,t,s)=>{if(!gt()||!Se())return null;try{const a=Ik.safeParse(await Y(e,t));return a.success?a.data:null}catch(a){return console.warn(s,a),null}},ZM=()=>sr("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),JM=e=>sr("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),QM=e=>sr("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),$M=e=>sr("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),YM=async()=>{if(!gt()||!Se())return null;try{const e=await Y("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}},XM=async e=>{if(!gt()||!Se())return null;try{const t=await Y("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}},kp=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}}},jr=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}}},jk=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Pn=e=>{const t=jk(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Se=()=>{if(typeof window>"u"||!Ye())return!1;if(D()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=jr(e),s=jr(us());if(!s&&t&&om()?.target==="local")return!0;if(t&&s){if(t.origin===s.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&o===r&&Pn(t.hostname)&&Pn(s.hostname)}const a=jr(window.location.origin);if(t&&a){if(t.origin===a.origin)return!0;const o=t.port||(t.protocol==="https:"?"443":"80"),r=a.port||(a.protocol==="https:"?"443":"80");return t.protocol===a.protocol&&o===r&&Pn(t.hostname)&&Pn(a.hostname)}const n=kp(e),i=kp(window.location.origin)||window.location.origin;return n&&i&&n===i?!0:!!(a&&Pn(a.hostname))},Ye=()=>typeof window>"u"?!1:ua(),eE=async()=>{if(!Ye())return null;const e=g({visible:T()}).safeParse(await Y("desktop_get_current_window_state"));return e.success?e.data.visible:null},tE=async()=>{if(!Ye())return!1;try{return!!await Y("desktop_focus_window")}catch{return!1}},sE=(e,t,s=null)=>!t||t===D()||!gt()?!1:(Y("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(n=>{console.warn("[desktop] failed to open host session",n)}),!0),bm=()=>Ye()&&tt()&&Se(),Ok=z(g({sessionId:p().min(1),messageId:p().min(1).optional(),runtimeKey:p().min(1).optional(),requireKnownSession:T().optional()})),aE=async()=>{if(!Ye())return[];try{const e=z(p()).safeParse(await Y("desktop_take_pending_extension_installs"));return e.success?e.data:[]}catch{return[]}},nE=async()=>{if(!Ye()||!Se())return[];try{const e=Ok.safeParse(await Y("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===!0})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},Dk=z(ve("type",[g({type:k("pairing"),link:p().min(1)}),g({type:k("host"),hostId:p().min(1)})])),iE=async()=>{if(!Ye())return[];try{const e=Dk.safeParse(await Y("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},Fk=p().min(1),oE=e=>{if(!bm())return null;try{const t=Fk.safeParse(ms()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},rE=async()=>{if(!Ye())return!1;try{return await Y("desktop_start_window_drag"),!0}catch{return!1}},Oe=()=>um()?!0:pn()?.runtime?.isVSCode===!0,cE=()=>{const t=pn()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Oe()},lE=(e,t=Ye())=>e==="web"&&!t,wm=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},dE=async e=>{if(bm())try{const t=await ms()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},Bk=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),pE=async e=>{if(tt()&&Se())try{const t=await ms()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!Bk(t))return{success:!1,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:!0,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},gE=async e=>({success:!0}),uE=async e=>({success:!0}),mE=async()=>tt()?await Y("desktop_check_for_updates"):null,hE=async e=>{if(!tt())return!1;const t=ms();let s=null,a=0,n;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",i=>{const o=i?.payload;if(!o||typeof o!="object")return;const r=o,c=typeof r.event=="string"?r.event:null,l=r.data&&typeof r.data=="object"?r.data:null;if(c==="Started"){a=0,n=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:a,total:n});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(a=d),typeof u=="number"&&(n=u),e({downloaded:a,total:n});return}c==="Finished"&&e({downloaded:a,total:n})})),await Y("desktop_download_and_install_update"),!0}catch(i){throw i instanceof Error?i:new Error(String(i))}finally{if(s)try{const i=s();i instanceof Promise&&await i}catch{}}},fE=async()=>tt()?(await Y("desktop_restart"),!0):!1,bE=async()=>{if(!tt())return!1;try{return await Y("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},wE=async()=>{if(!tt()||!Se())return null;try{const e=await Y("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}},Nk=async(e,t)=>{if(!tt()||!Se())return!1;const s=e?.trim();if(!s)return!1;try{return await Y("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(a){return console.warn("Failed to open path",a),!1}},kE=async e=>{if(!tt()||!Se())return!1;const t=e?.trim();if(!t)return!1;try{return await Y("desktop_reveal_path",{path:t}),!0}catch{return Nk(t)}},yE=async(e,t)=>{if(!tt()||!Se())return null;const s=e?.trim();if(!s)return null;try{const a=await Y("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof a=="string"&&a.trim().length>0?a:null}catch(a){return console.warn("Failed to save markdown file",a),null}},vE=async(e,t,s)=>{if(!tt()||!Se())return!1;const a=e?.trim(),n=t?.trim(),i=s?.trim();if(!a||!n||!i)return!1;try{return await Y("desktop_open_in_app",{projectPath:a,appId:n,appName:i}),!0}catch(o){return console.warn("Failed to open project in app",o),!1}},CE=async(e,t,s)=>{if(!tt()||!Se())return!1;const a=e?.trim(),n=t?.trim(),i=s?.trim();if(!a||!n||!i)return!1;try{return await Y("desktop_open_file_in_app",{filePath:a,appId:n,appName:i}),!0}catch(o){return console.warn("Failed to open file in app",o),!1}},SE=async(e,t)=>{if(!tt()||!Se())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=Array.isArray(e)?e.filter(a=>typeof a=="string"):[];if(s.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const a=await Y("desktop_get_installed_apps",{apps:s,force:t===!0?!0:void 0});if(!a||typeof a!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=a;return n.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(n.apps)?{apps:n.apps.filter(o=>o&&typeof o=="object").map(o=>{const r=o;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(o=>o.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(a){return console.warn("Failed to fetch installed apps",a),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},xE=()=>navigator.platform.toLowerCase().startsWith("linux"),ma=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",PE=()=>typeof window>"u"||!ma()?!1:km()==="ios"&&Mk(),Mk=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},km=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Oe()?"vscode":Ye()?"desktop":"web"},Ek="2.7.1-canary.20261108.12",Zi=new Uint8Array(0),Lk=typeof DecompressionStream=="function",qk=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")),ym=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,Vk=new TextEncoder,Uk=new TextDecoder,xt=e=>e instanceof Error?e:new Error(String(e)),Ji=()=>new DOMException("The operation was aborted.","AbortError"),Wk=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(ym(s))},close(s,a){e.close(s,a)},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},Hk=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(ym(s))},close(s,a){e.close(s,a)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const a=s.data;(typeof a=="string"||a instanceof ArrayBuffer)&&t.onmessage?.({data:a})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},Gk=e=>e?.state==="error"&&e.closeCode===Ns.LimitExceeded,yp=0,Or=1,vp=2,Cp=3,_k=new Set([Ns.AuthFailed,Ns.DuplicateClient,Ns.LimitExceeded]),Kk={[Ns.AuthFailed]:"relay authentication failed",[Ns.DuplicateClient]:"relay connection replaced by another client",[Ns.LimitExceeded]:"relay connection limit reached"},Dr=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},$l=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,a=e.pingIntervalMs??3e4,n=e.pingTimeoutMs??15e3,i=e.batchWindowMs??tm,o=e.batch!==!1,r=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(N=>Wk(new WebSocket(N)));let u=!1,m=null,f={state:"idle"};const b=new Set;let w=null,y=null,A=null,x=0,M=0,Q=null,he=[],L=!1;const U=N=>{if(!(f.state===N.state&&f.lastError===N.lastError&&f.terminal===N.terminal&&f.closeCode===N.closeCode)){f=N;for(const ce of b)try{ce(f)}catch{}}},Z=N=>{const ce=he;he=[];for(const W of ce)W.reject(N)},ot=N=>{const ce=he;he=[];for(const W of ce)W.resolve(N)},de=(N,ce)=>{N.dead=!0;const W=Array.from(N.streams.values());N.streams.clear();for(const _ of W)try{_.fail(ce)}catch{}},st=()=>{Q!==null&&(clearTimeout(Q),Q=null)},vn=()=>{if(!u){if(Q!==null){if(Dr())return;st(),Ct(),ya();return}Dr()||Vs()}},Vs=()=>{u||m===null||(Ct(),m=null,ya())},G=()=>{typeof document<"u"&&document.visibilityState==="visible"&&vn()},rt=()=>{L||typeof window>"u"||(L=!0,window.addEventListener("online",vn),typeof document<"u"&&document.addEventListener("visibilitychange",G))},Ct=()=>{!L||typeof window>"u"||(L=!1,window.removeEventListener("online",vn),typeof document<"u"&&document.removeEventListener("visibilitychange",G))},Cn=()=>{if(u||Q!==null)return;const N=Math.max(0,M-1),ce=r*2**Math.min(N,10),W=Dr()?l:c,_=Math.min(W,ce);rt(),Q=setTimeout(()=>{Q=null,Ct(),ya()},_)},xr=()=>{const N=new URL(e.relayUrl);return N.searchParams.set("v",String(Hn)),N.searchParams.set("role","client"),N.searchParams.set("serverId",e.serverId),N.searchParams.set("appId","openchamber"),N.searchParams.set("appVersion",Ek),N.searchParams.set("platform",km()),e.grant&&N.searchParams.set("grant",e.grant),N.toString()},ya=async()=>{if(u)return;st(),x+=1;const N=x;U({state:M>0?"reconnecting":"connecting",lastError:f.lastError});let ce;try{ce=await qw(e.hostEncPubJwk,{batch:o,flowControl:e.flowControl})}catch(ge){if(N!==x||u)return;cp(N,xt(ge),!0);return}if(N!==x||u)return;let W;try{W=d(xr())}catch(ge){cp(N,xt(ge));return}y=W;let _=!1,$=null,pe=null,ct=null,Me=null,te=Promise.resolve(),ae=null,Re=null,es=!1,De=!1,Fe=0,Ee=0,Le=null,ts=null,Ce=Date.now();const ws=()=>{Le!==null&&(clearTimeout(Le),Le=null),$!==null&&(clearInterval($),$=null),pe!==null&&(clearTimeout(pe),pe=null),ct!==null&&(clearInterval(ct),ct=null),Me!==null&&(clearTimeout(Me),Me=null),ts!==null&&(ts.dispose(),ts=null)};A=ws;function ue(ge,xe=!1,me=null){if(!(_||N!==x)){_=!0,me!==null&&(m=ge),ws(),ae&&(w=null,de(ae,new Error(`relay tunnel reset: ${ge.message}`))),Z(ge);try{W.close()}catch{}if(y===W&&(y=null),!u){if(M+=1,me!==null){rt(),U({state:"error",lastError:ge.message,terminal:!0,closeCode:me});return}U({state:xe?"error":"reconnecting",lastError:ge.message}),Cn()}}}const Sn=()=>{try{W.send(ce.helloText)}catch{}},Us=(ge,xe,me)=>{Re=ge,es=xe,De=me,$!==null&&(clearInterval($),$=null),pe!==null&&(clearTimeout(pe),pe=null);const lt=new Map,We=Yw(),St=Gw();let Ws=Promise.resolve();const ks=xn=>{Ws=Ws.then(async()=>{if(Hs.dead)return;const gw=await ge.encryptor.encrypt(xn);Hs.dead||W.send(gw)}).catch(()=>{ue(new Error("relay encrypt/send failed"))})},zr=xe?$w({windowMs:i,sendBatch:ks}):null;ts=zr;const Hs={streams:lt,assembler:St,nextStreamId:()=>We.next(),dead:!1,send(xn){Hs.dead||(zr?zr.enqueue(xn):ks(xn))}};ae=Hs,w=Hs,M=0,Ce=Date.now(),U({state:"connected"}),ot(Hs),ct=setInterval(()=>{Date.now()-Ce<a||(Hs.send(zt(se.Ping,0,Zi)),Me===null&&(Me=setTimeout(()=>{Me=null,ue(new Error("relay keepalive timeout"))},n)))},a)},Vi=()=>{Le!==null&&clearTimeout(Le),Le=null,!(!ae||ae.dead||Fe===Ee)&&(Ee=Fe,ae.send(zt(se.DeliveryAck,0,Vw(Fe))))},Tr=(ge,xe)=>{let me;try{me=Uw(xe)}catch(St){ue(xt(St));return}if(me.frameType===se.DeliveryAck){ue(new Error("unexpected downstream delivery acknowledgement"));return}if(De&&me.streamId!==0&&(Fe+=xe.length,Le===null&&(Le=setTimeout(Vi,10))),Ce=Date.now(),Me!==null&&(clearTimeout(Me),Me=null),me.frameType===se.Ping){ge.send(zt(se.Pong,me.streamId,Zi));return}if(me.frameType===se.Pong)return;let lt=me.payload;if(me.frameType===se.WsText||me.frameType===se.WsBinary){let St;try{St=ge.assembler.push(me)}catch(Ws){ue(xt(Ws));return}if(St===null)return;lt=St}else if(me.hasMoreFragments){ue(new Error("unexpected fragmented tunnel frame"));return}const We=ge.streams.get(me.streamId);We&&We.handleFrame(me.frameType,lt)};W.onopen=()=>{_||N!==x||(Sn(),$=setInterval(Sn,t))};const va=ge=>{const xe=_k.has(ge);ue(new Error(Kk[ge]??`relay socket closed (code ${ge})`),xe,xe?ge:null)};W.onmessage=ge=>{if(_||N!==x)return;const xe=ge.data;if(typeof xe=="string"){const lt=vw(xe);if(lt){va(lt.code);return}te=te.then(async()=>{if(_||N!==x)return;const We=await ce.handleText(xe);if(We.type==="established"){if(Re)return;Us(We.channel,We.batch,We.flowControl)}else We.type==="fail"&&ue(new Error(`relay handshake failed: ${We.reason}`))}).catch(We=>{ue(xt(We))});return}const me=xe instanceof ArrayBuffer?new Uint8Array(xe):xe instanceof Uint8Array?xe:null;me&&(te=te.then(async()=>{if(_||N!==x)return;const lt=ae,We=Re;if(!lt||!We){ue(new Error("encrypted frame before handshake completed"));return}let St;try{St=await We.decryptor.decrypt(me)}catch(ks){ue(xt(ks));return}let Ws;try{Ws=es?Kw(St):[St]}catch(ks){ue(xt(ks));return}for(const ks of Ws){if(_||N!==x||lt.dead)return;Tr(lt,ks)}De&&Fe-Ee>=16*1024&&Vi()}).catch(lt=>{ue(xt(lt))}))},W.onclose=ge=>va(ge.code),W.onerror=()=>{},pe=setTimeout(()=>{pe=null,ue(new Error("relay handshake timeout"),!0)},s);function cp(ge,xe,me=!1){ge!==x||u||(Z(xe),M+=1,U({state:me?"error":"reconnecting",lastError:xe.message}),Cn())}},Xt=N=>u?Promise.reject(new Error("relay tunnel closed")):N?.aborted?Promise.reject(Ji()):m?Promise.reject(m):w&&!w.dead?Promise.resolve(w):new Promise((ce,W)=>{let _=null;const $={resolve(pe){_&&N&&N.removeEventListener("abort",_),ce(pe)},reject(pe){_&&N&&N.removeEventListener("abort",_),W(pe)}};N&&(_=()=>{he=he.filter(pe=>pe!==$),W(Ji())},N.addEventListener("abort",_,{once:!0})),he.push($)}),Pr=async(N,ce)=>{const W=await ok(N,ce),_=W.signal;if(_?.aborted)throw Ji();const $=await Xt(_),pe=$.nextStreamId();return await new Promise((ct,Me)=>{let te=!1,ae=!1,Re=null,es=null;const De=()=>{$.streams.delete(pe),$.assembler.dropStream(pe),es&&_&&_.removeEventListener("abort",es)},Fe=Ce=>{if(!ae){if(ae=!0,De(),!te){Me(Ce);return}try{Re?.error(Ce)}catch{}}},Ee=Ce=>{$.dead||$.send(zt(se.StreamAbort,pe,Hi({reason:Ce})))},Le=Ce=>Dc(new Error(Ce));es=()=>{Ee("aborted"),Fe(Ji())},$.streams.set(pe,{handleFrame(Ce,ws){if(Ce===se.HttpResponse){if(te||ae)return;let ue;try{ue=Gi(ws,ek)}catch(va){Ee("malformed response head"),Fe(Le(xt(va).message));return}const Sn=ue.status===204||ue.status===205||ue.status===304;let Us=null;Sn||(Us=new ReadableStream({start(va){Re=va},cancel(){ae||(ae=!0,De(),Ee("response body cancelled"))}})),te=!0;const{[Pw]:Vi,...Tr}=ue.headers;Us&&Vi==="gzip"&&(Us=qk(Us)),ct(new Response(Us,{status:ue.status,headers:Tr})),Sn&&(ae=!0,De());return}if(Ce===se.HttpBody){if(!te||ae)return;try{Re?.enqueue(ws)}catch{}return}if(Ce===se.StreamEnd){if(ae)return;if(!te){Fe(Le("tunnel stream ended before response head"));return}ae=!0,De();try{Re?.close()}catch{}return}if(Ce===se.StreamAbort){let ue="stream aborted by host";try{ue=Gi(ws,gp).reason}catch{}Fe(Le(ue))}},fail(Ce){Fe(Le(Ce.message))}}),_&&_.addEventListener("abort",es,{once:!0});const ts={method:W.method,path:W.path,query:W.query,headers:Lk?{...W.headers,[xw]:"gzip"}:W.headers,hasBody:W.body!==null};$.send(zt(se.HttpRequest,pe,Hi(ts))),(async()=>{try{let Ce=!1;if(W.body)for await(const ws of W.body){if(ae||$.dead)return;for(const ue of em(ws))$.send(zt(se.HttpBody,pe,ue)),Ce=!0}!ae&&!$.dead&&(W.body&&!Ce&&$.send(zt(se.HttpBody,pe,Zi)),$.send(zt(se.StreamEnd,pe,Zi)))}catch(Ce){Ee("request body failed"),Fe(Le(xt(Ce).message))}})()})},lw=N=>{const ce=N.indexOf("?");return ce===-1?{path:N,query:""}:{path:N.slice(0,ce),query:N.slice(ce+1)}},dw=(N,ce)=>{let W=yp,_=null,$=0,pe=!1;const ct={get readyState(){return W},onopen:null,onmessage:null,onerror:null,onclose:null,send(te){if(W!==Or||!_||_.dead)throw new Error("relay tunnel socket is not open");if(typeof te=="string"){for(const Re of pp(se.WsText,$,Vk.encode(te)))_.send(Re);return}const ae=te instanceof ArrayBuffer?new Uint8Array(te.slice(0)):(()=>{const Re=new Uint8Array(te.byteLength);return Re.set(new Uint8Array(te.buffer,te.byteOffset,te.byteLength)),Re})();for(const Re of pp(se.WsBinary,$,ae))_.send(Re)},close(te=1e3,ae=""){W===Cp||W===vp||(W===Or&&_&&!_.dead&&(W=vp,_.send(zt(se.WsClose,$,Hi({code:te,reason:ae})))),Me(te,ae))}},Me=(te,ae,Re=!1)=>{if(!pe){if(pe=!0,_&&(_.streams.delete($),_.assembler.dropStream($)),W=Cp,Re)try{ct.onerror?.()}catch{}try{ct.onclose?.({code:te,reason:ae})}catch{}}};return(async()=>{let te;try{te=await Xt()}catch(De){Me(1006,xt(De).message,!0);return}if(pe)return;_=te,$=te.nextStreamId(),te.streams.set($,{handleFrame(De,Fe){if(De===se.WsOpened){if(W===yp){W=Or;try{ct.onopen?.()}catch{}}return}if(De===se.WsText){try{ct.onmessage?.({data:Uk.decode(Fe)})}catch{}return}if(De===se.WsBinary){const Ee=new ArrayBuffer(Fe.byteLength);new Uint8Array(Ee).set(Fe);try{ct.onmessage?.({data:Ee})}catch{}return}if(De===se.WsClose){let Ee=1e3,Le="";try{const ts=Gi(Fe,tk);Ee=ts.code,Le=ts.reason}catch{}Me(Ee,Le);return}if(De===se.StreamAbort){let Ee="stream aborted";try{Ee=Gi(Fe,gp).reason}catch{}Me(1006,Ee,!0)}},fail(De){Me(1012,De.message,!0)}});const{path:ae,query:Re}=lw(N),es=ce&&ce.length>0?{path:ae,query:Re,protocols:ce}:{path:ae,query:Re};te.send(zt(se.WsOpen,$,Hi(es)))})(),ct},pw=()=>{if(u)return;u=!0,x+=1,st(),Ct(),A?.(),A=null;const N=w;w=null;const ce=new Error("relay tunnel closed");N&&de(N,ce),Z(ce);try{y?.close()}catch{}y=null,U({state:"idle"})};return ya(),{fetch:Pr,openWebSocket:dw,getStatus:()=>f,subscribeStatus(N){return b.add(N),()=>{b.delete(N)}},retry:Vs,close:pw}};let Qt=null,Kt=null;const Uc=new Set;let Fr=null;const Yl=e=>{Fr?.(),Fr=null,Qt=e,e&&(Fr=e.subscribeStatus(t=>{for(const s of Uc)s(t)}))},TE=e=>(Uc.add(e),()=>{Uc.delete(e)}),Zk=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),gn=()=>Qt,zE=()=>!Qt||!Kt?null:{relayUrl:Kt.relayUrl,serverId:Kt.serverId,hostEncPubJwk:{...Kt.hostEncPubJwk}},Jk=()=>Qt!==null,Qk=e=>{if(Qt&&Kt&&Zk(Kt,e))return Qt;Qt?.close(),Kt=e;const t=$l(e);return Yl(t),t},AE=(e,t)=>{if(Qt===t){Kt=e;return}Qt?.close(),Kt=e,Yl(t)},$k=()=>{Qt?.close(),Yl(null),Kt=null};let vm=()=>null,Cm="",No={},Xa="",mi=0,Xs=null,Ua="",hi=0,da="",ea=null,zs="",wo=0,ko=0;const Xl=1e4,Yk=e=>e.toLowerCase()==="authorization",Sm=e=>{const t={};for(const[s,a]of Object.entries(e||{})){const n=s.trim(),i=a.trim();n&&i&&!Yk(n)&&(t[n]=i)}return t},Xk=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?!1:s.every(([a,n])=>t[a]===n)},ar=e=>typeof e!="string"?"":e.trim(),ey=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return ar(e)},ty=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},xm=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():ty();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},ed=e=>{try{return new URL(e).origin}catch{return""}},Pm=()=>{Ua="",hi=0,da="",ea=null,zs="",wo+=1},Ai=()=>{Xa="",mi=0,Pm()},Tm=()=>{ko+=1,Xs=null,Ai(),sd()},zm=e=>{const t=ar(e);Cm=t,Tm(),vm=()=>t?{type:"bearer",token:t}:null},Am=e=>{const t=Sm(e);Xk(No,t)||(No=t,Tm())},un=()=>{if(Object.keys(No).length>0)return No;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Sm(e):{}},td=()=>Cm||ey(),sy=(e,t)=>{const s=ar(e);if(!s||typeof t!="number"||!Number.isFinite(t)){Ai();return}Xa=s,mi=t},Rm=()=>!Xa||mi<=Date.now()+Xl?(Ai(),""):Xa,Im=e=>{const t=ed(e);return!t||da!==t?"":!Ua||hi<=Date.now()+Xl?(Ua="",hi=0,da="",""):Ua},ay=()=>{const e=Rm();return!e&&(td()||typeof window<"u")&&nr().catch(()=>{}),e},ny=e=>{const t=e?Im(e):"";return!t&&e&&typeof window<"u"&&Fm(e).catch(()=>{}),t},jm=async()=>{const e=await vm(),t=e?.type==="bearer"?ar(e.token):td();return t?{type:"bearer",token:t}:null},iy=g({token:p(),expiresAt:v(),expiresIn:v().optional()}),Om=async(e,t)=>{const s=await jm(),a=new Headers;for(const[u,m]of Object.entries(un()))a.set(u,m);s?.type==="bearer"&&a.set("Authorization",`Bearer ${s.token}`);const n=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",i=gn(),o=i?await i.fetch(n,{method:"POST",headers:a}):await fetch(xm(e,n),{method:"POST",headers:a,credentials:"include"});if(!o.ok)throw new Error(`Failed to mint runtime URL auth token (${o.status})`);const r=iy.safeParse(await o.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:c,expiresAt:l,expiresIn:d}=r.data;return{token:c.trim(),expiresAt:d===void 0?l:Date.now()+d}},RE=async e=>{const t=await Om(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Dm=e=>{if(Xs)return Xs;const t=ko,a=(async()=>{let n;try{n=await Om(e)}catch(i){throw t===ko&&Ai(),i}if(t!==ko)throw new Error("Runtime URL auth token response is stale");if(sy(n.token,n.expiresAt),!Xa)throw new Error("Runtime URL auth token response was invalid");return Xa})().finally(()=>{Xs===a&&(Xs=null)});return Xs=a,Xs},oy=e=>{const t=ed(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(ea&&zs===t)return ea;const s=wo,n=(async()=>{const i=await fetch(xm(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!i.ok)throw s===wo&&t===zs&&(Ua="",hi=0,da=""),new Error(`Failed to mint local runtime URL auth token (${i.status})`);const o=await i.json().catch(()=>null),r=typeof o?.token=="string"?o.token.trim():"",c=typeof o?.expiresAt=="number"?o.expiresAt:0;if(!r||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(s!==wo||t!==zs)throw new Error("Local runtime URL auth token response is stale");return Ua=r,hi=c,da=t,r})().finally(()=>{ea===n&&(ea=null,zs="")});return ea=n,zs=t,ea},nr=async e=>{const t=Rm();return t||Dm(e)},Fm=async e=>{const t=ed(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=Im(t);return s||((da&&da!==t||zs&&zs!==t)&&Pm(),oy(t))};let Na=0,_n=null,ry=null;const cy=5e3,Bm=()=>{_n!==null&&(clearTimeout(_n),_n=null)},sd=()=>{if(Bm(),Na<=0||typeof window>"u")return;const e=mi-Xl-cy,t=mi>0?Math.max(0,e-Date.now()):0;_n=setTimeout(()=>{_n=null,!(Na<=0)&&Dm(ry).catch(()=>{}).finally(()=>{sd()})},t)},IE=e=>{Na+=1,sd();let t=!1;return()=>{t||(t=!0,Na=Math.max(0,Na-1),Na===0&&Bm())}},Nm=async e=>{const t=new Headers(e);for(const[a,n]of Object.entries(un()))t.has(a)||t.set(a,n);if(t.has("Authorization"))return t;const s=await jm();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},en=vt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),jE=e=>new Promise(t=>{if(e.aborted||en.getState().state==="ok"){t();return}const s=()=>{a(),e.removeEventListener("abort",s),t()},a=en.subscribe(n=>{n.state==="ok"&&s()});e.addEventListener("abort",s,{once:!0})}),ly=15e3,dy=5*6e4;let Wc=0,Br=!1;const py=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),gy=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!py(t)},Mm=async()=>{if(!Br){Br=!0;try{const{runtimeFetch:e}=await qe(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>Iy);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){en.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:a}=en.getState();s==="expired"&&a()}}catch{}finally{Br=!1}}},uy=(e,t)=>{if(t!==401||en.getState().state==="expired"||!gy(e))return;const s=Date.now();s-Wc<ly||(Wc=s,Mm())};let Sp=!1;const OE=()=>{if(Sp)return;Sp=!0;let e=Date.now();const t=()=>{if(en.getState().state!=="ok")return;const s=Date.now();s-e<dy||(e=s,Wc=s,Mm())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},my=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,yt=e=>{if(!e)return null;const t=my.exec(e);return t?t[1]:null},Hc=e=>yt(e)!==null,hy=()=>um()||pn()?.runtime?.isVSCode===!0,fy=e=>!e||hy()||!Hc(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},Em=e=>`/spaces/${e}`,pa=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",by=()=>typeof window>"u"?"":window.location.origin||"",ad=e=>{if(typeof window>"u")return!1;const t=by();if(t&&e.origin===t)return!0;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return!1}},nd=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),wy=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),as=(e,t)=>{try{wy(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},id=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},ky=e=>{if(!e)return!1;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!0;return!1},yy=(e,t,s)=>{const a=fy(s);if(a===null||ky(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const n=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...n,...Object.entries(a)]}},vy=()=>{const e=ds().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$/,"")}`},Cy=e=>{try{const t=vy();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const a=s.pathname.replace(/\/+$/,"");return a?e.pathname!==a&&!e.pathname.startsWith(`${a}/`)?null:e.pathname.slice(a.length)||"/":e.pathname}catch{return null}},yo=e=>{const t=Cy(e);return t!==null&&pa(t)},Nr=e=>{if(pa(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ad(t)&&pa(t.pathname)}catch{return!1}},Sy=(e,t)=>{try{const s=new URL(e);if(!ad(s))return e;const a=Ms(`${s.pathname}${s.search}`,t);return!nd(a)&&(s.protocol==="http:"||s.protocol==="https:")?(id(s,t),s.toString()):s.hash?`${a}${s.hash}`:a}catch{return e}},Ms=(e,t)=>e==="/health"?ds().health(t):e.startsWith("/auth/")||e==="/auth"?ds().auth(e,t):pa(e)?ds().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Sy(e,t):e,Lm=e=>{const t=e instanceof Request?e.url:e.toString();if(!nd(t))return pa(t);try{return yo(new URL(t))}catch{return!1}},qm=(e,t)=>Object.keys(un()).length>0&&ma()&&Lm(e)?{...t,redirect:"error"}:t,Vm=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},xy=(e,t)=>!Vm(t),Mo=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 a=!1,n=!1;for(const[i,o]of t)xy(i,o)?(s.push([i,encodeURIComponent(o)]),a=!0,i.toLowerCase()==="x-opencode-directory"&&(n=!0)):s.push([i,o]);return n&&s.push(["x-opencode-directory-encoding","uri"]),a?s:void 0},ns=async(e,t,s=!0)=>{const a=new Headers(Mo(e)??e);return t&&new Headers(Mo(t)??t).forEach((n,i)=>a.set(i,n)),s?Nm(a):a},Py=(e,t)=>{if(!t)return e;const s=new URL(e,Kl);return id(s,t),`${s.pathname}${s.search}`},Um=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!nd(s))return pa(s)?Py(s,t):null;try{const a=new URL(s);return!ad(a)||!pa(a.pathname)?null:(id(a,t),`${a.pathname}${a.search}`)}catch{return null}},Ty=async(e,t,s)=>{const a=gn();if(!a)return null;const n=Um(e,s);if(n===null)return null;const i=e instanceof Request?e.headers:void 0,o=await ns(i,t.headers,!0);return e instanceof Request?a.fetch(e,{...t,headers:o}):a.fetch(n,{...t,headers:o})},zy=(e,t)=>{if(typeof e=="string")return Ms(e,t);if(e instanceof URL)return Ms(e.toString(),t);const s=Ms(e.url,t);return s===e.url?e:new Request(s,e)},Ay=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Qi=new Map,Ry=(e,t,s,a)=>s||e!=="GET"||t.includes("/event")||!Ay.test(t)?null:`GET ${t}\0${a.get("x-opencode-directory")??""}`,C=async(e,t={})=>{const{query:s,directory:a,...n}=t,i=e,o=yy(i,n,a),r=gn(),c=r?Um(i,s):null;let l,d,u,m;if(r&&c!==null){const x=i instanceof Request?i.headers:void 0,M=await ns(x,o.headers,!0);l=i instanceof Request?()=>r.fetch(i,{...o,headers:M}):()=>r.fetch(c,{...o,headers:M}),m=M,d=c,u=String(o.method??(i instanceof Request?i.method:"GET")).toUpperCase()}else{const x=zy(i,s),M=x instanceof Request?x.headers:void 0,Q=await ns(M,o.headers,Lm(x)),he=x instanceof Request?x.url:x instanceof URL?x.toString():String(x);as(he,Q);const L=qm(x,{...o,headers:Q});l=x instanceof Request?()=>fetch(new Request(x,L)):()=>fetch(x,L),m=Q,d=he,u=String(o.method??(x instanceof Request?x.method:"GET")).toUpperCase()}const f=l;l=()=>f().then(x=>(uy(d,x.status),x));const b=o.signal!=null||i instanceof Request,w=Ry(u,d,b,m);if(!w)return l();const y=Qi.get(w);if(y)return y.then(x=>x.clone());const A=l();return Qi.set(w,A),A.then(()=>Qi.delete(w),()=>Qi.delete(w)),A.then(x=>x.clone())};let xp=!1,Wm=null;const Hm=(e,t)=>(Wm??globalThis.fetch.bind(globalThis))(e,t),Gm=()=>{if(xp||typeof window>"u")return;xp=!0;const e=window.fetch.bind(window);Wm=e;const t=(s,a)=>e(s,qm(s,a));window.fetch=async(s,a)=>{const n=await Ty(s,a??{});if(n)return n;if(typeof s=="string"){if(!Nr(s)){try{const r=new URL(s);if(yo(r)){const c=await ns(void 0,a?.headers);return as(r.toString(),c),t(s,{...a,headers:c})}}catch{}return t(s,a)}const i=await ns(void 0,a?.headers),o=Ms(s);return as(o,i),t(o,{...a,headers:i})}if(s instanceof URL){const i=s.toString();if(!Nr(i)){if(yo(s)){const c=await ns(void 0,a?.headers);return as(s.toString(),c),t(s,{...a,headers:c})}return t(s,a)}const o=await ns(void 0,a?.headers),r=Ms(i);return as(r,o),t(r,{...a,headers:o})}if(s instanceof Request){if(!Nr(s.url)){try{const c=new URL(s.url);if(yo(c)){const l=await ns(s.headers,a?.headers);return as(c.toString(),l),t(new Request(s,{...a,headers:l}))}}catch{}return t(s,a)}const i=await ns(s.headers,a?.headers),o=Ms(s.url);as(o,i);const r=o===s.url?s:new Request(o,s);return t(new Request(r,{...a,headers:i}))}return t(s,a)}},Iy=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:as,buildRuntimeFetchUrl:Ms,fetchBypassingRuntimeBridge:Hm,installRuntimeFetchBridge:Gm,isLatin1Safe:Vm,runtimeFetch:C,sanitizeHeadersForBrowser:Mo},Symbol.toStringTag,{value:"Module"})),Wa=16384,Eo=globalThis,jy=e=>{if(Eo.Buffer)return Eo.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let a=0;a<t.length;a+=32768)s+=String.fromCharCode(...t.slice(a,a+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},_m=e=>{try{if(Eo.Buffer)return Eo.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),a=new Uint8Array(s.length);for(let n=0;n<s.length;n+=1)a[n]=s.charCodeAt(n);return new TextDecoder().decode(a)}catch{return null}},Oy=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}},Dy=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}},Pp=e=>typeof e=="string"&&e.length>0,Fy=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Pp(t.x)||!Pp(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},By=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ny=e=>{if(!e||typeof e!="object")return null;const t=e,s=By(t.priority);if(t.type==="lan"||t.type==="tunnel"){const a=Oy(t.url);return a?s===void 0?{type:t.type,url:a}:{type:t.type,url:a,priority:s}:null}if(t.type==="relay"){const a=Dy(t.relayUrl);if(!a)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const i=Fy(t.hostEncPubJwk);if(!i)return null;const o=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:a,serverId:n,hostEncPubJwk:i,...o?{grant:o}:{},...s===void 0?{}:{priority:s}}}return null},od=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():"",a=typeof t.secret=="string"?t.secret.trim():"";if(!s||!a)return null;const n=Array.isArray(t.candidates)?t.candidates.map(Ny).filter(c=>!!c):[];if(n.length===0)return null;const i=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(i){const c=Date.parse(i);if(!Number.isFinite(c)||c<=Date.now())return null}const o=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:a,...o?{label:o}:{},...r?{fingerprint:r}:{},...i?{expiresAt:i}:{},candidates:n}},DE=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}),FE=e=>{const t=od(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",jy(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},My=e=>{const t=e.trim();if(!t||t.length>Wa)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const a=s.searchParams.get("p")||"";if(!a||a.length>Wa)return null;const n=_m(a);return!n||n.length>Wa?null:od(JSON.parse(n))}catch{return null}},BE=e=>{const t=e.trim();if(!t||t.length>Wa)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let a=null,n=null;for(const o of t.slice(s+1).split("&")){const r=o.indexOf("=");if(r===-1)continue;const c=o.slice(0,r),l=o.slice(r+1);c==="v"?a=l:c==="p"&&(n=l)}if(a!=="2"||!n||n.length>Wa)return null;const i=_m(n);if(!i||i.length>Wa)return null;try{return od(JSON.parse(i))}catch{return null}},tn=e=>typeof e=="object"&&e!==null,Ey=e=>e.trim().toLowerCase()==="authorization",Ly=e=>{if(!tn(e))return;const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),i=typeof a=="string"?a.trim():"";!n||!i||/[\r\n:]/.test(n)||/[\r\n]/.test(i)||Ey(n)||(t[n]=i)}return Object.keys(t).length>0?t:void 0},qy=e=>`relay://${e}`,Vy=e=>{if(!tn(e))return null;const t=Ke(e,"relayUrl")||Ke(e,"relay_url"),s=Ke(e,"serverId")||Ke(e,"server_id"),a=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!tn(a)?null:{relayUrl:t,serverId:s,hostEncPubJwk:a}},Uy=()=>{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"},Tp=15e3,NE=async(e,t)=>{const s=My(e);if(!s)throw new Error("invalid-connect-link");const a=await Ky().catch(()=>""),n={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:Uy(),...a?{dedupeKey:`desktop:${a}`}:{}})},i=async y=>{if(!y.ok)return null;const A=await y.json().catch(()=>null);return(typeof A?.clientToken=="string"?A.clientToken.trim():"")||null};let o=null;const r=[...s.candidates].sort((y,A)=>(y.type==="relay"?1:0)-(A.type==="relay"?1:0));for(const y of r){if(y.type==="relay"){const x=$l({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const M=await i(await x.fetch("/api/client-auth/pairing/redeem",{...n,signal:AbortSignal.timeout(Tp)}));if(M){o={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:M};break}}catch{}finally{x.close()}continue}const A=Ue(y.url);if(A)try{const x=await i(await fetch(`${A}/api/client-auth/pairing/redeem`,{...n,signal:AbortSignal.timeout(Tp)}));if(x){o={directUrl:A,token:x};break}}catch{}}if(!o)throw new Error("pairing-redeem-failed");const c=s.candidates.find(y=>y.type==="relay"),l=o.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),d=s.candidates.filter(y=>y.type!=="relay").map(y=>Ue(y.url)).find(y=>!!y),u=o.directUrl||d,m=u||(l?qy(l.serverId):null);if(!m)throw new Error("pairing-missing-transport");const f=t.find(y=>l?y.relay?.serverId===l.serverId:!y.relay&&Ue(y.apiUrl||y.url)===m),b=f?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),w={...f||{},id:b,label:s.label||f?.label||Km(m),url:m,apiUrl:u,clientToken:o.token,...l?{relay:l}:{}};return{hostId:b,hosts:f?t.map(y=>y.id===b?w:y):[w,...t]}},Wy=/^(t|.*(?:token|auth|secret|api).*)$/i,Ue=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}},ME=e=>{const t=Ue(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"}},Km=e=>{const t=Ue(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const a=Array.from(new Set(Array.from(s.searchParams.keys())));for(const n of a)Wy.test(n)&&s.searchParams.set(n,"[REDACTED]");return s.toString()}catch{return t}},$i=(e,t)=>{const s=Ue(e),a=Ue(t);if(!s||!a)return!1;try{const n=new URL(s),i=new URL(a);if(n.origin!==i.origin||i.search&&n.search!==i.search)return!1;const o=i.pathname.length>1?i.pathname.replace(/\/+$/,""):i.pathname,r=n.pathname.length>1?n.pathname.replace(/\/+$/,""):n.pathname;return o==="/"?!0:r===o||r.startsWith(`${o}/`)}catch{return!1}},Ke=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},zp=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},Hy=e=>{if(!tn(e))return null;const t=Ke(e,"id"),s=Ke(e,"label"),a=Ke(e,"url"),n=Ke(e,"apiUrl")||Ke(e,"api_url"),i=Ke(e,"clientToken")||Ke(e,"client_token"),o=Ly(e.requestHeaders),r=Vy(e.relay);if(!t||!s||!a)return null;const c={id:t,label:s,url:a,...n?{apiUrl:n}:{},...i?{clientToken:i}:{},...o?{requestHeaders:o}:{},...r?{relay:r}:{}};return e.sshForwarded===!0&&(c.sshForwarded=!0),c},Ha=e=>Ue(e.apiUrl||e.url)||e.apiUrl||e.url,bs=()=>tt()?(e,t)=>Y(e,t):null,fi=async()=>{const e=bs();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!tn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const s=t.hosts,a=Array.isArray(s)?s.map(Hy).filter(r=>!!r):[],n=Ke(t,"defaultHostId")||Ke(t,"default_host_id")||Ke(t,"defaultHostID"),i=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,o=Ke(t,"localOrigin")||Ke(t,"local_origin");return{hosts:a,defaultHostId:n,initialHostChoiceCompleted:i,localOrigin:o}},Gy=async e=>{const t=bs();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})},_y=async()=>{const e=bs();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},EE=async()=>{const e=bs();return e?await e("desktop_switch_to_local").catch(()=>!1)===!0:!1},Ky=async()=>{const e=bs();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Zy=8e3,Jy=15e3,Qy=400,$y=async(e,t,s,a)=>{const n=new AbortController,i=window.setTimeout(()=>n.abort(),s);try{return await e.fetch(t,{...a,signal:n.signal})}finally{window.clearTimeout(i)}},Ap=async(e,t,s,a)=>{for(;;){const n=s-Date.now();if(n<=0)throw new Error("relay probe deadline exceeded");try{return await $y(e,t,Math.min(Zy,n),a)}catch(i){if(e.getStatus().state==="error"||Date.now()>=s)throw i;await new Promise(o=>window.setTimeout(o,Qy))}}},Yy=async(e,t)=>{const s=$l({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),a=Date.now(),n=a+Jy;let i=!1;try{if(!(await Ap(s,"/health",n)).ok)return{status:"unreachable",latencyMs:0};const r=new Headers({Accept:"application/json"});for(const[d,u]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&r.set(d,u);const c=t?.clientToken?.trim();c&&r.set("Authorization",`Bearer ${c}`);const l=await Ap(s,"/auth/session",n,{headers:r});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-a)}:l.ok?(i=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-a),...i?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:Gk(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{i||s.close()}},ir=async(e,t)=>{const s=bs();if(!s)return{status:"unreachable",latencyMs:0};const a=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!tn(a))return{status:"unreachable",latencyMs:0};const n=a.status,i=n==="ok"||n==="auth"||n==="update-recommended"||n==="incompatible"||n==="wrong-service"||n==="unreachable"?n:"unreachable",o=zp(a,"latencyMs")??zp(a,"latency_ms")??0;return{status:i,latencyMs:o}},Xy=ve("status",[g({status:k("started")}),g({status:k("auth")}),g({status:k("failed"),error:p().nullable()})]),LE=async e=>{const t=bs();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),a=Xy.safeParse(s);return a.success?a.data:{status:"failed",error:null}},ev=600*1e3,tv=3e3,qE=async(e,{maxWaitMs:t=ev,intervalMs:s=tv,readHosts:a=fi,probe:n=ir}={})=>{const i=Date.now()+t;for(;Date.now()<i;){await new Promise(c=>setTimeout(c,Math.min(s,Math.max(0,i-Date.now()))));const o=(await a()).hosts.find(c=>c.id===e);if(!o)return"timeout";const r=await n(Ha(o),{clientToken:o.clientToken,requestHeaders:o.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},VE=async(e,t)=>{const s=bs();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},UE=async e=>{const t=bs();t&&await t("desktop_new_window_for_host",{hostId:e})},Bs="local",sv=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",av=(e,t)=>t?[{id:Bs,label:"Local",url:t},...e]:e,nv=e=>e.id===Bs?"local":`host:${e.id}`,WE=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(m=>m.id===Bs)?.url||sv(),a=us(),n=Ue(s)||s,i=Ue(t)||t,o=D(),r=e.find(m=>m.relay&&nv(m)===o);if(r)return{id:r.id,label:r.label,url:r.url};if(a&&$i(a,s))return{id:Bs,label:"Local",url:n};const c=e.find(m=>a?$i(a,Ha(m)):!1);if(c)return{id:c.id,label:c.label,url:Ue(Ha(c))||Ha(c)};if(t&&$i(t,s))return{id:Bs,label:"Local",url:n};const l=e.find(m=>t?$i(t,m.url):!1);if(l)return{id:l.id,label:l.label,url:Ue(l.url)||l.url};const d=t.startsWith("openchamber-ui://");if(d&&s&&!a)return{id:Bs,label:"Local",url:n};const u=a?Ue(a)||a:d?"":i;return{id:"custom",label:Km(u||"Instance"),url:u}},Lo=new Map;let Zm=0;const Kn=new Map,Ga=new Set;let Gc=0,Jm={byHostId:{},isProbing:!1};const _c=new Set,qo=()=>{Jm={byHostId:Object.fromEntries(Lo),isProbing:Gc>0};for(const e of _c)try{e()}catch{}},HE=e=>(_c.add(e),()=>{_c.delete(e)}),GE=()=>Jm,Qm=(e,t)=>{Lo.set(e,t),qo()},_E=(e,t)=>{Kn.set(e,++Zm),Ga.delete(e),Qm(e,t)},KE=e=>Ga.has(e),iv=e=>{const t=new Set([Bs,...e]);let s=!1;for(const a of Array.from(Lo.keys()))t.has(a)||(Lo.delete(a),Kn.delete(a),Ga.delete(a),s=!0);s&&qo()},ov=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",rv=async()=>ua()?_y().catch(()=>""):"",cv=async(e,t)=>{const s=e.id===Bs?t:e.clientToken||"",a=async()=>{const o=await Yy(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:o.status,latencyMs:o.latencyMs};return o.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return a();const n=Ue(ua()?Ha(e):e.url);if(!n)return{status:"unreachable",latencyMs:0};const i=await ir(n,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(ov(i.status)&&e.relay){const o=await a();if(o.status==="ok"||o.status==="relay-limit")return o}return{status:i.status,latencyMs:i.latencyMs}},lv=async e=>{if(!Ye())return;const t=++Zm;for(const s of e)Kn.set(s.id,t),Ga.add(s.id);Gc+=1,qo();try{const s=await rv();await Promise.all(e.map(async a=>{const n=await cv(a,s);Kn.get(a.id)===t&&(Ga.delete(a.id),Qm(a.id,n))}))}finally{for(const s of e)Kn.get(s.id)===t&&Ga.delete(s.id);Gc-=1,qo()}};let Rp=!1;const dv=async()=>{if(Rp||!Ye())return;Rp=!0;const e=await fi().catch(()=>null);e&&(iv(e.hosts.map(t=>t.id)),await lv(av(e.hosts,e.localOrigin)))},pv=5e3,gv=1500;let Mr=!1;const Er=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}},uv=async e=>{if(!ua()||Mr)return;const t=`host:${e}`;if(D()===t){Mr=!0;try{const s=await fi().catch(()=>null),a=s?.hosts.find(b=>b.id===e);if(!s||!a?.relay)return;const n=a.apiUrl?Ue(a.apiUrl):null;if(n&&n.startsWith("https://"))return;const i=await C("/api/client-auth/connection/candidates").catch(()=>null);if(!i?.ok)return;const o=await i.json().catch(()=>null);if(!o||o.serverId!==a.relay.serverId)return;const r=Array.isArray(o.candidates)?o.candidates:[],c=[];for(const b of r){if(!b||typeof b!="object")continue;const w=b;if(w.type!=="lan"||typeof w.url!="string")continue;const y=Ue(w.url);y&&!c.includes(y)&&c.push(y)}if(c.length===0)return;const l=n&&c.includes(n)?n:c[0],d=Er(l);d&&d!==Er(n)&&await Gy({hosts:s.hosts.map(b=>b.id===e?{...b,apiUrl:l}:b),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const m=(await fi().catch(()=>null))?.hosts.find(b=>b.id===e)??null;if(!m||!d||Er(m.apiUrl)!==d)return;const f=await ir(l,{clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,expectedServerId:a.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(f.status==="unreachable"||f.status==="wrong-service"||f.status==="incompatible"||D()!==t)return;qc({apiBaseUrl:l,clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,runtimeKey:t})}finally{Mr=!1}}},mv=e=>{typeof window>"u"||window.setTimeout(()=>{uv(e).catch(()=>{})},pv)},Ip=async(e,t)=>{if(!ua())return;const s=await fi().catch(()=>null);if(!s)return;const a=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!a)return;const n=s.hosts.find(m=>m.id===a);if(!n?.relay)return;const i=`host:${n.id}`;if(D()===i&&!t?.reconnectActive)return;const o=m=>{qc({apiBaseUrl:m,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:i})},r=()=>{qc({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:n.clientToken||null,runtimeKey:i,relay:n.relay??void 0}),mv(n.id)},c=n.apiUrl?Ue(Ha(n)):null;if(!c){r();return}const l=m=>m.status!=="unreachable"&&m.status!=="wrong-service"&&m.status!=="incompatible",d=ir(c,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),u=await Promise.race([d,new Promise(m=>setTimeout(()=>m(null),gv))]);if(u){if(l(u)){o(c);return}r();return}r(),d.then(m=>{l(m)&&D()===i&&o(c)})};class jp 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 hv=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class jt 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 fv=e=>e instanceof jt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),Zn=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"}},bv=g({message:p()}),ZE=e=>{if(fv(e)&&e.reason==="not-found")return!0;const t=bv.safeParse(e),a=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return a.includes("file not found")||a.includes("enoent")||a.includes("no such file")||a.includes("does not exist")},Gs=new Map;let Lr;async function Op(e){const t=ds().api("/api").replace(/\/api\/?$/,""),s=gn(),a=await Nm();if(D()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(i,o)=>{const r=i instanceof Request?i.url:String(i),c=r.startsWith("/")?`${t}${r}`:r,l=new Headers(i instanceof Request?i.headers:void 0);return new Headers(Mo(o?.headers)??o?.headers).forEach((d,u)=>l.set(u,d)),a.forEach((d,u)=>l.set(u,d)),s?s.fetch(i,{...o,headers:l}):(as(c,l),Hm(i instanceof Request?new Request(c,i):c,{...o,headers:l}))},baseUrl:t}}async function $m(e){const t=!!us()&&!gn(),s=await Op(e);return async a=>{let n=!1;const i=async()=>{if(!n){n=!0;try{const r=D()===e;if(!t&&!r)return;await a(r?await Op(e):s),Gs.get(e)?.delete(i),Gs.get(e)?.size===0&&Gs.delete(e),Gs.size===0&&(Lr?.(),Lr=void 0)}catch{}finally{n=!1}}},o=Gs.get(e)??new Set;o.add(i),Gs.set(e,o),Lr??=tr(({runtimeKey:r})=>{for(const c of Gs.get(r)??[])c()}),await i()}}const Vo=()=>({active:0,waiters:[],activeSessionWaiters:[]});let As=Vo(),oa=Vo();const wv=3,Dp=2;er(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[As,oa];As=Vo(),oa=Vo();for(const a of s){for(const n of[...a.activeSessionWaiters,...a.waiters])n(!1);a.activeSessionWaiters.length=0,a.waiters.length=0}});const Fp=()=>{for(;As.active+oa.active<wv;){const e=oa.active<Dp&&oa.waiters.length>0?oa:As.active<Dp&&(As.activeSessionWaiters.length>0||As.waiters.length>0)?As:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(!0)}};async function Ym(e,t,s){const a=gm();if(await new Promise(i=>{s==="active-session"?e.activeSessionWaiters.push(i):e.waiters.push(i),Fp()}))try{if(!a())return;const i=await t();return a()?i:void 0}finally{e.active-=1,Fp()}}const kv=(e,t="normal")=>Ym(As,e,t),JE=e=>Ym(oa,e,"normal"),Xm="/api/opencode/trust",yv="opencode_trust_required",vv=g({kind:I(["plugin","package","mcp","lsp","formatter","shell","config"]),source:p(),name:p(),detail:p()}),Cv=g({directory:p(),trusted:T(),fingerprint:p().nullable(),items:z(vv)}),Sv=g({code:k(yv),directory:p()});let ca=null;const Kc=new Set,Nn=new Map,bi=new Set;let Zc=Promise.resolve(),Rs=0;const qr=()=>{for(const e of Kc)e()},QE=()=>ca,$E=e=>(Kc.add(e),()=>{Kc.delete(e)}),YE=e=>ca?ca.settle(e):Promise.resolve("skipped");er(()=>{Rs+=1,ca?.settle("skip"),Nn.clear(),bi.clear(),Zc=Promise.resolve()});const xv=()=>{bi.clear()},Pv=async e=>{if(e.status!==403)return null;try{const t=Sv.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},eh=async e=>Cv.parse(await e.json()),Vr=async e=>{const t=await C(Xm,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return eh(t)},Tv=async e=>{const t=await C(Xm,{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 eh(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},zv=(e,t)=>new Promise(s=>{const a=n=>{if(t!==Rs){s(!1);return}ca={directory:n.directory,items:n.items,settle:async i=>{if(i==="skip")return bi.add(`${n.directory}
|
|
3
3
|
${n.fingerprint}`),ca=null,qr(),s(!1),"skipped";let o;try{o=await Tv(n)}catch(r){return console.warn("[opencode-trust] Failed to save the answer:",r),"failed"}return t!==Rs?"skipped":o.kind==="changed"?(a(o.assessment),"changed"):(ca=null,qr(),s(!0),"saved")}},qr()};a(e)}),Av=(e,{deliberate:t,background:s=!1,throwOnError:a=!1})=>{const n=c=>a?c:c.catch(l=>(console.warn("[opencode-trust] Could not check the folder:",l),!1)),i=Nn.get(e);if(i)return n(i);const o=Rs,r=(async()=>{const c=await(s?kv(()=>o===Rs?Vr(e):Promise.resolve(null)):Vr(e));if(!c||o!==Rs)return!1;if(c.trusted)return!0;if(!t&&bi.has(`${c.directory}
|
|
4
4
|
${c.fingerprint}`))return!1;const l=Zc.then(async()=>{if(o!==Rs)return!1;const d=await Vr(e);return o!==Rs?!1:d.trusted?!0:!t&&bi.has(`${d.directory}
|
|
5
5
|
${d.fingerprint}`)?!1:zv(d,o)});return Zc=l.catch(()=>{}),l})().finally(()=>{Nn.get(e)===r&&Nn.delete(e)});return Nn.set(e,r),n(r)},Rv=/\/api\/(?:session|(?:experimental\/)?session\/[^/]+\/(?:prompt|command|shell|skill|move))$/,Iv=(e,t)=>e==="POST"&&Rv.test(t.replace(/\/+$/,"")),oe="/api/openchamber/spaces",mn=p().regex(/^[0-9a-f]{12}$/),rd=g({title:p().min(1).max(120),by:I(["user","agent"])}),ha=g({code:p(),message:p()}),Jn=g({count:v().int().min(0),paths:z(p())}),jv=g({path:p().optional(),other:p().nullable().optional(),branch:p().optional(),stillThere:Jn.optional(),ignoredInTheWay:Jn.optional(),filteredInTheWay:Jn.optional(),tooLarge:z(p()).optional(),failed:v().int().min(0).optional()});class Ur extends Error{code;status;details;constructor(t,s,a,n={}){super(s),this.name="SpacesRequestError",this.code=t,this.status=a,this.details=n}}const Ov=g({id:mn,name:p(),state:p()}),Dv=ve("enabled",[g({enabled:k(!1)}),g({enabled:k(!0),spaces:z(Ov).nullable(),failure:ha.optional()})]),Fv=g({id:mn,name:p(),code:p(),message:p()}),Bv=g({enabled:T(),stopped:z(g({id:mn,name:p()})),stillRunning:z(Fv),unknown:ha.optional()}),th=g({mode:I(["allowlist","open"]),domains:z(p())}),sh=ve("kind",[g({kind:k("model"),id:p(),provider:p(),upstream:p(),source:ve("kind",[g({kind:k("typed")}),g({kind:k("env"),name:p()})]),url:p()}),g({kind:k("login"),id:p(),provider:p(),method:p(),url:p()}),g({kind:k("custom"),id:p(),provider:p(),url:p()}),g({kind:k("domain"),id:p(),upstream:p(),url:p()})]),XE=(e,t)=>e.find(s=>(s.kind==="model"||s.kind==="login"||s.kind==="custom")&&s.provider===t),Nv=["checking_place","creating","downloading_image","preparing_tools","setting_network","bringing_code","giving_access","ready"],Mv=I(Nv),ah=ve("state",[g({state:k("queued"),total:v().int().min(1)}),g({state:k("running"),index:v().int().min(0),total:v().int().min(1),command:p()}),g({state:k("done"),total:v().int().min(1)}),g({state:k("failed"),index:v().int().min(0),total:v().int().min(1),command:p(),exitCode:v().int().nullable(),timedOut:T(),startedAt:p().nullable().default(null),finishedAt:p().nullable().default(null)}),g({state:k("interrupted"),total:v().int().min(1)})]),fa=g({id:mn,name:p(),taskTitle:rd.nullish(),placeId:p(),machine:p().nullable().default(null),projectDirectory:p().nullable(),directory:p().nullable(),projectFolder:g({path:p().nullable(),found:T().nullable()}).default({path:null,found:null}),state:I(["preparing","running","exited","missing","failed","unreachable"]),stoppedIdle:T().default(!1),step:J([Mv,k("failed")]).nullable(),failure:ha.nullable(),network:th.nullable(),grants:z(sh),access:I(["granted","needs_access","unknown"]).nullable(),needsAccess:z(p()),accessFailures:z(g({provider:p(),code:p(),message:p()})).default([]),damage:I(["repairable","gatekeeper_gone"]).nullable().default(null),setup:ah.nullable().default(null)}),nh=["install_all","install_cli","start_colima","start_desktop"],Ev=[...nh,"get_brew","linux_install","linux_start","permission","windows_install","windows_start"],cd=g({action:I(nh),running:T(),failure:ha.extend({output:p().default("")}).nullable()}),Bp=g({remedy:I(Ev).nullable().catch(null),job:cd.nullable(),memory:g({bytes:v().min(0),engine:I(["colima","docker_desktop","other"]).catch("other"),low:T()}).nullable()}).nullable().default(null),ih=J([g({id:p(),machine:p().nullable().default(null),available:k(!0),hostIsolation:T(),version:p().default(""),setup:Bp}),g({id:p(),machine:p().nullable().default(null),available:k(!1),code:p(),message:p(),setup:Bp})]),eL="docker-ssh",Lv=g({provider:p(),method:p(),expires:p().nullable(),state:I(["usable","expired","unsupported"])}),qv=g({id:p(),name:p(),package:p(),baseURL:p().nullable(),loopback:T(),models:z(p()),hasKey:T(),supported:T()}),Vv=g({code:p(),message:p(),details:jv.nullable().optional().catch(null)}),re=async(e,t,s={})=>{const a=await C(e,{...s,headers:s.body===void 0?s.headers:{"Content-Type":"application/json",...s.headers}}),n=await a.json().catch(()=>null);if(!a.ok){const o=Vv.safeParse(n);throw o.success?new Ur(o.data.code,o.data.message,a.status,o.data.details??{}):new Ur("space_request_failed",`The server answered ${a.status}.`,a.status)}const i=t.safeParse(n);if(!i.success)throw new Ur("space_answer_malformed","The server answered in a shape this version does not know.",a.status);return i.data},Uv=e=>e.enabled?e.spaces!==null?{enabled:!0,spaces:e.spaces}:{enabled:!0,spaces:null,failure:e.failure??{code:"space_journey_failed",message:""}}:{enabled:!1},tL=async e=>Uv(await re(`${oe}/switch`,Dv,{signal:e})),sL=e=>re(`${oe}/switch`,Bv,{method:"PUT",body:JSON.stringify({enabled:e})}),aL=async e=>(await re(`${oe}/places`,g({places:z(ih)}),{signal:e})).places,nL=async e=>(await re(`${oe}/machine`,g({place:ih.nullable()}),{method:"PUT",body:JSON.stringify({machine:e})})).place,ld=g({imageBytes:v().min(0).nullable(),imagePulling:T().default(!1),imageFailure:ha.nullable().default(null),toolsBytes:v().min(0),spacesBytes:v().min(0),bytesBySpace:kt(p(),v().min(0)).default({}),freeBytes:v().min(0),freesImage:T()}),Wv=g({freedBytes:v().min(0),kept:z(g({kind:p(),reason:I(["in_use","failed"])})),disk:ld}),iL=(e,t)=>re(`${oe}/places/${encodeURIComponent(e)}/disk`,ld,{signal:t}),oL=e=>re(`${oe}/places/${encodeURIComponent(e)}/clean-up`,Wv,{method:"POST"}),rL=async e=>(await re(`${oe}/places/local/setup`,g({job:cd.nullable()}),{signal:e})).job,cL=async e=>(await re(`${oe}/places/local/setup`,g({job:cd.nullable()}),{method:"POST",body:JSON.stringify({action:e})})).job,lL=e=>re(`${oe}/places/${encodeURIComponent(e)}/image`,ld,{method:"POST"}),Hv=async e=>(await re(oe,g({spaces:z(fa)}),{signal:e})).spaces,dL=e=>re(oe,fa,{method:"POST",body:JSON.stringify(e)}),pL=async e=>(await re(`${oe}/logins`,g({logins:z(Lv)}),{signal:e})).logins,Gv=async(e,t)=>(await re(`${oe}/custom-providers?directory=${encodeURIComponent(e)}`,g({providers:z(qv)}),{signal:t})).providers,gL=async(e,t)=>(await re(`${oe}/${e}/grants`,g({grant:sh}),{method:"POST",body:JSON.stringify(t)})).grant,uL=async(e,t)=>(await re(`${oe}/${e}/network/domains`,g({network:th}),{method:"POST",body:JSON.stringify({domain:t})})).network,_v=g({at:p(),listener:p(),host:p(),port:v(),decision:p()}),Kv=g({records:z(_v),dropped:v(),since:p()}),mL=(e,t)=>re(`${oe}/${e}/journal`,Kv,{signal:t}),Zv=g({saved:v().int().min(0)}),oh=g({id:mn,removed:T(),failures:z(ha),chats:Zv.nullable().default(null)}),hL=e=>re(`${oe}/${e}/start`,fa,{method:"POST"}),fL=async(e,t)=>{await re(`${oe}/${e}/task-title`,g({applied:T(),taskTitle:rd.nullable()}),{method:"PUT",body:JSON.stringify({title:t})})},bL=e=>re(`${oe}/${e}/stop`,fa,{method:"POST"}),wL=e=>re(`${oe}/${e}/restart`,fa,{method:"POST"}),kL=e=>re(`${oe}/${e}/restart-opencode`,fa,{method:"POST"}),Jv=1,Qv=168,rh=g({enabled:T(),hours:v().int().min(Jv).max(Qv)}),yL=e=>re(`${oe}/idle-stop`,rh,{signal:e}),vL=e=>re(`${oe}/idle-stop`,rh,{method:"PUT",body:JSON.stringify(e)}),CL=(e,t)=>re(`${oe}/${e}/setup`,fa,{method:"POST",body:JSON.stringify({commands:t})}),$v=g({setup:ah.nullable(),output:p().nullable()}),SL=(e,t)=>re(`${oe}/${e}/setup`,$v,{signal:t}),xL=(e,{deleteUnsavedChats:t=!1}={})=>re(`${oe}/${e}${t?"?unsavedChats=delete":""}`,oh,{method:"DELETE"}),Yv=g({spaceId:mn,name:p(),directory:p()}),PL=async e=>(await re(`${oe}/archives`,g({archives:z(Yv)}),{signal:e})).archives,Xv=g({changedPaths:v().int().min(0),changedBytes:v().min(0),nestedRepositories:Jn,unmerged:Jn,changesRoute:I(["open","closed"]),lastApplied:p().nullable(),newPaths:v().int().min(0).nullable(),newPathsUndecided:T().default(!1)}),eC=J([g({status:k("applied"),branch:p()}),g({status:k("applied"),appliedPaths:v().int().min(0)}),g({status:k("nothing_to_apply")})]),tC=g({applied:eC,removal:oh.nullable(),kept:ha.nullable().default(null)}),TL=(e,t)=>re(`${oe}/${e}/apply`,Xv,{signal:t}),zL=(e,t)=>re(`${oe}/${e}/apply`,tC,{method:"POST",body:JSON.stringify(t)}),ch=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,Np=/^(?:\/\/\?\/)?[A-Za-z]:$/u,sC=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/UNC\/[^/]+\/[^/]+)$/iu,ze=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const s=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,i)=>i.toUpperCase()+":");return s==="/"?"/":ch.test(s)?s.replace(/\/+$/u,"/"):(s.length>1?s.replace(/\/+$/,""):s)||null},aC=e=>{if(e==="/"||ch.test(e)||Np.test(e)||sC.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const s=e.slice(0,t);return Np.test(s)?`${s}/`:s},nC=e=>ze(e)??"",iC=g({id:p().regex(/^[0-9a-f]{12}$/),name:p().default(""),taskTitle:rd.nullish(),state:I(["complete","partial","stale","unknown"]),projectDirectory:p().nullable().default(null),directory:p().nullable().default(null)}),Jc=new Map,Ca=new Map,oC=(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},Mp=(e,t,s)=>{const a=e.get(t);if(!a||a.state===s)return e;const n=new Map(e);return n.set(t,{...a,state:s}),n},Xe=vt((e,t)=>({spaces:Jc,journey:null,progressRevision:0,applyJourney:(s,a)=>e(n=>{const i=new Map(s.map(o=>[o.id,o]));for(const[o,r]of Ca){const c=n.journey?.get(o);r>a&&c&&i.set(o,c)}return{journey:i}}),addJourneyEntry:s=>e(a=>{const n=a.progressRevision+1;Ca.set(s.id,n);const i=new Map(a.journey??[]);return i.set(s.id,s),{journey:i,progressRevision:n}}),noteTaskTitle:(s,a)=>{const n=t(),i=n.journey?.get(s),o=n.spaces.get(s),r=n.progressRevision+1;Ca.set(s,r);const c=i?new Map(n.journey).set(s,{...i,taskTitle:a}):n.journey,l=o?new Map(n.spaces).set(s,{...o,taskTitle:a}):n.spaces;return e({journey:c,spaces:l,progressRevision:r}),!!i},noteGrantGiven:(s,a)=>e(n=>{const i=n.journey?.get(s);if(!i)return n;const o=n.progressRevision+1;Ca.set(s,o);const r=new Map(n.journey);return r.set(s,{...i,grants:[...i.grants.filter(c=>c.id!==a.id),a],needsAccess:i.needsAccess.filter(c=>c!==a.id),accessFailures:a.kind==="domain"?i.accessFailures:i.accessFailures.filter(c=>c.provider!==a.provider)}),{journey:r,progressRevision:o}}),customProviders:new Map,noteCustomProviders:(s,a)=>e(n=>{const i=new Map(n.customProviders);return i.set(s,a),{customProviders:i}}),accessDialog:null,openAccessDialog:(s,a=null)=>e({accessDialog:{spaceId:s,providerId:a}}),closeAccessDialog:()=>e({accessDialog:null}),actions:new Map,noteAction:(s,a)=>e(n=>{const i=new Map(n.actions);return a?i.set(s,a):i.delete(s),{actions:i}}),applyDialog:null,openApplyDialog:s=>e({applyDialog:s}),closeApplyDialog:()=>e({applyDialog:null}),deleteDialog:null,deleteUnsaved:null,openDeleteDialog:(s,a=null)=>e({deleteDialog:s,deleteUnsaved:a}),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 a=t().progressRevision+1;Ca.set(s.spaceId,a);const n=t().journey?.get(s.spaceId);if(!n)return e({progressRevision:a}),!1;const i=new Map(t().journey);return i.set(s.spaceId,oC(n,s)),e({journey:i,progressRevision:a}),!0},applyMarks:s=>e(a=>{const n=new Map(s.map(i=>[i.id,i]));return n.size===0&&a.spaces.size===0?a:{spaces:n}}),noteStream:(s,a)=>e(n=>a==="connected"?n:{spaces:Mp(n.spaces,s,"stale")}),noteReachable:s=>e(a=>({spaces:Mp(a.spaces,s,"complete")})),resetForRuntimeSwitch:()=>{Ca.clear(),sn+=1,e({spaces:Jc,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 sn=0;const AL=()=>sn,rC=async()=>{const e=sn,t=Xe.getState().progressRevision,s=await Hv();if(e===sn){Xe.getState().applyJourney(s,t);for(const a of new Set(s.flatMap(n=>n.projectDirectory?[n.projectDirectory]:[])))Xe.getState().customProviders.has(a)||cC(a)}},Wr=new Map,cC=e=>{const t=Wr.get(e);if(t)return t;const s=sn,a=Gv(e).then(n=>{s===sn&&Xe.getState().noteCustomProviders(e,n)}).catch(()=>{}).finally(()=>{Wr.delete(e)});return Wr.set(e,a),a},lC=e=>Xe.getState().spaces.get(e)??null,lh=e=>e?.state==="exited"||e?.state==="missing"||e?.state==="unreachable",dC=e=>lh(Xe.getState().journey?.get(e)),dh=e=>e?.state==="failed"||e?.state==="missing"||e?.state==="unreachable",RL=e=>{const t=Mt.c(2);let s;return t[0]!==e?(s=a=>e!=null&&dh(a.journey?.get(e)),t[0]=e,t[1]=s):s=t[1],Xe(s)},IL=e=>{const t=yt(e);return t!==null&&dh(Xe.getState().journey?.get(t))},ph=(e,t)=>{const s=yt(t);return s===null?null:e.spaces.get(s)?.projectDirectory??e.journey?.get(s)?.projectDirectory??null},jL=e=>ph(Xe.getState(),e),OL=e=>{const t=Mt.c(2);let s;return t[0]!==e?(s=a=>ph(a,e),t[0]=e,t[1]=s):s=t[1],Xe(s)},DL=e=>{const t=yt(e);return t!==null&&dC(t)},pC=e=>new Set([...e.spaces.keys(),...e.journey?.keys()??[]]),FL=e=>{const t=yt(e);return t===null||pC(Xe.getState()).has(t)},BL=(e,t)=>Array.from(e).filter(s=>!t.has(s)),NL=e=>{const t=Mt.c(4);let s;t[0]!==e?(s=yt(e),t[0]=e,t[1]=s):s=t[1];const a=s;let n;return t[2]!==a?(n=i=>a!==null&&lh(i.journey?.get(a)),t[2]=a,t[3]=n):n=t[3],Xe(n)},gC=(e,t)=>{const s=Array.from(e.values(),a=>{const n=t?.get(a.id);return n?{...a,taskTitle:n.taskTitle??null}:a});for(const a of t?.values()??[])e.has(a.id)||a.projectDirectory===null||a.directory===null||s.push({id:a.id,name:a.name,taskTitle:a.taskTitle??null,state:"complete",projectDirectory:a.projectDirectory,directory:a.directory});return s},ML=e=>{const t=Mt.c(7),s=e===void 0?!0:e;let a;t[0]!==s?(a=c=>s?c.spaces:Jc,t[0]=s,t[1]=a):a=t[1];const n=Xe(a);let i;t[2]!==s?(i=c=>s?c.journey:null,t[2]=s,t[3]=i):i=t[3];const o=Xe(i);let r;return t[4]!==o||t[5]!==n?(r=gC(n,o),t[4]=o,t[5]=n,t[6]=r):r=t[6],r},EL=(e,t)=>{const s=ze(t);return Array.from(e.values()).filter(a=>s!==null&&ze(a.projectDirectory)===s)},LL=e=>Array.from(e.values()).filter(t=>t.projectDirectory===null),qL=()=>{const e=Mt.c(5),t=Xe(uC),[s,a]=Qa.useState(null);let n,i;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{let r=!0;return rC().then(()=>{r&&a(null)},c=>{r&&a(c)}),()=>{r=!1}},i=[],e[0]=n,e[1]=i):(n=e[0],i=e[1]),Qa.useEffect(n,i);let o;return e[2]!==s||e[3]!==t?(o={journey:t,error:s},e[2]=s,e[3]=t,e[4]=o):o=e[4],o};function uC(e){return e.journey}const Ep=500,gh=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("OPENCHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},VL=()=>gh(),It=(e,t)=>{if(!gh())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>Ep&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Ep)},mC=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(a=>a.name==="ModelControls:ready"),s=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,s).filter(a=>a.name.includes("checkConnection")||a.name.includes("checkHealth")||a.name.includes("initializeApp")||a.name.includes("initApp")||a.name.includes("loadProviders")||a.name.includes("loadAgents")||a.name.includes("config.defaults")||a.name.includes("modelsMetadata")||a.name.includes("ModelControls")||a.name.includes("activateDirectory")||a.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=mC);const UL=async(e,t,s)=>{const a=typeof performance<"u"?performance.now():Date.now();It(`${e}:start`,s);try{const n=await t(),i=typeof performance<"u"?performance.now():Date.now();return It(`${e}:end`,{durationMs:Math.round(i-a)}),n}catch(n){const i=typeof performance<"u"?performance.now():Date.now();throw It(`${e}:error`,{durationMs:Math.round(i-a),error:n instanceof Error?n.message:String(n)}),n}},hC=3,fC=3e4,bC=32e3,wC=3600*1e3,kC=600*1e3,yC=200,vC=new Set([429,502,503,504]),os=new Map,dd=e=>JSON.stringify([D(),e]);function CC(){const e=Date.now();for(const[t,s]of os){const a=Math.max(s.lastErrorAt,s.circuitOpenAt);e-a>wC&&os.delete(t)}}typeof setInterval<"u"&&setInterval(CC,kC).unref?.();function SC(e){const t=dd(e);let s=os.get(t);if(!s)for(s={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:fC},os.set(t,s);os.size>yC;){const a=os.keys().next().value;if(!a)break;os.delete(a)}return s}function xC(e){e&&os.delete(dd(e))}function PC(e,t){if(!e)return;const s=SC(e);s.consecutiveErrors+=1,s.lastErrorAt=Date.now(),TC(t)&&s.consecutiveErrors>=hC&&(s.circuitOpen=!0,s.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${s.consecutiveErrors} consecutive errors`))}function TC(e){return e!==void 0&&vC.has(e)}function zC(e){const t=os.get(dd(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,bC*4),!1):!0:!1}function AC(e){if(!(!e||!zC(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}function Hr({providerID:e,id:t,variant:s}){return s?{providerID:e,id:t,variant:s}:{providerID:e,id:t}}function WL(e,t){return e.providerID===t.providerID&&e.id===t.id&&(e.variant??"default")===(t.variant??"default")}function HL(e,t){if(!(!e||!t))return e.find(s=>s.id===t)??e.find(s=>s.modelID===t)}function X(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const _a={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}`},GL=e=>e==="completed"||e==="error",uh=e=>e.role==="user"||e.role==="assistant",_L=e=>e==="user"||e==="assistant",KL=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s&&uh(s))return s}},ZL=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s?.info&&uh(s.info))return s}},JL=e=>e?.role==="assistant"&&e.time.completed===void 0,E={edit:"edit",execute:"execute",glob:"glob",grep:"grep",patch:"patch",question:"question",read:"read",shell:"shell",skill:"skill",subagent:"subagent",webfetch:"webfetch",websearch:"websearch",write:"write",sessionRename:"session_rename",sessionMove:"session_move",models:"models"};function et(e){const t=e?.trim().toLowerCase();if(!t)return"";const s=t.replace(/:\d+$/,"");if(!s.includes("."))return s;const a=s.split(".").filter(Boolean);return a[a.length-1]??s}const qs=e=>t=>et(t)===e,RC=qs(E.shell),QL=qs(E.execute),pd=qs(E.subagent),$L=qs(E.question),YL=qs(E.skill),XL=qs(E.edit),eq=qs(E.write),tq=qs(E.patch),IC=new Set([E.read,E.skill]),jC=e=>IC.has(et(e)),OC=new Set([E.edit,E.write,E.patch]),DC=new Set([E.read,E.grep,E.glob,E.skill]),FC=new Set([E.webfetch,E.websearch]),sq=e=>OC.has(et(e)),aq=e=>{const t=et(e);return t===E.edit||t===E.patch},nq=e=>DC.has(et(e)),iq=e=>FC.has(et(e)),oq=e=>et(e)===E.websearch,q=p().trim().min(1).optional().catch(void 0),Lp=v().int().nonnegative().optional().catch(void 0),Qc=J([T(),I(["true","false"]).transform(e=>e==="true")]).optional().catch(void 0),BC=g({path:q,filePath:q,file_path:q,command:q,description:q,agent:q,name:q,id:q,server:q,uri:q,prompt:q,title:q,directory:q,search:q,provider:q,patchText:q,pattern:q,query:q,url:q,code:q,questions:z(ee()).optional().catch(void 0),action:q,parameters:g({title:q,name:q,prompt:q,path:q,url:q,query:q,text:q,selector:q,taskId:q,providerId:q,body:q,link:g({identifier:q,title:q}).optional().catch(void 0)}).optional().catch(void 0)}).catch({}),NC=g({file:q,patch:q,additions:Lp,deletions:Lp,status:I(["added","deleted","modified"]).optional().catch(void 0)}),MC=g({tool:q,status:q,input:ci().optional().catch(void 0)}),hn=g({files:z(NC.nullable().catch(null)).optional().catch(void 0),sessionID:q,sessionId:q,shellID:q,status:q,name:q,toolCalls:z(MC.nullable().catch(null)).optional().catch(void 0),truncated:T().optional().catch(void 0),outputPath:q}).catch({}),ba=e=>BC.parse(e??{}),qp=g({html:p().optional().catch(void 0),ui:p().optional().catch(void 0),title:q,awaitAnswer:Qc}),EC=qp.extend({parameters:qp.optional().catch(void 0)}).catch({}),LC=J([g({answered:k(!0),summary:p(),data:ci().catch(null)}),g({answered:k(!1),reason:p().optional().catch(void 0)})]),qC=g({openchamber:g({ok:T().optional().catch(void 0),answer:LC.optional().catch(void 0)}).optional().catch(void 0)}).catch({});function VC(e){const t=ba(e);return t.path??t.filePath??t.file_path}function $c(e){return(hn.parse(e??{}).files??[]).filter(s=>s!==null&&s.file!==void 0)}const Vp=160;function rq(e){const t=hn.parse(e??{});return t.shellID||t.status==="running"&&(t.sessionID||t.sessionId)?!0:(t.toolCalls??[]).some(s=>s?.status==="running"&&(RC(s.tool)||pd(s.tool)))}function mh(e){const t=hn.parse(e??{}).toolCalls??[],s=[];for(const a of t){if(!a?.tool)continue;const n={tool:a.tool},i=kh(a.tool,a.input)?.action;i&&(n.action=i),a.status&&(n.status=a.status);const o=UC(a.input);o&&o!=="{}"&&o!=="null"&&(n.input=o.length>Vp?`${o.slice(0,Vp)}…`:o),s.push(n)}return s}const hh=g({toolCalls:z(g({tool:q,status:q,input:ci().optional().catch(void 0)}).nullable().catch(null)).optional().catch(void 0)}).catch({});function cq(e){const t=hh.parse(e??{}).toolCalls??[];for(let s=t.length-1;s>=0;s-=1){const a=t[s];if(a?.tool)return{tool:a.tool,input:a.input}}}function lq(e){const t=hh.parse(e??{}).toolCalls??[];if(t.length!==1||!t[0]?.tool)return;const{tool:s,input:a,status:n}=t[0],i=md(s),o=kh(s,a)?.tool??(i?`opencode.${i}`:void 0);if(o)return{tool:o,input:a&&typeof a=="object"&&!Array.isArray(a)?a:{},status:n}}function dq(e){const t=new Set(mh(e).map(({tool:a})=>{if(md(a))return"opencode";if(Ri.has(et(a)))return et(a);const n=a.indexOf(".");return n>0?a.slice(0,n).toLowerCase():""})),[s]=t;return t.size===1&&s?s:void 0}function UC(e){if(e!=null)try{return JSON.stringify(e)}catch{return}}function pq(e){const t=hn.parse(e??{});return t.truncated?t.outputPath?{outputPath:t.outputPath}:{}:null}function gq(e){return ba(e).code}const WC=e=>e===fh,HC={amp:"&",lt:"<",gt:">",quot:'"',"#39":"'",apos:"'",nbsp:" "},GC=120,Up=(e,t)=>(t.exec(e)?.[1]??"").replace(/<[^>]*>/g," ").replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g,(s,a)=>HC[a]).replace(/\s+/g," ").trim(),_C=e=>(Up(e,/<title\b[^>]*>([\s\S]*?)<\/title>/i)||Up(e,/<h[1-3]\b[^>]*>([\s\S]*?)<\/h[1-3]>/i)).slice(0,GC).trim();function KC(e,t){if(!WC(e))return null;const s=EC.parse(t.input??{}),a=s.parameters?.html??s.html??"",n=s.parameters?.ui??s.ui,i=n?.trim()?{html:"",ui:n}:a.trim()?{html:a}:null;if(!i)return null;const o=(s.parameters?.title??s.title)?.trim()||_C(a);if((s.parameters?.awaitAnswer??s.awaitAnswer)===!0){if(t.status==="running")return{...i,title:o,ask:{kind:"waiting"}};if(t.status==="error")return{...i,title:o,ask:{kind:"unanswered"}}}if(t.status!=="completed")return null;const r=qC.parse(t.metadata??{}).openchamber;if(r?.ok!==!0)return null;const c=r.answer;if(c?.answered===!0)return{...i,title:o,ask:{kind:"answered",summary:c.summary,data:c.data}};if(c?.answered===!1){const l=c.reason==="chat-sent-earlier"?"chat-sent-earlier":c.reason==="ui-not-drawn"?"not-drawn":c.reason==="declined"?"declined":"answered-in-chat";return{...i,title:o,ask:{kind:l}}}return{...i,title:o,ask:{kind:"show"}}}const Wp=g({label:q,reason:q,placeholder:q}),ZC=Wp.extend({parameters:Wp.optional().catch(void 0)}).catch({}),JC=g({openchamber:g({ok:T().optional().catch(void 0),answer:J([g({status:I(["saved","declined"])}).transform(({status:e})=>e),g({answered:k(!1)}).transform(()=>"not-given")]).optional().catch(void 0)}).optional().catch(void 0)}).catch({});function QC(e,t){if(e!==ud)return null;const s=ZC.parse(t.input??{}),a=s.parameters?.label??s.label,n=s.parameters?.reason??s.reason;if(!a||!n)return null;const i={label:a,reason:n,placeholder:s.parameters?.placeholder??s.placeholder};if(t.status==="running")return{...i,state:"waiting"};if(t.status==="error")return{...i,state:"not-given"};if(t.status!=="completed")return null;const o=JC.parse(t.metadata??{}).openchamber;return o?.ok!==!0||!o.answer?null:{...i,state:o.answer}}function uq(e){return ba(e).agent}function mq(e){return ba(e).description}function $C(e){const t=hn.parse(e??{});return t.sessionID??t.sessionId}const gd=100,YC=4,XC=120,fh="openchamber_render",ud="openchamber_secret",bh="openchamber_workflow",wh="openchamber_image",Ri=new Set(["openchamber","openchamber_schedule","openchamber_web","openchamber_memory","openchamber_knowledge","openchamber_notify","openchamber_usage",fh,wh,ud,bh]),hq=e=>Ri.has(et(e)),eS=g({ok:k(!0),action:k("workflow.run"),data:g({runId:p().min(1)})});function tS(e,t){if(e!==bh||t.status!=="completed")return null;let s;try{s=JSON.parse(t.output)}catch{return null}const a=eS.safeParse(s);return a.success?a.data.data.runId:null}const sS=g({ok:k(!0),action:k("image.generate"),data:g({images:z(g({path:p().min(1)})).min(1)})});function aS(e,t){if(e!==wh||t.status!=="completed")return[];let s;try{s=JSON.parse(t.output)}catch{return[]}const a=sS.safeParse(s);return a.success?a.data.data.images.map(n=>n.path):[]}const fq=(e,t)=>KC(e,t)!==null||tS(e,t)!==null||aS(e,t).length>0||QC(e,t)!==null,nS=g({action:q,awaitAnswer:Qc,parameters:g({awaitAnswer:Qc}).optional().catch(void 0)}).catch({}),iS=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"]),Hp="opencode_";function md(e){const t=e?.trim().toLowerCase()??"",s=t.startsWith(Hp)?t.slice(Hp.length):et(t);return iS.has(s)?s:void 0}function bq(e,t){const s=e?.trim()??"";let a;for(const n of t){const i=`${n.replace(/[^a-zA-Z0-9_-]/g,"_")}_`;s.length>i.length&&s.startsWith(i)&&n.length>(a?.length??0)&&(a=n)}return a}function kh(e,t){const s=et(e);if(!Ri.has(s))return null;const a=nS.parse(t??{}),n=s===ud||(a.parameters?.awaitAnswer??a.awaitAnswer)===!0;return{tool:s,action:a.action,awaitsAnswer:n}}function yh(e){const t=e.parameters,s=t?.link;return(s?[s.identifier,s.title].filter(Boolean).join(" "):void 0)||t?.title||t?.name||t?.path||t?.url||t?.query||t?.text||t?.selector||t?.prompt?.split(`
|
|
@@ -31,7 +31,7 @@ A new session could conflict with them. You may want to commit them first or use
|
|
|
31
31
|
|
|
32
32
|
Skip creates the worktree without running them. You can run them yourself after reading the code.`,"session.newWorktree.toast.worktreeCreated":"Worktree created","session.newWorktree.toast.worktreeCreatedDescription":"{target} - bootstrapping in background","session.newWorktree.toast.fetchSourceFailed":"Couldn't fetch from remote — created from local state","session.newWorktree.toast.fetchSourceAccess":"Couldn't fetch: this repository's access needs attention in Configure repository. Created from local state.","session.newWorktree.toast.startFolderMissing":'This worktree has no "{folder}" folder, so OpenCode started at the worktree root.',"session.newWorktree.toast.startFolderUnverified":`Couldn't check the "{folder}" folder, so OpenCode started at the worktree root.`,"session.newWorktree.toast.startFolderUnknown":"Couldn't tell which folder of the repository this project opens, so OpenCode started at the worktree root.","session.newWorktree.toast.branchBackup":"{branch} now matches the remote. Its previous commits are kept in {backup}.","session.githubIntegration.tabs.pullRequests":"Pull Requests","session.githubIntegration.validation.branchAlreadyCheckedOut":"Branch is already checked out in a worktree","session.githubIntegration.validation.failed":"Validation failed","chat.fileAttachment.toast.attachFailed":"Failed to attach file","chat.fileAttachment.toast.tooLarge":"{name} is too large to attach (over {size}). Mention it with @ if it is in the project.","chat.fileAttachment.toast.overSendLimit":"{name} is too large to attach (over {size}).","chat.fileAttachment.toast.someFilesSkipped":`Some files were skipped:
|
|
33
33
|
{summary}`,"chat.fileAttachment.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.fileAttachment.fileFallback":"file","chat.fileAttachment.skippedFallback":"skipped","chat.fileAttachment.actions.attachAria":"Attach files","chat.fileAttachment.actions.attach":"Attach files","chat.fileAttachment.actions.removeNamed":"Remove {name}","chat.fileAttachment.actions.removeImage":"Remove image","chat.fileAttachment.activeEditor.addFile":"Add file:{name} to context","chat.fileAttachment.activeEditor.pinSelection":"Pin selection to context","chat.fileAttachment.activeEditor.remove":"Remove from context","chat.fileAttachment.openInDiagram":"Open in diagram view","chat.changedFiles.title":"Changed files","chat.changedFiles.actions.openFileTitle":"Open {path}","chat.changedFiles.actions.otherFiles":"Other changed files ({count})","chat.changedFiles.actions.showFewer":"Show fewer files","chat.emptyState.opencodeUnreachable":"OpenCode is not reachable","chat.emptyState.startNewChat":"Start a new chat","chat.emptyState.draftTitle":"What are we working on?","chat.emptyState.draftTitleWithProject":"What are we working on in {project}?","chat.draftPresets.explore.label":"Explore the codebase","chat.draftPresets.catchup.label":"Catch me up","chat.draftPresets.weigh.label":"Weigh my options","chat.draftPresets.plan.label":"Start feature planning","chat.draftPresets.craftGoal.label":"Craft a Goal","chat.draftPresets.scheduleTask.label":"Schedule a Task","chat.draftPresets.debug.label":"Debug an issue","chat.draftPresets.review.label":"Review my changes","chat.draftStarters.add":"Add a starter","chat.draftStarters.searchPlaceholder":"Search commands and skills…","chat.draftStarters.empty":"Nothing to add","chat.draftStarters.sectionBuiltIn":"Built-in","chat.draftStarters.sectionCommands":"Commands","chat.draftStarters.sectionSkills":"Skills","chat.draftStarters.remove":"Remove","chat.draftStarters.sharedTitle":"Pinned in the repository config; change it there","chat.draftStarters.share":"Move to repository config","chat.draftStarters.makePersonal":"Move to my settings","chat.scrollToBottom.aria":"Scroll to bottom","chat.promptNavigator.aria":"Prompt navigation","chat.promptNavigator.currentPrompt":"Current prompt","chat.promptNavigator.loadMore":"Load more prompts","chat.timeline.relative.justNow":"just now","chat.timeline.relative.minutesAgo":"{count}m ago","chat.timeline.relative.hoursAgo":"{count}h ago","chat.timeline.relative.daysAgo":"{count}d ago","chat.timeline.title":"Conversation Timeline","chat.timeline.description":"Navigate to any point in the conversation or fork a new session","chat.timeline.searchPlaceholder":"Search messages...","chat.timeline.empty.search":"No messages found","chat.timeline.empty.session":"No messages in this session yet","chat.timeline.noTextContent":"[No text content]","chat.timeline.actions.title":"Actions","chat.timeline.actions.revertFromHere":"Revert from here","chat.timeline.actions.forkFromHere":"Fork from here","chat.timeline.actions.previousTurn":"Previous turn","chat.timeline.actions.latest":"Latest","chat.timeline.help.clickMessage":"Click on a message to scroll to it in the conversation","chat.timeline.help.undoToPoint":"Undo to this point (message text will populate input)","chat.timeline.help.createSessionFromHere":"Create a new session starting from here","chat.statusRow.todo.status.inProgress":"In progress","chat.statusRow.todo.status.pending":"Pending","chat.statusRow.todo.status.completed":"Completed","chat.statusRow.todo.status.cancelled":"Cancelled","chat.statusRow.todo.priority.high":"High priority","chat.statusRow.todo.priority.medium":"Medium priority","chat.statusRow.todo.priority.low":"Low priority","chat.statusRow.actions.stopGeneratingAria":"Stop generating","chat.statusRow.tasksTitle":"Tasks","chat.statusRow.modelStatus":"{model} is {status}","chat.statusRow.summary.activeLeft":"{active} active · {left} left","chat.revertIndicator.redo":"Redo","chat.revertIndicator.redoAria":"Redo — restore reverted messages","chat.revertPopover.title":"Reverted","chat.revertPopover.noTextContent":"No text content","chat.revertPopover.forkFromHere":"Fork from here","chat.revertPopover.forkFromMessage":"Fork from this message","chat.revertPopover.restoreAll":"Restore all","chat.revertPopover.restore":"Restore","chat.revertPopover.revert":"Revert","chat.revert.toast.undo":"Reverted to {preview}","chat.revert.toast.redo":"Redone","chat.revert.toast.restored":"Restored all messages","chat.toast.opencodeRestartInterrupted.title":"Chat interrupted","chat.toast.opencodeRestartInterrupted.description":"OpenCode restarted while a response was still running. Send a message to continue.","chat.toast.opencodeRestartInterrupted.autoResumeDescription":"OpenCode restarted while a response was still running. The chat will resume automatically; send a message if it does not.","chat.toast.opencodeRestartInterrupted.openSession":"Open session","chat.errorBoundary.title":"Chat Error","chat.errorBoundary.description":"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.","chat.errorBoundary.sessionLabel":"Session","chat.errorBoundary.detailsSummary":"Error details","chat.errorBoundary.resetAction":"Reset Chat","chat.errorBoundary.persistentHint":"If the problem persists, try refreshing the page.","chat.autocomplete.tabs.commands":"Commands","chat.autocomplete.tabs.agents":"Agents","chat.autocomplete.tabs.files":"Files","chat.autocomplete.keyboardHint":"↑↓ navigate • Enter select • Esc close","chat.commandAutocomplete.command.initDescription":"Create/update AGENTS.md file","chat.commandAutocomplete.command.undoDescription":"Undo the last message","chat.commandAutocomplete.command.redoDescription":"Redo previously undone messages","chat.commandAutocomplete.command.timelineDescription":"Open the conversation timeline","chat.commandAutocomplete.command.compactDescription":"Compress session history using AI to reduce context size","chat.commandAutocomplete.command.summaryDescription":"Non-destructive session summary. Optional topic hint after the command.","chat.commandAutocomplete.command.workspaceReviewDescription":"Review the workspace diff for intent, correctness, and adequacy, graded by severity.","chat.commandAutocomplete.command.handoffReviewDescription":"Create or reuse a separate review session from a generated handoff.","chat.commandAutocomplete.command.featurePlanDescription":"Start a guided, back-and-forth planning session for a new feature.","chat.commandAutocomplete.command.craftGoalDescription":"Turn an idea or task into a clear, verifiable Goal.","chat.commandAutocomplete.command.scheduleTaskDescription":"Define a scheduled task through a guided dialogue.","chat.chatInput.toast.craftGoalFailed":"Failed to start Goal crafting","chat.chatInput.toast.scheduleTaskFailed":"Failed to start scheduled task setup","chat.commandAutocomplete.command.catchUpDescription":"Re-establish context: what you were doing and where to pick up.","chat.commandAutocomplete.command.debugDescription":"Guided root-cause investigation for a bug before proposing a fix.","chat.commandAutocomplete.command.weighDescription":"Weigh 2-3 approaches with trade-offs and a recommendation before you commit.","chat.commandAutocomplete.command.exploreDescription":"Get oriented in this codebase: a high-level tour of the architecture and main parts.","chat.commandAutocomplete.command.btwDescription":"Ask a side question in a temporary child session without derailing this chat.","chat.commandAutocomplete.command.forkDescription":"Fork this chat from the last finished reply and continue there; text after /fork is sent to the fork.","chat.commandAutocomplete.empty":"No commands found","chat.agentMentionAutocomplete.badge.system":"system","chat.agentMentionAutocomplete.empty":"No agents found","chat.fileMentionAutocomplete.searchMoreAgents":"Type to search more agents","chat.fileMentionAutocomplete.empty":"No matches found","chat.queuedMessage.attachments":"+{count} file(s)","chat.queuedMessage.empty":"(empty)","chat.queuedMessage.title":"Queued messages","chat.queuedMessage.edit":"edit","chat.queuedMessage.send":"send","chat.queuedMessage.removeAria":"Remove from queue","chat.queuedMessage.goal":"Starts a goal when sent","chat.queuedMessage.sendsAsAgent":"Sends as {agent}.","chat.queuedMessage.reorderAria":"Drag to reorder","chat.queuedMessage.toast.queueFailed":"Couldn't queue the message. It's back in the composer.","chat.queuedMessage.toast.takeFailed":"Couldn't load the queued message. Please try again.","chat.container.returnToParent.aria":"Return to parent session","chat.container.returnToParent.titleNamed":"Return to: {title}","chat.container.returnToParent.title":"Return to parent session","chat.container.returnToParent.label":"Parent","chat.container.readOnlySubagentPromptBanner":"Subagent sessions cannot be prompted.","chat.btw.destroyAria":"Destroy this btw session","chat.btw.titleFallback":"btw session","chat.btw.mainComposerPlaceholder":"Ask in this btw session…","chat.btw.loading":"Starting btw session…","chat.btw.toast.emptyArgument":"Type a question after /btw","chat.btw.toast.createFailed":"Failed to start the btw session","chat.btw.toast.destroyFailed":"Failed to destroy the btw session. It will remain in the sidebar.","chat.btw.working":"Working…","chat.btw.collapseAria":"Collapse the btw panel","chat.btw.draftHint":"Ask your question","chat.btw.cancelAria":"Cancel this BTW question","chat.btw.expandAria":"Expand the btw panel","chat.btw.promoteAria":"Keep as a separate session","chat.btw.toast.promoteFailed":"Failed to keep the btw session","chat.container.sessionLoadError.title":"Session could not be loaded","chat.container.sessionLoadError.description":"The conversation could not be fetched — the server may be offline or unreachable. Nothing is lost; retry once it is back.","chat.container.sessionLoadError.authDescription":"Your session expired, so the server refused the request. Log in and the conversation will load.","chat.container.sessionLoadError.retry":"Try again","sessions.sidebar.group.empty.loadingSessions":"Loading sessions…","sessions.sidebar.group.empty.loadFailed":"Could not refresh sessions.","sessions.sidebar.group.empty.initializationFailed":"Could not initialize workspace.","sessions.search.submitHint":"Press Enter to search","sessions.sidebar.group.empty.retry":"Try again","sessions.sidebar.group.empty.permissionDenied":"Folder access is required.","sessions.sidebar.group.empty.grantAccess":"Grant access","chat.unifiedControls.title":"Controls","chat.unifiedControls.model.title":"Model","chat.unifiedControls.model.noRecent":"No recent models","chat.unifiedControls.model.moreAria":"More models","chat.unifiedControls.effort.title":"Effort","chat.unifiedControls.effort.moreAria":"More effort options","chat.questionCard.summaryTab":"Summary","chat.questionCard.noAnswer":"(no answer)","chat.questionCard.inputNeeded":"Input needed","chat.questionCard.fromSubagent":"From subagent","chat.questionCard.questionFallback":"Question {index}","chat.questionCard.selectMultiple":"Select multiple","chat.questionCard.recommended":"recommended","chat.questionCard.other":"Other…","chat.questionCard.yourAnswer":"Your answer","chat.questionCard.submit":"Submit","chat.questionCard.next":"Next","chat.questionCard.dismiss":"Dismiss","chat.questionCard.copyMarkdown":"Copy as Markdown","chat.questionCard.copyJson":"Copy as JSON","chat.questionCard.copiedMarkdown":"Question copied as Markdown","chat.questionCard.copiedJson":"Question copied as JSON","chat.questionCard.copyFailed":"Failed to copy question","chat.questionCard.submitFailed":"Failed to send response","chat.questionCard.dismissFailed":"Failed to dismiss question","chat.questionCard.noLongerPending":"This question is no longer waiting for a response.","chat.questionCard.tryAgain":"Please try again in a moment.","chat.textSelection.toast.noProject":"No project found for this session","chat.textSelection.toast.addToNotesFailed":"Failed to add to notes","chat.textSelection.toast.addToNotesSuccess":"Added selected text to notes","chat.textSelection.toast.addToNotesSummaryFailed":"Could not summarize selection, added selected text to notes","chat.textSelection.actions.addToInput":"Quote","chat.textSelection.actions.read":"Read","chat.textSelection.actions.stopReading":"Stop","chat.textSelection.actions.comment":"Comment","chat.textSelection.actions.askOpenChamber":"By the way…","chat.textSelection.title.askOpenChamber":"Open a BTW draft with the selection","chat.textSelection.title.commentOnSelection":"Comment on selection","chat.textSelection.comment.placeholder":"Add an optional comment...","chat.textSelection.comment.attach":"Attach","chat.textSelection.comment.save":"Save comment","chat.textSelection.comment.attachFailed":"Could not attach the comment. Shorten it or remove other attached context, then try again.","chat.textSelection.actions.addToNotes":"Add to notes","chat.textSelection.title.addToCurrentChat":"Add to current chat","chat.textSelection.title.saveInsightToNotes":"Save selected text to notes","chat.messageBody.actions.revertAria":"Revert to this message","chat.messageBody.actions.revert":"Revert from here","chat.messageBody.actions.forkAria":"Fork from this message","chat.messageBody.actions.fork":"Fork from here","chat.messageBody.actions.copyMessageAria":"Copy message text","chat.messageBody.actions.copyMessage":"Copy message","chat.messageBody.actions.copyLink":"Copy link","chat.messageBody.toast.linkCopied":"Link copied","chat.messageBody.toast.linkCopyFailed":"Could not copy the link","chat.messageLink.notFound":"The linked message is not in this session","chat.messageBody.actions.pinContext":"Pin into context (survives compaction)","chat.messageBody.actions.unpinContext":"Unpin from context (will not survive compaction)","chat.messageBody.actions.contextPinFailed":"Could not update the context pin","chat.messageBody.actions.copyAnswer":"Copy answer","chat.messageBody.actions.moreActions":"More actions","chat.messageBody.toast.copied":"Copied to clipboard","chat.messageBody.actions.savingImage":"Saving image...","chat.messageBody.actions.saveAsImage":"Save as image","chat.messageBody.actions.saveAsPlan":"Save as plan","chat.messageBody.actions.startNewSession":"Start new session from this answer","chat.messageBody.actions.startNewMultiRun":"Start new multi-run from this answer","chat.messageBody.actions.branchMenu":"Continue from this answer","chat.messageBody.footer.reasoningTooltip":"Reasoning: {effort}","chat.messageBody.forkDialog.instructions.label":"Instructions","chat.messageBody.forkDialog.instructions.placeholder":"Add instructions for the new session…","chat.messageBody.forkDialog.createWorktree":"Create worktree","chat.generatedResult.actions.copy":"Copy","chat.generatedResult.actions.copied":"Copied","chat.generatedResult.commit.title":"Generated commit message","chat.generatedResult.commit.highlights":"Highlights","chat.generatedResult.pullRequest.title":"Generated pull request","chat.generatedResult.mergeRequest.title":"Generated merge request","chat.generatedResult.pullRequest.titleLabel":"Title","chat.generatedResult.pullRequest.bodyLabel":"Body","chat.messageBody.tts.stopSpeaking":"Stop speaking","chat.messageBody.tts.readAloud":"Read aloud","chat.messageBody.tts.readAloudWithProvider":"Read aloud ({provider} voice)","planView.tts.readAloud":"Read plan aloud","planView.tts.stopSpeaking":"Stop speaking","filesView.tts.readAloud":"Read file aloud","filesView.tts.stopSpeaking":"Stop speaking","chat.messageBody.toast.noProject":"No project found for this session","chat.messageBody.toast.savePlanFailed":"Failed to save plan","chat.messageBody.toast.planSaved":"Plan saved","chat.messageBody.toast.imageSaved":"Image saved","chat.messageBody.toast.generateImageFailed":"Failed to generate image","chat.chatInput.actions.commands":"Commands","chat.chatInput.actions.attachFiles":"Attach files","chat.chatInput.actions.addAttachment":"Add attachment","chat.chatInput.actions.modelAgentSettings":"Model and agent settings","chat.chatInput.actions.sendMessageAria":"Send message","chat.chatInput.actions.queueMessageAria":"Queue message","chat.chatInput.actions.stopGeneratingAria":"Stop generating","chat.chatInput.linked.byAuthor":"by {author}","chat.chatInput.linked.issue.openInBrowserAria":"Open issue in browser","chat.chatInput.linked.issue.removeAria":"Remove linked issue","chat.chatInput.linked.pr.openInBrowserAria":"Open pull request in browser","chat.chatInput.linked.mr.openInBrowserAria":"Open merge request in browser","chat.chatInput.linked.pr.removeAria":"Remove linked pull request","chat.chatInput.linked.mr.removeAria":"Remove linked merge request","chat.chatInput.placeholder.shell":"Enter shell command...","chat.chatInput.placeholder.chat":"Plan, build, or ask. @ to mention, $ for skills, / for commands","chat.chatInput.placeholder.chatCompact":"Plan, build, or ask","chat.chatInput.placeholder.selectSession":"Select or create a session to start chatting","chat.dictation.start":"Start dictation","chat.dictation.overlayAria":"Dictation","chat.dictation.downloadingModel":"Downloading speech model...","chat.dictation.downloadingModelProgress":"Downloading speech model... {percent}%","chat.dictation.listening":"Listening...","chat.dictation.processing":"Transcribing...","chat.dictation.failed":"Transcription failed","chat.dictation.cancel":"Discard dictation","chat.dictation.insert":"Insert transcript","chat.dictation.insertAndSend":"Insert and send","chat.dictation.retry":"Retry transcription","chat.dictation.discard":"Discard recording","chat.snippetAutocomplete.action.addNew":"Add new snippet","chat.snippetAutocomplete.empty":"No snippets found","chat.snippetAutocomplete.footer":"↑↓ navigate • Enter select • Esc close","chat.chatInput.toast.compactFailed":"Failed to compact session","chat.chatInput.toast.forkFailed":"Couldn't fork the session","chat.chatInput.toast.forkNothingToFork":"Nothing to fork yet: no reply has finished in this session","chat.chatInput.toast.forkSendFailed":"Forked, but the message wasn't sent. It's back in the composer.","chat.chatInput.toast.summaryFailed":"Failed to generate summary","chat.messageBody.actions.sendReviewFeedback":"Send review feedback to implementing agent","chat.messageBody.actions.sendImplementationResponse":"Send implementation response to reviewing agent","chat.chatInput.toast.reviewFailed":"Failed to review changes","chat.chatInput.toast.planFeatureFailed":"Failed to start feature planning","chat.chatInput.toast.catchUpFailed":"Failed to catch up","chat.chatInput.toast.debugFailed":"Failed to start debugging","chat.chatInput.toast.weighFailed":"Failed to weigh options","chat.chatInput.toast.exploreFailed":"Failed to start the tour","chat.chatInput.toast.attachmentsTooLarge":"Attachments are too large to send. Please try reducing the number or size of images.","chat.chatInput.toast.sendAttachmentsFailed":"Failed to send attachments. Try fewer files or smaller images.","chat.chatInput.toast.messageSendFailed":"Message failed to send. Attachments restored.","chat.chatInput.toast.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent and send again.`,"chat.chatInput.toast.noModelSelected":"Select a provider and model before sending.","chat.chatInput.toast.clipboardAttachFailed":"Failed to attach image from clipboard","chat.chatInput.toast.clipboardTextAttachFailed":"Failed to attach pasted text as a file","chat.chatInput.largeTextPaste.title":"Large text detected","chat.chatInput.largeTextPaste.attach":"Attach as file","chat.chatInput.largeTextPaste.inline":"Paste inline","chat.chatInput.toast.addedFileMentions":"Added {count} file mention(s)","chat.chatInput.toast.attachFileFailed":"Failed to attach file","chat.chatInput.mentionChip.editHint":"Double-click to edit as text","chat.chatInput.toast.attachNamedFailed":"Failed to attach {name}","chat.chatInput.toast.unsupportedAttachmentModalities":"{model} does not support {modalities} input required by {files}. You can still send the message, but these attachments may be ignored.","chat.chatInput.toast.imagesSaving":"Saving {files}…","chat.chatInput.toast.imagesSavedForTextModel":"{model} can't read images. Saved {files} to {folder}.","chat.chatInput.toast.imageSaveFailed":"Couldn't save {files}. Attached instead.","chat.chatInput.toast.imagesSaved":"Saved {files} to {folder}.","chat.chatInput.toast.imageCopySaveFailed":"Couldn't save {files}.","chat.chatInput.toast.someFilesSkipped":`Some files were skipped:
|
|
34
|
-
{summary}`,"chat.chatInput.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.chatInput.toast.openSessionFirst":"Open a session first","chat.chatInput.toast.dictationKeptForOriginalSession":"Dictation saved as a draft in the session where you started it","chat.chatInput.toast.togglePermissionAutoAcceptFailed":"Failed to toggle permission auto-accept","chat.chatInput.reviewComments":"Review comments:","chat.chatInput.reviewCommentsRemove":"Remove review comments","chat.chatInput.previewAnnotations":"Preview annotations:","chat.chatInput.previewContext":"Preview context:","chat.chatInput.previewContextRemove":"Remove preview context","chat.chatInput.projectRoot":"Project root","chat.chatInput.branch":"Branch","chat.chatInput.draftPicker.projectTitle":"Project","chat.chatInput.draftPicker.searchProjects":"Search projects...","chat.chatInput.draftPicker.searchBranches":"Search branches...","chat.chatInput.draftPicker.noProjectsFound":"No projects found.","chat.chatInput.worktrees":"Worktrees","chat.chatInput.worktreeQuick":"Quick worktree","chat.chatInput.worktreeCustom":"New worktree…","chat.chatInput.drop.insertMention":"Drop to insert as mention","chat.chatInput.drop.attachFiles":"Drop files here to attach","chat.chatInput.fileFallback":"file","chat.toolOutputDialog.image.previousAria":"Previous image","chat.toolOutputDialog.image.nextAria":"Next image","chat.toolOutputDialog.image.closeAria":"Close image preview","chat.toolOutputDialog.mermaid.missingSource":"Missing Mermaid source URL.","chat.toolOutputDialog.mermaid.loadFailed":"Unable to load Mermaid diagram.","chat.toolOutputDialog.mermaid.dataUrlMalformed":"The Mermaid data URL is malformed.","chat.toolOutputDialog.mermaid.invalidLocalPath":"The local Mermaid file path is invalid.","chat.toolOutputDialog.mermaid.readFileFailedWithStatus":"Unable to read Mermaid file. Status: {status}.","chat.toolOutputDialog.mermaid.unsupportedUrlProtocol":"The Mermaid URL protocol is unsupported.","chat.toolOutputDialog.mermaid.loadFailedWithStatus":"Unable to load Mermaid diagram. Status: {status}.","chat.toolOutputDialog.mermaid.closeAria":"Close diagram preview","chat.toolOutputDialog.mermaid.loading":"Loading diagram...","chat.toolOutputDialog.mermaid.renderFailed":"Unable to render Mermaid diagram.","chat.toolOutputDialog.mermaid.retry":"Retry","chat.toolOutputDialog.commandCompleted":"Command completed successfully","chat.toolOutputDialog.noOutputProduced":"No output was produced","chat.statusRow.background.action":"Move to background — the agent stops waiting and continues","chat.statusRow.background.failed":"Couldn't move the work to the background","chat.toolPart.background.label":"in background","chat.toolPart.background.stop":"Stop command","chat.toolPart.background.stopLabel":"Stop","chat.toolPart.background.stopFailed":"Couldn't stop the command","chat.toolPart.background.stoppedLabel":"stopped","chat.toolPart.background.stoppedNotice":"Stopped by you. The agent was told this was your stop, not a failure.","chat.toolPart.subagent.stop":"Stop subagent","chat.toolPart.subagent.stopFailed":"Couldn't stop the subagent","chat.toolPart.lspErrors":"LSP errors","chat.toolPart.moreErrors":"+{count} more errors","chat.toolPart.moreRows":"+{count} more rows","chat.toolPart.error":"Error:","chat.toolPart.awaitingResponse":"Awaiting response...","chat.toolPart.noOutputProduced":"No output produced","chat.toolPart.questionsAsked":"Questions asked: {count}","chat.toolPart.filesCount":"Files: {count}","chat.toolPart.moreToolCalls":"+{count} more","chat.toolPart.scriptCalls":"Tool calls","chat.toolPart.outputTruncated":"Output was truncated","chat.toolPart.content.loading":"Loading the result…","chat.toolPart.content.loadFailed":"Couldn't load the result.","chat.toolPart.content.retry":"Retry","chat.toolPart.output":"Output","chat.toolPart.showRawJson":"Show raw JSON","chat.toolPart.showFormattedJson":"Show formatted JSON","chat.toolPart.showNavigableJson":"Show navigable JSON","chat.toolPart.openFile":"Open file","chat.toolPart.openImageExpanded":"Open","chat.toolPart.openFileAtFirstChange":"Open file at first change","chat.toolPart.openFileDiff":"Open file diff","chat.toolPart.copyOutput":"Copy output","chat.toolPart.copiedOutput":"Copied output","chat.toolPart.copyOutputFailed":"Failed to copy output","chat.toolPart.openSubtask":"Open {type} subtask","chat.todo.total":"Total","chat.todo.inProgress":"In Progress","chat.todo.pending":"Pending","chat.todo.completed":"Completed","chat.todo.cancelled":"Cancelled","chat.permissionCard.workingDirectory":"Working Directory:","chat.permissionCard.timeout":"Timeout:","chat.permissionCard.request":"Request:","chat.permissionCard.headers":"Headers:","chat.permissionCard.body":"Body:","chat.permissionCard.action":"Action:","chat.permissionCard.patterns":"Patterns:","chat.permissionToast.sessionFallback":"Session","chat.permissionToast.permissionFallback":"Permission details unavailable","chat.permissionToast.labels.session":"Session:","chat.permissionToast.labels.permission":"Permission:","chat.permissionToast.actions.once":"Once","chat.permissionToast.actions.always":"Always","chat.permissionToast.actions.deny":"Deny","chat.permissionToast.actions.approveOnceAria":"Approve once","chat.permissionToast.actions.approveOnceAriaWithSession":"Approve once for {session}","chat.permissionToast.actions.approveAlwaysAria":"Approve always","chat.permissionToast.actions.approveAlwaysAriaWithSession":"Approve always for {session}","chat.permissionToast.actions.denyAria":"Deny permission","chat.permissionToast.actions.denyAriaWithSession":"Deny permission for {session}","chat.permissionRequest.required":"Permission required:","chat.permissionRequest.actions.once":"Once","chat.permissionRequest.actions.always":"Always","chat.permissionRequest.actions.reject":"Reject","chat.modelControls.provider":"Provider","chat.modelControls.capability.toolCalling":"Tool calling","chat.modelControls.capability.reasoning":"Reasoning","chat.modelControls.modality.text":"Text","chat.modelControls.modality.image":"Image","chat.modelControls.modality.video":"Video","chat.modelControls.modality.audio":"Audio","chat.modelControls.modality.pdf":"PDF","chat.modelControls.capabilities":"Capabilities","chat.modelControls.modalities":"Modalities","chat.modelControls.input":"Input","chat.modelControls.output":"Output","chat.modelControls.limits":"Limits","chat.modelControls.context":"Context","chat.modelControls.metadata":"Metadata","chat.modelControls.knowledge":"Knowledge","chat.modelControls.release":"Release","chat.modelControls.mode":"Mode","chat.modelControls.model":"Model","chat.modelControls.temperature":"Temperature","chat.modelControls.topP":"Top P","chat.modelControls.permissions":"Permissions","chat.modelControls.edit":"Edit","chat.modelControls.bash":"Bash","chat.modelControls.webFetch":"WebFetch","chat.modelControls.customPrompt":"Custom Prompt","chat.modelControls.selectModel":"Select model","chat.modelControls.thinking":"Thinking","chat.modelControls.inheritedVariantTooltip":"Thinking: {variant}, this model's default","chat.modelControls.rememberedVariantTooltip":"Thinking: {variant}, last used with this model","chat.modelControls.default":"Default","chat.modelControls.selectAgent":"Select agent","chat.modelControls.costPerMillion":"Cost ($/1M tokens)","chat.modelControls.metadataUnavailable":"Model metadata unavailable.","chat.modelControls.addNewProvider":"Add new provider","chat.modelControls.noAgentSelected":"No agent selected.","chat.modelControls.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent.`,"chat.modelControls.searchModels":"Search models","chat.modelControls.modelListAria":"Models","chat.modelControls.searchAgents":"Search agents","chat.modelControls.noModelsFound":"No models found","chat.modelControls.favorites":"Favorites","chat.modelControls.agentsSection":"Agents","chat.modelControls.favoriteAgentsCycleHint":"{shortcut} to cycle","chat.modelControls.favoriteAgentsTapHint":"Tap the agent to cycle","chat.modelControls.noAgentsFound":"No agents found","chat.modelControls.recent":"Recent","chat.modelControls.addToFavorites":"Add to favorites","chat.modelControls.removeFromFavorites":"Remove from favorites","chat.modelControls.useModel":"Use model","chat.modelControls.favoriteAria":"Favorite","chat.modelControls.unfavoriteAria":"Unfavorite","chat.modelControls.collapseProvider":"Collapse provider","chat.modelControls.expandProvider":"Expand provider","chat.modelControls.keyboardHint":"↑↓ navigate{thinking} • Enter select • Esc close","chat.modelControls.keyboardHintNavigate":"↑↓ navigate","chat.modelControls.keyboardHintSwitchAgent":"{shortcut} switch agent","chat.modelControls.keyboardHintSwitchThinking":"{shortcut} switch","chat.modelControls.keyboardHintThinking":"←→ thinking","chat.modelControls.reorderProviderTitle":"Drag to reorder provider","chat.modelControls.permissionLabel.custom":"Custom","chat.modelControls.permissionLabel.allow":"Allow","chat.modelControls.permissionLabel.deny":"Deny","chat.modelControls.permissionLabel.ask":"Ask","chat.modelControls.modeValue.primary":"Primary","chat.modelControls.modeValue.subagent":"Subagent","chat.modelControls.modeValue.all":"All","chat.modelControls.modeValue.none":"—","chat.reasoningTrace.thinking":"Thinking","chat.reasoningTrace.expandAria":"Expand reasoning trace","chat.reasoningTrace.collapseAria":"Collapse reasoning trace","chat.reasoningTrace.thought":"Thought","chat.messageBody.subtask.title":"Delegated task","chat.messageBody.subtask.hidePrompt":"Hide prompt","chat.messageBody.subtask.showPrompt":"Show prompt","chat.messageBody.subtask.openSession":"Open subtask session","chat.messageBody.shellCommand.copied":"Copied","chat.messageBody.shellCommand.copyOutput":"Copy output","commandPalette.title":"Command Palette","commandPalette.description":"Search files, sessions, and commands.","commandPalette.input.placeholder":"Search files, sessions, commands...","commandPalette.empty.noResults":"No results found.","commandPalette.empty.searchingFiles":"Searching files...","commandPalette.item.newSession":"New Session","commandPalette.item.newMiniChat":"New Mini Chat Window","commandPalette.item.quickWorktree":"Quick Worktree","commandPalette.item.newWorktreeDialog":"New Worktree…","commandPalette.item.addProject":"Add Project","commandPalette.item.showSessionSwitcher":"Show Session Switcher","commandPalette.item.toggleSidebar":"Toggle Sidebar","commandPalette.item.showContextUsage":"Show Context Usage","commandPalette.item.toggleTerminal":"Toggle Terminal","commandPalette.item.cycleTheme":"Cycle theme","commandPalette.item.showOpenCodeStatus":"Show diagnostic timeline","commandPalette.item.restartOpenCode":"Restart OpenCode","commandPalette.item.toggleMemoryDebug":"Toggle memory debug panel","commandPalette.item.pinSession":"Pin or unpin session","commandPalette.item.copySessionId":"Copy session ID","commandPalette.item.openMultiRun":"Run in parallel","commandPalette.item.openArchive":"Open archived sessions","commandPalette.item.openNotes":"Open notes surface","commandPalette.item.openTodos":"Open todos surface","commandPalette.item.openSettings":"Open Settings...","commandPalette.session.untitled":"Untitled Session","commandPalette.item.reloadUi":"Reload UI","commandPalette.group.openFiles":"Open files","commandPalette.group.commands":"Commands","commandPalette.group.settings":"Settings","chat.search.placeholder":"Search this conversation","chat.search.position":"{current} of {total}","chat.search.noResults":"No results","chat.search.searching":"Searching…","chat.search.tooShort":"3+ characters","chat.search.error":"Couldn't search","chat.search.unavailable":"Not available here","chat.search.previous":"Previous match","chat.search.next":"Next match","chat.search.close":"Close search","commandPalette.group.sessions":"Sessions","commandPalette.group.messages":"Messages","commandPalette.messages.showAll":"Show all message results","commandPalette.messages.placeholder":"Search messages…","commandPalette.messages.back":"Back","commandPalette.messages.filter.scopeLabel":"Where","commandPalette.messages.filter.allProjects":"All projects","commandPalette.messages.filter.thisProject":"This project","commandPalette.messages.filter.authorLabel":"Written by","commandPalette.messages.filter.anyone":"Anyone","commandPalette.messages.filter.you":"You","commandPalette.messages.filter.agent":"Agent","commandPalette.messages.filter.reasoning":"Thinking","commandPalette.messages.inReasoning":"Thinking","commandPalette.messages.tooShort":"Type at least 3 characters to search messages","commandPalette.messages.searching":"Searching messages…","commandPalette.messages.error":"Couldn't search messages","commandPalette.messages.unavailable":"Message search is not available on this server","commandPalette.messages.empty":"No messages found","commandPalette.messages.indexing":"Still indexing older conversations: {done} of {total}.","commandPalette.messages.loadMore":"Load more","commandPalette.messages.byYou":"Your message","commandPalette.messages.byAgent":"Agent reply","commandPalette.group.files":"Files","commandPalette.group.projects":"Projects","commandPalette.footer.navigate":"to navigate","commandPalette.footer.open":"to open","commandPalette.footer.close":"to close","openCodeStatusDialog.title":"Diagnostic timeline","openCodeStatusDialog.description":"Local events in time order. Private log text and remote sources are excluded.","openCodeStatusDialog.actions.download":"Download log","openCodeStatusDialog.toast.collectFailed":"Failed to collect diagnostics","openCodeStatusDialog.actions.copy":"Copy","openCodeStatusDialog.empty.noData":"No data.","openCodeStatusDialog.toast.copiedTitle":"Copied","openCodeStatusDialog.toast.copiedDescription":"Diagnostic log copied to clipboard","openCodeStatusDialog.toast.copyFailed":"Failed to copy diagnostic log","saveProjectPlanDialog.title":"Save Project Plan","saveProjectPlanDialog.description":"Save this plan into your project as a Markdown file.","saveProjectPlanDialog.field.title":"Title","saveProjectPlanDialog.field.titlePlaceholder":"Plan title","saveProjectPlanDialog.field.contentPreview":"Content preview","saveProjectPlanDialog.actions.cancel":"Cancel","saveProjectPlanDialog.actions.save":"Save","saveProjectPlanDialog.actions.saving":"Saving...","branchPickerDialog.title":"Branch Picker","branchPickerDialog.description.localBranchesForProject":"Local branches for {project}","branchPickerDialog.description.selectProject":"Select a project to view branches","branchPickerDialog.search.placeholder":"Search branches...","branchPickerDialog.search.renameBranchPlaceholder":"Rename branch","branchPickerDialog.state.noProjectSelected":"No project selected","branchPickerDialog.state.loadingBranches":"Loading branches...","branchPickerDialog.state.noMatchingBranches":"No matching branches","branchPickerDialog.state.noBranchesFound":"No branches found","branchPickerDialog.badge.head":"HEAD","branchPickerDialog.badge.worktree":"worktree","branchPickerDialog.actions.createWorktreeAria":"Create worktree from branch","branchPickerDialog.actions.renameAria":"Rename branch","branchPickerDialog.actions.deleteAria":"Delete branch","branchPickerDialog.actions.deleteWorktreeAria":"Remove worktree","branchPickerDialog.actions.confirmRenameAria":"Confirm rename","branchPickerDialog.actions.cancelRenameAria":"Cancel rename","branchPickerDialog.actions.confirmDeleteAria":"Confirm delete branch","branchPickerDialog.actions.cancelDeleteAria":"Cancel delete branch","branchPickerDialog.actions.deletePrompt":"Delete","branchPickerDialog.actions.forceDeletePrompt":"Force Delete","branchPickerDialog.tooltip.createWorktree":"Create worktree","branchPickerDialog.tooltip.worktreeAlreadyExists":"Worktree already exists","branchPickerDialog.tooltip.rename":"Rename branch","branchPickerDialog.tooltip.renameDisabledForRoot":"Cannot rename root branch","branchPickerDialog.tooltip.delete":"Delete branch","branchPickerDialog.tooltip.deleteCurrentBranch":"Cannot delete current branch","branchPickerDialog.tooltip.deleteDisabledForRoot":"Cannot delete root branch","branchPickerDialog.tooltip.deleteWorktree":"Remove worktree","branchPickerDialog.tooltip.deleteWorktreeRootProtected":"Cannot remove root worktree","branchPickerDialog.toast.branchRenamed":"Branch renamed","branchPickerDialog.toast.failedToRenameBranch":"Failed to rename branch","branchPickerDialog.toast.branchDeleted":"Branch deleted","branchPickerDialog.toast.branchNotMerged":"Branch is not fully merged","branchPickerDialog.toast.confirmAgainToForceDelete":"Confirm again to force delete","branchPickerDialog.toast.failedToDeleteBranch":"Failed to delete branch","branchPickerDialog.toast.worktreeCreated":"Worktree created","branchPickerDialog.toast.failedToCreateWorktree":"Failed to create worktree","branchPickerDialog.error.failedToLoad":"Failed to load branches","branchPickerDialog.error.renameRejected":"Rename was rejected","branchPickerDialog.error.renameFailed":"Failed to rename branch","branchPickerDialog.error.deleteRejected":"Delete was rejected","branchPickerDialog.error.deleteFailed":"Failed to delete branch","branchPickerDialog.error.createWorktreeFailed":"Failed to create worktree","projectEditDialog.title":"Edit project","projectEditDialog.field.name":"Name","projectEditDialog.field.namePlaceholder":"Project name","projectEditDialog.field.color":"Color","projectEditDialog.field.icon":"Icon","projectEditDialog.field.preview":"Preview","projectEditDialog.field.iconBackground":"Icon Background","projectEditDialog.field.iconBackgroundAria":"Project icon background color","projectEditDialog.option.none":"None","projectEditDialog.actions.uploadIcon":"Upload Icon","projectEditDialog.actions.uploading":"Uploading...","projectEditDialog.actions.discoverFavicon":"Discover Favicon","projectEditDialog.actions.discovering":"Discovering...","projectEditDialog.actions.removeProjectIcon":"Remove Project Icon","projectEditDialog.actions.removing":"Removing...","projectEditDialog.actions.undoRemove":"Undo Remove","projectEditDialog.actions.clear":"Clear","projectEditDialog.actions.cancel":"Cancel","projectEditDialog.actions.save":"Save","projectEditDialog.toast.failedToUploadIcon":"Failed to upload project icon","projectEditDialog.toast.iconUpdated":"Project icon updated","projectEditDialog.toast.failedToRemoveIcon":"Failed to remove project icon","projectEditDialog.toast.iconRemoved":"Project icon removed","projectEditDialog.toast.failedToDiscoverIcon":"Failed to discover project icon","projectEditDialog.toast.customIconAlreadySet":"Custom icon already set for this project","projectEditDialog.toast.iconDiscovered":"Project icon discovered","openInApp.actions.open":"Open","openInApp.actions.openInAria":"Open in {app}","openInApp.actions.copyPath":"Copy Path","openInApp.actions.refreshApps":"Refresh Apps","openInApp.toast.pathCopied":"Path copied to clipboard","projectActions.actions.addActionAria":"Add action","projectActions.actions.addAction":"Add action","projectActions.actions.addNewAction":"Add new action","projectActions.actions.autoDiscover":"Auto-discover dev server","projectActions.menu.sharedBadge":"repo","projects.sharedTrust.title":"Run the commands stored in this repository?","projects.sharedTrust.description":"{path} in this repository defines commands that run on this machine. Trust them once, and OpenChamber asks again only when they change.","projects.sharedTrust.setupCommands":"Worktree setup commands","projects.sharedTrust.teardownCommands":"Worktree teardown commands","projects.sharedTrust.actions":"Actions","projects.sharedTrust.skip":"Not this time","projects.sharedTrust.trust":"Trust and run","projects.opencodeTrust.title":"Let OpenCode run code from this folder?","projects.opencodeTrust.description":"OpenCode runs the plugins and commands in the configuration of {path} as soon as it opens the folder. Trust them once, and OpenChamber asks again only when they change.","projects.opencodeTrust.plugins":"Plugins","projects.opencodeTrust.commands":"Commands","projects.opencodeTrust.kind.package":"{name} (npm package)","projects.opencodeTrust.kind.config":"{path}: a configuration file OpenChamber can't read","projects.opencodeTrust.kind.mcp":"MCP server {name}","projects.opencodeTrust.kind.lsp":"Language server {name}","projects.opencodeTrust.kind.formatter":"Formatter {name}","projects.opencodeTrust.kind.shell":"Shell","projects.opencodeTrust.paused":"Without trust, agents can't work in this folder, but you can still browse its files and Git changes.","projects.opencodeTrust.skip":"Not this time","projects.opencodeTrust.trust":"Trust and open","projects.opencodeTrust.saveFailed":"Couldn't save your answer. Try again.","projectActions.actions.autoDiscoverTooltip":"Automatically discover and run the development server","projectActions.actions.chooseActionAria":"Choose project action","projectActions.actions.openPreview":"Open Preview","projectActions.actions.runNamedAria":"Run {name}","projectActions.actions.stopNamedAria":"Stop {name}","projectActions.label.fallbackAction":"Action","projectActions.toast.openedUrlFromOutput":"Opened URL from action output","projectActions.toast.openedForwardedUrl":"Opened forwarded URL","projectActions.toast.openedActionUrl":"Opened action URL","projectActions.error.noActiveDirectory":"No active directory","projectActions.error.noActiveDirectoryForAction":"No active directory for action","projectActions.error.failedToCreateTerminalSession":"Failed to create terminal session","projectActions.error.invalidCustomUrlFormat":"Invalid custom URL format","projectActions.error.openUrlTemplateUnresolved":"Couldn't read the branch for the action URL","projectActions.error.selectedDesktopSshForwardUnavailable":"Selected desktop SSH forward is unavailable","projectActions.error.failedToRunAction":"Failed to run action","mcpDropdown.title":"MCP Servers","mcpDropdown.actions.refreshAria":"Refresh","mcpDropdown.actions.openAria":"MCP servers","mcpDropdown.statusAria":"MCP status","mcpDropdown.status.unknown":"Unknown","mcpDropdown.status.connected":"Connected","mcpDropdown.status.failed":"Failed: {error}","mcpDropdown.status.unknownError":"Unknown error","mcpDropdown.status.needsAuth":"Needs authentication","mcpDropdown.status.needsRegistration":"Needs registration: {error}","mcpDropdown.empty.configureInConfig":"Configure MCP servers in Settings.","sessionAuth.error.rateLimitTitle":"Too many attempts","sessionAuth.error.networkTitle":"Unable to reach server","sessionAuth.error.rateLimitDescriptionSingle":"Please wait {minutes} minute before trying again.","sessionAuth.error.rateLimitDescriptionPlural":"Please wait {minutes} minutes before trying again.","sessionAuth.error.networkDescription":"We could not verify the UI session. If you're opening OpenChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings.","sessionAuth.error.retry":"Retry","sessionAuth.error.passkeySetupFailed":"Passkey setup failed.","sessionAuth.error.incorrectPassword":"Incorrect password. Try again.","sessionAuth.error.unexpectedResponse":"Unexpected response from server.","sessionAuth.error.networkRetry":"Network error. Check connection and retry.","sessionAuth.error.passkeySignInCanceled":"Passkey sign-in was canceled.","sessionAuth.error.enterPasswordForPasskey":"Enter your password to add a passkey.","sessionAuth.locked.tunnelTitle":"Tunnel access required","sessionAuth.expired.banner":"Your session expired — log in to continue.","sessionAuth.expired.loginAction":"Log in","sessionAuth.expired.sendBlocked":"Session expired — log in to send messages.","sessionAuth.locked.unlockTitle":"Unlock OpenChamber","sessionAuth.locked.tunnelDescription":"Open this tunnel using the one-time connect link from the desktop app.","sessionAuth.locked.passwordDescription":"This session is password-protected.","sessionAuth.locked.hostSwitcherHint":"Use Local if remote is unreachable.","sessionAuth.actions.cancelPasskey":"Cancel passkey","sessionAuth.actions.usePasskey":"Use passkey","sessionAuth.actions.unlockingAria":"Unlocking","sessionAuth.actions.unlockAria":"Unlock","sessionAuth.actions.trustDevice":"Trust this device","sessionAuth.actions.trustDeviceAria":"Trust this device","sessionAuth.actions.cancelPasskeySetup":"Cancel passkey setup","sessionAuth.actions.addPasskey":"Add passkey","sessionAuth.password.placeholder":"Enter password","sessionAuth.toast.passkeyAdded":"Passkey added","sessionAuth.toast.passkeySetupCanceled":"Passkey setup canceled","desktopHostSwitcher.title":"Instance","desktopHostSwitcher.description":"Switch between Local and remote OpenChamber servers","desktopHostSwitcher.header.current":"Current","desktopHostSwitcher.header.default":"Default","desktopHostSwitcher.header.currentColon":"Current:","desktopHostSwitcher.header.currentDefaultColon":"Current default:","desktopHostSwitcher.status.connected":"Connected","desktopHostSwitcher.status.authRequired":"Auth required","desktopHostSwitcher.status.checking":"Checking","desktopHostSwitcher.status.updateRecommended":"Update recommended","desktopHostSwitcher.status.incompatible":"Incompatible","desktopHostSwitcher.status.wrongService":"Wrong service","desktopHostSwitcher.status.unreachable":"Unreachable","desktopHostSwitcher.status.relayLimit":"Relay limit reached","desktopHostSwitcher.status.unknown":"Unknown","desktopHostSwitcher.status.ping":" · {ms}ms ping","desktopHostSwitcher.statusAria":"Instance status","desktopHostSwitcher.sshPhase.ready":"Ready","desktopHostSwitcher.sshPhase.error":"Error","desktopHostSwitcher.sshPhase.reconnecting":"Reconnecting","desktopHostSwitcher.sshPhase.resolvingConfig":"Resolving config","desktopHostSwitcher.sshPhase.checkingAuth":"Checking auth","desktopHostSwitcher.sshPhase.connectingSsh":"Connecting SSH","desktopHostSwitcher.sshPhase.probingRemote":"Probing remote","desktopHostSwitcher.sshPhase.installing":"Installing","desktopHostSwitcher.sshPhase.updating":"Updating","desktopHostSwitcher.sshPhase.detectingServer":"Detecting server","desktopHostSwitcher.sshPhase.startingServer":"Starting server","desktopHostSwitcher.sshPhase.forwardingPorts":"Forwarding ports","desktopHostSwitcher.sshPhase.idle":"Idle","desktopHostSwitcher.ssh.needInstancesHint":"Need SSH instances? Manage them in Settings.","desktopHostSwitcher.ssh.instanceFallback":"SSH instance","desktopHostSwitcher.ssh.connectingTo":"Connecting to {host}","desktopHostSwitcher.actions.refresh":"Refresh","desktopHostSwitcher.actions.refreshInstancesAria":"Refresh instances","desktopHostSwitcher.actions.remoteSsh":"Remote SSH","desktopHostSwitcher.actions.instanceActionsAria":"Instance actions","desktopHostSwitcher.actions.edit":"Edit","desktopHostSwitcher.actions.delete":"Delete","desktopHostSwitcher.actions.connect":"Connect","desktopHostSwitcher.actions.defaultInstanceAria":"Default instance","desktopHostSwitcher.actions.setAsDefaultAria":"Set as default","desktopHostSwitcher.actions.setAsDefault":"Set as default","desktopHostSwitcher.actions.openInNewWindowAria":"Open in new window","desktopHostSwitcher.actions.openInNewWindow":"Open in new window","desktopHostSwitcher.actions.addInstance":"Add instance","desktopHostSwitcher.actions.cancel":"Cancel","desktopHostSwitcher.actions.save":"Save","desktopHostSwitcher.actions.add":"Add","desktopHostSwitcher.actions.switchToLocal":"Switch to Local","desktopHostSwitcher.actions.retry":"Retry","desktopHostSwitcher.actions.switchInstanceAria":"Switch instance","desktopHostSwitcher.actions.switchInstance":"Switch instance","desktopHostSwitcher.actions.switchToAria":"Switch to {instance}","desktopHostSwitcher.field.labelPlaceholder":"Label","desktopHostSwitcher.field.labelOptionalPlaceholder":"Label (optional)","desktopHostSwitcher.field.urlPlaceholder":"https://host:port","desktopHostSwitcher.state.limitedOnPage":"Instance switcher is limited on this page. Use Local to recover.","desktopHostSwitcher.state.loading":"Loading...","desktopHostSwitcher.state.instanceUnreachable":"Instance unreachable","desktopHostSwitcher.edit.title":"Edit instance","desktopHostSwitcher.add.title":"Add instance","desktopHostSwitcher.error.failedToSave":"Failed to save","desktopHostSwitcher.error.failedToLoad":"Failed to load","desktopHostSwitcher.error.invalidUrl":"Invalid URL (must be http/https)","desktopHostSwitcher.error.pairingRejected":"Pairing link is invalid or expired. Generate a new one.","desktopHostSwitcher.error.pairingFailed":"Pairing failed (HTTP {status}).","desktopHostSwitcher.error.pairingInvalidResponse":"The server returned an invalid pairing response.","desktopHostSwitcher.error.failedToOpenNewWindow":"Failed to open new window","desktopHostSwitcher.instance.local":"Local","desktopHostSwitcher.instance.fallback":"Instance","desktopHostSwitcher.startup.title":"Default SSH instance unavailable","desktopHostSwitcher.startup.connectingTo":"Connecting to {host}...","desktopHostSwitcher.startup.failed":"Failed to connect the default SSH instance.","desktopHostSwitcher.toast.sshConnected":'SSH instance "{host}" connected',"desktopHostSwitcher.toast.sshFailedToConnect":'SSH instance "{host}" failed to connect',"desktopHostSwitcher.toast.instanceUnreachable":'Instance "{host}" is unreachable',"desktopHostSwitcher.toast.relayLimit":'The relay refused the connection to "{host}": too many devices or reconnects. Close OpenChamber on another device or wait a minute, then try again.',"relayConnection.limitReached.title":"The relay refused the connection","relayConnection.limitReached.description":"Too many devices or reconnects for this instance. Close OpenChamber on another device or wait a minute, then try again.","relayConnection.limitReached.retry":"Try again","miniChat.header.newSession":"New session","miniChat.header.session":"Session","miniChat.header.defaultAgent":"Default agent","miniChat.header.noModel":"No model","miniChat.status.busy":"Running","miniChat.status.retry":"Retrying","miniChat.status.idle":"Idle","miniChat.actions.pin":"Pin above other windows","miniChat.actions.unpin":"Unpin window","miniChat.actions.pinAria":"Pin Mini Chat window","miniChat.actions.unpinAria":"Unpin Mini Chat window","miniChat.actions.openMain":"Open in main window","miniChat.actions.openMainAria":"Open session in main window","miniChat.unavailable.title":"Session unavailable","miniChat.unavailable.description":"This session could not be loaded. It may have been deleted, archived, or opened from a different project context.","sessions.sidebar.session.menu.openMiniChatWindow":"Open in Mini Chat Window","header.windowControls.groupAria":"Window controls","header.windowControls.minimize":"Minimize window","header.windowControls.maximize":"Maximize window","header.windowControls.restore":"Restore window","header.windowControls.close":"Close window","errorBoundary.title":"Something went wrong","errorBoundary.description":"The application encountered an unexpected error. This has been logged for debugging.","errorBoundary.state.unknownError":"Unknown error","errorBoundary.state.componentStackLabel":"Component stack:","errorBoundary.actions.errorDetails":"Error details","errorBoundary.actions.tryAgain":"Try again","errorBoundary.actions.copy":"Copy","errorBoundary.actions.copied":"Copied","jsonTreeView.error.emptyJson":"Empty JSON content","jsonTreeView.error.invalidJson":"Invalid JSON","jsonTreeView.error.invalidJsonTitle":"Invalid JSON","jsonTreeView.actions.expandAll":"Expand All","jsonTreeView.actions.collapseAll":"Collapse All","numberInput.actions.decreaseAria":"Decrease value","numberInput.actions.increaseAria":"Increase value","goToLineDialog.field.linePlaceholderShort":"Line","goToLineDialog.field.linePlaceholder":"Line number","goToLineDialog.actions.go":"Go","goToLineDialog.helper.editorUnavailable":"Editor unavailable.","goToLineDialog.helper.currentLineRange":"Current Line: {current}. Type a line number between 1 and {max} to navigate to.","goToLineDialog.helper.goToLine":"Go to line {line}","dialog.common.actions.close":"Close","session.newWorktree.trust.run":"Run","session.newWorktree.trust.skip":"Skip","session.newWorktree.trust.title":"Run setup on code from a fork?","gitView.publish.contributorCommitFirstAction":"Continue","gitView.publish.contributorCommitFirstTitle":"Commit, then choose where to push?","dialog.common.actions.cancel":"Cancel","filesView.toast.relativePathCopied":"Relative path copied","filesView.tree.menu.copyRelativePath":"Copy Relative Path","multiRun.branchSelector.placeholder.selectSourceBranch":"Select source branch...","multiRun.branchSelector.status.loadingBranches":"Loading branches...","multiRun.branchSelector.status.noBranchesFound":"No branches found","multiRun.branchSelector.status.notInGitRepository":"Not in a git repository.","multiRun.branchSelector.groups.localBranches":"Local branches","multiRun.branchSelector.groups.remoteBranches":"Remote branches","multiRun.window.actions.closeAria":"Close multi-run","multiRun.window.description":"OpenChamber Multi-Run window.","voice.status.idle":"Voice Ready","voice.status.listening":"Listening...","voice.status.processing":"Processing...","voice.status.speaking":"Speaking...","voice.status.error":"Voice Error","voice.status.conversationModeActiveAria":"Conversation mode active","voice.action.finishAndTranscribe":"Finish and transcribe voice input","onboarding.common.actions.back":"Back","onboarding.common.copyToClipboard":"Copy to clipboard","onboarding.common.status.copiedToClipboard":"Copied to clipboard","onboarding.chooser.title":"Welcome to OpenChamber","onboarding.chooser.description":"Choose how you want to connect to get started.","onboarding.chooser.tabs.localInstall":"Local Install","onboarding.chooser.tabs.connectRemote":"Connect Remote","onboarding.localSetup.title":"Setting Up OpenCode","onboarding.localSetup.description":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.dialog.selectOpencodeBinary":"Select opencode binary","onboarding.localSetup.errors.cliNotReady":"OpenCode CLI is not ready yet. Please confirm installation is complete and try again.","onboarding.localSetup.errors.detectionFailed":"Detection failed","onboarding.localSetup.windows.title":"Windows setup","onboarding.localSetup.windows.stepInstallWsl":"Install OpenCode with the command below.","onboarding.localSetup.windows.stepInstallWslSuffix":"","onboarding.localSetup.windows.stepRunInstallInWsl":"Run the install command below in a Windows terminal.","onboarding.localSetup.windows.stepSetBinaryPath":"If OpenChamber does not detect OpenCode automatically, set the binary path below.","onboarding.localSetup.intro":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.docs.windows":"Installation guide","onboarding.localSetup.docs.default":"Installation guide","onboarding.localSetup.actions.checking":"Checking…","onboarding.localSetup.actions.checkAndContinue":"I've completed installation, check and continue","onboarding.localSetup.actions.checkNow":"Check now","onboarding.localSetup.helper.checkAndContinue":"Click to check if OpenCode CLI is available. If successful, you'll automatically enter the main screen.","onboarding.localSetup.status.watching":"Waiting for OpenCode v2","onboarding.localSetup.status.autoContinue":"We'll continue automatically once it's detected.","onboarding.localSetup.field.alreadyInstalled":"Already installed? Set the OpenCode CLI path:","onboarding.localSetup.advanced.title":"Set a custom binary path","onboarding.localSetup.troubleshoot.title":"Having trouble?","onboarding.localSetup.actions.browse":"Browse","onboarding.localSetup.actions.apply":"Apply","onboarding.localSetup.helper.saveAndReload":"Saves to OpenChamber settings and reloads OpenCode configuration.","onboarding.localSetup.helper.pinnedByAdministrator":"Your administrator set this path. If OpenCode isn’t there, ask them to install it.","onboarding.localSetup.remotePreference":"Prefer to use a remote server?","onboarding.localSetup.actions.connectRemoteServer":"Connect to Remote Server →","onboarding.localSetup.windows.hintInstallInWsl":"On Windows, install and run OpenCode natively.","onboarding.localSetup.windows.hintDetectionFailed":"If detection fails, set a native path such as opencode.cmd or opencode.exe.","onboarding.localSetup.hint.ensurePath":"Already installed? Make sure opencode is in your PATH.","onboarding.localSetup.hint.setEnv":"Or set OPENCODE_BINARY environment variable.","onboarding.localSetup.hint.missingRuntime":'If you see "env: node: No such file or directory" or "env: bun: No such file or directory", install that runtime or ensure it is on PATH.',"onboarding.remoteConnection.title":"Connect to Remote Server","onboarding.remoteConnection.titleRecovery":"Connect to a Different Server","onboarding.remoteConnection.description":"Enter the address of an OpenChamber server to connect to.","onboarding.remoteConnection.field.serverAddress":"Server Address","onboarding.remoteConnection.field.serverAddressPlaceholder":"https://your-server.example.com:4096","onboarding.remoteConnection.field.nameOptional":"Name (optional)","onboarding.remoteConnection.field.namePlaceholder":"My Remote Server","onboarding.remoteConnection.errors.connectionTestFailed":"Connection test failed","onboarding.remoteConnection.errors.failedToSaveConnection":"Failed to save connection","onboarding.remoteConnection.status.connectedSuccessfully":"Connected successfully ({latencyMs}ms)","onboarding.remoteConnection.status.authWarning":"Server requires authentication. You can still connect.","onboarding.remoteConnection.status.connectionFailed":"Connection Failed","onboarding.remoteConnection.status.suggestionsUnreachable":"Suggestions: Check the server address, verify the server is running, or check your network connection.","onboarding.remoteConnection.status.suggestionsWrongService":"Suggestions: Verify the URL points to an OpenChamber server, or contact the server administrator.","onboarding.remoteConnection.actions.testing":"Testing…","onboarding.remoteConnection.actions.testConnection":"Test Connection","onboarding.remoteConnection.actions.connectAndRestart":"Connect & Restart","onboarding.remoteConnection.actions.whatToDo":"What would you like to do?","onboarding.remoteConnection.actions.chooseDifferentServer":"Choose Different Server","onboarding.remoteConnection.actions.useLocalInstead":"Use Local Instead","onboarding.remoteConnection.probe.authMessage":"Server requires authentication. You can still connect, but may need to provide credentials.","onboarding.remoteConnection.probe.updateRecommendedMessage":"This instance is running a different OpenChamber version. You can connect, but update both apps if something does not work.","onboarding.remoteConnection.probe.incompatibleMessage":"Server is running OpenChamber but is not compatible with this app version. Update OpenChamber on the server, then try again.","onboarding.remoteConnection.probe.wrongServiceMessage":"Server responded but is not running OpenChamber. Verify the address points to an OpenChamber server.","onboarding.remoteConnection.probe.unreachableMessage":"Server is unreachable. Check your network connection and verify the server address.","onboarding.desktopRecovery.localUnavailable.title":"Local OpenCode Unavailable","onboarding.desktopRecovery.localUnavailable.description":"OpenCode CLI could not be started or is not installed. Install OpenCode or connect to a remote server instead.","onboarding.desktopRecovery.localUnavailable.retry":"Retry Local","onboarding.desktopRecovery.localUnavailable.useLocal":"Set Up Local","onboarding.desktopRecovery.noDefaultConnection.title":"No Default Connection","onboarding.desktopRecovery.noDefaultConnection.description":"Your saved default connection could not be found. Choose how you want to connect.","onboarding.desktopRecovery.remoteUnreachable.title":"Remote Server Unreachable","onboarding.desktopRecovery.remoteUnreachable.description":'Could not connect to "{host}". Check your network connection and verify the server address.',"onboarding.desktopRecovery.remoteUnreachable.retry":"Retry Connection","onboarding.desktopRecovery.incompatibleServer.title":"Incompatible Server","onboarding.desktopRecovery.incompatibleServer.description":'The server at "{host}" is not running OpenChamber. Verify the address points to an OpenChamber server.',"onboarding.desktopRecovery.remoteIncompatible.title":"Server Update Required","onboarding.desktopRecovery.remoteIncompatible.description":'The OpenChamber server at "{host}" is not compatible with this app version. Update OpenChamber on the server, then try again.',"onboarding.desktopRecovery.remoteIncompatible.updateServer":"Update server","onboarding.desktopRecovery.remoteIncompatible.updatingServer":"Updating the server...","onboarding.desktopRecovery.remoteIncompatible.updatingHint":"The server installs the update and restarts. The app connects as soon as it is back.","onboarding.desktopRecovery.remoteIncompatible.updateRefused":"The server could not update itself.","onboarding.desktopRecovery.remoteIncompatible.updateAuth":"The server did not accept this app's sign-in, so it could not be updated from here.","onboarding.desktopRecovery.remoteIncompatible.updateTimeout":"The server has not come back with the new version yet. Check it, then retry the connection.","onboarding.desktopRecovery.remoteIncompatible.manualUpdate":"To update it by hand, run this on the server, then restart OpenChamber there:","onboarding.desktopRecovery.common.useLocal":"Use Local","onboarding.desktopRecovery.common.useRemote":"Use Remote","onboarding.desktopRecovery.actions.retrying":"Retrying…","onboarding.desktopRecovery.actions.retryConnection":"Retry Connection","projectConfigError.toast.title":"OpenCode can't load this project's config","projectConfigError.toast.unknownFile":"Project config","projectConfigError.toast.hint":"Fix the file, then retry. Other projects keep working.","projectConfigError.toast.retry":"Retry","projectConfigError.toast.retrying":"Retrying…","startup.initRecovery.title":"Startup failed","startup.serverOutdated.title":"Server update required","startup.serverOutdated.description":"The server runs OpenChamber {version}, and this app needs 2.0 or later there. Update OpenChamber on the server to continue.","startup.serverOutdated.checking":"Checking the server...","startup.serverOutdated.noUpdate":"The server did not offer an update it can install itself.","startup.initRecovery.openCodeUnavailable":"OpenChamber is reachable, but OpenCode is not ready. Check OpenCode on the server, then retry.","startup.initRecovery.binary":"OpenCode executable","startup.initRecovery.error":"OpenCode error","startup.initRecovery.serverUnreachable":"OpenChamber could not reach its server. Check that the server is running, then retry.","startup.initRecovery.loadAgentsFailed":"The server is running, but OpenCode could not load agents. Retry once the cause is fixed.","startup.initRecovery.unexpected":"OpenChamber could not finish starting. Retry once the cause is fixed.","startup.initRecovery.lastError":"Last error","startup.initRecovery.retry":"Retry","startup.initRecovery.retrying":"Retrying…","startup.overlay.slow":"Startup is taking longer than expected…","onboarding.desktopRecovery.placeholders.remoteServer":"the remote server","onboarding.desktopRecovery.placeholders.unknownServer":"unknown","vscodeLayout.title.chat":"Chat","vscodeLayout.title.newSession":"New session","vscodeLayout.title.sessions":"Sessions","vscodeLayout.title.sessionFallback":"Session","vscodeLayout.actions.backToSessionsAria":"Back to sessions","vscodeLayout.actions.archiveAllAria":"Archive all sessions","vscodeLayout.actions.archiveAllConfirm":"Archive all","vscodeLayout.actions.archiveAllSuccess":"Archived {count} session(s)","vscodeLayout.actions.archiveAllError":"Failed to archive {count} session(s)","vscodeLayout.actions.cancel":"Cancel","vscodeLayout.actions.newSessionAria":"New session","vscodeLayout.actions.resizeSessionsSidebarAria":"Resize sessions sidebar","vscodeLayout.actions.settingsAria":"Settings","vscodeLayout.quota.title":"Rate limits","vscodeLayout.quota.mode.used":"Used","vscodeLayout.quota.mode.remaining":"Remaining","vscodeLayout.quota.lastUpdated":"Last updated {time}","vscodeLayout.quota.noRateLimitsAvailable":"No rate limits available.","vscodeLayout.quota.noRateLimitsReported":"No rate limits reported.","vscodeLayout.quota.actions.rateLimitsAria":"Rate limits","vscodeLayout.quota.actions.showUsedAria":"Show used quota","vscodeLayout.quota.actions.showRemainingAria":"Show remaining quota","vscodeLayout.quota.actions.refreshAria":"Refresh rate limits","updateDialog.header.updateAvailable":"Update Available","updateDialog.header.updating":"Updating OpenChamber...","updateDialog.changelog.title":"What's new","updateDialog.status.installingUpdate":"Installing update...","updateDialog.status.serverRestarting":"Server restarting...","updateDialog.status.waitingForServer":"Waiting for server...","updateDialog.status.autoReloadHint":"The page will reload automatically when the update is complete.","updateDialog.fallback.updateViaTerminal":"Or update via terminal:","updateDialog.desktopHostInstall":"OpenChamber {version} is available. Update it on the computer it runs on.","updateDialog.actions.copyCommand":"Copy command","updateDialog.actions.copied":"Copied!","updateDialog.status.downloadingPayload":"Downloading update payload...","updateDialog.actions.downloadUpdate":"Download Update","updateDialog.status.downloading":"Downloading...","updateDialog.actions.restartToUpdate":"Restart to Update","updateDialog.status.restarting":"Restarting...","updateDialog.actions.updateNow":"Update Now","updateDialog.actions.openMobileUpdate":"Open update","updateDialog.status.updating":"Updating...","updateDialog.error.updateFailed":"Update failed","updateDialog.error.takingLonger":"Update is taking longer than expected. Wait a bit and refresh, or run: openchamber update","updateDialog.error.signatureRejected":"The downloaded update was rejected: its code signature does not match this installation. This usually means the running copy was not installed from an official signed release. Install OpenChamber from an official release, then update again.","updateDialog.error.updaterDisabled":"The updater stopped after a failed install. Quit OpenChamber, open it again, and retry the update.","updateDialog.error.restartFailed":"Could not restart to install the update.","updateDialog.error.restartUnavailable":"Installing the update requires the OpenChamber desktop app.","mobileUpdate.toast.available.title":"OpenChamber update available","mobileUpdate.toast.available.description":"Version {version} is ready for Android.","mobileUpdate.toast.actions.download":"Download","opencodeUpdate.toast.available.title":"OpenCode update","opencodeUpdate.toast.available.description":"Version {version} available.","opencodeUpdate.toast.available.manualDescription":"Version {version} available. Update OpenCode the way you installed it, then restart OpenChamber.","opencodeUpdate.toast.actions.update":"Update","opencodeUpdate.toast.actions.reload":"Reload OpenCode","opencodeUpdate.toast.upgrading.title":"Updating OpenCode...","opencodeUpdate.toast.upgrading.description":"Keep OpenChamber open.","opencodeUpdate.toast.updated.title":"OpenCode updated","opencodeUpdate.toast.updated.description":"Update installed.","opencodeUpdate.toast.updated.descriptionWithVersion":"Version {version} installed.","opencodeUpdate.toast.failed.title":"Could not update OpenCode","opencodeUpdate.toast.failed.description":"The OpenCode upgrade failed.","opencodeUpdate.toast.reload.message":"Restarting OpenCode...","memoryDebugPanel.title":"Debug Panel","memoryDebugPanel.tabs.memory":"Memory","memoryDebugPanel.tabs.streaming":"Streaming","memoryDebugPanel.tabs.requests":"Requests","memoryDebugPanel.section.sessionsInMemory":"Sessions in Memory","memoryDebugPanel.section.uiStreamingMetrics":"UI Streaming Metrics","memoryDebugPanel.section.vscodeBridgeMetrics":"VS Code Bridge Metrics","memoryDebugPanel.section.noUiSamples":"No UI streaming samples yet. Start a stream and keep this panel open.","memoryDebugPanel.section.noVscodeSamples":"No VS Code bridge samples yet.","memoryDebugPanel.metric.totalMessages":"Total Messages","memoryDebugPanel.metric.cachedSessions":"Cached Sessions","memoryDebugPanel.metric.userMessages":"User Messages","memoryDebugPanel.metric.assistantMessages":"Assistant Messages","memoryDebugPanel.metric.viewportWindow":"Viewport Window","memoryDebugPanel.metric.zombieTimeout":"Zombie Timeout","memoryDebugPanel.metric.githubTotalRequests":"GitHub Total Requests","memoryDebugPanel.metric.metrics":"Metrics","memoryDebugPanel.metric.samples":"Samples","memoryDebugPanel.metric.lastUpdate":"Last Update","memoryDebugPanel.metric.uiMetrics":"UI Metrics","memoryDebugPanel.metric.vscodeMetrics":"VS Code Metrics","memoryDebugPanel.metric.messageListRenders":"MsgList Renders","memoryDebugPanel.metric.messageListStreamRenders":"MsgList Stream Renders","memoryDebugPanel.metric.chatMessageRenders":"ChatMessage Renders","memoryDebugPanel.metric.chatMessageStreamRenders":"ChatMessage Stream Renders","memoryDebugPanel.metric.chatMessageStaticDuringStream":"ChatMessage Static During Stream","memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn":"ChatMessage Static Outside Active Turn","memoryDebugPanel.metric.messagesValue":"{count} messages","memoryDebugPanel.metric.minutesValue":"{count} minutes","memoryDebugPanel.metric.msgsValue":"{count} msgs","memoryDebugPanel.metric.roleMsgsValue":"U {user} / A {assistant}","memoryDebugPanel.metric.countValue":"count {value}","memoryDebugPanel.metric.avgValue":"avg {value}","memoryDebugPanel.metric.maxValue":"max {value}","memoryDebugPanel.metric.totalValue":"total {value}","memoryDebugPanel.actions.logState":"Log State","memoryDebugPanel.actions.copyJson":"Copy JSON","memoryDebugPanel.tooltip.logCurrentState":"Log current memory state to browser console","memoryDebugPanel.streaming.copy.copied":"Streaming debug JSON copied","memoryDebugPanel.streaming.copy.failed":"Failed to copy JSON","memoryDebugPanel.streaming.copy.hint":"Copy exports both UI and VS Code streaming metrics as JSON","memoryDebugPanel.requests.inFlight":"In flight","memoryDebugPanel.requests.peak":"Peak","memoryDebugPanel.requests.duration":"Duration","memoryDebugPanel.requests.totalRequests":"Total Requests","memoryDebugPanel.requests.tracking":"Tracking","memoryDebugPanel.requests.now":"now","memoryDebugPanel.requests.noSamples":"No requests tracked yet. Keep this panel open to record fetch activity.","memoryDebugPanel.requests.chartLabel":"Fetch requests in flight over time, peak {peak}","memoryDebugPanel.requests.windowHint":"last {seconds}s","memoryDebugPanel.requests.percentileChartLabel":"In-flight request age percentiles (p50, p90, p99, max) over time","memoryDebugPanel.common.idle":"idle","memoryDebugPanel.common.live":"live","memoryDebugPanel.common.notAvailable":"n/a","memoryDebugPanel.common.untitled":"Untitled","directoryTree.field.newDirectoryPlaceholder":"new_directory","textarea.resizeHandleAria":"Resize textarea","sidebar.resize.leftPanelAria":"Resize left panel","sidebar.resize.rightPanelAria":"Resize right panel","mainLayout.mobile.closeDrawerAria":"Close drawer","sortableTabsStrip.aria.tabs":"Tabs","openChamberLogo.aria.logo":"OpenChamber logo","markdownRenderer.code.proposal":"Proposal","markdownRenderer.code.actions.copyTitle":"Copy code","markdownRenderer.code.actions.copiedTitle":"Copied","markdownRenderer.code.actions.runTitle":"Run command. The agent continues from its output","markdownRenderer.code.actions.stopTitle":"Stop command","markdownRenderer.code.run.startFailed":"Could not start the command","markdownRenderer.code.run.running":"Running","markdownRenderer.code.run.finished":"Finished","markdownRenderer.code.run.failed":"Exit code {code}","markdownRenderer.code.run.stopped":"Stopped","markdownRenderer.table.actions.copyTitle":"Copy table","markdownRenderer.code.actions.enableWrapTitle":"Enable line wrap","markdownRenderer.code.actions.disableWrapTitle":"Disable line wrap","markdownRenderer.table.actions.enableWrapTitle":"Enable cell wrap","markdownRenderer.table.actions.disableWrapTitle":"Disable cell wrap","markdownRenderer.table.actions.downloadTitle":"Download table","markdownRenderer.table.toast.downloadedAsFormat":"Table downloaded as {format}","markdownRenderer.mermaid.actions.copyTitle":"Copy","markdownRenderer.mermaid.actions.copySourceTitle":"Copy source","markdownRenderer.mermaid.actions.downloadSvgTitle":"Download SVG","markdownRenderer.mermaid.actions.zoomInTitle":"Zoom in","markdownRenderer.mermaid.actions.zoomOutTitle":"Zoom out","markdownRenderer.mermaid.actions.resetViewTitle":"Reset view","markdownRenderer.mermaid.toast.downloadFailed":"Failed to download diagram","common.date.today":"Today","common.date.yesterday":"Yesterday","common.date.yesterdayWithTime":"Yesterday {time}","common.relative.justNow":"Just now","common.relative.minutesAgoShort":"{count}min ago","common.relative.hoursAgoShort":"{count}h ago","common.relative.daysAgoShort":"{count}d ago","common.relative.weeksAgoShort":"{count}w ago","common.relative.yearsAgoShort":"{count}y ago","common.relative.minutesAgoCompact":"{count}m","common.relative.hoursAgoCompact":"{count}h","common.relative.daysAgoCompact":"{count}d","common.relative.weeksAgoCompact":"{count}w","common.relative.monthsAgoCompact":"{count}mo","common.relative.yearsAgoCompact":"{count}y","common.duration.secondsCompact":"{seconds}s","common.duration.minutesSecondsCompact":"{minutes}m {seconds}s","common.duration.hoursMinutesCompact":"{hours}h {minutes}m","contextFileOpen.failure.tooLarge":"{name} is too large to open","contextFileOpen.failure.tooLargeDetail":"More than {count} lines · {size}","contextFileOpen.failure.tooLargeSize":"Larger than {limit} · {size}","contextFileOpen.failure.missing":"{name} was not found","contextFileOpen.failure.unreadable":"Couldn't open {name}","quota.window.5h":"5-Hour","quota.window.7d":"7-Day Limit","quota.window.extraUsage":"Extra Usage","quota.window.weekly":"Weekly","quota.window.daily":"Daily","quota.window.monthly":"Monthly","quota.window.credits":"Credits","quota.value.creditsUsed":"{credits} Credits Used","quota.window.keyLimit":"Key Limit","quota.window.creditsBalance":"Credits Balance","quota.window.monthlyCredits":"Monthly Credits","quota.window.purchasedCredits":"Purchased Credits","quota.window.freeCredits":"Free Credits","quota.window.billingCycle":"Billing Cycle","quota.window.auto":"Auto","quota.window.api":"API","quota.window.planLimit":"Plan Limit","quota.window.onDemand":"On-demand","quota.window.session":"Session","quota.window.premium":"Premium Interactions","quota.window.chat":"Chat Requests","quota.window.completions":"Completions","quota.window.premiumInteractions":"AI Credits","chat.workStatus.ariaLabel":"Work status","chat.workStatus.mobileEmpty":"Nothing to show for this session yet","chat.workStatus.context.label":"Context","chat.workStatus.cost.breakdown":"Session {session} · Subagents {subagents}","chat.workStatus.git.changedFileSingle":"{count} file changed","chat.workStatus.git.changedFilePlural":"{count} files changed","chat.workStatus.pr.untitled":"Untitled pull request","chat.workStatus.mr.untitled":"Untitled merge request","chat.workStatus.pr.draft":"Draft","chat.workStatus.pr.checks":"Checks","chat.workStatus.pr.checksFailed":"{count} failed","chat.workStatus.pr.checksPending":"{count} running","chat.workStatus.pr.checksPassed":"{count} passed","chat.workStatus.attention.merge":"Merge in progress","chat.workStatus.attention.rebase":"Rebase in progress","chat.workStatus.attention.cherryPick":"Cherry-pick in progress","chat.workStatus.attention.revert":"Revert in progress","chat.workStatus.attention.bisect":"Bisect in progress","chat.workStatus.subagent.done":"Done","chat.workStatus.subagent.failed":"Failed","chat.workStatus.subagent.untitled":"Subagent","chat.workStatus.mcp.toggle":"Toggle {name}","chat.workStatus.mcp.needsAuth":"Sign in","chat.workStatus.mcp.failed":"Failed","chat.workStatus.pinned.unavailable":"Pinned message","chat.workStatus.section.session":"Session","chat.workStatus.section.project":"Project","chat.workStatus.section.subagents":"Subagents","chat.workStatus.section.mcp":"MCP","chat.workStatus.section.pinned":"Pinned messages","chat.workStatus.section.tasks":"Tasks","chat.workStatus.subagent.working":"is working","chat.workStatus.subagent.needsPermission":"needs permission","chat.workStatus.subagent.askedQuestion":"asked a question","chat.workStatus.section.contextBreakdown":"Context sources","chat.workStatus.breakdown.skills":"Skills","chat.workStatus.breakdown.pinnedNote":"note","chat.workStatus.breakdown.unpin":"Unpin from context","chat.workStatus.breakdown.pinnedPlan":"plan","chat.workStatus.breakdown.memory":"Agent memory","chat.workStatus.breakdown.pinnedKnowledgeSingle":"{count} pinned","chat.workStatus.breakdown.pinnedKnowledgePlural":"{count} pinned","chat.workStatus.breakdown.mcp":"MCP servers","chat.workStatus.action.openChanges":"Open changes","chat.workStatus.action.openGit":"Open Git panel","chat.workStatus.action.openPr":"Open pull request","chat.workStatus.action.openMr":"Open merge request","chat.workStatus.action.openSubagent":"Open {name}","chat.workStatus.section.usage":"Usage","chat.workStatus.section.telemetry":"Turn stats","chat.workStatus.telemetry.previousTurn":"Previous turn","chat.workStatus.telemetry.previousTurnRate":"Previous turn · {rate}","chat.workStatus.telemetry.responseSpeed":"Response","chat.workStatus.telemetry.responseSpeedDescription":"How fast the final text arrived. Excludes the initial wait, reasoning, and earlier tool calls. An estimate from text timestamps, not a provider speed measurement.","chat.workStatus.telemetry.speed":"Whole turn","chat.workStatus.telemetry.speedDescription":"Tokens generated across all steps, including reasoning, divided by time with tool execution removed. Waiting for the model still counts, so many short tool calls can lower this number.","chat.workStatus.telemetry.elapsed":"Elapsed","chat.workStatus.telemetry.elapsedDescription":"Wall-clock time from the first user message to the final assistant response. Includes model waiting, tool execution, compaction, and other gaps.","chat.workStatus.telemetry.llmDuration":"Model time","chat.workStatus.telemetry.llmDurationDescription":"Time spent on all model steps, including waiting for responses. Tool execution time is removed. This is not just time spent generating text.","chat.workStatus.telemetry.toolDuration":"Tool time","chat.workStatus.telemetry.toolDurationDescription":"Time spent running tools, including failed calls. Tools running at the same time are counted once, not added together.","chat.workStatus.telemetry.ttft":"Average TTFT","chat.workStatus.telemetry.ttftDescription":"Average wait before the first text or reasoning starts in each model step. Hidden when a step has no start after it was created, which is common for tool-only steps and for parts stamped at creation time.","chat.workStatus.telemetry.steps":"Steps","chat.workStatus.telemetry.stepsDescription":"How many times the model was called for this prompt. Reading tool results and deciding what to do next usually takes another step.","chat.workStatus.telemetry.tokens":"Tokens","chat.workStatus.telemetry.tokens.inOut":"{input} ↑ · {output} ↓","chat.workStatus.telemetry.tokensDescription":"↑ Input without cached tokens: {input}. ↓ Generated tokens: {output} for text and tool calls, plus {reasoning} for reasoning. Totals cover all steps of this prompt.","chat.workStatus.telemetry.cacheHit":"Cache","chat.workStatus.telemetry.cacheHitDescription":"Share of input tokens reused from the prompt cache across all steps. Reusing context can reduce cost and waiting, but this is not a speed score.","chat.workStatus.telemetry.cost":"Cost","chat.workStatus.telemetry.costDescription":"Cost reported by the provider for all model steps of this prompt, in US dollars. Excludes separate subagent sessions. Zero can mean a free model or a provider that reports no charge.","chat.workStatus.goal.open":"Manage goal","chat.workStatus.goal.pause":"Pause","chat.workStatus.goal.resume":"Resume","chat.workStatus.goal.updateFailed":"Could not update the goal","chat.workStatus.pinned.unpin":"Unpin message","chat.workStatus.pinned.reveal":"Go to message","chat.workStatus.pinned.unpinFailed":"Could not unpin the message","chat.workStatus.action.openContext":"Open context panel","chat.workStatus.section.linkedIssues":"Linked","chat.workStatus.linkedIssues.openOnProvider":"Open {reference} on {provider}","chat.workStatus.linkedIssues.unlink":"Remove link","chat.workStatus.linkedIssues.unlinkFailed":"Could not remove the link","chat.workStatus.linkedIssues.link":"Link to session","chat.workStatus.linkedIssues.linkFailed":"Could not link","chat.workStatus.breakdown.issueCountSingle":"{count} issue","chat.workStatus.breakdown.issueCountPlural":"{count} issues","chat.workStatus.breakdown.prCountSingle":"{count} PR","chat.workStatus.breakdown.mrCountSingle":"{count} MR","chat.workStatus.breakdown.prCountPlural":"{count} PRs","chat.workStatus.breakdown.mrCountPlural":"{count} MRs","chat.workStatus.breakdown.skillCountSingle":"{count} skill","chat.workStatus.breakdown.skillCountPlural":"{count} skills","chat.workStatus.breakdown.mcpCountSingle":"{count} MCP","chat.workStatus.breakdown.mcpCountPlural":"{count} MCP","chat.workStatus.sections.open":"Choose sections","chat.workStatus.sections.dialogTitle":"Panel sections","chat.workStatus.sections.reorder":"Drag {label} to reorder","chat.workStatus.sections.dragInstructions":"Press Space to pick up a section, use the arrow keys to move it, and press Space to drop. Press Escape to cancel.","chat.workStatus.sections.position":"{label}, position {position} of {count}.","chat.workStatus.sections.dragCancelled":"Reordering cancelled.","chat.workStatus.sections.dialogDescription":"Choose what the work-status panel shows. Hidden sections keep their data — they are only left out of the panel.","chat.workStatus.sections.allHidden":"No sections selected","chat.workStatus.sections.showAll":"Show all","chat.workStatus.sections.noneWarning":"The panel will appear empty.","header.workStatusPanel.toggleAria":"Toggle work-status panel","header.actions.newMiniChat":"New Mini Chat Window","header.actions.newMiniChatAria":"Open a new Mini Chat window","header.actions.openSessionMiniChat":"Open Session in Mini Chat","header.actions.openSessionMiniChatAria":"Open current session in Mini Chat","header.workStatusPanel.hide":"Hide work status","header.workStatusPanel.show":"Show work status","chat.workStatus.mcp.authorizeOpenFailed":"Could not open the authorization page","chat.workStatus.mcp.authorizeFailed":"Authorization failed","chat.formCard.inputNeeded":"Input needed","chat.formCard.fromSubagent":"from a subagent","chat.formCard.required":"Required","chat.formCard.openLink":"Open link","chat.formCard.yes":"Yes","chat.formCard.other":"Other","chat.formCard.yourAnswer":"Your answer","chat.formCard.submit":"Submit","chat.formCard.cancel":"Cancel","chat.formCard.missingRequired":"Fill in the required fields first.","chat.formCard.submitFailed":"Could not submit the answer","chat.formCard.cancelFailed":"Could not cancel the request","chat.formCard.tryAgain":"Try again.","chat.formCard.recoveredNotice":"The turn stopped while waiting. Submit starts a new paid turn.","chat.formDock.progress":"{current} of {total}","chat.formDock.waiting":"{count} more waiting","chat.formDock.back":"Back","chat.formDock.expandAria":"Expand the question","chat.formDock.collapseAria":"Collapse the question","chat.formDock.stepAria":"Question {index}: {title}","chat.formDock.linkInfo":"Open the link, then continue.","chat.permissionCard.title":"Permission required","chat.permissionCard.summary.externalDirectory":"Access files outside the project","chat.permissionCard.summary.read":"Read a file","chat.permissionCard.summary.edit":"Edit files","chat.permissionCard.summary.shell":"Run a command","chat.permissionCard.summary.glob":"Find files","chat.permissionCard.summary.grep":"Search file contents","chat.permissionCard.summary.webfetch":"Open a web page","chat.permissionCard.summary.websearch":"Search the web","chat.permissionCard.summary.skill":"Load a skill","chat.permissionCard.summary.tool":"Use {tool}","chat.permissionCard.summary.inPath":"in {path}","chat.permissionCard.showDetails":"Show details","chat.permissionDock.expandAria":"Expand the permission request","chat.permissionDock.collapseAria":"Collapse the permission request","chat.permissionDock.stepAria":"Request {index}: {tool}","chat.permissionCard.allowOnce":"Allow once","chat.permissionCard.alwaysAllow":"Always allow","chat.permissionCard.alwaysAllowPatterns":"Always: {patterns}","chat.permissionCard.deny":"Deny","chat.permissionCard.replaceAll":"Replaces every occurrence","chat.compaction.running":"Compacting the conversation","chat.compaction.completed":"Conversation compacted","chat.compaction.failed":"Compaction failed","chat.compaction.showSummary":"Show summary","chat.compaction.hideSummary":"Hide summary","chat.dispatchedSession.completed":"Session finished: {title}","chat.dispatchedSession.failed":"Session failed: {title}","chat.dispatchedSession.cancelled":"Session stopped: {title}","chat.dispatchedSession.completedUntitled":"Session finished","chat.dispatchedSession.failedUntitled":"Session failed","chat.dispatchedSession.cancelledUntitled":"Session stopped","chat.dispatchedSession.showAnswer":"Show answer","chat.dispatchedSession.hideAnswer":"Hide answer","chat.dispatchedSession.open":"Open session","chat.fileOpenRequest.toast.description":"Shown in {session}","chat.fileOpenRequest.toast.descriptionUntitled":"Shown in another session","chat.fileOpenRequest.toast.openSession":"Open session","chat.revertPopover.staged":"Reverted: {count}","chat.revertPopover.toast.restoreFailed":"Couldn't restore the reverted messages","chat.workStatus.mcp.needsAuthHint":"Sign in to this MCP server from Settings → MCP.","mcpDropdown.toast.authorizeOpenFailed":"Could not open the authorization page","mcpDropdown.toast.authorizeFailed":"Authorization failed","header.services.tooltip.currentInstance":"Current instance: {current} ({toggle})","header.workStatusPanel.showOverlay":"Show work status over the chat","settings.mcp.page.connection.title":"How to reach it","settings.mcp.page.connection.description":"Paste the command that starts it, or the link to a hosted server.","settings.mcp.page.registration.title":"This server needs its own app","settings.mcp.page.registration.description":"It does not hand out credentials automatically. Create an app in the service’s own settings, paste its details here, then sign in.","settings.mcp.page.registration.callbackLabel":"Give the service this address","settings.mcp.page.registration.clientId":"App ID","settings.mcp.page.registration.clientSecret":"App secret","settings.mcp.page.registration.afterSaving":"Save, then press Authorize to sign in.","settings.mcp.page.toast.copiedCallbackUrl":"Address copied","settings.mcp.page.toast.clipboardWriteFailed":"Could not copy to the clipboard","settings.mcp.page.scope.everywhere":"Available in every project","settings.mcp.page.scope.thisProject":"Only in this project","settings.mcp.page.env.description":"Values the server needs, such as an API key.","settings.mcp.page.connection.kindCommand":"Command","settings.mcp.page.connection.kindLink":"Link","settings.mcp.page.connection.hintCommand":"Runs on this machine. Paste a whole command and it is split into one argument per line.","settings.mcp.page.connection.hintLink":"Connects to a server someone else hosts. Paste its https address.","chat.messageBody.actions.askOtherModels":"Ask other models","chat.modelControls.runInParallel":"Run on several models","chat.parallel.defaultTitle":"Parallel run","chat.parallel.exit":"Leave parallel mode","chat.parallel.fuse.judge":"Fuse with {model}","chat.parallel.fuse.off":"Fuse: off","chat.parallel.isolation.shared":"Shared directory","chat.parallel.isolation.worktrees":"Separate worktrees","chat.parallel.models.add":"Add model","chat.parallel.models.decrement":"Run {model} one time less","chat.parallel.models.increment":"Run {model} one more time","chat.parallel.runAria":"Start parallel runs ({count})","chat.parallel.setup.dialogDescription":"Commands run in every new worktree before its prompt, one per line.","chat.parallel.toast.failed":"Could not start the parallel run.","chat.parallel.toast.incomplete":"Every prompt variant needs text and at least one model.","chat.parallel.variant.removeAria":"Remove variant {variant}","chat.parallel.variant.runsPlural":"{count} runs","chat.parallel.variant.runsSingle":"{count} run","chat.parallel.variant.tabsAria":"Prompt variants","multirun.ask.checking":"Checking this answer…","multirun.ask.description":"This chat becomes the first run. Each model gets the same first prompt in its own worktree.","multirun.ask.failed":"Could not ask other models.","multirun.ask.notFirstTurn":"Only the first answer of a chat can be compared for now.","multirun.ask.startPlural":"Run {count} more","multirun.ask.startSingle":"Run {count} more","multirun.ask.title":"Ask other models","multirun.overview.archive.action":"Archive run","multirun.overview.archive.failed":"Some runs could not be archived.","multirun.overview.ask.failed":"Could not add the model to this run.","multirun.overview.ask.working":"Adding…","multirun.overview.bar.fuse":"Fuse results","multirun.overview.bar.hint":"Fuse the answers into one result","multirun.overview.cancel":"Cancel","multirun.overview.card.changesUnavailable":"Changes unavailable","multirun.overview.card.diff":"Diff","multirun.overview.card.filesPlural":"{count} files","multirun.overview.card.filesSingle":"{count} file","multirun.overview.card.noChanges":"No file changes","multirun.overview.card.noReply":"No answer yet","multirun.overview.card.openChat":"Open chat","multirun.overview.card.replyUnavailable":"Answer unavailable","multirun.overview.card.selectAria":"Select {name}","multirun.overview.card.working":"Working…","multirun.overview.fuse.modeAnswers":"Combines the final answers","multirun.overview.fuse.modeCode":"Works in its own worktree and reads each run with git","multirun.overview.fuse.selected":"{count} of {total} selected","multirun.overview.fuse.with":"Fuse with","multirun.overview.fusedResult":"Fused result","multirun.overview.headerTitle":"Run in parallel","multirun.overview.keep.confirm":"Keep and clean up","multirun.overview.keep.confirmPlural":"Keep {name}? The other {count} runs are archived and their worktrees removed. Their work stays recoverable.","multirun.overview.keep.confirmSingle":"Keep {name}? The other run is archived and its worktree removed. Its work stays recoverable.","multirun.overview.keep.done":"Kept {name}","multirun.overview.keep.failed":"Could not clean up the other runs.","multirun.overview.keep.partialPlural":"Kept {name}. {count} runs could not be cleaned up and were left as they were.","multirun.overview.keep.partialSingle":"Kept {name}. One run could not be cleaned up and was left as it was.","multirun.overview.keep.working":"Cleaning up…","multirun.overview.meta.autoFusion":"Fuses with {model} when all finish","multirun.overview.meta.progress":"{done} of {total} finished","multirun.overview.meta.runsPlural":"{count} runs","multirun.overview.meta.runsSingle":"{count} run","multirun.overview.meta.sharedDirectory":"Shared directory","multirun.overview.meta.variants":"{count} prompt variants","multirun.overview.meta.worktrees":"Separate worktrees","multirun.overview.missing":"This run is no longer available.","multirun.overview.rename.aria":"Rename run","multirun.overview.rename.failed":"Some runs kept the old name.","sessions.sidebar.run.collapse":"Hide runs","sessions.sidebar.run.expand":"Show runs","sessions.sidebar.run.laneCountPlural":"{count} runs","sessions.sidebar.run.laneCountSingle":"{count} run","sessions.sidebar.run.openOverviewAria":"Open parallel run {title}","sessions.sidebar.run.menu.openOverview":"Open overview","sessions.sidebar.session.menu.openRunOverview":"Open run overview","chat.parallel.models.effortAria":"Thinking effort: {effort}","chat.parallel.settings.title":"Launch settings","chat.parallel.settings.whereTitle":"Where the runs work","chat.parallel.settings.setupTitle":"Setup commands","chat.parallel.settings.fusionTitle":"Fusion","chat.parallel.settings.variantsTitle":"Prompt variants","chat.parallel.settings.variantsDescription":"Send different prompts, for example to compare skills or wording. Each variant gets its own tab.","chat.parallel.settings.addVariant":"Add a prompt variant","chat.parallel.settings.done":"Done","chat.parallel.settings.openAria":"Launch settings: {summary}","multirun.overview.card.keep":"Keep this","multirun.overview.addModel.action":"Add a model","multirun.overview.addModel.hint":"Runs the same prompt on one more model in this run","chat.parallel.settings.whereShared":"Project directory","chat.parallel.settings.whereSharedHint":"All runs work in your checkout. Best for questions and research.","chat.parallel.settings.whereWorktrees":"Separate worktrees","chat.parallel.settings.whereWorktreesHint":"Each run gets its own branch, so code changes never collide. Keep the best one.","chat.parallel.settings.baseBranchTitle":"Base branch","chat.parallel.settings.fusionOff":"Off","chat.parallel.settings.fusionOffHint":"Compare the results yourself.","chat.parallel.settings.fusionAuto":"Automatic","chat.parallel.settings.fusionAutoHint":"Fuse the results as soon as every run finishes.","chat.parallel.settings.judgeTitle":"Fusion model","multirun.overview.card.detach":"Make a separate session","multirun.overview.card.detachHint":"Leave this run and continue as an ordinary session","multirun.overview.card.detachDone":"{name} is now a separate session","multirun.overview.card.detachFailed":"Could not move this session out of the run.","multirun.overview.card.archive":"Archive this session","multirun.overview.addModel.confirm":"Run","multirun.overview.status.permission":"Waiting for your permission","multirun.overview.status.question":"Waiting for your answer","multirun.overview.status.working":"Working","multirun.overview.status.failed":"Failed","multirun.overview.status.stopped":"Stopped","multirun.overview.status.notStarted":"Not started","multirun.overview.status.noReply":"Finished without an answer","multirun.overview.status.finished":"Finished","multirun.overview.status.count.permission":"{count} waiting for permission","multirun.overview.status.count.question":"{count} waiting for an answer","multirun.overview.status.count.working":"{count} working","multirun.overview.status.count.failed":"{count} failed","multirun.overview.status.count.stopped":"{count} stopped","multirun.overview.status.count.notStarted":"{count} not started","multirun.overview.status.count.noReply":"{count} without an answer","multirun.overview.status.count.finished":"{count} finished","multirun.overview.card.body.permission":"Waiting for your permission to go on. Open the chat to answer.","multirun.overview.card.body.question":"Asked you a question. Open the chat to answer.","multirun.overview.card.body.failed":"Failed. Open the chat for details.","multirun.overview.card.body.notStarted":"Has not started yet.","multirun.overview.card.body.stopped":"Stopped before answering.","multirun.overview.bar.waiting":"Runs waiting for you: {count}. The run can't finish until you answer them.","multirun.overview.prompt.expand":"Show all","multirun.overview.prompt.collapse":"Show less","gitView.changes.revertFileDialogTitle":"Revert file changes?","gitView.changes.revertFileDescription":"This will discard your local changes in {path}.","gitView.changes.revertFileConfirm":"Revert file","diffView.hunk.discardDialogTitle":"Discard this hunk?","diffView.hunk.discardDescription":"This will discard these local changes in {path}.","sessions.sidebar.project.actions.archiveAll":"Archive all sessions","sessions.sidebar.project.archiveAll.title":"Archive sessions in {project}?","sessions.sidebar.project.archiveAll.descriptionSingle":"{count} session moves to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.descriptionPlural":"{count} sessions move to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.nothing":"Nothing to archive: every session here is pinned, running or In work.","contextPanel.browser.devServers.hide":"Hide port {port} from this list","contextPanel.browser.devServers.showHiddenSingle":"Show {count} hidden port","contextPanel.browser.devServers.showHiddenPlural":"Show {count} hidden ports","sidebarFilesTree.menu.openInDefaultApp":"Open in default app","sessions.sidebar.header.displayMode.showChats":"Show chats section","sessions.scheduledTasks.editor.useDefaults.label":"Use session defaults","sessions.scheduledTasks.editor.useDefaults.hint":"Each run takes the default model, thinking level and agent from Settings → Sessions (or the project's own defaults) at the time it starts.","sessions.scheduledTasks.editor.worktree.label":"Run each run in a fresh worktree","sessions.scheduledTasks.editor.worktree.hint":"Each run gets its own worktree and branch.","sessions.scheduledTasks.editor.worktree.baseBranch.label":"Source branch","sessions.scheduledTasks.editor.worktree.cleanup.label":"Clean up worktree after run","sessions.scheduledTasks.editor.worktree.cleanup.hint":"The worktree and its branch are removed when the run ends.","sessions.scheduledTasks.editor.worktree.cleanup.keepHint":"The worktree and its branch stay after the run so you can review the result.","sessions.scheduledTasks.editor.worktree.notRepo":"The project folder is not a git repository; runs will use the checkout as-is.","sessions.scheduledTasks.dialog.usesDefaults":"Session defaults","sessions.moveSession.menu":"Move session…","sessions.moveSession.hint":"Files stay in the old folder","sessions.moveSession.title":"Move session","sessions.moveSession.description":"The session continues in the chosen folder. Files stay where they are.","sessions.moveSession.chooseFolder":"Choose folder…","sessions.moveSession.current":"Current folder","sessions.moveSession.success":"Session moved","sessions.moveSession.failed":"Could not move the session","chat.folderMissing.text":"Folder {name} no longer exists","chat.folderMissing.action":"Move session","chat.worktreeSetup.running":"Setting up the worktree: running the project's setup commands…","chat.draft.creatingSession":"Creating session…","desktopHostSwitcher.startup.fellBackToLocal":"Its connection didn't open, so OpenChamber started on Local. Connect it from the instance switcher once it's reachable.","desktopSafeStart.title":"OpenChamber kept crashing","desktopSafeStart.description":"Panels are closed and folders collapsed.","chat.chatInput.contextPreview.saveEdit":"Save comment","chat.chatInput.contextPreview.cancelEdit":"Cancel editing","sessions.scheduledTasks.dialog.actions.openSession":"Open session","sessions.scheduledTasks.dialog.actions.openSessionAria":"Open the session from the last run of {taskName}","sessions.scheduledTasks.dialog.toast.alreadyRunningSince":"This task already has a run in progress, started at {time}","sessions.scheduledTasks.dialog.toast.alreadyRunning":"This task already has a run in progress","sessions.scheduledTasks.dialog.toast.alreadyQueued":"This task is already waiting in the queue and will run when a slot frees up","chat.modelControls.agentFavoriteAdd":"Add to favorites. With favorites, Tab cycles through them only","notifications.error.bodyFallback":"An error occurred","notifications.question.bodyFallback":"Agent is waiting for your response","notifications.permission.bodyFallback":"Agent is waiting for your approval","notifications.permission.title":"Permission required","chat.promptHistorySearch.title":"Search prompt history","chat.promptHistorySearch.searchPlaceholder":"Search remembered prompts","chat.promptHistorySearch.close":"Close prompt history search","chat.promptHistorySearch.empty":"No prompts to search yet","chat.promptHistorySearch.noMatches":"No matching prompts","chat.promptHistorySearch.attachmentsSingle":"{count} attachment","chat.promptHistorySearch.attachmentsPlural":"{count} attachments","chat.promptHistorySearch.hint":"↑ ↓ to browse · Enter to load · Esc to close","helpDialog.item.searchPromptHistory":"Search prompt history (chat input)"},ml=new Map([[wi,ki]]);async function wA(e){const t=ml.get(e);if(t)return t;const s=e==="zh-CN"?await qe(()=>import("./zh-CN-BPcuR4-K.js"),__vite__mapDeps([3,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="fr"?await qe(()=>import("./fr-DN3Tx1EV.js"),__vite__mapDeps([109,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="nl"?await qe(()=>import("./nl-CL94_9kf.js"),__vite__mapDeps([110,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="zh-TW"?await qe(()=>import("./zh-TW-CmPAjna9.js"),__vite__mapDeps([111,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="es"?await qe(()=>import("./es-BWlkhnKy.js"),__vite__mapDeps([112,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pt-BR"?await qe(()=>import("./pt-BR-Bfrsw-GS.js"),__vite__mapDeps([113,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="uk"?await qe(()=>import("./uk-zPAKOL1d.js"),__vite__mapDeps([114,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ko"?await qe(()=>import("./ko-CETaCyB8.js"),__vite__mapDeps([115,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pl"?await qe(()=>import("./pl-Bk1GuZBm.js"),__vite__mapDeps([116,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="de"?await qe(()=>import("./de-SUU4F7Nt.js"),__vite__mapDeps([117,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ja"?await qe(()=>import("./ja-DE4Yf-rX.js"),__vite__mapDeps([118,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="tr"?await qe(()=>import("./tr-Cgg3eQb7.js"),__vite__mapDeps([119,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ar"?await qe(()=>import("./ar-DnPStsLU.js"),__vite__mapDeps([120,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="he"?await qe(()=>import("./he-B-7jIB_R.js"),__vite__mapDeps([121,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):{dict:ki};return ml.set(e,s.dict),s.dict}const _o=vt()((e,t)=>({locale:wi,dictionary:ki,loadingLocale:null,setLocale:s=>{const a=t(),n=ml.get(s);a.locale===s&&a.loadingLocale!==s&&n||(ez(s),e({locale:s,dictionary:n??a.dictionary,loadingLocale:n?null:s}),!n&&wA(s).then(i=>{t().locale===s&&e({dictionary:i,loadingLocale:null})}).catch(i=>{console.error(`[i18n] failed to load locale ${s}`,i),t().locale===s&&e({dictionary:ki,loadingLocale:null})}))}}));function kA(){_o.getState().setLocale(tz())}function yA(e,t,s){const a=e[t]??ki[t]??t;return s?a.replace(/\{([^{}]+)\}/g,(n,i)=>{const o=s[i.trim()];return o==null?n:String(o)}):a}const WV=Object.freeze(Object.defineProperty({__proto__:null,formatMessage:yA,initializeLocale:kA,useI18nStore:_o},Symbol.toStringTag,{value:"Module"})),Tf="session",zf=40,vA=1,CA=100,Af=e=>e==="global"||e==="session",Ad=e=>e!=null&&Number.isInteger(e)&&e>=vA&&e<=CA,SA=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Rd=e=>e==="auto"||typeof e=="string"&&SA.includes(e),Ma="openchamber-input-history.v1",xA=8,PA=50,TA=[40,25,10,5,1],pc=Object.freeze([]);let is=null,zg=0;const Yn=(e=Tf,t=zf)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Rf=()=>(zg+=1,Date.now()*1e3+zg),If=e=>JSON.stringify([e]),hl=(e,t,s)=>JSON.stringify([e,t,s]),Id=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},zA=()=>{const e=Id(),t=Dt?JSON.stringify(To(Dt.base)):is;if(!e)return t;try{return e.getItem(Ma)??(Dt?null:is)}catch{return t}},Ag=kt(p(),ee()),AA=g({key:p().min(1),source:J([k("file-url"),k("vscode-file")]),filename:p().min(1),mimeType:p().min(1),size:v().finite().nonnegative(),reference:p().min(1),path:p().min(1).optional()}),RA=g({text:p(),attachmentKeys:z(p()),restorableAttachments:z(AA),submittedAt:v().finite().nonnegative()}),IA=g({touchedAt:v().finite().nonnegative(),entries:z(ee())}),jA=(e,t)=>{try{const s=JSON.parse(e),n=(t===1?jo([p().trim().min(1)]):jo([p().trim().min(1),p().trim().min(1),p().trim().min(1)])).safeParse(s);if(!n.success)return null;if(t===3){const i=ze(n.data[1]);if(!i||i!==n.data[1])return null}return n.data}catch{return null}},Rg=(e,t)=>{const s=[];for(const[a,n]of Object.entries(e)){if(!jA(a,t))continue;const i=IA.safeParse(n);if(!i.success)continue;const o=i.data.entries.map(r=>RA.safeParse(r)).filter(r=>r.success).map(r=>r.data);s.push([a,{touchedAt:i.data.touchedAt,entries:o}])}return Object.fromEntries(s)},OA=()=>{const e=zA();if(e===null)return Yn();try{const t=JSON.parse(e),s=g({version:k(1),entryLimit:v().int().optional(),scope:J([k("global"),k("session")]).optional(),global:Ag.default({}),session:Ag.default({})}).safeParse(t);return s.success?{entryLimit:Ad(s.data.entryLimit)?s.data.entryLimit:zf,scope:s.data.scope??Tf,globalBuckets:Rg(s.data.global,1),sessionBuckets:Rg(s.data.session,3)}:Yn()}catch{const t=Id();if(t)try{t.removeItem(Ma)}catch{}return is=null,Yn()}};let Dt=null,Po=Yn();const Ig=(e,t,s)=>{const a={...e};for(const n of new Set([...Object.keys(t),...Object.keys(s)])){if(JSON.stringify(t[n])===JSON.stringify(s[n]))continue;const i=s[n];if(!i){delete a[n];continue}const o=new Set((t[n]?.entries??[]).map(d=>JSON.stringify(d))),r=new Set(i.entries.map(d=>JSON.stringify(d))),c=(e[n]?.entries??[]).filter(d=>{const u=JSON.stringify(d);return!o.has(u)||r.has(u)}),l=new Set(c.map(d=>JSON.stringify(d)));for(const d of i.entries){const u=JSON.stringify(d);!o.has(u)&&!l.has(u)&&c.push(d)}c.sort((d,u)=>d.submittedAt-u.submittedAt),a[n]={touchedAt:Math.max(i.touchedAt,e[n]?.touchedAt??0),entries:c}}return a},qn=()=>{const e=OA();if(Po=e,!Dt)return e;const{base:t,value:s}=Dt;return fl({entryLimit:s.entryLimit===t.entryLimit?e.entryLimit:s.entryLimit,scope:s.scope===t.scope?e.scope:s.scope,globalBuckets:Ig(e.globalBuckets,t.globalBuckets,s.globalBuckets),sessionBuckets:Ig(e.sessionBuckets,t.sessionBuckets,s.sessionBuckets)})},jf=(e,t)=>e.slice(Math.max(0,e.length-t)),jg=(e,t,s)=>{const a=Object.entries(e).map(([n,i])=>[n,{touchedAt:i.touchedAt,entries:jf(i.entries,s)}]).sort((n,i)=>i[1].touchedAt-n[1].touchedAt).slice(0,t);return Object.fromEntries(a)},fl=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:jg(e.globalBuckets,xA,t),sessionBuckets:jg(e.sessionBuckets,PA,t)}),To=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Og=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Vn=e=>{const t=fl(e),s=JSON.stringify(To(t));Dt={base:Po,value:t};const a=Id();if(!a)return is=s,t;try{return a.setItem(Ma,s),Dt=null,is=s,t}catch(o){if(!(o instanceof Error)||!Og(o))return is=s,t}try{a.removeItem(Ma)}catch{}for(const o of TA){const r=fl(t,o),c=JSON.stringify(To(r));try{return a.setItem(Ma,c),Dt=null,is=c,r}catch(l){if(!(l instanceof Error)||!Og(l))return Dt={base:Po,value:r},is=c,r}}const n=Yn(t.scope,t.entryLimit),i=JSON.stringify(To(n));try{a.setItem(Ma,i),Dt=null}catch{Dt={base:Po,value:n}}return is=i,n},DA=(e,t,s)=>{const a=e.trim(),n=ze(t),i=s.trim();return!a||!n||!i?null:{runtimeKey:a,directory:n,sessionId:i}},Of=e=>e.source==="vscode"&&e.vscodeSource==="file"?ze(e.vscodePath??null):e.dataUrl.trim()||null,FA=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),bl=e=>{const t=Of(e),s=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),s].join("|")},BA=e=>{const t=Of(e);if(!t)return null;const s=e.agentPath&&e.serverPath===e.agentPath?e.agentPath:void 0;return!s&&!FA(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:bl(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:bl(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t,path:s}},NA=(e,t)=>({text:e,attachmentKeys:t.map(bl),restorableAttachments:t.map(BA).filter(s=>s!==null)}),MA=(e,t)=>e.length===t.length&&e.every((s,a)=>{const n=t[a];return n!==void 0&&s.key===n.key&&s.source===n.source&&s.filename===n.filename&&s.mimeType===n.mimeType&&s.size===n.size&&s.reference===n.reference&&s.path===n.path}),EA=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((s,a)=>s===t.attachmentKeys[a])&&MA(e.restorableAttachments,t.restorableAttachments),Dg=(e,t,s,a)=>{const n=e?[...e.entries]:[];for(const i of t){const o=n.at(-1);EA(o,i)||n.push({text:i.text,attachmentKeys:[...i.attachmentKeys],restorableAttachments:i.restorableAttachments.map(r=>({...r})),submittedAt:Rf()})}return{touchedAt:s,entries:jf(n,a)}},LA=Vn(qn()),Un=vt(e=>({...LA,applyEntryLimit:t=>{Ad(t)&&e(s=>{const a=qn();if(a.entryLimit===t)return{...s,...a};const n=Vn({entryLimit:t,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},applyScope:t=>{Af(t)&&e(s=>{const a=qn();if(a.scope===t)return{...s,...a};const n=Vn({entryLimit:a.entryLimit,scope:t,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},appendSubmissions:(t,s)=>{s.length!==0&&e(a=>{const n=qn(),i=Rf(),o=If(t.runtimeKey),r=hl(t.runtimeKey,t.directory,t.sessionId),c=Vn({entryLimit:n.entryLimit,scope:n.scope,globalBuckets:{...n.globalBuckets,[o]:Dg(n.globalBuckets[o],s,i,n.entryLimit)},sessionBuckets:{...n.sessionBuckets,[r]:Dg(n.sessionBuckets[r],s,i,n.entryLimit)}});return{...a,...c}})},clearSession:t=>{e(s=>{const a=qn(),n=hl(t.runtimeKey,t.directory,t.sessionId);if(!(n in a.sessionBuckets))return{...s,...a};const i={...a.sessionBuckets};delete i[n];const o=Vn({entryLimit:a.entryLimit,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:i});return{...s,...o}})}})),HV=(e,t)=>t?e.scope==="session"?e.sessionBuckets[hl(t.runtimeKey,t.directory,t.sessionId)]?.entries??pc:e.globalBuckets[If(t.runtimeKey)]?.entries??pc:pc,Df=["guest","link","external","repository"],qA=new Set([...Df,"linear"]),Os=p().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!qA.has(e),{message:"Reserved provider id"}),VA=I(["pullRequest","mergeRequest","change"]),UA=I(["checks","pipeline"]),WA=I(["device","pat","cli"]),HA=J([I(["instance-url","personal-access-token","username","http-password"]),p().transform(()=>"unknown")]),GA=p().max(8192).regex(/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/),Fg=p().min(1).max(64),Rn=z(p().min(1).max(256)).max(8),_A=g({id:Os,label:Fg,order:v().int(),terminology:g({changeRequest:VA.catch("pullRequest"),changeRequestPrefix:p().min(1).max(4),issuePrefix:p().min(1).max(4),sharedNumberSpace:T(),abbreviation:p().min(1).max(8),promptNoun:Fg,ci:UA.catch("checks")}),icon:g({sprite:p().max(64).optional(),filledSprite:p().max(64).optional(),path:GA.optional()}),repository:g({nestedNamespaces:T(),pathStyle:k("path").optional().catch(void 0)}),instances:g({format:I(["host","origin"]),defaultInstance:p().min(1).max(256).nullable(),multiple:T(),allowLoopbackHttp:T(),allowPort:T(),reserved:z(p().max(256)).max(16),placeholder:p().max(256),legacyFlow:g({instance:p().min(1).max(256),kind:k("github-com-device")}).optional()}),auth:g({methods:z(J([WA,p().transform(()=>null)])).transform(e=>e.filter(t=>t!==null)),cliName:p().min(1).max(32).optional(),cliTransport:T(),token:g({scopes:z(p().min(1).max(64)).max(32),createPath:p().max(256).optional()}).optional()}),settings:g({fields:z(g({id:p().min(1).max(64),kind:HA,secret:T()})).max(16)}),urls:g({changeRequest:Rn,issue:Rn,discussion:Rn.default([]).catch([]),commit:Rn.default([]).catch([]),user:Rn.default([]).catch([])}),features:g({referenceSearch:T().default(!1),referenceDetail:T().default(!1),listStatuses:T().default(!1),referencesAcross:T().default(!1),startThread:T().default(!1),reviewDrafts:T().default(!1),reviewDraftFileComments:T().default(!1),authorCanReview:T().default(!1),projectUploads:T().default(!1),issueCloseReason:T().default(!1),changeRequestTemplates:z(p().min(1).max(256)).max(8).default([]),changeRequestPatch:T().default(!0),reviewModel:I(["verdict","votes"]).default("verdict").catch("verdict"),revisions:T().default(!1).catch(!1),submitRequirements:T().default(!1).catch(!1),createByPush:T().default(!1).catch(!1),branchHeads:T().default(!0).catch(!0),discussions:T().default(!1).catch(!1)}),extension:g({guestId:p().min(1).max(128),name:p().min(1).max(200),version:p().min(1).max(64)}).optional().catch(void 0)}),KA=(e,t)=>e.order-t.order||(e.id<t.id?-1:e.id>t.id?1:0),wl=z(_A.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const a of e)!a||t.has(a.id)||(t.add(a.id),s.push(a));return s.sort(KA)}),Bg=new Map,jd=e=>{const t=Bg.get(e);if(t)return t;const s={id:e,label:e,order:Number.MAX_SAFE_INTEGER,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"git-branch"},repository:{nestedNamespaces:!1},instances:{format:"origin",defaultInstance:null,multiple:!1,allowLoopbackHttp:!1,allowPort:!1,reserved:[],placeholder:""},auth:{methods:[],cliTransport:!1},settings:{fields:[]},urls:{changeRequest:[],issue:[],discussion:[],commit:[],user:[]},features:{referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,reviewDrafts:!1,reviewDraftFileComments:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1,reviewModel:"verdict",revisions:!1,submitRequirements:!1,createByPush:!1,branchHeads:!0,discussions:!1}};return Bg.set(e,s),s},ZA=16,JA=(e,t)=>{const s=z(jo([p(),t])),a=()=>{try{const n=s.safeParse(JSON.parse(window.localStorage.getItem(e)??"[]"));return n.success?n.data:[]}catch{return[]}};return{read:n=>Lc(n)?null:a().find(([i])=>i===n)?.[1]??null,remember:(n,i)=>{if(Lc(n))return;const o=a().filter(([r])=>r!==n);o.push([n,[...i]]);try{window.localStorage.setItem(e,JSON.stringify(o.slice(-ZA)))}catch{}}}},QA=(e,t)=>e===t||e.length===t.length&&JSON.stringify(e)===JSON.stringify(t),$A=e=>Math.min(6e4,2e3*2**Math.max(0,e-1)),Ff=JA("openchamber.sourceControlProviders.v1",wl),Od=e=>({ordered:e,byId:new Map(e.map(t=>[t.id,t]))}),YA=Od([]),Ng=e=>{const t=Ff.read(e);return t?{runtimeKey:e,...Od(t),status:"stale",holdsList:!0}:{runtimeKey:e,...YA,status:"idle",holdsList:!1}};let Zs=0,Ta=null,za=null,co=0,Xn=null;const Mg=()=>{Xn!==null&&clearTimeout(Xn),Xn=null},wa=vt((e,t)=>{const s=a=>{Zs+=1,Ta=null,za=null,co=0,Mg(),e(Ng(a))};return{...Ng(D()),refresh:a=>{const n=D();if(n!==t().runtimeKey&&s(n),Ta){if(!za){const d=Zs,u=Ta.then(()=>{if(za===u&&(za=null),d===Zs)return t().refresh(a)});za=u}return za}Mg();const i=Zs,{holdsList:o,ordered:r}=t();e({status:"loading"});const l=(async()=>{try{const d=await a.providers();if(i!==Zs)return;co=0,Ff.remember(n,d),e(o&&QA(r,d)?{status:"ready"}:{...Od(d),status:"ready",holdsList:!0})}catch{if(i!==Zs)return;if(o){e({status:"stale"});return}e({status:"error"}),co+=1,Xn=setTimeout(()=>{Xn=null,i===Zs&&t().refresh(a)},$A(co))}})().finally(()=>{Ta===l&&(Ta=null)});return Ta=l,l},resetForRuntimeSwitch:s}});queueMicrotask(()=>{const e=wa.getState(),t=D();e.status==="idle"&&t!==e.runtimeKey&&e.resetForRuntimeSwitch(t)});const GV=()=>wa(eR),XA=e=>{const t=Mt.c(5);let s;t[0]!==e?(s=i=>e?i.byId.get(e):void 0,t[0]=e,t[1]=s):s=t[1];const a=wa(s);let n;return t[2]!==a||t[3]!==e?(n=a??jd(e??""),t[2]=a,t[3]=e,t[4]=n):n=t[4],n},_V=e=>XA(e).terminology.changeRequest,KV=e=>{const t=Mt.c(2);let s;return t[0]!==e?(s=a=>e&&a.byId.has(e)?"served":a.holdsList?"not-served":"unknown",t[0]=e,t[1]=s):s=t[1],wa(s)},ZV=e=>{const t=Mt.c(2);let s;return t[0]!==e?(s=a=>{const n=e?a.byId.get(e):void 0;return n?n.features.changeRequestPatch?"served":"not-served":a.holdsList?"not-served":"unknown"},t[0]=e,t[1]=s):s=t[1],wa(s)},JV=()=>{const e=Mt.c(2),t=wa(tR);let s;return e[0]!==t?(s=a=>(a?t.get(a):void 0)??jd(a??""),e[0]=t,e[1]=s):s=e[1],s},pr=e=>(e?wa.getState().byId.get(e):void 0)??jd(e??"");function eR(e){return e.ordered}function tR(e){return e.byId}const sR=g({text:p(),prefix:p(),suffix:p(),start:v(),page:g({partId:p(),kind:k("ui").optional()}).optional()}),Eg=32,Bf=200,aR="[data-chat-quote-root]";function QV(e,t){return[...e.querySelectorAll(`[data-message-id="${CSS.escape(t)}"]`)].flatMap(s=>s.querySelector(aR)??[]).sort((s,a)=>s.getBoundingClientRect().top-a.getBoundingClientRect().top)}function $V(e,t,s){return e.querySelector(`[data-ui-render-message="${CSS.escape(t)}"][data-ui-render-part="${CSS.escape(s)}"]`)}function Nf(e,t,s){const a=s+t.text.length,n=e.slice(Math.max(0,s-t.prefix.length),s),i=e.slice(a,a+t.suffix.length);return t.prefix.endsWith(n)&&t.suffix.startsWith(i)}function Lg(e,t,s){const a=e.ownerDocument.createRange();return a.setStart(e,0),a.setEnd(t,s),a.toString().length}function Mf(e){const t=[];let s="";for(const a of e)t.push(s.length),s+=a.textContent??"";return{stream:s,bases:t}}function YV(e,t){const s=Array.isArray(e)?e:[e],a=s.findIndex(d=>d.contains(t.startContainer)),n=s.findIndex(d=>d.contains(t.endContainer));if(a<0||n<a)return null;const{stream:i,bases:o}=Mf(s),r=o[a]+Lg(s[a],t.startContainer,t.startOffset),c=o[n]+Lg(s[n],t.endContainer,t.endOffset),l=i.slice(r,c);return l.trim()?{text:l,prefix:i.slice(Math.max(0,r-Eg),r),suffix:i.slice(c,c+Eg),start:r}:null}function nR(e,t){if(!t.text)return null;const s=[];for(let n=e.indexOf(t.text);n!==-1&&s.length<Bf;n=e.indexOf(t.text,n+1))s.push(n);if(s.length<=1)return s[0]??null;if(!t.prefix&&!t.suffix)return null;const a=s.filter(n=>Nf(e,t,n));return a.length===0?null:a.reduce((n,i)=>Math.abs(i-t.start)<Math.abs(n-t.start)?i:n)}function Ef(e,t){for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType===3?t.push(s):Ef(s,t);return t}function iR(e){const t=new Set;let s=1;for(const a of e){const n=a.closest("[data-message-id]")?.getAttribute("data-message-row");if(!n)return e.length===1;const[i,o]=n.split("/");t.add(i),s=Number(o)}return t.size===s}const In=32;function oR(e,t){const{text:s,prefix:a,suffix:n}=t,i=!!(a||n),o=l=>{const d=[];for(let u=e.indexOf(l);u!==-1&&d.length<Bf;u=e.indexOf(l,u+1))d.push(u);return d},r=[];for(const l of o(s))(!i||Nf(e,t,l))&&r.push({start:l,end:l+s.length});if(s.length>In&&(r.length===0||!i)){for(const l of o(s.slice(0,In))){const d=e.slice(l);d.length<s.length&&s.startsWith(d)&&a.endsWith(e.slice(Math.max(0,l-a.length),l))&&r.push({start:l,end:e.length})}for(const l of o(s.slice(-In))){const d=l+In;d<s.length&&s.endsWith(e.slice(0,d))&&n.startsWith(e.slice(d,d+n.length))&&r.push({start:0,end:d})}e.length>=In&&e.length<s.length&&s.includes(e)&&r.push({start:0,end:e.length})}return i?r[0]??null:new Set(r.map(l=>`${l.start}:${l.end}`)).size===1?r[0]:null}function rR(e,t){const{stream:s}=Mf(e);let a,n;if(iR(e))a=nR(s,t),n=(a??0)+t.text.length;else{const r=oR(s,t);a=r?.start??null,n=r?.end??0}if(a===null||n<=a)return null;const i=[];let o=0;for(const r of e){let c=null;for(const l of Ef(r,[])){const d=l.data.length;if(!c&&a<o+d&&n>o&&(c=r.ownerDocument.createRange(),c.setStart(l,Math.max(0,a-o)),c.setEnd(r,r.childNodes.length)),c&&n<=o+d)return c.setEnd(l,n-o),i.push(c),i;o+=d}c&&i.push(c)}return null}function XV(e,t){return rR([e],t)?.[0]??null}const cR=fw.gfm,lR=bw().use(ww).use(cR[0],{singleTilde:!1});function eU(e){const t=s=>{if("children"in s){if(s.type==="list")return`
|
|
34
|
+
{summary}`,"chat.chatInput.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.chatInput.toast.openSessionFirst":"Open a session first","chat.chatInput.toast.dictationKeptForOriginalSession":"Dictation saved as a draft in the session where you started it","chat.chatInput.toast.togglePermissionAutoAcceptFailed":"Failed to toggle permission auto-accept","chat.chatInput.reviewComments":"Review comments:","chat.chatInput.reviewCommentsRemove":"Remove review comments","chat.chatInput.previewAnnotations":"Preview annotations:","chat.chatInput.previewContext":"Preview context:","chat.chatInput.previewContextRemove":"Remove preview context","chat.chatInput.projectRoot":"Project root","chat.chatInput.branch":"Branch","chat.chatInput.draftPicker.projectTitle":"Project","chat.chatInput.draftPicker.searchProjects":"Search projects...","chat.chatInput.draftPicker.searchBranches":"Search branches...","chat.chatInput.draftPicker.noProjectsFound":"No projects found.","chat.chatInput.worktrees":"Worktrees","chat.chatInput.worktreeQuick":"Quick worktree","chat.chatInput.worktreeCustom":"New worktree…","chat.chatInput.drop.insertMention":"Drop to insert as mention","chat.chatInput.drop.attachFiles":"Drop files here to attach","chat.chatInput.fileFallback":"file","chat.toolOutputDialog.image.previousAria":"Previous image","chat.toolOutputDialog.image.nextAria":"Next image","chat.toolOutputDialog.image.closeAria":"Close image preview","chat.toolOutputDialog.mermaid.missingSource":"Missing Mermaid source URL.","chat.toolOutputDialog.mermaid.loadFailed":"Unable to load Mermaid diagram.","chat.toolOutputDialog.mermaid.dataUrlMalformed":"The Mermaid data URL is malformed.","chat.toolOutputDialog.mermaid.invalidLocalPath":"The local Mermaid file path is invalid.","chat.toolOutputDialog.mermaid.readFileFailedWithStatus":"Unable to read Mermaid file. Status: {status}.","chat.toolOutputDialog.mermaid.unsupportedUrlProtocol":"The Mermaid URL protocol is unsupported.","chat.toolOutputDialog.mermaid.loadFailedWithStatus":"Unable to load Mermaid diagram. Status: {status}.","chat.toolOutputDialog.mermaid.closeAria":"Close diagram preview","chat.toolOutputDialog.mermaid.loading":"Loading diagram...","chat.toolOutputDialog.mermaid.renderFailed":"Unable to render Mermaid diagram.","chat.toolOutputDialog.mermaid.retry":"Retry","chat.toolOutputDialog.commandCompleted":"Command completed successfully","chat.toolOutputDialog.noOutputProduced":"No output was produced","chat.statusRow.background.action":"Move to background — the agent stops waiting and continues","chat.statusRow.background.failed":"Couldn't move the work to the background","chat.toolPart.background.label":"in background","chat.toolPart.background.stop":"Stop command","chat.toolPart.background.stopLabel":"Stop","chat.toolPart.background.stopFailed":"Couldn't stop the command","chat.toolPart.background.stoppedLabel":"stopped","chat.toolPart.background.stoppedNotice":"Stopped by you. The agent was told this was your stop, not a failure.","chat.toolPart.subagent.stop":"Stop subagent","chat.toolPart.subagent.stopFailed":"Couldn't stop the subagent","chat.toolPart.lspErrors":"LSP errors","chat.toolPart.moreErrors":"+{count} more errors","chat.toolPart.moreRows":"+{count} more rows","chat.toolPart.error":"Error:","chat.toolPart.awaitingResponse":"Awaiting response...","chat.toolPart.noOutputProduced":"No output produced","chat.toolPart.questionsAsked":"Questions asked: {count}","chat.toolPart.filesCount":"Files: {count}","chat.toolPart.moreToolCalls":"+{count} more","chat.toolPart.scriptCalls":"Tool calls","chat.toolPart.outputTruncated":"Output was truncated","chat.toolPart.content.loading":"Loading the result…","chat.toolPart.content.loadFailed":"Couldn't load the result.","chat.toolPart.content.retry":"Retry","chat.toolPart.output":"Output","chat.toolPart.showRawJson":"Show raw JSON","chat.toolPart.showFormattedJson":"Show formatted JSON","chat.toolPart.showNavigableJson":"Show navigable JSON","chat.toolPart.openFile":"Open file","chat.toolPart.openImageExpanded":"Open","chat.toolPart.openFileAtFirstChange":"Open file at first change","chat.toolPart.openFileDiff":"Open file diff","chat.toolPart.copyOutput":"Copy output","chat.toolPart.copiedOutput":"Copied output","chat.toolPart.copyOutputFailed":"Failed to copy output","chat.toolPart.openSubtask":"Open {type} subtask","chat.todo.total":"Total","chat.todo.inProgress":"In Progress","chat.todo.pending":"Pending","chat.todo.completed":"Completed","chat.todo.cancelled":"Cancelled","chat.permissionCard.workingDirectory":"Working Directory:","chat.permissionCard.timeout":"Timeout:","chat.permissionCard.request":"Request:","chat.permissionCard.headers":"Headers:","chat.permissionCard.body":"Body:","chat.permissionCard.action":"Action:","chat.permissionCard.patterns":"Patterns:","chat.permissionToast.sessionFallback":"Session","chat.permissionToast.permissionFallback":"Permission details unavailable","chat.permissionToast.labels.session":"Session:","chat.permissionToast.labels.permission":"Permission:","chat.permissionToast.actions.once":"Once","chat.permissionToast.actions.always":"Always","chat.permissionToast.actions.deny":"Deny","chat.permissionToast.actions.approveOnceAria":"Approve once","chat.permissionToast.actions.approveOnceAriaWithSession":"Approve once for {session}","chat.permissionToast.actions.approveAlwaysAria":"Approve always","chat.permissionToast.actions.approveAlwaysAriaWithSession":"Approve always for {session}","chat.permissionToast.actions.denyAria":"Deny permission","chat.permissionToast.actions.denyAriaWithSession":"Deny permission for {session}","chat.permissionRequest.required":"Permission required:","chat.permissionRequest.actions.once":"Once","chat.permissionRequest.actions.always":"Always","chat.permissionRequest.actions.reject":"Reject","chat.modelControls.provider":"Provider","chat.modelControls.capability.toolCalling":"Tool calling","chat.modelControls.capability.reasoning":"Reasoning","chat.modelControls.modality.text":"Text","chat.modelControls.modality.image":"Image","chat.modelControls.modality.video":"Video","chat.modelControls.modality.audio":"Audio","chat.modelControls.modality.pdf":"PDF","chat.modelControls.capabilities":"Capabilities","chat.modelControls.modalities":"Modalities","chat.modelControls.input":"Input","chat.modelControls.output":"Output","chat.modelControls.limits":"Limits","chat.modelControls.context":"Context","chat.modelControls.metadata":"Metadata","chat.modelControls.knowledge":"Knowledge","chat.modelControls.release":"Release","chat.modelControls.mode":"Mode","chat.modelControls.model":"Model","chat.modelControls.temperature":"Temperature","chat.modelControls.topP":"Top P","chat.modelControls.permissions":"Permissions","chat.modelControls.edit":"Edit","chat.modelControls.bash":"Bash","chat.modelControls.webFetch":"WebFetch","chat.modelControls.customPrompt":"Custom Prompt","chat.modelControls.selectModel":"Select model","chat.modelControls.thinking":"Thinking","chat.modelControls.inheritedVariantTooltip":"Thinking: {variant}, this model's default","chat.modelControls.rememberedVariantTooltip":"Thinking: {variant}, last used with this model","chat.modelControls.default":"Default","chat.modelControls.selectAgent":"Select agent","chat.modelControls.costPerMillion":"Cost ($/1M tokens)","chat.modelControls.metadataUnavailable":"Model metadata unavailable.","chat.modelControls.addNewProvider":"Add new provider","chat.modelControls.noAgentSelected":"No agent selected.","chat.modelControls.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent.`,"chat.modelControls.searchModels":"Search models","chat.modelControls.modelListAria":"Models","chat.modelControls.searchAgents":"Search agents","chat.modelControls.noModelsFound":"No models found","chat.modelControls.favorites":"Favorites","chat.modelControls.agentsSection":"Agents","chat.modelControls.favoriteAgentsCycleHint":"{shortcut} to cycle","chat.modelControls.favoriteAgentsTapHint":"Tap the agent to cycle","chat.modelControls.noAgentsFound":"No agents found","chat.modelControls.recent":"Recent","chat.modelControls.addToFavorites":"Add to favorites","chat.modelControls.removeFromFavorites":"Remove from favorites","chat.modelControls.useModel":"Use model","chat.modelControls.favoriteAria":"Favorite","chat.modelControls.unfavoriteAria":"Unfavorite","chat.modelControls.collapseProvider":"Collapse provider","chat.modelControls.expandProvider":"Expand provider","chat.modelControls.keyboardHint":"↑↓ navigate{thinking} • Enter select • Esc close","chat.modelControls.keyboardHintNavigate":"↑↓ navigate","chat.modelControls.keyboardHintSwitchAgent":"{shortcut} switch agent","chat.modelControls.keyboardHintSwitchThinking":"{shortcut} switch","chat.modelControls.keyboardHintThinking":"←→ thinking","chat.modelControls.reorderProviderTitle":"Drag to reorder provider","chat.modelControls.permissionLabel.custom":"Custom","chat.modelControls.permissionLabel.allow":"Allow","chat.modelControls.permissionLabel.deny":"Deny","chat.modelControls.permissionLabel.ask":"Ask","chat.modelControls.modeValue.primary":"Primary","chat.modelControls.modeValue.subagent":"Subagent","chat.modelControls.modeValue.all":"All","chat.modelControls.modeValue.none":"—","chat.reasoningTrace.thinking":"Thinking","chat.reasoningTrace.expandAria":"Expand reasoning trace","chat.reasoningTrace.collapseAria":"Collapse reasoning trace","chat.reasoningTrace.thought":"Thought","chat.messageBody.subtask.title":"Delegated task","chat.messageBody.subtask.hidePrompt":"Hide prompt","chat.messageBody.subtask.showPrompt":"Show prompt","chat.messageBody.subtask.openSession":"Open subtask session","chat.messageBody.shellCommand.copied":"Copied","chat.messageBody.shellCommand.copyOutput":"Copy output","commandPalette.title":"Command Palette","commandPalette.description":"Search files, sessions, and commands.","commandPalette.input.placeholder":"Search files, sessions, commands...","commandPalette.empty.noResults":"No results found.","commandPalette.empty.searchingFiles":"Searching files...","commandPalette.item.newSession":"New Session","commandPalette.item.newMiniChat":"New Mini Chat Window","commandPalette.item.quickWorktree":"Quick Worktree","commandPalette.item.newWorktreeDialog":"New Worktree…","commandPalette.item.addProject":"Add Project","commandPalette.item.showSessionSwitcher":"Show Session Switcher","commandPalette.item.toggleSidebar":"Toggle Sidebar","commandPalette.item.showContextUsage":"Show Context Usage","commandPalette.item.toggleTerminal":"Toggle Terminal","commandPalette.item.cycleTheme":"Cycle theme","commandPalette.item.showOpenCodeStatus":"Show diagnostic timeline","commandPalette.item.restartOpenCode":"Restart OpenCode","commandPalette.item.toggleMemoryDebug":"Toggle memory debug panel","commandPalette.item.pinSession":"Pin or unpin session","commandPalette.item.copySessionId":"Copy session ID","commandPalette.item.openMultiRun":"Run in parallel","commandPalette.item.openArchive":"Open archived sessions","commandPalette.item.openNotes":"Open notes surface","commandPalette.item.openTodos":"Open todos surface","commandPalette.item.openSettings":"Open Settings...","commandPalette.session.untitled":"Untitled Session","commandPalette.item.reloadUi":"Reload UI","commandPalette.group.openFiles":"Open files","commandPalette.group.commands":"Commands","commandPalette.group.settings":"Settings","chat.search.placeholder":"Search this conversation","chat.search.position":"{current} of {total}","chat.search.noResults":"No results","chat.search.searching":"Searching…","chat.search.tooShort":"3+ characters","chat.search.error":"Couldn't search","chat.search.unavailable":"Not available here","chat.search.previous":"Previous match","chat.search.next":"Next match","chat.search.close":"Close search","commandPalette.group.sessions":"Sessions","commandPalette.group.messages":"Messages","commandPalette.messages.showAll":"Show all message results","commandPalette.messages.placeholder":"Search messages…","commandPalette.messages.back":"Back","commandPalette.messages.filter.scopeLabel":"Where","commandPalette.messages.filter.allProjects":"All projects","commandPalette.messages.filter.thisProject":"This project","commandPalette.messages.filter.authorLabel":"Written by","commandPalette.messages.filter.anyone":"Anyone","commandPalette.messages.filter.you":"You","commandPalette.messages.filter.agent":"Agent","commandPalette.messages.filter.reasoning":"Thinking","commandPalette.messages.inReasoning":"Thinking","commandPalette.messages.tooShort":"Type at least 3 characters to search messages","commandPalette.messages.searching":"Searching messages…","commandPalette.messages.error":"Couldn't search messages","commandPalette.messages.unavailable":"Message search is not available on this server","commandPalette.messages.empty":"No messages found","commandPalette.messages.indexing":"Still indexing older conversations: {done} of {total}.","commandPalette.messages.loadMore":"Load more","commandPalette.messages.byYou":"Your message","commandPalette.messages.byAgent":"Agent reply","commandPalette.group.files":"Files","commandPalette.group.projects":"Projects","commandPalette.footer.navigate":"to navigate","commandPalette.footer.open":"to open","commandPalette.footer.close":"to close","openCodeStatusDialog.title":"Diagnostic timeline","openCodeStatusDialog.description":"Local events in time order. Private log text and remote sources are excluded.","openCodeStatusDialog.actions.download":"Download log","openCodeStatusDialog.toast.collectFailed":"Failed to collect diagnostics","openCodeStatusDialog.actions.copy":"Copy","openCodeStatusDialog.empty.noData":"No data.","openCodeStatusDialog.toast.copiedTitle":"Copied","openCodeStatusDialog.toast.copiedDescription":"Diagnostic log copied to clipboard","openCodeStatusDialog.toast.copyFailed":"Failed to copy diagnostic log","saveProjectPlanDialog.title":"Save Project Plan","saveProjectPlanDialog.description":"Save this plan into your project as a Markdown file.","saveProjectPlanDialog.field.title":"Title","saveProjectPlanDialog.field.titlePlaceholder":"Plan title","saveProjectPlanDialog.field.contentPreview":"Content preview","saveProjectPlanDialog.actions.cancel":"Cancel","saveProjectPlanDialog.actions.save":"Save","saveProjectPlanDialog.actions.saving":"Saving...","branchPickerDialog.title":"Branch Picker","branchPickerDialog.description.localBranchesForProject":"Local branches for {project}","branchPickerDialog.description.selectProject":"Select a project to view branches","branchPickerDialog.search.placeholder":"Search branches...","branchPickerDialog.search.renameBranchPlaceholder":"Rename branch","branchPickerDialog.state.noProjectSelected":"No project selected","branchPickerDialog.state.loadingBranches":"Loading branches...","branchPickerDialog.state.noMatchingBranches":"No matching branches","branchPickerDialog.state.noBranchesFound":"No branches found","branchPickerDialog.badge.head":"HEAD","branchPickerDialog.badge.worktree":"worktree","branchPickerDialog.actions.createWorktreeAria":"Create worktree from branch","branchPickerDialog.actions.renameAria":"Rename branch","branchPickerDialog.actions.deleteAria":"Delete branch","branchPickerDialog.actions.deleteWorktreeAria":"Remove worktree","branchPickerDialog.actions.confirmRenameAria":"Confirm rename","branchPickerDialog.actions.cancelRenameAria":"Cancel rename","branchPickerDialog.actions.confirmDeleteAria":"Confirm delete branch","branchPickerDialog.actions.cancelDeleteAria":"Cancel delete branch","branchPickerDialog.actions.deletePrompt":"Delete","branchPickerDialog.actions.forceDeletePrompt":"Force Delete","branchPickerDialog.tooltip.createWorktree":"Create worktree","branchPickerDialog.tooltip.worktreeAlreadyExists":"Worktree already exists","branchPickerDialog.tooltip.rename":"Rename branch","branchPickerDialog.tooltip.renameDisabledForRoot":"Cannot rename root branch","branchPickerDialog.tooltip.delete":"Delete branch","branchPickerDialog.tooltip.deleteCurrentBranch":"Cannot delete current branch","branchPickerDialog.tooltip.deleteDisabledForRoot":"Cannot delete root branch","branchPickerDialog.tooltip.deleteWorktree":"Remove worktree","branchPickerDialog.tooltip.deleteWorktreeRootProtected":"Cannot remove root worktree","branchPickerDialog.toast.branchRenamed":"Branch renamed","branchPickerDialog.toast.failedToRenameBranch":"Failed to rename branch","branchPickerDialog.toast.branchDeleted":"Branch deleted","branchPickerDialog.toast.branchNotMerged":"Branch is not fully merged","branchPickerDialog.toast.confirmAgainToForceDelete":"Confirm again to force delete","branchPickerDialog.toast.failedToDeleteBranch":"Failed to delete branch","branchPickerDialog.toast.worktreeCreated":"Worktree created","branchPickerDialog.toast.failedToCreateWorktree":"Failed to create worktree","branchPickerDialog.error.failedToLoad":"Failed to load branches","branchPickerDialog.error.renameRejected":"Rename was rejected","branchPickerDialog.error.renameFailed":"Failed to rename branch","branchPickerDialog.error.deleteRejected":"Delete was rejected","branchPickerDialog.error.deleteFailed":"Failed to delete branch","branchPickerDialog.error.createWorktreeFailed":"Failed to create worktree","projectEditDialog.title":"Edit project","projectEditDialog.field.name":"Name","projectEditDialog.field.namePlaceholder":"Project name","projectEditDialog.field.color":"Color","projectEditDialog.field.icon":"Icon","projectEditDialog.field.preview":"Preview","projectEditDialog.field.iconBackground":"Icon Background","projectEditDialog.field.iconBackgroundAria":"Project icon background color","projectEditDialog.option.none":"None","projectEditDialog.actions.uploadIcon":"Upload Icon","projectEditDialog.actions.uploading":"Uploading...","projectEditDialog.actions.discoverFavicon":"Discover Favicon","projectEditDialog.actions.discovering":"Discovering...","projectEditDialog.actions.removeProjectIcon":"Remove Project Icon","projectEditDialog.actions.removing":"Removing...","projectEditDialog.actions.undoRemove":"Undo Remove","projectEditDialog.actions.clear":"Clear","projectEditDialog.actions.cancel":"Cancel","projectEditDialog.actions.save":"Save","projectEditDialog.toast.failedToUploadIcon":"Failed to upload project icon","projectEditDialog.toast.iconUpdated":"Project icon updated","projectEditDialog.toast.failedToRemoveIcon":"Failed to remove project icon","projectEditDialog.toast.iconRemoved":"Project icon removed","projectEditDialog.toast.failedToDiscoverIcon":"Failed to discover project icon","projectEditDialog.toast.customIconAlreadySet":"Custom icon already set for this project","projectEditDialog.toast.iconDiscovered":"Project icon discovered","openInApp.actions.open":"Open","openInApp.actions.openInAria":"Open in {app}","openInApp.actions.copyPath":"Copy Path","openInApp.actions.refreshApps":"Refresh Apps","openInApp.toast.pathCopied":"Path copied to clipboard","projectActions.actions.addActionAria":"Add action","projectActions.actions.addAction":"Add action","projectActions.actions.addNewAction":"Add new action","projectActions.actions.autoDiscover":"Auto-discover dev server","projectActions.menu.sharedBadge":"repo","projects.sharedTrust.title":"Run the commands stored in this repository?","projects.sharedTrust.description":"{path} in this repository defines commands that run on this machine. Trust them once, and OpenChamber asks again only when they change.","projects.sharedTrust.setupCommands":"Worktree setup commands","projects.sharedTrust.teardownCommands":"Worktree teardown commands","projects.sharedTrust.actions":"Actions","projects.sharedTrust.skip":"Not this time","projects.sharedTrust.trust":"Trust and run","projects.opencodeTrust.title":"Let OpenCode run code from this folder?","projects.opencodeTrust.description":"OpenCode runs the plugins and commands in the configuration of {path} as soon as it opens the folder. Trust them once, and OpenChamber asks again only when they change.","projects.opencodeTrust.plugins":"Plugins","projects.opencodeTrust.commands":"Commands","projects.opencodeTrust.kind.package":"{name} (npm package)","projects.opencodeTrust.kind.config":"{path}: a configuration file OpenChamber can't read","projects.opencodeTrust.kind.mcp":"MCP server {name}","projects.opencodeTrust.kind.lsp":"Language server {name}","projects.opencodeTrust.kind.formatter":"Formatter {name}","projects.opencodeTrust.kind.shell":"Shell","projects.opencodeTrust.paused":"Without trust, agents can't work in this folder, but you can still browse its files and Git changes.","projects.opencodeTrust.skip":"Not this time","projects.opencodeTrust.trust":"Trust and open","projects.opencodeTrust.saveFailed":"Couldn't save your answer. Try again.","projectActions.actions.autoDiscoverTooltip":"Automatically discover and run the development server","projectActions.actions.chooseActionAria":"Choose project action","projectActions.actions.openPreview":"Open Preview","projectActions.actions.runNamedAria":"Run {name}","projectActions.actions.stopNamedAria":"Stop {name}","projectActions.label.fallbackAction":"Action","projectActions.toast.openedUrlFromOutput":"Opened URL from action output","projectActions.toast.openedForwardedUrl":"Opened forwarded URL","projectActions.toast.openedActionUrl":"Opened action URL","projectActions.error.noActiveDirectory":"No active directory","projectActions.error.noActiveDirectoryForAction":"No active directory for action","projectActions.error.failedToCreateTerminalSession":"Failed to create terminal session","projectActions.error.invalidCustomUrlFormat":"Invalid custom URL format","projectActions.error.openUrlTemplateUnresolved":"Couldn't read the branch for the action URL","projectActions.error.selectedDesktopSshForwardUnavailable":"Selected desktop SSH forward is unavailable","projectActions.error.failedToRunAction":"Failed to run action","mcpDropdown.title":"MCP Servers","mcpDropdown.actions.refreshAria":"Refresh","mcpDropdown.actions.openAria":"MCP servers","mcpDropdown.statusAria":"MCP status","mcpDropdown.status.unknown":"Unknown","mcpDropdown.status.connected":"Connected","mcpDropdown.status.failed":"Failed: {error}","mcpDropdown.status.unknownError":"Unknown error","mcpDropdown.status.needsAuth":"Needs authentication","mcpDropdown.status.needsRegistration":"Needs registration: {error}","mcpDropdown.empty.configureInConfig":"Configure MCP servers in Settings.","sessionAuth.error.rateLimitTitle":"Too many attempts","sessionAuth.error.networkTitle":"Unable to reach server","sessionAuth.error.rateLimitDescriptionSingle":"Please wait {minutes} minute before trying again.","sessionAuth.error.rateLimitDescriptionPlural":"Please wait {minutes} minutes before trying again.","sessionAuth.error.networkDescription":"We could not verify the UI session. If you're opening OpenChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings.","sessionAuth.error.retry":"Retry","sessionAuth.error.passkeySetupFailed":"Passkey setup failed.","sessionAuth.error.incorrectPassword":"Incorrect password. Try again.","sessionAuth.error.unexpectedResponse":"Unexpected response from server.","sessionAuth.error.networkRetry":"Network error. Check connection and retry.","sessionAuth.error.passkeySignInCanceled":"Passkey sign-in was canceled.","sessionAuth.error.enterPasswordForPasskey":"Enter your password to add a passkey.","sessionAuth.locked.tunnelTitle":"Tunnel access required","sessionAuth.expired.banner":"Your session expired — log in to continue.","sessionAuth.expired.loginAction":"Log in","sessionAuth.expired.sendBlocked":"Session expired — log in to send messages.","sessionAuth.locked.unlockTitle":"Unlock OpenChamber","sessionAuth.locked.tunnelDescription":"Open this tunnel using the one-time connect link from the desktop app.","sessionAuth.locked.passwordDescription":"This session is password-protected.","sessionAuth.locked.hostSwitcherHint":"Use Local if remote is unreachable.","sessionAuth.actions.cancelPasskey":"Cancel passkey","sessionAuth.actions.usePasskey":"Use passkey","sessionAuth.actions.unlockingAria":"Unlocking","sessionAuth.actions.unlockAria":"Unlock","sessionAuth.actions.trustDevice":"Trust this device","sessionAuth.actions.trustDeviceAria":"Trust this device","sessionAuth.actions.cancelPasskeySetup":"Cancel passkey setup","sessionAuth.actions.addPasskey":"Add passkey","sessionAuth.password.placeholder":"Enter password","sessionAuth.toast.passkeyAdded":"Passkey added","sessionAuth.toast.passkeySetupCanceled":"Passkey setup canceled","desktopHostSwitcher.title":"Instance","desktopHostSwitcher.description":"Switch between Local and remote OpenChamber servers","desktopHostSwitcher.header.current":"Current","desktopHostSwitcher.header.default":"Default","desktopHostSwitcher.header.currentColon":"Current:","desktopHostSwitcher.header.currentDefaultColon":"Current default:","desktopHostSwitcher.status.connected":"Connected","desktopHostSwitcher.status.authRequired":"Auth required","desktopHostSwitcher.status.checking":"Checking","desktopHostSwitcher.status.updateRecommended":"Update recommended","desktopHostSwitcher.status.incompatible":"Incompatible","desktopHostSwitcher.status.wrongService":"Wrong service","desktopHostSwitcher.status.unreachable":"Unreachable","desktopHostSwitcher.status.relayLimit":"Relay limit reached","desktopHostSwitcher.status.unknown":"Unknown","desktopHostSwitcher.status.ping":" · {ms}ms ping","desktopHostSwitcher.statusAria":"Instance status","desktopHostSwitcher.sshPhase.ready":"Ready","desktopHostSwitcher.sshPhase.error":"Error","desktopHostSwitcher.sshPhase.reconnecting":"Reconnecting","desktopHostSwitcher.sshPhase.resolvingConfig":"Resolving config","desktopHostSwitcher.sshPhase.checkingAuth":"Checking auth","desktopHostSwitcher.sshPhase.connectingSsh":"Connecting SSH","desktopHostSwitcher.sshPhase.probingRemote":"Probing remote","desktopHostSwitcher.sshPhase.installing":"Installing","desktopHostSwitcher.sshPhase.updating":"Updating","desktopHostSwitcher.sshPhase.detectingServer":"Detecting server","desktopHostSwitcher.sshPhase.startingServer":"Starting server","desktopHostSwitcher.sshPhase.forwardingPorts":"Forwarding ports","desktopHostSwitcher.sshPhase.idle":"Idle","desktopHostSwitcher.ssh.needInstancesHint":"Need SSH instances? Manage them in Settings.","desktopHostSwitcher.ssh.instanceFallback":"SSH instance","desktopHostSwitcher.ssh.connectingTo":"Connecting to {host}","desktopHostSwitcher.actions.refresh":"Refresh","desktopHostSwitcher.actions.refreshInstancesAria":"Refresh instances","desktopHostSwitcher.actions.remoteSsh":"Remote SSH","desktopHostSwitcher.actions.instanceActionsAria":"Instance actions","desktopHostSwitcher.actions.edit":"Edit","desktopHostSwitcher.actions.delete":"Delete","desktopHostSwitcher.actions.connect":"Connect","desktopHostSwitcher.actions.defaultInstanceAria":"Default instance","desktopHostSwitcher.actions.setAsDefaultAria":"Set as default","desktopHostSwitcher.actions.setAsDefault":"Set as default","desktopHostSwitcher.actions.openInNewWindowAria":"Open in new window","desktopHostSwitcher.actions.openInNewWindow":"Open in new window","desktopHostSwitcher.actions.addInstance":"Add instance","desktopHostSwitcher.actions.cancel":"Cancel","desktopHostSwitcher.actions.save":"Save","desktopHostSwitcher.actions.add":"Add","desktopHostSwitcher.actions.switchToLocal":"Switch to Local","desktopHostSwitcher.actions.retry":"Retry","desktopHostSwitcher.actions.switchInstanceAria":"Switch instance","desktopHostSwitcher.actions.switchInstance":"Switch instance","desktopHostSwitcher.actions.switchToAria":"Switch to {instance}","desktopHostSwitcher.field.labelPlaceholder":"Label","desktopHostSwitcher.field.labelOptionalPlaceholder":"Label (optional)","desktopHostSwitcher.field.urlPlaceholder":"https://host:port","desktopHostSwitcher.state.limitedOnPage":"Instance switcher is limited on this page. Use Local to recover.","desktopHostSwitcher.state.loading":"Loading...","desktopHostSwitcher.state.instanceUnreachable":"Instance unreachable","desktopHostSwitcher.edit.title":"Edit instance","desktopHostSwitcher.add.title":"Add instance","desktopHostSwitcher.error.failedToSave":"Failed to save","desktopHostSwitcher.error.failedToLoad":"Failed to load","desktopHostSwitcher.error.invalidUrl":"Invalid URL (must be http/https)","desktopHostSwitcher.error.pairingRejected":"Pairing link is invalid or expired. Generate a new one.","desktopHostSwitcher.error.pairingFailed":"Pairing failed (HTTP {status}).","desktopHostSwitcher.error.pairingInvalidResponse":"The server returned an invalid pairing response.","desktopHostSwitcher.error.failedToOpenNewWindow":"Failed to open new window","desktopHostSwitcher.instance.local":"Local","desktopHostSwitcher.instance.fallback":"Instance","desktopHostSwitcher.startup.title":"Default SSH instance unavailable","desktopHostSwitcher.startup.connectingTo":"Connecting to {host}...","desktopHostSwitcher.startup.failed":"Failed to connect the default SSH instance.","desktopHostSwitcher.toast.sshConnected":'SSH instance "{host}" connected',"desktopHostSwitcher.toast.sshFailedToConnect":'SSH instance "{host}" failed to connect',"desktopHostSwitcher.toast.instanceUnreachable":'Instance "{host}" is unreachable',"desktopHostSwitcher.toast.relayLimit":'The relay refused the connection to "{host}": too many devices or reconnects. Close OpenChamber on another device or wait a minute, then try again.',"relayConnection.limitReached.title":"The relay refused the connection","relayConnection.limitReached.description":"Too many devices or reconnects for this instance. Close OpenChamber on another device or wait a minute, then try again.","relayConnection.limitReached.retry":"Try again","miniChat.header.newSession":"New session","miniChat.header.session":"Session","miniChat.header.defaultAgent":"Default agent","miniChat.header.noModel":"No model","miniChat.status.busy":"Running","miniChat.status.retry":"Retrying","miniChat.status.idle":"Idle","miniChat.actions.pin":"Pin above other windows","miniChat.actions.unpin":"Unpin window","miniChat.actions.pinAria":"Pin Mini Chat window","miniChat.actions.unpinAria":"Unpin Mini Chat window","miniChat.actions.openMain":"Open in main window","miniChat.actions.openMainAria":"Open session in main window","miniChat.unavailable.title":"Session unavailable","miniChat.unavailable.description":"This session could not be loaded. It may have been deleted, archived, or opened from a different project context.","sessions.sidebar.session.menu.openMiniChatWindow":"Open in Mini Chat Window","header.windowControls.groupAria":"Window controls","header.windowControls.minimize":"Minimize window","header.windowControls.maximize":"Maximize window","header.windowControls.restore":"Restore window","header.windowControls.close":"Close window","errorBoundary.title":"Something went wrong","errorBoundary.description":"The application encountered an unexpected error. This has been logged for debugging.","errorBoundary.state.unknownError":"Unknown error","errorBoundary.state.componentStackLabel":"Component stack:","errorBoundary.actions.errorDetails":"Error details","errorBoundary.actions.tryAgain":"Try again","errorBoundary.actions.copy":"Copy","errorBoundary.actions.copied":"Copied","jsonTreeView.error.emptyJson":"Empty JSON content","jsonTreeView.error.invalidJson":"Invalid JSON","jsonTreeView.error.invalidJsonTitle":"Invalid JSON","jsonTreeView.actions.expandAll":"Expand All","jsonTreeView.actions.collapseAll":"Collapse All","numberInput.actions.decreaseAria":"Decrease value","numberInput.actions.increaseAria":"Increase value","goToLineDialog.field.linePlaceholderShort":"Line","goToLineDialog.field.linePlaceholder":"Line number","goToLineDialog.actions.go":"Go","goToLineDialog.helper.editorUnavailable":"Editor unavailable.","goToLineDialog.helper.currentLineRange":"Current Line: {current}. Type a line number between 1 and {max} to navigate to.","goToLineDialog.helper.goToLine":"Go to line {line}","dialog.common.actions.close":"Close","session.newWorktree.trust.run":"Run","session.newWorktree.trust.skip":"Skip","session.newWorktree.trust.title":"Run setup on code from a fork?","gitView.publish.contributorCommitFirstAction":"Continue","gitView.publish.contributorCommitFirstTitle":"Commit, then choose where to push?","dialog.common.actions.cancel":"Cancel","filesView.toast.relativePathCopied":"Relative path copied","filesView.tree.menu.copyRelativePath":"Copy Relative Path","multiRun.branchSelector.placeholder.selectSourceBranch":"Select source branch...","multiRun.branchSelector.status.loadingBranches":"Loading branches...","multiRun.branchSelector.status.noBranchesFound":"No branches found","multiRun.branchSelector.status.notInGitRepository":"Not in a git repository.","multiRun.branchSelector.groups.localBranches":"Local branches","multiRun.branchSelector.groups.remoteBranches":"Remote branches","multiRun.window.actions.closeAria":"Close multi-run","multiRun.window.description":"OpenChamber Multi-Run window.","voice.status.idle":"Voice Ready","voice.status.listening":"Listening...","voice.status.processing":"Processing...","voice.status.speaking":"Speaking...","voice.status.error":"Voice Error","voice.status.conversationModeActiveAria":"Conversation mode active","voice.action.finishAndTranscribe":"Finish and transcribe voice input","onboarding.common.actions.back":"Back","onboarding.common.copyToClipboard":"Copy to clipboard","onboarding.common.status.copiedToClipboard":"Copied to clipboard","onboarding.chooser.title":"Welcome to OpenChamber","onboarding.chooser.description":"Choose how you want to connect to get started.","onboarding.chooser.tabs.localInstall":"Local Install","onboarding.chooser.tabs.connectRemote":"Connect Remote","onboarding.localSetup.title":"Setting Up OpenCode","onboarding.localSetup.description":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.dialog.selectOpencodeBinary":"Select opencode binary","onboarding.localSetup.errors.cliNotReady":"OpenCode CLI is not ready yet. Please confirm installation is complete and try again.","onboarding.localSetup.errors.detectionFailed":"Detection failed","onboarding.localSetup.windows.title":"Windows setup","onboarding.localSetup.windows.stepInstallWsl":"Install OpenCode with the command below.","onboarding.localSetup.windows.stepInstallWslSuffix":"","onboarding.localSetup.windows.stepRunInstallInWsl":"Run the install command below in a Windows terminal.","onboarding.localSetup.windows.stepSetBinaryPath":"If OpenChamber does not detect OpenCode automatically, set the binary path below.","onboarding.localSetup.intro":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.docs.windows":"Installation guide","onboarding.localSetup.docs.default":"Installation guide","onboarding.localSetup.actions.checking":"Checking…","onboarding.localSetup.actions.checkAndContinue":"I've completed installation, check and continue","onboarding.localSetup.actions.checkNow":"Check now","onboarding.localSetup.helper.checkAndContinue":"Click to check if OpenCode CLI is available. If successful, you'll automatically enter the main screen.","onboarding.localSetup.status.watching":"Waiting for OpenCode v2","onboarding.localSetup.status.autoContinue":"We'll continue automatically once it's detected.","onboarding.localSetup.field.alreadyInstalled":"Already installed? Set the OpenCode CLI path:","onboarding.localSetup.advanced.title":"Set a custom binary path","onboarding.localSetup.troubleshoot.title":"Having trouble?","onboarding.localSetup.actions.browse":"Browse","onboarding.localSetup.actions.apply":"Apply","onboarding.localSetup.helper.saveAndReload":"Saves to OpenChamber settings and reloads OpenCode configuration.","onboarding.localSetup.helper.pinnedByAdministrator":"Your administrator set this path. If OpenCode isn’t there, ask them to install it.","onboarding.localSetup.remotePreference":"Prefer to use a remote server?","onboarding.localSetup.actions.connectRemoteServer":"Connect to Remote Server →","onboarding.localSetup.windows.hintInstallInWsl":"On Windows, install and run OpenCode natively.","onboarding.localSetup.windows.hintDetectionFailed":"If detection fails, set a native path such as opencode.cmd or opencode.exe.","onboarding.localSetup.hint.ensurePath":"Already installed? Make sure opencode is in your PATH.","onboarding.localSetup.hint.setEnv":"Or set OPENCODE_BINARY environment variable.","onboarding.localSetup.hint.missingRuntime":'If you see "env: node: No such file or directory" or "env: bun: No such file or directory", install that runtime or ensure it is on PATH.',"onboarding.remoteConnection.title":"Connect to Remote Server","onboarding.remoteConnection.titleRecovery":"Connect to a Different Server","onboarding.remoteConnection.description":"Enter the address of an OpenChamber server to connect to.","onboarding.remoteConnection.field.serverAddress":"Server Address","onboarding.remoteConnection.field.serverAddressPlaceholder":"https://your-server.example.com:4096","onboarding.remoteConnection.field.nameOptional":"Name (optional)","onboarding.remoteConnection.field.namePlaceholder":"My Remote Server","onboarding.remoteConnection.errors.connectionTestFailed":"Connection test failed","onboarding.remoteConnection.errors.failedToSaveConnection":"Failed to save connection","onboarding.remoteConnection.status.connectedSuccessfully":"Connected successfully ({latencyMs}ms)","onboarding.remoteConnection.status.authWarning":"Server requires authentication. You can still connect.","onboarding.remoteConnection.status.connectionFailed":"Connection Failed","onboarding.remoteConnection.status.suggestionsUnreachable":"Suggestions: Check the server address, verify the server is running, or check your network connection.","onboarding.remoteConnection.status.suggestionsWrongService":"Suggestions: Verify the URL points to an OpenChamber server, or contact the server administrator.","onboarding.remoteConnection.actions.testing":"Testing…","onboarding.remoteConnection.actions.testConnection":"Test Connection","onboarding.remoteConnection.actions.connectAndRestart":"Connect & Restart","onboarding.remoteConnection.actions.whatToDo":"What would you like to do?","onboarding.remoteConnection.actions.chooseDifferentServer":"Choose Different Server","onboarding.remoteConnection.actions.useLocalInstead":"Use Local Instead","onboarding.remoteConnection.probe.authMessage":"Server requires authentication. You can still connect, but may need to provide credentials.","onboarding.remoteConnection.probe.updateRecommendedMessage":"This instance is running a different OpenChamber version. You can connect, but update both apps if something does not work.","onboarding.remoteConnection.probe.incompatibleMessage":"Server is running OpenChamber but is not compatible with this app version. Update OpenChamber on the server, then try again.","onboarding.remoteConnection.probe.wrongServiceMessage":"Server responded but is not running OpenChamber. Verify the address points to an OpenChamber server.","onboarding.remoteConnection.probe.unreachableMessage":"Server is unreachable. Check your network connection and verify the server address.","onboarding.desktopRecovery.localUnavailable.title":"Local OpenCode Unavailable","onboarding.desktopRecovery.localUnavailable.description":"OpenCode CLI could not be started or is not installed. Install OpenCode or connect to a remote server instead.","onboarding.desktopRecovery.localUnavailable.retry":"Retry Local","onboarding.desktopRecovery.localUnavailable.useLocal":"Set Up Local","onboarding.desktopRecovery.noDefaultConnection.title":"No Default Connection","onboarding.desktopRecovery.noDefaultConnection.description":"Your saved default connection could not be found. Choose how you want to connect.","onboarding.desktopRecovery.remoteUnreachable.title":"Remote Server Unreachable","onboarding.desktopRecovery.remoteUnreachable.description":'Could not connect to "{host}". Check your network connection and verify the server address.',"onboarding.desktopRecovery.remoteUnreachable.retry":"Retry Connection","onboarding.desktopRecovery.incompatibleServer.title":"Incompatible Server","onboarding.desktopRecovery.incompatibleServer.description":'The server at "{host}" is not running OpenChamber. Verify the address points to an OpenChamber server.',"onboarding.desktopRecovery.remoteIncompatible.title":"Server Update Required","onboarding.desktopRecovery.remoteIncompatible.description":'The OpenChamber server at "{host}" is not compatible with this app version. Update OpenChamber on the server, then try again.',"onboarding.desktopRecovery.remoteIncompatible.updateServer":"Update server","onboarding.desktopRecovery.remoteIncompatible.updatingServer":"Updating the server...","onboarding.desktopRecovery.remoteIncompatible.updatingHint":"The server installs the update and restarts. The app connects as soon as it is back.","onboarding.desktopRecovery.remoteIncompatible.updateRefused":"The server could not update itself.","onboarding.desktopRecovery.remoteIncompatible.updateAuth":"The server did not accept this app's sign-in, so it could not be updated from here.","onboarding.desktopRecovery.remoteIncompatible.updateTimeout":"The server has not come back with the new version yet. Check it, then retry the connection.","onboarding.desktopRecovery.remoteIncompatible.manualUpdate":"To update it by hand, run this on the server, then restart OpenChamber there:","onboarding.desktopRecovery.common.useLocal":"Use Local","onboarding.desktopRecovery.common.useRemote":"Use Remote","onboarding.desktopRecovery.actions.retrying":"Retrying…","onboarding.desktopRecovery.actions.retryConnection":"Retry Connection","projectConfigError.toast.title":"OpenCode can't load this project's config","projectConfigError.toast.unknownFile":"Project config","projectConfigError.toast.hint":"Fix the file, then retry. Other projects keep working.","projectConfigError.toast.retry":"Retry","projectConfigError.toast.retrying":"Retrying…","startup.initRecovery.title":"Startup failed","startup.serverOutdated.title":"Server update required","startup.serverOutdated.description":"The server runs OpenChamber {version}, and this app needs 2.0 or later there. Update OpenChamber on the server to continue.","startup.serverOutdated.checking":"Checking the server...","startup.serverOutdated.noUpdate":"The server did not offer an update it can install itself.","startup.initRecovery.openCodeUnavailable":"OpenChamber is reachable, but OpenCode is not ready. Check OpenCode on the server, then retry.","startup.initRecovery.binary":"OpenCode executable","startup.initRecovery.error":"OpenCode error","startup.initRecovery.serverUnreachable":"OpenChamber could not reach its server. Check that the server is running, then retry.","startup.initRecovery.loadAgentsFailed":"The server is running, but OpenCode could not load agents. Retry once the cause is fixed.","startup.initRecovery.unexpected":"OpenChamber could not finish starting. Retry once the cause is fixed.","startup.initRecovery.lastError":"Last error","startup.initRecovery.retry":"Retry","startup.initRecovery.retrying":"Retrying…","startup.overlay.slow":"Startup is taking longer than expected…","onboarding.desktopRecovery.placeholders.remoteServer":"the remote server","onboarding.desktopRecovery.placeholders.unknownServer":"unknown","vscodeLayout.title.chat":"Chat","vscodeLayout.title.newSession":"New session","vscodeLayout.title.sessions":"Sessions","vscodeLayout.title.sessionFallback":"Session","vscodeLayout.actions.backToSessionsAria":"Back to sessions","vscodeLayout.actions.archiveAllAria":"Archive all sessions","vscodeLayout.actions.archiveAllConfirm":"Archive all","vscodeLayout.actions.archiveAllSuccess":"Archived {count} session(s)","vscodeLayout.actions.archiveAllError":"Failed to archive {count} session(s)","vscodeLayout.actions.cancel":"Cancel","vscodeLayout.actions.newSessionAria":"New session","vscodeLayout.actions.resizeSessionsSidebarAria":"Resize sessions sidebar","vscodeLayout.actions.settingsAria":"Settings","vscodeLayout.quota.title":"Rate limits","vscodeLayout.quota.mode.used":"Used","vscodeLayout.quota.mode.remaining":"Remaining","vscodeLayout.quota.lastUpdated":"Last updated {time}","vscodeLayout.quota.noRateLimitsAvailable":"No rate limits available.","vscodeLayout.quota.noRateLimitsReported":"No rate limits reported.","vscodeLayout.quota.actions.rateLimitsAria":"Rate limits","vscodeLayout.quota.actions.showUsedAria":"Show used quota","vscodeLayout.quota.actions.showRemainingAria":"Show remaining quota","vscodeLayout.quota.actions.refreshAria":"Refresh rate limits","updateDialog.header.updateAvailable":"Update Available","updateDialog.header.updating":"Updating OpenChamber...","updateDialog.changelog.title":"What's new","updateDialog.status.installingUpdate":"Installing update...","updateDialog.status.serverRestarting":"Server restarting...","updateDialog.status.waitingForServer":"Waiting for server...","updateDialog.status.autoReloadHint":"The page will reload automatically when the update is complete.","updateDialog.fallback.updateViaTerminal":"Or update via terminal:","updateDialog.desktopHostInstall":"OpenChamber {version} is available. Update it on the computer it runs on.","updateDialog.actions.copyCommand":"Copy command","updateDialog.actions.copied":"Copied!","updateDialog.status.downloadingPayload":"Downloading update payload...","updateDialog.actions.downloadUpdate":"Download Update","updateDialog.status.downloading":"Downloading...","updateDialog.actions.restartToUpdate":"Restart to Update","updateDialog.status.restarting":"Restarting...","updateDialog.actions.updateNow":"Update Now","updateDialog.actions.openMobileUpdate":"Open update","updateDialog.status.updating":"Updating...","updateDialog.error.updateFailed":"Update failed","updateDialog.error.takingLonger":"Update is taking longer than expected. Wait a bit and refresh, or run: openchamber update","updateDialog.error.signatureRejected":"The downloaded update was rejected: its code signature does not match this installation. This usually means the running copy was not installed from an official signed release. Install OpenChamber from an official release, then update again.","updateDialog.error.updaterDisabled":"The updater stopped after a failed install. Quit OpenChamber, open it again, and retry the update.","updateDialog.error.restartFailed":"Could not restart to install the update.","updateDialog.error.restartUnavailable":"Installing the update requires the OpenChamber desktop app.","mobileUpdate.toast.available.title":"OpenChamber update available","mobileUpdate.toast.available.description":"Version {version} is ready for Android.","mobileUpdate.toast.actions.download":"Download","opencodeUpdate.toast.available.title":"OpenCode update","opencodeUpdate.toast.available.description":"Version {version} available.","opencodeUpdate.toast.available.manualDescription":"Version {version} available. Update OpenCode the way you installed it, then restart OpenChamber.","opencodeUpdate.toast.actions.update":"Update","opencodeUpdate.toast.actions.reload":"Reload OpenCode","opencodeUpdate.toast.upgrading.title":"Updating OpenCode...","opencodeUpdate.toast.upgrading.description":"Keep OpenChamber open.","opencodeUpdate.toast.updated.title":"OpenCode updated","opencodeUpdate.toast.updated.description":"Update installed.","opencodeUpdate.toast.updated.descriptionWithVersion":"Version {version} installed.","opencodeUpdate.toast.failed.title":"Could not update OpenCode","opencodeUpdate.toast.failed.description":"The OpenCode upgrade failed.","opencodeUpdate.toast.reload.message":"Restarting OpenCode...","memoryDebugPanel.title":"Debug Panel","memoryDebugPanel.tabs.memory":"Memory","memoryDebugPanel.tabs.streaming":"Streaming","memoryDebugPanel.tabs.requests":"Requests","memoryDebugPanel.section.sessionsInMemory":"Sessions in Memory","memoryDebugPanel.section.uiStreamingMetrics":"UI Streaming Metrics","memoryDebugPanel.section.vscodeBridgeMetrics":"VS Code Bridge Metrics","memoryDebugPanel.section.noUiSamples":"No UI streaming samples yet. Start a stream and keep this panel open.","memoryDebugPanel.section.noVscodeSamples":"No VS Code bridge samples yet.","memoryDebugPanel.metric.totalMessages":"Total Messages","memoryDebugPanel.metric.cachedSessions":"Cached Sessions","memoryDebugPanel.metric.userMessages":"User Messages","memoryDebugPanel.metric.assistantMessages":"Assistant Messages","memoryDebugPanel.metric.viewportWindow":"Viewport Window","memoryDebugPanel.metric.zombieTimeout":"Zombie Timeout","memoryDebugPanel.metric.githubTotalRequests":"GitHub Total Requests","memoryDebugPanel.metric.metrics":"Metrics","memoryDebugPanel.metric.samples":"Samples","memoryDebugPanel.metric.lastUpdate":"Last Update","memoryDebugPanel.metric.uiMetrics":"UI Metrics","memoryDebugPanel.metric.vscodeMetrics":"VS Code Metrics","memoryDebugPanel.metric.messageListRenders":"MsgList Renders","memoryDebugPanel.metric.messageListStreamRenders":"MsgList Stream Renders","memoryDebugPanel.metric.chatMessageRenders":"ChatMessage Renders","memoryDebugPanel.metric.chatMessageStreamRenders":"ChatMessage Stream Renders","memoryDebugPanel.metric.chatMessageStaticDuringStream":"ChatMessage Static During Stream","memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn":"ChatMessage Static Outside Active Turn","memoryDebugPanel.metric.messagesValue":"{count} messages","memoryDebugPanel.metric.minutesValue":"{count} minutes","memoryDebugPanel.metric.msgsValue":"{count} msgs","memoryDebugPanel.metric.roleMsgsValue":"U {user} / A {assistant}","memoryDebugPanel.metric.countValue":"count {value}","memoryDebugPanel.metric.avgValue":"avg {value}","memoryDebugPanel.metric.maxValue":"max {value}","memoryDebugPanel.metric.totalValue":"total {value}","memoryDebugPanel.actions.logState":"Log State","memoryDebugPanel.actions.copyJson":"Copy JSON","memoryDebugPanel.tooltip.logCurrentState":"Log current memory state to browser console","memoryDebugPanel.streaming.copy.copied":"Streaming debug JSON copied","memoryDebugPanel.streaming.copy.failed":"Failed to copy JSON","memoryDebugPanel.streaming.copy.hint":"Copy exports both UI and VS Code streaming metrics as JSON","memoryDebugPanel.requests.inFlight":"In flight","memoryDebugPanel.requests.peak":"Peak","memoryDebugPanel.requests.duration":"Duration","memoryDebugPanel.requests.totalRequests":"Total Requests","memoryDebugPanel.requests.tracking":"Tracking","memoryDebugPanel.requests.now":"now","memoryDebugPanel.requests.noSamples":"No requests tracked yet. Keep this panel open to record fetch activity.","memoryDebugPanel.requests.chartLabel":"Fetch requests in flight over time, peak {peak}","memoryDebugPanel.requests.windowHint":"last {seconds}s","memoryDebugPanel.requests.percentileChartLabel":"In-flight request age percentiles (p50, p90, p99, max) over time","memoryDebugPanel.common.idle":"idle","memoryDebugPanel.common.live":"live","memoryDebugPanel.common.notAvailable":"n/a","memoryDebugPanel.common.untitled":"Untitled","directoryTree.field.newDirectoryPlaceholder":"new_directory","textarea.resizeHandleAria":"Resize textarea","sidebar.resize.leftPanelAria":"Resize left panel","sidebar.resize.rightPanelAria":"Resize right panel","mainLayout.mobile.closeDrawerAria":"Close drawer","sortableTabsStrip.aria.tabs":"Tabs","openChamberLogo.aria.logo":"OpenChamber logo","markdownRenderer.code.proposal":"Proposal","markdownRenderer.code.actions.copyTitle":"Copy code","markdownRenderer.code.actions.copiedTitle":"Copied","markdownRenderer.code.actions.runTitle":"Run command. The agent continues from its output","markdownRenderer.code.actions.stopTitle":"Stop command","markdownRenderer.code.run.startFailed":"Could not start the command","markdownRenderer.code.run.running":"Running","markdownRenderer.code.run.finished":"Finished","markdownRenderer.code.run.failed":"Exit code {code}","markdownRenderer.code.run.stopped":"Stopped","markdownRenderer.table.actions.copyTitle":"Copy table","markdownRenderer.code.actions.enableWrapTitle":"Enable line wrap","markdownRenderer.code.actions.disableWrapTitle":"Disable line wrap","markdownRenderer.table.actions.enableWrapTitle":"Enable cell wrap","markdownRenderer.table.actions.disableWrapTitle":"Disable cell wrap","markdownRenderer.table.actions.downloadTitle":"Download table","markdownRenderer.table.toast.downloadedAsFormat":"Table downloaded as {format}","markdownRenderer.mermaid.actions.copyTitle":"Copy","markdownRenderer.mermaid.actions.copySourceTitle":"Copy source","markdownRenderer.mermaid.actions.downloadSvgTitle":"Download SVG","markdownRenderer.mermaid.actions.zoomInTitle":"Zoom in","markdownRenderer.mermaid.actions.zoomOutTitle":"Zoom out","markdownRenderer.mermaid.actions.resetViewTitle":"Reset view","markdownRenderer.mermaid.toast.downloadFailed":"Failed to download diagram","common.date.today":"Today","common.date.yesterday":"Yesterday","common.date.yesterdayWithTime":"Yesterday {time}","common.relative.justNow":"Just now","common.relative.minutesAgoShort":"{count}min ago","common.relative.hoursAgoShort":"{count}h ago","common.relative.daysAgoShort":"{count}d ago","common.relative.weeksAgoShort":"{count}w ago","common.relative.yearsAgoShort":"{count}y ago","common.relative.minutesAgoCompact":"{count}m","common.relative.hoursAgoCompact":"{count}h","common.relative.daysAgoCompact":"{count}d","common.relative.weeksAgoCompact":"{count}w","common.relative.monthsAgoCompact":"{count}mo","common.relative.yearsAgoCompact":"{count}y","common.duration.secondsCompact":"{seconds}s","common.duration.minutesSecondsCompact":"{minutes}m {seconds}s","common.duration.hoursMinutesCompact":"{hours}h {minutes}m","contextFileOpen.failure.tooLarge":"{name} is too large to open","contextFileOpen.failure.tooLargeDetail":"More than {count} lines · {size}","contextFileOpen.failure.tooLargeSize":"Larger than {limit} · {size}","contextFileOpen.failure.missing":"{name} was not found","contextFileOpen.failure.unreadable":"Couldn't open {name}","quota.window.5h":"5-Hour","quota.window.7d":"7-Day Limit","quota.window.extraUsage":"Extra Usage","quota.window.weekly":"Weekly","quota.window.daily":"Daily","quota.window.monthly":"Monthly","quota.window.credits":"Credits","quota.value.creditsUsed":"{credits} Credits Used","quota.window.keyLimit":"Key Limit","quota.window.creditsBalance":"Credits Balance","quota.window.monthlyCredits":"Monthly Credits","quota.window.purchasedCredits":"Purchased Credits","quota.window.freeCredits":"Free Credits","quota.window.billingCycle":"Billing Cycle","quota.window.auto":"Auto","quota.window.api":"API","quota.window.planLimit":"Plan Limit","quota.window.onDemand":"On-demand","quota.window.session":"Session","quota.window.premium":"Premium Interactions","quota.window.chat":"Chat Requests","quota.window.completions":"Completions","quota.window.premiumInteractions":"AI Credits","chat.workStatus.ariaLabel":"Work status","chat.workStatus.mobileEmpty":"Nothing to show for this session yet","chat.workStatus.context.label":"Context","chat.workStatus.cost.breakdown":"Session {session} · Subagents {subagents}","chat.workStatus.git.changedFileSingle":"{count} file changed","chat.workStatus.git.changedFilePlural":"{count} files changed","chat.workStatus.pr.untitled":"Untitled pull request","chat.workStatus.mr.untitled":"Untitled merge request","chat.workStatus.pr.draft":"Draft","chat.workStatus.pr.checks":"Checks","chat.workStatus.pr.checksFailed":"{count} failed","chat.workStatus.pr.checksPending":"{count} running","chat.workStatus.pr.checksPassed":"{count} passed","chat.workStatus.attention.merge":"Merge in progress","chat.workStatus.attention.rebase":"Rebase in progress","chat.workStatus.attention.cherryPick":"Cherry-pick in progress","chat.workStatus.attention.revert":"Revert in progress","chat.workStatus.attention.bisect":"Bisect in progress","chat.workStatus.subagent.done":"Done","chat.workStatus.subagent.failed":"Failed","chat.workStatus.subagent.untitled":"Subagent","chat.workStatus.mcp.toggle":"Toggle {name}","chat.workStatus.mcp.needsAuth":"Sign in","chat.workStatus.mcp.failed":"Failed","chat.workStatus.pinned.unavailable":"Pinned message","chat.workStatus.section.session":"Session","chat.workStatus.section.project":"Project","chat.workStatus.section.subagents":"Subagents","chat.workStatus.section.mcp":"MCP","chat.workStatus.section.pinned":"Pinned messages","chat.workStatus.section.tasks":"Tasks","chat.workStatus.subagent.working":"is working","chat.workStatus.subagent.needsPermission":"needs permission","chat.workStatus.subagent.askedQuestion":"asked a question","chat.workStatus.section.contextBreakdown":"Context sources","chat.workStatus.breakdown.skills":"Skills","chat.workStatus.breakdown.pinnedNote":"note","chat.workStatus.breakdown.unpin":"Unpin from context","chat.workStatus.breakdown.pinnedPlan":"plan","chat.workStatus.breakdown.memory":"Agent memory","chat.workStatus.breakdown.pinnedKnowledgeSingle":"{count} pinned","chat.workStatus.breakdown.pinnedKnowledgePlural":"{count} pinned","chat.workStatus.breakdown.mcp":"MCP servers","chat.workStatus.action.openChanges":"Open changes","chat.workStatus.action.openGit":"Open Git panel","chat.workStatus.action.openPr":"Open pull request","chat.workStatus.action.openMr":"Open merge request","chat.workStatus.action.openSubagent":"Open {name}","chat.workStatus.section.usage":"Usage","chat.workStatus.section.telemetry":"Turn stats","chat.workStatus.telemetry.previousTurn":"Previous turn","chat.workStatus.telemetry.previousTurnRate":"Previous turn · {rate}","chat.workStatus.telemetry.responseSpeed":"Response","chat.workStatus.telemetry.responseSpeedDescription":"How fast the final text arrived. Excludes the initial wait, reasoning, and earlier tool calls. An estimate from text timestamps, not a provider speed measurement.","chat.workStatus.telemetry.speed":"Whole turn","chat.workStatus.telemetry.speedDescription":"Tokens generated across all steps, including reasoning, divided by time with tool execution removed. Waiting for the model still counts, so many short tool calls can lower this number.","chat.workStatus.telemetry.elapsed":"Elapsed","chat.workStatus.telemetry.elapsedDescription":"Wall-clock time from the first user message to the final assistant response. Includes model waiting, tool execution, compaction, and other gaps.","chat.workStatus.telemetry.llmDuration":"Model time","chat.workStatus.telemetry.llmDurationDescription":"Time spent on all model steps, including waiting for responses. Tool execution time is removed. This is not just time spent generating text.","chat.workStatus.telemetry.toolDuration":"Tool time","chat.workStatus.telemetry.toolDurationDescription":"Time spent running tools, including failed calls. Tools running at the same time are counted once, not added together.","chat.workStatus.telemetry.ttft":"Average TTFT","chat.workStatus.telemetry.ttftDescription":"Average wait before the first text or reasoning starts in each model step. Hidden when a step has no start after it was created, which is common for tool-only steps and for parts stamped at creation time.","chat.workStatus.telemetry.steps":"Steps","chat.workStatus.telemetry.stepsDescription":"How many times the model was called for this prompt. Reading tool results and deciding what to do next usually takes another step.","chat.workStatus.telemetry.tokens":"Tokens","chat.workStatus.telemetry.tokens.inOut":"{input} ↑ · {output} ↓","chat.workStatus.telemetry.tokensDescription":"↑ Input without cached tokens: {input}. ↓ Generated tokens: {output} for text and tool calls, plus {reasoning} for reasoning. Totals cover all steps of this prompt.","chat.workStatus.telemetry.cacheHit":"Cache","chat.workStatus.telemetry.cacheHitDescription":"Share of input tokens reused from the prompt cache across all steps. Reusing context can reduce cost and waiting, but this is not a speed score.","chat.workStatus.telemetry.cost":"Cost","chat.workStatus.telemetry.costDescription":"Cost reported by the provider for all model steps of this prompt, in US dollars. Excludes separate subagent sessions. Zero can mean a free model or a provider that reports no charge.","chat.workStatus.goal.open":"Manage goal","chat.workStatus.goal.pause":"Pause","chat.workStatus.goal.resume":"Resume","chat.workStatus.goal.updateFailed":"Could not update the goal","chat.workStatus.pinned.unpin":"Unpin message","chat.workStatus.pinned.reveal":"Go to message","chat.workStatus.pinned.unpinFailed":"Could not unpin the message","chat.workStatus.action.openContext":"Open context panel","chat.workStatus.section.linkedIssues":"Linked","chat.workStatus.linkedIssues.openOnProvider":"Open {reference} on {provider}","chat.workStatus.linkedIssues.unlink":"Remove link","chat.workStatus.linkedIssues.unlinkFailed":"Could not remove the link","chat.workStatus.linkedIssues.link":"Link to session","chat.workStatus.linkedIssues.linkFailed":"Could not link","chat.workStatus.breakdown.issueCountSingle":"{count} issue","chat.workStatus.breakdown.issueCountPlural":"{count} issues","chat.workStatus.breakdown.prCountSingle":"{count} PR","chat.workStatus.breakdown.mrCountSingle":"{count} MR","chat.workStatus.breakdown.prCountPlural":"{count} PRs","chat.workStatus.breakdown.mrCountPlural":"{count} MRs","chat.workStatus.breakdown.skillCountSingle":"{count} skill","chat.workStatus.breakdown.skillCountPlural":"{count} skills","chat.workStatus.breakdown.mcpCountSingle":"{count} MCP","chat.workStatus.breakdown.mcpCountPlural":"{count} MCP","chat.workStatus.sections.open":"Choose sections","chat.workStatus.sections.dialogTitle":"Panel sections","chat.workStatus.sections.reorder":"Drag {label} to reorder","chat.workStatus.sections.dragInstructions":"Press Space to pick up a section, use the arrow keys to move it, and press Space to drop. Press Escape to cancel.","chat.workStatus.sections.position":"{label}, position {position} of {count}.","chat.workStatus.sections.dragCancelled":"Reordering cancelled.","chat.workStatus.sections.dialogDescription":"Choose what the work-status panel shows. Hidden sections keep their data — they are only left out of the panel.","chat.workStatus.sections.allHidden":"No sections selected","chat.workStatus.sections.showAll":"Show all","chat.workStatus.sections.noneWarning":"The panel will appear empty.","header.workStatusPanel.toggleAria":"Toggle work-status panel","header.actions.newMiniChat":"New Mini Chat Window","header.actions.newMiniChatAria":"Open a new Mini Chat window","header.actions.openSessionMiniChat":"Open Session in Mini Chat","header.actions.openSessionMiniChatAria":"Open current session in Mini Chat","header.workStatusPanel.hide":"Hide work status","header.workStatusPanel.show":"Show work status","chat.workStatus.mcp.authorizeOpenFailed":"Could not open the authorization page","chat.workStatus.mcp.authorizeFailed":"Authorization failed","chat.formCard.inputNeeded":"Input needed","chat.formCard.fromSubagent":"from a subagent","chat.formCard.required":"Required","chat.formCard.openLink":"Open link","chat.formCard.yes":"Yes","chat.formCard.other":"Other","chat.formCard.yourAnswer":"Your answer","chat.formCard.submit":"Submit","chat.formCard.cancel":"Cancel","chat.formCard.missingRequired":"Fill in the required fields first.","chat.formCard.submitFailed":"Could not submit the answer","chat.formCard.cancelFailed":"Could not cancel the request","chat.formCard.tryAgain":"Try again.","chat.formCard.recoveredNotice":"The turn stopped while waiting. Submit starts a new paid turn.","chat.formDock.progress":"{current} of {total}","chat.formDock.waiting":"{count} more waiting","chat.formDock.back":"Back","chat.formDock.expandAria":"Expand the question","chat.formDock.collapseAria":"Collapse the question","chat.formDock.stepAria":"Question {index}: {title}","chat.formDock.linkInfo":"Open the link, then continue.","chat.permissionCard.title":"Permission required","chat.permissionCard.summary.externalDirectory":"Access files outside the project","chat.permissionCard.summary.read":"Read a file","chat.permissionCard.summary.edit":"Edit files","chat.permissionCard.summary.shell":"Run a command","chat.permissionCard.summary.glob":"Find files","chat.permissionCard.summary.grep":"Search file contents","chat.permissionCard.summary.webfetch":"Open a web page","chat.permissionCard.summary.websearch":"Search the web","chat.permissionCard.summary.skill":"Load a skill","chat.permissionCard.summary.tool":"Use {tool}","chat.permissionCard.summary.inPath":"in {path}","chat.permissionCard.showDetails":"Show details","chat.permissionDock.expandAria":"Expand the permission request","chat.permissionDock.collapseAria":"Collapse the permission request","chat.permissionDock.stepAria":"Request {index}: {tool}","chat.permissionCard.allowOnce":"Allow once","chat.permissionCard.alwaysAllow":"Always allow","chat.permissionCard.alwaysAllowPatterns":"Always: {patterns}","chat.permissionCard.deny":"Deny","chat.permissionCard.replaceAll":"Replaces every occurrence","chat.compaction.running":"Compacting the conversation","chat.compaction.completed":"Conversation compacted","chat.compaction.failed":"Compaction failed","chat.compaction.showSummary":"Show summary","chat.compaction.hideSummary":"Hide summary","chat.dispatchedSession.completed":"Session finished: {title}","chat.dispatchedSession.failed":"Session failed: {title}","chat.dispatchedSession.cancelled":"Session stopped: {title}","chat.dispatchedSession.completedUntitled":"Session finished","chat.dispatchedSession.failedUntitled":"Session failed","chat.dispatchedSession.cancelledUntitled":"Session stopped","chat.dispatchedSession.showAnswer":"Show answer","chat.dispatchedSession.hideAnswer":"Hide answer","chat.dispatchedSession.open":"Open session","chat.fileOpenRequest.toast.description":"Shown in {session}","chat.fileOpenRequest.toast.descriptionUntitled":"Shown in another session","chat.fileOpenRequest.toast.openSession":"Open session","chat.revertPopover.staged":"Reverted: {count}","chat.revertPopover.toast.restoreFailed":"Couldn't restore the reverted messages","chat.workStatus.mcp.needsAuthHint":"Sign in to this MCP server from Settings → MCP.","mcpDropdown.toast.authorizeOpenFailed":"Could not open the authorization page","mcpDropdown.toast.authorizeFailed":"Authorization failed","header.services.tooltip.currentInstance":"Current instance: {current} ({toggle})","header.workStatusPanel.showOverlay":"Show work status over the chat","settings.mcp.page.connection.title":"How to reach it","settings.mcp.page.connection.description":"Paste the command that starts it, or the link to a hosted server.","settings.mcp.page.registration.title":"This server needs its own app","settings.mcp.page.registration.description":"It does not hand out credentials automatically. Create an app in the service’s own settings, paste its details here, then sign in.","settings.mcp.page.registration.callbackLabel":"Give the service this address","settings.mcp.page.registration.clientId":"App ID","settings.mcp.page.registration.clientSecret":"App secret","settings.mcp.page.registration.afterSaving":"Save, then press Authorize to sign in.","settings.mcp.page.toast.copiedCallbackUrl":"Address copied","settings.mcp.page.toast.clipboardWriteFailed":"Could not copy to the clipboard","settings.mcp.page.scope.everywhere":"Available in every project","settings.mcp.page.scope.thisProject":"Only in this project","settings.mcp.page.env.description":"Values the server needs, such as an API key.","settings.mcp.page.connection.kindCommand":"Command","settings.mcp.page.connection.kindLink":"Link","settings.mcp.page.connection.hintCommand":"Runs on this machine. Paste a whole command and it is split into one argument per line.","settings.mcp.page.connection.hintLink":"Connects to a server someone else hosts. Paste its https address.","chat.messageBody.actions.askOtherModels":"Ask other models","chat.modelControls.runInParallel":"Run on several models","chat.parallel.defaultTitle":"Parallel run","chat.parallel.exit":"Leave parallel mode","chat.parallel.fuse.judge":"Fuse with {model}","chat.parallel.fuse.off":"Fuse: off","chat.parallel.isolation.shared":"Shared directory","chat.parallel.isolation.worktrees":"Separate worktrees","chat.parallel.models.add":"Add model","chat.parallel.models.decrement":"Run {model} one time less","chat.parallel.models.increment":"Run {model} one more time","chat.parallel.runAria":"Start parallel runs ({count})","chat.parallel.setup.dialogDescription":"Commands run in every new worktree before its prompt, one per line.","chat.parallel.toast.failed":"Could not start the parallel run.","chat.parallel.toast.incomplete":"Every prompt variant needs text and at least one model.","chat.parallel.variant.removeAria":"Remove variant {variant}","chat.parallel.variant.runsPlural":"{count} runs","chat.parallel.variant.runsSingle":"{count} run","chat.parallel.variant.tabsAria":"Prompt variants","multirun.ask.checking":"Checking this answer…","multirun.ask.description":"This chat becomes the first run. Each model gets the same first prompt in its own worktree.","multirun.ask.failed":"Could not ask other models.","multirun.ask.notFirstTurn":"Only the first answer of a chat can be compared for now.","multirun.ask.startPlural":"Run {count} more","multirun.ask.startSingle":"Run {count} more","multirun.ask.title":"Ask other models","multirun.overview.archive.action":"Archive run","multirun.overview.archive.failed":"Some runs could not be archived.","multirun.overview.ask.failed":"Could not add the model to this run.","multirun.overview.ask.working":"Adding…","multirun.overview.bar.fuse":"Fuse results","multirun.overview.bar.hint":"Fuse the answers into one result","multirun.overview.cancel":"Cancel","multirun.overview.card.changesUnavailable":"Changes unavailable","multirun.overview.card.diff":"Diff","multirun.overview.card.filesPlural":"{count} files","multirun.overview.card.filesSingle":"{count} file","multirun.overview.card.noChanges":"No file changes","multirun.overview.card.noReply":"No answer yet","multirun.overview.card.openChat":"Open chat","multirun.overview.card.replyUnavailable":"Answer unavailable","multirun.overview.card.selectAria":"Select {name}","multirun.overview.card.working":"Working…","multirun.overview.fuse.modeAnswers":"Combines the final answers","multirun.overview.fuse.modeCode":"Works in its own worktree and reads each run with git","multirun.overview.fuse.selected":"{count} of {total} selected","multirun.overview.fuse.with":"Fuse with","multirun.overview.fusedResult":"Fused result","multirun.overview.headerTitle":"Run in parallel","multirun.overview.keep.confirm":"Keep and clean up","multirun.overview.keep.confirmPlural":"Keep {name}? The other {count} runs are archived and their worktrees removed. Their work stays recoverable.","multirun.overview.keep.confirmSingle":"Keep {name}? The other run is archived and its worktree removed. Its work stays recoverable.","multirun.overview.keep.done":"Kept {name}","multirun.overview.keep.failed":"Could not clean up the other runs.","multirun.overview.keep.partialPlural":"Kept {name}. {count} runs could not be cleaned up and were left as they were.","multirun.overview.keep.partialSingle":"Kept {name}. One run could not be cleaned up and was left as it was.","multirun.overview.keep.working":"Cleaning up…","multirun.overview.meta.autoFusion":"Fuses with {model} when all finish","multirun.overview.meta.progress":"{done} of {total} finished","multirun.overview.meta.runsPlural":"{count} runs","multirun.overview.meta.runsSingle":"{count} run","multirun.overview.meta.sharedDirectory":"Shared directory","multirun.overview.meta.variants":"{count} prompt variants","multirun.overview.meta.worktrees":"Separate worktrees","multirun.overview.missing":"This run is no longer available.","multirun.overview.rename.aria":"Rename run","multirun.overview.rename.failed":"Some runs kept the old name.","sessions.sidebar.run.collapse":"Hide runs","sessions.sidebar.run.expand":"Show runs","sessions.sidebar.run.laneCountPlural":"{count} runs","sessions.sidebar.run.laneCountSingle":"{count} run","sessions.sidebar.run.openOverviewAria":"Open parallel run {title}","sessions.sidebar.run.menu.openOverview":"Open overview","sessions.sidebar.session.menu.openRunOverview":"Open run overview","chat.parallel.models.effortAria":"Thinking effort: {effort}","chat.parallel.settings.title":"Launch settings","chat.parallel.settings.whereTitle":"Where the runs work","chat.parallel.settings.setupTitle":"Setup commands","chat.parallel.settings.fusionTitle":"Fusion","chat.parallel.settings.variantsTitle":"Prompt variants","chat.parallel.settings.variantsDescription":"Send different prompts, for example to compare skills or wording. Each variant gets its own tab.","chat.parallel.settings.addVariant":"Add a prompt variant","chat.parallel.settings.done":"Done","chat.parallel.settings.openAria":"Launch settings: {summary}","multirun.overview.card.keep":"Keep this","multirun.overview.addModel.action":"Add a model","multirun.overview.addModel.hint":"Runs the same prompt on one more model in this run","chat.parallel.settings.whereShared":"Project directory","chat.parallel.settings.whereSharedHint":"All runs work in your checkout. Best for questions and research.","chat.parallel.settings.whereWorktrees":"Separate worktrees","chat.parallel.settings.whereWorktreesHint":"Each run gets its own branch, so code changes never collide. Keep the best one.","chat.parallel.settings.baseBranchTitle":"Base branch","chat.parallel.settings.fusionOff":"Off","chat.parallel.settings.fusionOffHint":"Compare the results yourself.","chat.parallel.settings.fusionAuto":"Automatic","chat.parallel.settings.fusionAutoHint":"Fuse the results as soon as every run finishes.","chat.parallel.settings.judgeTitle":"Fusion model","multirun.overview.card.detach":"Make a separate session","multirun.overview.card.detachHint":"Leave this run and continue as an ordinary session","multirun.overview.card.detachDone":"{name} is now a separate session","multirun.overview.card.detachFailed":"Could not move this session out of the run.","multirun.overview.card.archive":"Archive this session","multirun.overview.addModel.confirm":"Run","multirun.overview.status.permission":"Waiting for your permission","multirun.overview.status.question":"Waiting for your answer","multirun.overview.status.working":"Working","multirun.overview.status.failed":"Failed","multirun.overview.status.stopped":"Stopped","multirun.overview.status.notStarted":"Not started","multirun.overview.status.noReply":"Finished without an answer","multirun.overview.status.finished":"Finished","multirun.overview.status.count.permission":"{count} waiting for permission","multirun.overview.status.count.question":"{count} waiting for an answer","multirun.overview.status.count.working":"{count} working","multirun.overview.status.count.failed":"{count} failed","multirun.overview.status.count.stopped":"{count} stopped","multirun.overview.status.count.notStarted":"{count} not started","multirun.overview.status.count.noReply":"{count} without an answer","multirun.overview.status.count.finished":"{count} finished","multirun.overview.card.body.permission":"Waiting for your permission to go on. Open the chat to answer.","multirun.overview.card.body.question":"Asked you a question. Open the chat to answer.","multirun.overview.card.body.failed":"Failed. Open the chat for details.","multirun.overview.card.body.notStarted":"Has not started yet.","multirun.overview.card.body.stopped":"Stopped before answering.","multirun.overview.bar.waiting":"Runs waiting for you: {count}. The run can't finish until you answer them.","multirun.overview.prompt.expand":"Show all","multirun.overview.prompt.collapse":"Show less","gitView.changes.revertFileDialogTitle":"Revert file changes?","gitView.changes.revertFileDescription":"This will discard your local changes in {path}.","gitView.changes.revertFileConfirm":"Revert file","diffView.hunk.discardDialogTitle":"Discard this hunk?","diffView.hunk.discardDescription":"This will discard these local changes in {path}.","sessions.sidebar.project.actions.archiveAll":"Archive all sessions","sessions.sidebar.project.archiveAll.title":"Archive sessions in {project}?","sessions.sidebar.project.archiveAll.descriptionSingle":"{count} session moves to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.descriptionPlural":"{count} sessions move to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.nothing":"Nothing to archive: every session here is pinned, running or In work.","contextPanel.browser.devServers.hide":"Hide port {port} from this list","contextPanel.browser.devServers.showHiddenSingle":"Show {count} hidden port","contextPanel.browser.devServers.showHiddenPlural":"Show {count} hidden ports","sidebarFilesTree.menu.openInDefaultApp":"Open in default app","sessions.sidebar.header.displayMode.showChats":"Show chats section","sessions.scheduledTasks.editor.useDefaults.label":"Use session defaults","sessions.scheduledTasks.editor.useDefaults.hint":"Each run takes the default model, thinking level and agent from Settings → Sessions (or the project's own defaults) at the time it starts.","sessions.scheduledTasks.editor.worktree.label":"Run each run in a fresh worktree","sessions.scheduledTasks.editor.worktree.hint":"Each run gets its own worktree and branch.","sessions.scheduledTasks.editor.worktree.baseBranch.label":"Source branch","sessions.scheduledTasks.editor.worktree.cleanup.label":"Clean up worktree after run","sessions.scheduledTasks.editor.worktree.cleanup.hint":"The worktree and its branch are removed when the run ends.","sessions.scheduledTasks.editor.worktree.cleanup.keepHint":"The worktree and its branch stay after the run so you can review the result.","sessions.scheduledTasks.editor.worktree.notRepo":"The project folder is not a git repository; runs will use the checkout as-is.","sessions.scheduledTasks.dialog.usesDefaults":"Session defaults","sessions.moveSession.menu":"Move session…","sessions.moveSession.hint":"Files stay in the old folder","sessions.moveSession.title":"Move session","sessions.moveSession.description":"The session continues in the chosen folder. Files stay where they are.","sessions.moveSession.chooseFolder":"Choose folder…","sessions.moveSession.current":"Current folder","sessions.moveSession.success":"Session moved","sessions.moveSession.failed":"Could not move the session","chat.folderMissing.text":"Folder {name} no longer exists","chat.folderMissing.action":"Move session","chat.worktreeSetup.running":"Setting up the worktree: running the project's setup commands…","chat.draft.creatingSession":"Creating session…","desktopHostSwitcher.startup.fellBackToLocal":"Its connection didn't open, so OpenChamber started on Local. Connect it from the instance switcher once it's reachable.","desktopSafeStart.title":"OpenChamber kept crashing","desktopSafeStart.description":"Panels are closed and folders collapsed.","chat.chatInput.contextPreview.saveEdit":"Save comment","chat.chatInput.contextPreview.cancelEdit":"Cancel editing","sessions.scheduledTasks.dialog.actions.openSession":"Open session","sessions.scheduledTasks.dialog.actions.openSessionAria":"Open the session from the last run of {taskName}","sessions.scheduledTasks.dialog.toast.alreadyRunningSince":"This task already has a run in progress, started at {time}","sessions.scheduledTasks.dialog.toast.alreadyRunning":"This task already has a run in progress","sessions.scheduledTasks.dialog.toast.alreadyQueued":"This task is already waiting in the queue and will run when a slot frees up","chat.modelControls.agentFavoriteAdd":"Add to favorites. With favorites, Tab cycles through them only","notifications.error.bodyFallback":"An error occurred","notifications.question.bodyFallback":"Agent is waiting for your response","notifications.permission.bodyFallback":"Agent is waiting for your approval","notifications.permission.title":"Permission required","chat.promptHistorySearch.title":"Search prompt history","chat.promptHistorySearch.searchPlaceholder":"Search remembered prompts","chat.promptHistorySearch.close":"Close prompt history search","chat.promptHistorySearch.empty":"No prompts to search yet","chat.promptHistorySearch.noMatches":"No matching prompts","chat.promptHistorySearch.attachmentsSingle":"{count} attachment","chat.promptHistorySearch.attachmentsPlural":"{count} attachments","chat.promptHistorySearch.hint":"↑ ↓ to browse · Enter to load · Esc to close","helpDialog.item.searchPromptHistory":"Search prompt history (chat input)"},ml=new Map([[wi,ki]]);async function wA(e){const t=ml.get(e);if(t)return t;const s=e==="zh-CN"?await qe(()=>import("./zh-CN-Db0Y0Ij-.js"),__vite__mapDeps([3,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="fr"?await qe(()=>import("./fr-CeExWqT9.js"),__vite__mapDeps([109,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="nl"?await qe(()=>import("./nl-CavtTtNf.js"),__vite__mapDeps([110,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="zh-TW"?await qe(()=>import("./zh-TW-CuzqmROB.js"),__vite__mapDeps([111,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="es"?await qe(()=>import("./es-BFk4dosu.js"),__vite__mapDeps([112,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pt-BR"?await qe(()=>import("./pt-BR-iqkU-MRA.js"),__vite__mapDeps([113,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="uk"?await qe(()=>import("./uk-Bm__l5YX.js"),__vite__mapDeps([114,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ko"?await qe(()=>import("./ko-CGv47dWq.js"),__vite__mapDeps([115,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pl"?await qe(()=>import("./pl-BQZVI44N.js"),__vite__mapDeps([116,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="de"?await qe(()=>import("./de-BdVTH897.js"),__vite__mapDeps([117,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ja"?await qe(()=>import("./ja-BlUqUBMY.js"),__vite__mapDeps([118,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="tr"?await qe(()=>import("./tr-CYfLfxAg.js"),__vite__mapDeps([119,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ar"?await qe(()=>import("./ar-CT3AuXVj.js"),__vite__mapDeps([120,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="he"?await qe(()=>import("./he-C_O5IfNH.js"),__vite__mapDeps([121,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):{dict:ki};return ml.set(e,s.dict),s.dict}const _o=vt()((e,t)=>({locale:wi,dictionary:ki,loadingLocale:null,setLocale:s=>{const a=t(),n=ml.get(s);a.locale===s&&a.loadingLocale!==s&&n||(ez(s),e({locale:s,dictionary:n??a.dictionary,loadingLocale:n?null:s}),!n&&wA(s).then(i=>{t().locale===s&&e({dictionary:i,loadingLocale:null})}).catch(i=>{console.error(`[i18n] failed to load locale ${s}`,i),t().locale===s&&e({dictionary:ki,loadingLocale:null})}))}}));function kA(){_o.getState().setLocale(tz())}function yA(e,t,s){const a=e[t]??ki[t]??t;return s?a.replace(/\{([^{}]+)\}/g,(n,i)=>{const o=s[i.trim()];return o==null?n:String(o)}):a}const WV=Object.freeze(Object.defineProperty({__proto__:null,formatMessage:yA,initializeLocale:kA,useI18nStore:_o},Symbol.toStringTag,{value:"Module"})),Tf="session",zf=40,vA=1,CA=100,Af=e=>e==="global"||e==="session",Ad=e=>e!=null&&Number.isInteger(e)&&e>=vA&&e<=CA,SA=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Rd=e=>e==="auto"||typeof e=="string"&&SA.includes(e),Ma="openchamber-input-history.v1",xA=8,PA=50,TA=[40,25,10,5,1],pc=Object.freeze([]);let is=null,zg=0;const Yn=(e=Tf,t=zf)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Rf=()=>(zg+=1,Date.now()*1e3+zg),If=e=>JSON.stringify([e]),hl=(e,t,s)=>JSON.stringify([e,t,s]),Id=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},zA=()=>{const e=Id(),t=Dt?JSON.stringify(To(Dt.base)):is;if(!e)return t;try{return e.getItem(Ma)??(Dt?null:is)}catch{return t}},Ag=kt(p(),ee()),AA=g({key:p().min(1),source:J([k("file-url"),k("vscode-file")]),filename:p().min(1),mimeType:p().min(1),size:v().finite().nonnegative(),reference:p().min(1),path:p().min(1).optional()}),RA=g({text:p(),attachmentKeys:z(p()),restorableAttachments:z(AA),submittedAt:v().finite().nonnegative()}),IA=g({touchedAt:v().finite().nonnegative(),entries:z(ee())}),jA=(e,t)=>{try{const s=JSON.parse(e),n=(t===1?jo([p().trim().min(1)]):jo([p().trim().min(1),p().trim().min(1),p().trim().min(1)])).safeParse(s);if(!n.success)return null;if(t===3){const i=ze(n.data[1]);if(!i||i!==n.data[1])return null}return n.data}catch{return null}},Rg=(e,t)=>{const s=[];for(const[a,n]of Object.entries(e)){if(!jA(a,t))continue;const i=IA.safeParse(n);if(!i.success)continue;const o=i.data.entries.map(r=>RA.safeParse(r)).filter(r=>r.success).map(r=>r.data);s.push([a,{touchedAt:i.data.touchedAt,entries:o}])}return Object.fromEntries(s)},OA=()=>{const e=zA();if(e===null)return Yn();try{const t=JSON.parse(e),s=g({version:k(1),entryLimit:v().int().optional(),scope:J([k("global"),k("session")]).optional(),global:Ag.default({}),session:Ag.default({})}).safeParse(t);return s.success?{entryLimit:Ad(s.data.entryLimit)?s.data.entryLimit:zf,scope:s.data.scope??Tf,globalBuckets:Rg(s.data.global,1),sessionBuckets:Rg(s.data.session,3)}:Yn()}catch{const t=Id();if(t)try{t.removeItem(Ma)}catch{}return is=null,Yn()}};let Dt=null,Po=Yn();const Ig=(e,t,s)=>{const a={...e};for(const n of new Set([...Object.keys(t),...Object.keys(s)])){if(JSON.stringify(t[n])===JSON.stringify(s[n]))continue;const i=s[n];if(!i){delete a[n];continue}const o=new Set((t[n]?.entries??[]).map(d=>JSON.stringify(d))),r=new Set(i.entries.map(d=>JSON.stringify(d))),c=(e[n]?.entries??[]).filter(d=>{const u=JSON.stringify(d);return!o.has(u)||r.has(u)}),l=new Set(c.map(d=>JSON.stringify(d)));for(const d of i.entries){const u=JSON.stringify(d);!o.has(u)&&!l.has(u)&&c.push(d)}c.sort((d,u)=>d.submittedAt-u.submittedAt),a[n]={touchedAt:Math.max(i.touchedAt,e[n]?.touchedAt??0),entries:c}}return a},qn=()=>{const e=OA();if(Po=e,!Dt)return e;const{base:t,value:s}=Dt;return fl({entryLimit:s.entryLimit===t.entryLimit?e.entryLimit:s.entryLimit,scope:s.scope===t.scope?e.scope:s.scope,globalBuckets:Ig(e.globalBuckets,t.globalBuckets,s.globalBuckets),sessionBuckets:Ig(e.sessionBuckets,t.sessionBuckets,s.sessionBuckets)})},jf=(e,t)=>e.slice(Math.max(0,e.length-t)),jg=(e,t,s)=>{const a=Object.entries(e).map(([n,i])=>[n,{touchedAt:i.touchedAt,entries:jf(i.entries,s)}]).sort((n,i)=>i[1].touchedAt-n[1].touchedAt).slice(0,t);return Object.fromEntries(a)},fl=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:jg(e.globalBuckets,xA,t),sessionBuckets:jg(e.sessionBuckets,PA,t)}),To=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Og=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Vn=e=>{const t=fl(e),s=JSON.stringify(To(t));Dt={base:Po,value:t};const a=Id();if(!a)return is=s,t;try{return a.setItem(Ma,s),Dt=null,is=s,t}catch(o){if(!(o instanceof Error)||!Og(o))return is=s,t}try{a.removeItem(Ma)}catch{}for(const o of TA){const r=fl(t,o),c=JSON.stringify(To(r));try{return a.setItem(Ma,c),Dt=null,is=c,r}catch(l){if(!(l instanceof Error)||!Og(l))return Dt={base:Po,value:r},is=c,r}}const n=Yn(t.scope,t.entryLimit),i=JSON.stringify(To(n));try{a.setItem(Ma,i),Dt=null}catch{Dt={base:Po,value:n}}return is=i,n},DA=(e,t,s)=>{const a=e.trim(),n=ze(t),i=s.trim();return!a||!n||!i?null:{runtimeKey:a,directory:n,sessionId:i}},Of=e=>e.source==="vscode"&&e.vscodeSource==="file"?ze(e.vscodePath??null):e.dataUrl.trim()||null,FA=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),bl=e=>{const t=Of(e),s=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),s].join("|")},BA=e=>{const t=Of(e);if(!t)return null;const s=e.agentPath&&e.serverPath===e.agentPath?e.agentPath:void 0;return!s&&!FA(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:bl(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:bl(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t,path:s}},NA=(e,t)=>({text:e,attachmentKeys:t.map(bl),restorableAttachments:t.map(BA).filter(s=>s!==null)}),MA=(e,t)=>e.length===t.length&&e.every((s,a)=>{const n=t[a];return n!==void 0&&s.key===n.key&&s.source===n.source&&s.filename===n.filename&&s.mimeType===n.mimeType&&s.size===n.size&&s.reference===n.reference&&s.path===n.path}),EA=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((s,a)=>s===t.attachmentKeys[a])&&MA(e.restorableAttachments,t.restorableAttachments),Dg=(e,t,s,a)=>{const n=e?[...e.entries]:[];for(const i of t){const o=n.at(-1);EA(o,i)||n.push({text:i.text,attachmentKeys:[...i.attachmentKeys],restorableAttachments:i.restorableAttachments.map(r=>({...r})),submittedAt:Rf()})}return{touchedAt:s,entries:jf(n,a)}},LA=Vn(qn()),Un=vt(e=>({...LA,applyEntryLimit:t=>{Ad(t)&&e(s=>{const a=qn();if(a.entryLimit===t)return{...s,...a};const n=Vn({entryLimit:t,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},applyScope:t=>{Af(t)&&e(s=>{const a=qn();if(a.scope===t)return{...s,...a};const n=Vn({entryLimit:a.entryLimit,scope:t,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},appendSubmissions:(t,s)=>{s.length!==0&&e(a=>{const n=qn(),i=Rf(),o=If(t.runtimeKey),r=hl(t.runtimeKey,t.directory,t.sessionId),c=Vn({entryLimit:n.entryLimit,scope:n.scope,globalBuckets:{...n.globalBuckets,[o]:Dg(n.globalBuckets[o],s,i,n.entryLimit)},sessionBuckets:{...n.sessionBuckets,[r]:Dg(n.sessionBuckets[r],s,i,n.entryLimit)}});return{...a,...c}})},clearSession:t=>{e(s=>{const a=qn(),n=hl(t.runtimeKey,t.directory,t.sessionId);if(!(n in a.sessionBuckets))return{...s,...a};const i={...a.sessionBuckets};delete i[n];const o=Vn({entryLimit:a.entryLimit,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:i});return{...s,...o}})}})),HV=(e,t)=>t?e.scope==="session"?e.sessionBuckets[hl(t.runtimeKey,t.directory,t.sessionId)]?.entries??pc:e.globalBuckets[If(t.runtimeKey)]?.entries??pc:pc,Df=["guest","link","external","repository"],qA=new Set([...Df,"linear"]),Os=p().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!qA.has(e),{message:"Reserved provider id"}),VA=I(["pullRequest","mergeRequest","change"]),UA=I(["checks","pipeline"]),WA=I(["device","pat","cli"]),HA=J([I(["instance-url","personal-access-token","username","http-password"]),p().transform(()=>"unknown")]),GA=p().max(8192).regex(/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/),Fg=p().min(1).max(64),Rn=z(p().min(1).max(256)).max(8),_A=g({id:Os,label:Fg,order:v().int(),terminology:g({changeRequest:VA.catch("pullRequest"),changeRequestPrefix:p().min(1).max(4),issuePrefix:p().min(1).max(4),sharedNumberSpace:T(),abbreviation:p().min(1).max(8),promptNoun:Fg,ci:UA.catch("checks")}),icon:g({sprite:p().max(64).optional(),filledSprite:p().max(64).optional(),path:GA.optional()}),repository:g({nestedNamespaces:T(),pathStyle:k("path").optional().catch(void 0)}),instances:g({format:I(["host","origin"]),defaultInstance:p().min(1).max(256).nullable(),multiple:T(),allowLoopbackHttp:T(),allowPort:T(),reserved:z(p().max(256)).max(16),placeholder:p().max(256),legacyFlow:g({instance:p().min(1).max(256),kind:k("github-com-device")}).optional()}),auth:g({methods:z(J([WA,p().transform(()=>null)])).transform(e=>e.filter(t=>t!==null)),cliName:p().min(1).max(32).optional(),cliTransport:T(),token:g({scopes:z(p().min(1).max(64)).max(32),createPath:p().max(256).optional()}).optional()}),settings:g({fields:z(g({id:p().min(1).max(64),kind:HA,secret:T()})).max(16)}),urls:g({changeRequest:Rn,issue:Rn,discussion:Rn.default([]).catch([]),commit:Rn.default([]).catch([]),user:Rn.default([]).catch([])}),features:g({referenceSearch:T().default(!1),referenceDetail:T().default(!1),listStatuses:T().default(!1),referencesAcross:T().default(!1),startThread:T().default(!1),reviewDrafts:T().default(!1),reviewDraftFileComments:T().default(!1),authorCanReview:T().default(!1),projectUploads:T().default(!1),issueCloseReason:T().default(!1),changeRequestTemplates:z(p().min(1).max(256)).max(8).default([]),changeRequestPatch:T().default(!0),reviewModel:I(["verdict","votes"]).default("verdict").catch("verdict"),revisions:T().default(!1).catch(!1),submitRequirements:T().default(!1).catch(!1),createByPush:T().default(!1).catch(!1),branchHeads:T().default(!0).catch(!0),discussions:T().default(!1).catch(!1)}),extension:g({guestId:p().min(1).max(128),name:p().min(1).max(200),version:p().min(1).max(64)}).optional().catch(void 0)}),KA=(e,t)=>e.order-t.order||(e.id<t.id?-1:e.id>t.id?1:0),wl=z(_A.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const a of e)!a||t.has(a.id)||(t.add(a.id),s.push(a));return s.sort(KA)}),Bg=new Map,jd=e=>{const t=Bg.get(e);if(t)return t;const s={id:e,label:e,order:Number.MAX_SAFE_INTEGER,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"git-branch"},repository:{nestedNamespaces:!1},instances:{format:"origin",defaultInstance:null,multiple:!1,allowLoopbackHttp:!1,allowPort:!1,reserved:[],placeholder:""},auth:{methods:[],cliTransport:!1},settings:{fields:[]},urls:{changeRequest:[],issue:[],discussion:[],commit:[],user:[]},features:{referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,reviewDrafts:!1,reviewDraftFileComments:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1,reviewModel:"verdict",revisions:!1,submitRequirements:!1,createByPush:!1,branchHeads:!0,discussions:!1}};return Bg.set(e,s),s},ZA=16,JA=(e,t)=>{const s=z(jo([p(),t])),a=()=>{try{const n=s.safeParse(JSON.parse(window.localStorage.getItem(e)??"[]"));return n.success?n.data:[]}catch{return[]}};return{read:n=>Lc(n)?null:a().find(([i])=>i===n)?.[1]??null,remember:(n,i)=>{if(Lc(n))return;const o=a().filter(([r])=>r!==n);o.push([n,[...i]]);try{window.localStorage.setItem(e,JSON.stringify(o.slice(-ZA)))}catch{}}}},QA=(e,t)=>e===t||e.length===t.length&&JSON.stringify(e)===JSON.stringify(t),$A=e=>Math.min(6e4,2e3*2**Math.max(0,e-1)),Ff=JA("openchamber.sourceControlProviders.v1",wl),Od=e=>({ordered:e,byId:new Map(e.map(t=>[t.id,t]))}),YA=Od([]),Ng=e=>{const t=Ff.read(e);return t?{runtimeKey:e,...Od(t),status:"stale",holdsList:!0}:{runtimeKey:e,...YA,status:"idle",holdsList:!1}};let Zs=0,Ta=null,za=null,co=0,Xn=null;const Mg=()=>{Xn!==null&&clearTimeout(Xn),Xn=null},wa=vt((e,t)=>{const s=a=>{Zs+=1,Ta=null,za=null,co=0,Mg(),e(Ng(a))};return{...Ng(D()),refresh:a=>{const n=D();if(n!==t().runtimeKey&&s(n),Ta){if(!za){const d=Zs,u=Ta.then(()=>{if(za===u&&(za=null),d===Zs)return t().refresh(a)});za=u}return za}Mg();const i=Zs,{holdsList:o,ordered:r}=t();e({status:"loading"});const l=(async()=>{try{const d=await a.providers();if(i!==Zs)return;co=0,Ff.remember(n,d),e(o&&QA(r,d)?{status:"ready"}:{...Od(d),status:"ready",holdsList:!0})}catch{if(i!==Zs)return;if(o){e({status:"stale"});return}e({status:"error"}),co+=1,Xn=setTimeout(()=>{Xn=null,i===Zs&&t().refresh(a)},$A(co))}})().finally(()=>{Ta===l&&(Ta=null)});return Ta=l,l},resetForRuntimeSwitch:s}});queueMicrotask(()=>{const e=wa.getState(),t=D();e.status==="idle"&&t!==e.runtimeKey&&e.resetForRuntimeSwitch(t)});const GV=()=>wa(eR),XA=e=>{const t=Mt.c(5);let s;t[0]!==e?(s=i=>e?i.byId.get(e):void 0,t[0]=e,t[1]=s):s=t[1];const a=wa(s);let n;return t[2]!==a||t[3]!==e?(n=a??jd(e??""),t[2]=a,t[3]=e,t[4]=n):n=t[4],n},_V=e=>XA(e).terminology.changeRequest,KV=e=>{const t=Mt.c(2);let s;return t[0]!==e?(s=a=>e&&a.byId.has(e)?"served":a.holdsList?"not-served":"unknown",t[0]=e,t[1]=s):s=t[1],wa(s)},ZV=e=>{const t=Mt.c(2);let s;return t[0]!==e?(s=a=>{const n=e?a.byId.get(e):void 0;return n?n.features.changeRequestPatch?"served":"not-served":a.holdsList?"not-served":"unknown"},t[0]=e,t[1]=s):s=t[1],wa(s)},JV=()=>{const e=Mt.c(2),t=wa(tR);let s;return e[0]!==t?(s=a=>(a?t.get(a):void 0)??jd(a??""),e[0]=t,e[1]=s):s=e[1],s},pr=e=>(e?wa.getState().byId.get(e):void 0)??jd(e??"");function eR(e){return e.ordered}function tR(e){return e.byId}const sR=g({text:p(),prefix:p(),suffix:p(),start:v(),page:g({partId:p(),kind:k("ui").optional()}).optional()}),Eg=32,Bf=200,aR="[data-chat-quote-root]";function QV(e,t){return[...e.querySelectorAll(`[data-message-id="${CSS.escape(t)}"]`)].flatMap(s=>s.querySelector(aR)??[]).sort((s,a)=>s.getBoundingClientRect().top-a.getBoundingClientRect().top)}function $V(e,t,s){return e.querySelector(`[data-ui-render-message="${CSS.escape(t)}"][data-ui-render-part="${CSS.escape(s)}"]`)}function Nf(e,t,s){const a=s+t.text.length,n=e.slice(Math.max(0,s-t.prefix.length),s),i=e.slice(a,a+t.suffix.length);return t.prefix.endsWith(n)&&t.suffix.startsWith(i)}function Lg(e,t,s){const a=e.ownerDocument.createRange();return a.setStart(e,0),a.setEnd(t,s),a.toString().length}function Mf(e){const t=[];let s="";for(const a of e)t.push(s.length),s+=a.textContent??"";return{stream:s,bases:t}}function YV(e,t){const s=Array.isArray(e)?e:[e],a=s.findIndex(d=>d.contains(t.startContainer)),n=s.findIndex(d=>d.contains(t.endContainer));if(a<0||n<a)return null;const{stream:i,bases:o}=Mf(s),r=o[a]+Lg(s[a],t.startContainer,t.startOffset),c=o[n]+Lg(s[n],t.endContainer,t.endOffset),l=i.slice(r,c);return l.trim()?{text:l,prefix:i.slice(Math.max(0,r-Eg),r),suffix:i.slice(c,c+Eg),start:r}:null}function nR(e,t){if(!t.text)return null;const s=[];for(let n=e.indexOf(t.text);n!==-1&&s.length<Bf;n=e.indexOf(t.text,n+1))s.push(n);if(s.length<=1)return s[0]??null;if(!t.prefix&&!t.suffix)return null;const a=s.filter(n=>Nf(e,t,n));return a.length===0?null:a.reduce((n,i)=>Math.abs(i-t.start)<Math.abs(n-t.start)?i:n)}function Ef(e,t){for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType===3?t.push(s):Ef(s,t);return t}function iR(e){const t=new Set;let s=1;for(const a of e){const n=a.closest("[data-message-id]")?.getAttribute("data-message-row");if(!n)return e.length===1;const[i,o]=n.split("/");t.add(i),s=Number(o)}return t.size===s}const In=32;function oR(e,t){const{text:s,prefix:a,suffix:n}=t,i=!!(a||n),o=l=>{const d=[];for(let u=e.indexOf(l);u!==-1&&d.length<Bf;u=e.indexOf(l,u+1))d.push(u);return d},r=[];for(const l of o(s))(!i||Nf(e,t,l))&&r.push({start:l,end:l+s.length});if(s.length>In&&(r.length===0||!i)){for(const l of o(s.slice(0,In))){const d=e.slice(l);d.length<s.length&&s.startsWith(d)&&a.endsWith(e.slice(Math.max(0,l-a.length),l))&&r.push({start:l,end:e.length})}for(const l of o(s.slice(-In))){const d=l+In;d<s.length&&s.endsWith(e.slice(0,d))&&n.startsWith(e.slice(d,d+n.length))&&r.push({start:0,end:d})}e.length>=In&&e.length<s.length&&s.includes(e)&&r.push({start:0,end:e.length})}return i?r[0]??null:new Set(r.map(l=>`${l.start}:${l.end}`)).size===1?r[0]:null}function rR(e,t){const{stream:s}=Mf(e);let a,n;if(iR(e))a=nR(s,t),n=(a??0)+t.text.length;else{const r=oR(s,t);a=r?.start??null,n=r?.end??0}if(a===null||n<=a)return null;const i=[];let o=0;for(const r of e){let c=null;for(const l of Ef(r,[])){const d=l.data.length;if(!c&&a<o+d&&n>o&&(c=r.ownerDocument.createRange(),c.setStart(l,Math.max(0,a-o)),c.setEnd(r,r.childNodes.length)),c&&n<=o+d)return c.setEnd(l,n-o),i.push(c),i;o+=d}c&&i.push(c)}return null}function XV(e,t){return rR([e],t)?.[0]??null}const cR=fw.gfm,lR=bw().use(ww).use(cR[0],{singleTilde:!1});function eU(e){const t=s=>{if("children"in s){if(s.type==="list")return`
|
|
35
35
|
${s.children.map(t).join(`
|
|
36
36
|
`)}
|
|
37
37
|
`;if(s.type==="listItem"){const i=s.children.map(o=>t(o)).join(`
|
|
@@ -84,4 +84,4 @@ ${e.sessionId}`,sa=e=>{const[t,s,...a]=e.split(`
|
|
|
84
84
|
${t}`,jn=(e,t)=>({...t,directory:e.directory}),gc=(e,t)=>Fa(IR,"/api/message-queue",{directory:e?`/spaces/${e}`:null,signal:t}),po=new Set,Gg=new Map,Ut=new Map,On=new Map;let uc=0;const _g=e=>Object.fromEntries(Object.entries(e).map(([t,s])=>[t,s.map(a=>({...a,text:a.text??a.content}))])),NR=(e,t)=>{const s=e??{},a=t<2?s.queuedMessages??{}:{};return{queuedMessages:t<2?{}:_g(s.queuedMessages??{}),quarantinedLegacyMessages:_g({...s.quarantinedLegacyMessages??{},...a}),followUpBehavior:PR(s.followUpBehavior,s.queueModeEnabled??null)}},Ht=(e,t)=>{const{[t]:s,...a}=e;return a},go=(e,t,s)=>{const a=(e.queuedMessages[t]??[]).filter(n=>n.id!==s);return a.length===0?{queuedMessages:Ht(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:a}}},MR=(e,t,s,a)=>{let n=e.queuedMessages,i=e.sendingIds;for(const o of new Set([...Object.keys(n),...Object.keys(i)])){const r=sa(o);r?.runtimeKey!==t||r.sessionId!==s||(Ut.get(o)??-1)>a||(Ut.set(o,a),n=Ht(n,o),i=Ht(i,o))}return{queuedMessages:n,sendingIds:i}},vl=vt()(dn(zi((e,t)=>{let s=null,a=!1;const n=(c,l,d,u="")=>{if(d!==D()||$s(c.directory)!==u||(On.get(Hg(d,u))??-1)>l)return;const m=yl(c.sessionId,c.directory,d);if(!m){if(c.items.length>0)return;e(b=>MR(b,d,c.sessionId,l));return}const f=ut(m);(Ut.get(f)??-1)>l||(Ut.set(f,l),e(b=>{const w=c.items.map(lo),y=w.length>0?{...b.queuedMessages,[f]:w}:Ht(b.queuedMessages,f),A=c.sendingId?{...b.sendingIds,[f]:[c.sendingId]}:Ht(b.sendingIds,f);return{queuedMessages:y,sendingIds:A}}))},i=async c=>{const l=$s(c.directory);try{const d=await gc(l),u=d.sessions.find(m=>m.sessionId===c.sessionId)??{sessionId:c.sessionId,directory:c.directory,items:[],sendingId:null};n(u,d.revision,c.runtimeKey,l)}catch{}},o=async(c,l,d)=>{try{const u=await Fa(ei,l,jn(c,d));n(u.session,u.revision,c.runtimeKey,$s(c.directory))}catch(u){console.warn("[queue] server update failed:",u),await i(c)}},r=(c,l,d)=>{const u=Hg(l,d);return(On.get(u)??-1)>c.revision?!1:(On.set(u,c.revision),e(m=>{const f=x=>(Ut.get(x)??-1)>c.revision,b=x=>{const M=sa(x);return M?.runtimeKey===l&&$s(M.directory)===d},w=x=>!b(x)||f(x),y={},A={};for(const[x,M]of Object.entries(m.queuedMessages))w(x)&&(y[x]=M);for(const[x,M]of Object.entries(m.sendingIds))w(x)&&(A[x]=M);for(const x of c.sessions){if($s(x.directory)!==d)continue;const M=yl(x.sessionId,x.directory,l);if(!M)continue;const Q=ut(M);f(Q)||(Ut.set(Q,c.revision),x.items.length>0&&(y[Q]=x.items.map(lo)),x.sendingId&&(A[Q]=[x.sendingId]))}return{queuedMessages:y,sendingIds:A}}),!0)};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:Wf,sendingIds:{},addToQueue:async(c,l)=>{const d=ut(c),u=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,m={id:u,content:l.content,text:l.text??l.content,createdAt:Date.now(),sendConfig:l.sendConfig};if(l.agentMention&&(m.agentMention=l.agentMention),l.attachments&&l.attachments.length>0&&(m.attachments=l.attachments),l.context&&l.context.length>0&&(m.context=l.context),l.goal&&(m.goal=l.goal),e(w=>{const y=w.queuedMessages[d]??[],A={...w.queuedMessages,[d]:[...y,m].slice(-20)},x=Object.keys(A);if(x.length>Vg){x.sort((M,Q)=>(A[M]?.[0]?.createdAt??0)-(A[Q]?.[0]?.createdAt??0));for(const M of x.slice(0,x.length-Vg))delete A[M]}return{queuedMessages:A}}),!Ps())return;if(!l.sendConfig)throw e(w=>go(w,d,u)),new Error("A queued message needs a provider and model to be delivered later.");const f=DA(c.runtimeKey,c.directory,c.sessionId),b=NA(l.content,l.attachments??[]);try{const w=await Fa(ei,`${Qs(c.sessionId)}/items`,jn(c,Js("POST",{directory:c.directory,item:Wg(l,l.sendConfig)})));e(y=>go(y,d,u)),n(w.session,w.revision,c.runtimeKey,$s(c.directory)),f&&Un.getState().appendSubmissions(f,[b])}catch(w){throw e(y=>go(y,d,u)),w}},removeFromQueue:(c,l)=>{const d=ut(c);e(u=>go(u,d,l)),Ps()&&o(c,`${Qs(c.sessionId)}/items/${encodeURIComponent(l)}`,Js("DELETE"))},reorderQueue:(c,l,d)=>{if(l===d)return;const u=ut(c),m=t().queuedMessages[u];if(!m)return;const f=m.findIndex(A=>A.id===l),b=m.findIndex(A=>A.id===d);if(f===-1||b===-1)return;const w=m.slice(),[y]=w.splice(f,1);if(w.splice(b,0,y),e(A=>({queuedMessages:{...A.queuedMessages,[u]:w}})),Ps()){const A=w.map(x=>x.id);o(c,`${Qs(c.sessionId)}/order`,Js("PUT",{itemIds:A}))}},popToInput:async(c,l)=>{const[d]=await t().takeForSend(c,l);return d??null},takeForSend:async(c,l)=>{const d=ut(c);if(Ps())try{const w=$s(c.directory);if(l){const A=await Fa(jR,`${Qs(c.sessionId)}/items/${encodeURIComponent(l)}/take`,jn(c,Js("POST")));return n(A.session,A.revision,c.runtimeKey,w),[lo(A.item)]}const y=await Fa(OR,`${Qs(c.sessionId)}/take`,jn(c,Js("POST")));return n(y.session,y.revision,c.runtimeKey,w),y.items.map(lo)}catch(w){throw await i(c),w}const u=t(),m=u.sendingIds[d]??[],f=(u.queuedMessages[d]??[]).filter(w=>(l?w.id===l:!0)&&!m.includes(w.id));if(f.length===0)return[];const b=new Set(f.map(w=>w.id));return e(w=>{const y=(w.queuedMessages[d]??[]).filter(A=>!b.has(A.id));return y.length===0?{queuedMessages:Ht(w.queuedMessages,d)}:{queuedMessages:{...w.queuedMessages,[d]:y}}}),f},clearQueue:c=>{const l=ut(c);e(d=>{const u=d.sendingIds[l]??[],m=(d.queuedMessages[l]??[]).filter(f=>u.includes(f.id));return m.length>0?{queuedMessages:{...d.queuedMessages,[l]:m}}:{queuedMessages:Ht(d.queuedMessages,l)}}),Ps()&&o(c,Qs(c.sessionId),Js("DELETE"))},forgetQueue:c=>{const l=ut(c);Ut.delete(l),e(d=>({queuedMessages:Ht(d.queuedMessages,l),sendingIds:Ht(d.sendingIds,l)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(c,l)=>{const d=ut(c);e(u=>{const m=u.sendingIds[d]??[];return m.includes(l)?u:{sendingIds:{...u.sendingIds,[d]:[...m,l]}}})},clearSending:(c,l)=>{const d=ut(c);e(u=>{const m=u.sendingIds[d];if(!m||!m.includes(l))return u;const f=m.filter(b=>b!==l);return f.length===0?{sendingIds:Ht(u.sendingIds,d)}:{sendingIds:{...u.sendingIds,[d]:f}}})},getSendableQueue:c=>{const l=ut(c),d=t(),u=d.queuedMessages[l]??[],m=d.sendingIds[l];return!m||m.length===0?u:u.filter(f=>!m.includes(f.id))},setFollowUpBehavior:c=>{e({followUpBehavior:c}),Gt({followUpBehavior:c})},getQueueForTarget:c=>t().queuedMessages[ut(c)]??[],hydrate:()=>{if(!Ps())return Promise.resolve();const c=D();if(s?.runtimeKey===c)return s.promise;const l=++uc,d=()=>l===uc&&c===D(),u=(async()=>{let b=Gg.get(c);for(b||(b={items:Object.entries(t().queuedMessages).flatMap(([y,A])=>{const x=sa(y);return!x||x.runtimeKey!==c?[]:A.map(M=>({target:x,message:M}))}),pending:null},Gg.set(c,b));b.pending||b.items.length>0;){if(!d())return;if(b.pending){await b.pending;continue}const w=b.items.shift();if(!w?.message.sendConfig)continue;const{target:y,message:A}=w,x=Fa(ei,`${Qs(y.sessionId)}/items`,jn(y,Js("POST",{directory:y.directory,item:Wg(A,w.message.sendConfig)}))).then(()=>{}).catch(Q=>{console.warn("[queue] failed to migrate a locally queued message to the server:",Q)});b.pending=x;const M=b;x.then(()=>{M.pending===x&&(M.pending=null)}),await x}if(d())do{a=!1;let w;try{w=await gc("",AbortSignal.timeout(15e3))}catch(y){if(!d())return;if(a)continue;throw y}if(!d())return;po.add(c),r(w,c,"")}while(a&&d())})(),m={runtimeKey:c,promise:u};s=m;const f=()=>{s===m&&(s=null)};return u.then(f,f),u},resync:()=>(s?.runtimeKey===D()&&(a=!0),t().hydrate()),refreshSpaceQueue:async c=>{if(!Ps())return;const l=D();let d;try{d=await gc(c,AbortSignal.timeout(15e3))}catch{return}l===D()&&(po.add(l),r(d,l,c))},applyServerSession:n,resetForRuntimeSwitch:c=>{if(uc+=1,s=null,a=!1,c){for(const l of On.keys())l.startsWith(`${c}
|
|
85
85
|
`)&&On.delete(l);for(const l of Ut.keys())sa(l)?.runtimeKey===c&&Ut.delete(l)}!c||!po.has(c)||e(l=>{const d={},u={};for(const[m,f]of Object.entries(l.queuedMessages))sa(m)?.runtimeKey===c?Ut.delete(m):d[m]=f;for(const[m,f]of Object.entries(l.sendingIds))sa(m)?.runtimeKey!==c&&(u[m]=f);return{queuedMessages:d,sendingIds:u}})}}},{name:"message-queue-store",version:3,storage:wd(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const s=sa(t)?.runtimeKey;return!s||!po.has(s)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:NR}),{name:"message-queue-store"})),ER=g({type:k("openchamber:message-queue.updated"),properties:g({revision:v(),session:Md,spaceId:p().optional()})}),dU=(e,t)=>{if(!Ps())return;const s=ER.safeParse(e);if(!s.success)return;const{session:a,revision:n,spaceId:i}=s.data.properties;vl.getState().applyServerSession(a,n,t,i??"")},Hf=[{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"}],LR=new Set(Hf.map(e=>e.id)),qR=e=>typeof e=="string"&&LR.has(e),pU=e=>Hf.find(t=>t.id===e)?.icon??"server",VR=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const s=new TextEncoder().encode(t);let a="";for(const i of s)a+=String.fromCharCode(i);return`path_${typeof btoa=="function"?btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},gU=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,a=>a.charCodeAt(0)))}catch{return""}},V=e=>t=>{const s=e.safeParse(t);return s.success?s.data:void 0},fn=v().refine(Number.isFinite),it=p().transform(e=>e.trim()),Ie=it.pipe(p().min(1)),hs=kt(p(),ee()),R=V(T()),Be=V(p().min(1)),Ba=V(it),Ys=V(Ie),Aa=e=>V(p().max(e)),Ra=e=>V(it.transform(t=>t.slice(0,e))),ne=e=>V(it.pipe(I(e))),vs=V(fn),mc=(e,t)=>V(fn.transform(s=>Math.max(e,Math.min(t,Math.round(s))))),hc=e=>V(fn.transform(t=>Math.max(e,Math.round(t)))),UR=V(fn.positive().transform(Math.floor)),WR=V(J([li(),fn])),HR=V(J([li(),it.transform(e=>e.length>0?e:null)])),GR=V(J([li(),it])),Ed=z(ee()).transform(e=>e.filter(t=>p().min(1).safeParse(t).success)),Ia=V(Ed.transform(e=>Array.from(new Set(e.map(String))))),fc=V(Ed.transform(e=>e.map(String))),_R=hs.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=z(ee()).safeParse(a);n.success&&(t[s]=n.data.filter(i=>p().safeParse(i).success).map(String))}return t}),bc=V(_R.pipe(kt(p(),z(p())).refine(e=>Object.keys(e).length>0))),KR=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[s,a]of Object.entries(e)){const n=s.trim();n&&qR(a)&&(t[n]=a)}return t},ZR=g({providerID:Ie,modelID:Ie}),wc=e=>V(z(ee()).transform(t=>{const s=[],a=new Set;for(const n of t){const i=ZR.safeParse(n);if(!i.success)continue;const o=`${i.data.providerID}/${i.data.modelID}`;if(!a.has(o)&&(a.add(o),s.push(i.data),s.length>=e))break}return s})),JR=V(hs.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){if(!s)continue;const n=Ed.safeParse(a);if(!n.success)continue;const i=Array.from(new Set(n.data.map(String)));i.length>0&&(t[s]=i.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),QR=V(hs.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=s.trim();if(!n)continue;if(a===null){t[n]=null;continue}const i=Ie.safeParse(a);i.success&&(t[n]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),$R=V(hs.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),i=Ie.safeParse(a);!n||!i.success||(t[n]=i.data)}return t})),uo={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."}},YR=g({title:p().catch(""),message:p().catch("")}),XR=V(hs.transform(e=>{const t=o=>{const r=YR.safeParse(e[o]);return r.success?r.data:void 0},s=t("completion"),a=t("error"),n=t("question"),i=t("subtask");if(!(!s&&!a&&!n&&!i))return{completion:s??uo.completion,error:a??uo.error,question:n??uo.question,subtask:i??uo.subtask}}).pipe(Wu(e=>e!==void 0))),Kg=hs.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,s])=>{const a=p().safeParse(s);return a.success?[[t,a.data]]:[]}))),eI=g({id:ee().transform(e=>String(e??"")),label:ee().transform(e=>String(e??"")),models:z(ee()).transform(e=>e.filter(t=>p().safeParse(t).success).map(String)).catch([]),order:v().catch(0)}),tI=V(hs.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=hs.safeParse(a);if(!n.success)continue;const i={},o=z(ee()).safeParse(n.data.customGroups);o.success&&(i.customGroups=o.data.flatMap(l=>{const d=eI.safeParse(l);return d.success?[d.data]:[]}));const r=Kg.safeParse(n.data.modelAssignments);r.success&&(i.modelAssignments=r.data);const c=Kg.safeParse(n.data.renamedGroups);c.success&&(i.renamedGroups=c.data),Object.keys(i).length>0&&(t[s]=i)}return t}).refine(e=>Object.keys(e).length>0)),sI=g({id:Ie,name:Ie,hostname:Ie.transform(e=>e.toLowerCase())}),aI=V(z(ee()).transform(e=>{const t=[],s=new Set,a=new Set;for(const n of e){const i=sI.safeParse(n);i.success&&(s.has(i.data.id)||a.has(i.data.hostname)||(s.add(i.data.id),a.add(i.data.hostname),t.push(i.data)))}return t})),nI=V(hs.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),i=Ie.safeParse(a);!n||!i.success||(t[n]=i.data)}return t}).refine(e=>Object.keys(e).length>0)),iI=g({id:Ie,label:Ie,source:Ie,subpath:it.optional().catch(void 0),gitIdentityId:it.optional().catch(void 0)}),oI=V(z(ee()).transform(e=>{const t=[],s=new Set;for(const a of e){const n=iI.safeParse(a);if(!n.success||s.has(n.data.id))continue;s.add(n.data.id);const i={id:n.data.id,label:n.data.label,source:n.data.source};n.data.subpath&&(i.subpath=n.data.subpath),n.data.gitIdentityId&&(i.gitIdentityId=n.data.gitIdentityId),t.push(i)}return t})),rI=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,kc=fn.nonnegative(),cI=g({path:Ie,label:Ie.optional().catch(void 0),labelSource:I(["auto","manual"]).optional().catch(void 0),icon:Ie.optional().catch(void 0),iconImage:J([li(),g({mime:Ie,updatedAt:kc.transform(Math.round).pipe(v().positive()),source:I(["custom","auto"])})]).optional().catch(void 0),color:Ie.optional().catch(void 0),iconBackground:J([li(),it.pipe(p().regex(rI)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:kc.optional().catch(void 0),lastOpenedAt:kc.optional().catch(void 0),sidebarCollapsed:T().optional().catch(void 0),defaultModel:Ie.optional().catch(void 0),defaultAgent:Ie.optional().catch(void 0),defaultVariant:Ie.optional().catch(void 0)}),lI=V(z(ee()).transform(e=>{const t=[],s=new Set,a=new Set;for(const n of e){const i=cI.safeParse(n);if(!i.success)continue;const o=ze(i.data.path);if(!o)continue;const r=VR(o);if(!r||s.has(r)||a.has(o))continue;s.add(r),a.add(o);const c={id:r,path:o};i.data.label&&(c.label=i.data.label),i.data.label&&i.data.labelSource&&(c.labelSource=i.data.labelSource),i.data.icon&&(c.icon=i.data.icon),i.data.iconImage!==void 0&&(c.iconImage=i.data.iconImage),i.data.color&&(c.color=i.data.color),i.data.iconBackground!==void 0&&(c.iconBackground=i.data.iconBackground),i.data.addedAt!==void 0&&(c.addedAt=i.data.addedAt),i.data.lastOpenedAt!==void 0&&(c.lastOpenedAt=i.data.lastOpenedAt),i.data.defaultModel&&(c.defaultModel=i.data.defaultModel),i.data.defaultAgent&&(c.defaultAgent=i.data.defaultAgent),i.data.defaultVariant&&(c.defaultVariant=i.data.defaultVariant),i.data.sidebarCollapsed!==void 0&&(c.sidebarCollapsed=i.data.sidebarCollapsed),t.push(c)}return t}).refine(e=>e.length>0)),dI=I(["steer","queue"]),pI=(e,t)=>{const s=dI.safeParse(e);if(s.success)return s.data;if(e==="immediate")return"steer";const a=T().safeParse(t.queueModeEnabled);if(a.success)return a.data?"queue":"steer"},gI=it.pipe(I(["collapsed","summary"])),uI=(e,t)=>{if(t.chatRenderMode==="sorted")return"collapsed";const s=gI.safeParse(e);return s.success?s.data:void 0},mI=V(it.pipe(I(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),hI=V(it.pipe(I(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),fI=V(it.transform(e=>e.replace(/\s+/g," ").slice(0,64))),bI=e=>V(z(ee()).transform(t=>{const s=[];for(const a of t){const n=it.transform(i=>i.toLowerCase()).safeParse(a);n.success&&e(n.data)&&!s.includes(n.data)&&s.push(n.data)}return s})),Ld=e=>V(Wu(e)),yi=(e,t)=>(s,a)=>{const n=e(s,a);return n===void 0?void 0:t(n)},h=e=>e,S=(e,t,s={})=>({read:()=>P.getState()[e],write:t,autoSave:s.autoSave??!0}),Pt=e=>t=>{P.setState({[e]:t})},Zg=()=>globalThis.window?.__zustand_config_store__??null,Lt=e=>({read:()=>Zg()?.getState()[e],write:t=>{Zg()?.setState({[e]:t})},autoSave:!1}),Tt=e=>({read:()=>Ot.getState()[e],write:t=>{Ot.setState({[e]:t})},autoSave:!1}),wI=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],kI=Ld(Rd),yI=Ld(Jx),vI=Ld(Qx),CI=V(p().refine(Af)),SI=V(v().refine(Ad)),xI=yi(Ba,e=>or(e,void 0)),PI=yi(V(z(ee())),KT),TI=yi(V(z(ee())),e=>Yh(e)),zI=ne(["ask","attach","inline","inline-double-paste"]),AI=ne(["default","vim"]),RI=(e,t)=>{let s=e;const a=(n,i)=>{if(s.some(c=>c.type==="command"&&c.name===n))return;const o=s.findIndex(c=>c.type==="command"&&c.name===i),r=o>=0?o+1:s.length;s=[...s.slice(0,r),{type:"command",name:n},...s.slice(r)]};return t.draftStartersCraftGoalAdded!==!0&&a("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==!0&&a("schedule-task","craft-goal"),s},Oi={themeId:h({scope:"profile",perSurface:!0,parse:Be}),useSystemTheme:h({scope:"profile",perSurface:!0,parse:R}),themeVariant:h({scope:"profile",derived:!0,parse:ne(["light","dark"])}),lightThemeId:h({scope:"profile",perSurface:!0,parse:Be}),darkThemeId:h({scope:"profile",perSurface:!0,parse:Be}),locale:h({scope:"profile",parse:ne($T),ui:{read:()=>_o.getState().locale,write:e=>_o.getState().setLocale(e),autoSave:!1}}),lastDirectory:h({scope:"instance",adopt:"bootstrap-only",parse:Be}),homeDirectory:h({scope:"instance",parse:Be}),opencodeBinary:h({scope:"instance",parse:Ba}),serverUpdateChannel:h({scope:"instance",surfaces:["web"],parse:ne(["stable","canary"])}),projects:h({scope:"instance",parse:lI}),activeProjectId:h({scope:"instance",adopt:"bootstrap-only",parse:Be}),securityScopedBookmarks:h({scope:"instance",surfaces:["desktop"],parse:fc}),pinnedDirectories:h({scope:"instance",parse:Ia}),desktopLanAccessEnabled:h({scope:"instance",surfaces:["desktop"],parse:R}),desktopKeepAwakeEnabled:h({scope:"instance",surfaces:["desktop"],parse:R}),desktopMinimizeToTrayEnabled:h({scope:"instance",surfaces:["desktop"],parse:R}),desktopUpdateChannel:h({scope:"instance",surfaces:["desktop"],parse:ne(["stable","canary"])}),desktopMacMenuBarEnabled:h({scope:"instance",surfaces:["desktop"],parse:R}),desktopLinuxNativeFrame:h({scope:"instance",surfaces:["desktop"],parse:R}),desktopUiPassword:h({scope:"instance",secret:!0,surfaces:["desktop"],parse:Ba}),hasDesktopUiPassword:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:R}),desktopLanAccessActive:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:R}),desktopLanAccessBlockedReason:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:Ba}),githubClientId:h({scope:"instance",parse:Ys}),githubScopes:h({scope:"instance",parse:Ys}),gitlabClientId:h({scope:"instance",parse:Ys}),skillCatalogs:h({scope:"instance",parse:oI}),defaultGitIdentityId:h({scope:"instance",parse:Ba}),permissionAutoAccept:h({scope:"instance",parse:V(g({sessions:kt(p().min(1),J([T(),I(["ask","safety","auto"])])).catch({}),revision:v().int().nonnegative().catch(0)}))}),permissionDefaultMode:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:V(I(["ask","safety","auto"])),ui:S("permissionDefaultMode",e=>P.getState().setPermissionDefaultMode(e))}),messageSearchEnabled:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:R,ui:S("messageSearchEnabled",e=>P.getState().setMessageSearchEnabled(e))}),messageSearchReasoningEnabled:h({scope:"instance",surfaces:["web","desktop","mobile"],parse:R,ui:S("messageSearchReasoningEnabled",e=>P.getState().setMessageSearchReasoningEnabled(e))}),agentControlToolEnabled:h({scope:"instance",parse:R,ui:S("agentControlToolEnabled",e=>P.getState().setAgentControlToolEnabled(e))}),agentScheduleToolEnabled:h({scope:"instance",parse:R,ui:S("agentScheduleToolEnabled",e=>P.getState().setAgentScheduleToolEnabled(e))}),agentWebToolEnabled:h({scope:"instance",parse:R,ui:S("agentWebToolEnabled",e=>P.getState().setAgentWebToolEnabled(e))}),browserProvider:h({scope:"instance",parse:Be,ui:S("browserProvider",e=>P.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:h({scope:"instance",parse:R,ui:S("agentNotifyToolEnabled",e=>P.getState().setAgentNotifyToolEnabled(e))}),agentRenderToolEnabled:h({scope:"instance",parse:R,ui:S("agentRenderToolEnabled",e=>P.getState().setAgentRenderToolEnabled(e))}),agentUsageToolEnabled:h({scope:"instance",parse:R,ui:S("agentUsageToolEnabled",e=>P.getState().setAgentUsageToolEnabled(e))}),agentImageToolEnabled:h({scope:"instance",parse:R,ui:S("agentImageToolEnabled",e=>P.getState().setAgentImageToolEnabled(e))}),agentImageModel:h({scope:"instance",parse:Be,ui:S("agentImageModel",e=>P.getState().setAgentImageModel(e))}),agentSecretToolEnabled:h({scope:"instance",parse:R,ui:S("agentSecretToolEnabled",e=>P.getState().setAgentSecretToolEnabled(e))}),agentMemoryToolEnabled:h({scope:"instance",parse:R,ui:S("agentMemoryToolEnabled",e=>P.getState().setAgentMemoryToolEnabled(e))}),agentKnowledgeToolEnabled:h({scope:"instance",parse:R,ui:S("agentKnowledgeToolEnabled",e=>P.getState().setAgentKnowledgeToolEnabled(e))}),agentWorkflowToolEnabled:h({scope:"instance",parse:R,ui:S("agentWorkflowToolEnabled",e=>P.getState().setAgentWorkflowToolEnabled(e))}),isolatedSpacesEnabled:h({scope:"instance",parse:R,ui:S("isolatedSpacesEnabled",e=>P.getState().setIsolatedSpacesEnabled(e))}),isolatedSpacesIdleStop:h({scope:"instance",parse:V(g({enabled:T(),hours:v().int().min(1).max(168)}).strict())}),isolatedSpacesSshHost:h({scope:"instance",parse:Ra(320)}),agentMemoryFeatureAvailable:h({scope:"instance",computed:!0,parse:R,ui:S("agentMemoryFeatureAvailable",e=>P.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),agentWorkflowFeatureAvailable:h({scope:"instance",computed:!0,parse:R,ui:S("agentWorkflowFeatureAvailable",e=>P.getState().setAgentWorkflowFeatureAvailable(e),{autoSave:!1})}),overviewFeatureAvailable:h({scope:"instance",computed:!0,parse:R,ui:S("overviewFeatureAvailable",e=>P.getState().setOverviewFeatureAvailable(e),{autoSave:!1})}),routingFeatureAvailable:h({scope:"instance",computed:!0,parse:R,ui:S("routingFeatureAvailable",e=>P.getState().setRoutingFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:h({scope:"instance",parse:Ra(128)}),autoDeleteEnabled:h({scope:"instance",parse:R,ui:S("autoDeleteEnabled",e=>P.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:h({scope:"instance",parse:mc(1,365),ui:S("autoDeleteAfterDays",e=>P.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:h({scope:"instance",parse:R,ui:S("sessionRetentionOnlyArchived",e=>P.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionIncludeInWork:h({scope:"instance",parse:R,ui:S("sessionRetentionIncludeInWork",e=>P.getState().setSessionRetentionIncludeInWork(e))}),sessionRetentionAction:h({scope:"instance",parse:ne(["archive","delete"]),ui:S("sessionRetentionAction",e=>P.getState().setSessionRetentionAction(e))}),mergedWorktreeCleanupEnabled:h({scope:"instance",parse:R,ui:S("mergedWorktreeCleanupEnabled",e=>P.getState().setMergedWorktreeCleanupEnabled(e))}),worktreeArchiveOnDoneEnabled:h({scope:"instance",parse:R,ui:S("worktreeArchiveOnDoneEnabled",e=>P.getState().setWorktreeArchiveOnDoneEnabled(e))}),terminalShell:h({scope:"instance",parse:kI,ui:S("terminalShell",e=>P.getState().setTerminalShell(e))}),terminalLoginShells:h({scope:"instance",parse:bI(Rd),ui:S("terminalLoginShells",e=>P.getState().setTerminalLoginShells(e))}),openInAppId:h({scope:"instance",parse:Ys}),dictationEnabled:h({scope:"profile",parse:R,ui:Lt("dictationEnabled")}),dictationAutoSend:h({scope:"profile",parse:R,ui:Lt("dictationAutoSend")}),sttProvider:h({scope:"instance",parse:mI,ui:Lt("sttProvider")}),sttServerUrl:h({scope:"instance",parse:Ra(2048),ui:Lt("sttServerUrl")}),sttEndpointPath:h({scope:"instance",parse:V(p().trim().max(1024)),ui:Lt("sttEndpointPath")}),sttModel:h({scope:"instance",parse:Ra(256),ui:Lt("sttModel")}),sttLocalModel:h({scope:"instance",parse:Ra(256),ui:Lt("sttLocalModel")}),sttLanguage:h({scope:"profile",parse:Ra(64),ui:Lt("sttLanguage")}),sttCorrectTranscript:h({scope:"profile",parse:R,ui:Lt("sttCorrectTranscript")}),tunnelProvider:h({scope:"instance",parse:yi(Ys,e=>e.toLowerCase())}),tunnelMode:h({scope:"instance",parse:V(p().transform(e=>e.trim().toLowerCase()).pipe(I(["quick","managed-remote","managed-local","serve","funnel"])))}),tunnelHttpsPort:h({scope:"instance",parse:mc(1,65535)}),tunnelBootstrapTtlMs:h({scope:"instance",parse:WR}),tunnelSessionTtlMs:h({scope:"instance",parse:vs}),managedLocalTunnelConfigPath:h({scope:"instance",parse:HR}),managedRemoteTunnelHostname:h({scope:"instance",parse:Ba}),managedRemoteTunnelToken:h({scope:"instance",secret:!0,parse:GR}),hasManagedRemoteTunnelToken:h({scope:"instance",computed:!0,parse:R}),managedRemoteTunnelPresets:h({scope:"instance",parse:aI}),managedRemoteTunnelSelectedPresetId:h({scope:"instance",parse:Ys}),managedRemoteTunnelPresetTokens:h({scope:"instance",secret:!0,parse:nI}),sidebarProjectDisplayMode:h({scope:"profile",parse:ne(["all","single"]),ui:Tt("projectDisplayMode")}),sidebarViewMode:h({scope:"profile",perSurface:!0,parse:ne(["projects","timeline"]),ui:Tt("sidebarViewMode")}),sidebarListSessionGrouping:h({scope:"profile",perSurface:!0,parse:ne(["project","time"]),ui:Tt("listSessionGrouping")}),sidebarGrouping:h({scope:"profile",perSurface:!0,parse:ne(["project","time"]),ui:Tt("sidebarGrouping")}),sidebarKeepWorkInPlace:h({scope:"profile",perSurface:!0,parse:R,ui:Tt("keepWorkInPlace")}),sidebarProjectSortOrder:h({scope:"profile",parse:ne(["manual","a-z","z-a","date-added","recent"]),ui:Tt("projectSortOrder")}),sidebarShowChatsSection:h({scope:"profile",perSurface:!0,parse:R,ui:Tt("showChatsSection")}),sidebarShowWorkSection:h({scope:"profile",perSurface:!0,parse:R,ui:Tt("showWorkSection")}),sidebarShowPinnedSection:h({scope:"profile",perSurface:!0,parse:R,ui:Tt("showPinnedSection")}),sidebarDetailedZoneRows:h({scope:"profile",perSurface:!0,parse:R,ui:Tt("detailedZoneRows")}),sidebarWorktreeNameByBranch:h({scope:"profile",parse:R,ui:Tt("worktreeNameByBranch")}),sidebarSections:h({scope:"profile",parse:V(ll),ui:{read:()=>Ot.getState().sections,write:e=>Ot.getState().setSections(e),autoSave:!1}}),sidebarPinLists:h({scope:"profile",parse:V(bf),ui:{read:()=>Ot.getState().pinLists,write:e=>Ot.getState().setPinLists(e),autoSave:!1}}),sidebarHiddenSections:h({scope:"profile",perSurface:!0,parse:V(wf),ui:{read:()=>Ot.getState().hiddenSections,write:e=>Ot.getState().setHiddenSections(e),autoSave:!1}}),workStatusSectionOrder:h({scope:"profile",parse:yi(fc,Ka),ui:S("workStatusSectionOrder",(e,t)=>{const s=t.workStatusSectionOrderExplicit===!0;P.setState({workStatusSectionOrder:Ka(e,s),workStatusSectionOrderExplicit:s})})}),workStatusSectionOrderExplicit:h({scope:"profile",parse:R,ui:S("workStatusSectionOrderExplicit",e=>P.setState({workStatusSectionOrderExplicit:e}))}),workStatusPanelEnabled:h({scope:"profile",parse:R,ui:S("workStatusPanelEnabled",e=>P.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:h({scope:"profile",parse:TI,ui:{read:()=>P.getState().workStatusHiddenSections,write:(e,t)=>{const s=t.workStatusHiddenSectionsExplicit===!0;P.setState({workStatusHiddenSections:Yh(e,s),workStatusHiddenSectionsExplicit:s})},autoSave:!0}}),workStatusHiddenSectionsExplicit:h({scope:"profile",parse:R,ui:S("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:h({scope:"profile",parse:R,ui:S("showReasoningTraces",e=>P.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:h({scope:"profile",perSurface:!0,parse:R,ui:S("streamingAutoFollowEnabled",e=>P.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:h({scope:"profile",parse:R,ui:S("collapsibleThinkingBlocks",e=>P.getState().setCollapsibleThinkingBlocks(e))}),expandReasoningWhileStreaming:h({scope:"profile",parse:R,ui:S("expandReasoningWhileStreaming",e=>P.getState().setExpandReasoningWhileStreaming(e))}),showTextJustificationActivity:h({scope:"profile",parse:R}),chatRenderMode:h({scope:"profile",parse:ne(["sorted","live"])}),activityRenderMode:h({scope:"profile",parse:uI,ui:S("activityRenderMode",e=>P.getState().setActivityRenderMode(e))}),mermaidRenderingMode:h({scope:"profile",parse:ne(["svg","ascii"]),ui:S("mermaidRenderingMode",e=>P.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:h({scope:"profile",parse:ne(["markdown","plain"]),ui:S("userMessageRenderingMode",e=>P.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:h({scope:"profile",parse:R,ui:S("collapsibleUserMessages",e=>P.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:h({scope:"profile",perSurface:!0,parse:R,ui:S("stickyUserHeader",e=>P.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:h({scope:"profile",perSurface:!0,parse:R,ui:S("promptNavigatorEnabled",e=>P.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:h({scope:"profile",perSurface:!0,parse:R,ui:S("wideChatLayoutEnabled",e=>P.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:h({scope:"profile",parse:R,ui:S("showSplitAssistantMessageActions",e=>P.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:h({scope:"profile",parse:R,ui:S("showToolFileIcons",e=>P.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:h({scope:"profile",parse:R,ui:S("codeBlockLineWrap",e=>P.getState().setCodeBlockLineWrap(e))}),tableCellWrap:h({scope:"profile",parse:R,ui:S("tableCellWrap",e=>P.getState().setTableCellWrap(e))}),copyMessagesAsPlainText:h({scope:"profile",parse:R,ui:S("copyMessagesAsPlainText",e=>P.getState().setCopyMessagesAsPlainText(e))}),selectionApprovalText:h({scope:"profile",parse:Aa(1e3),ui:S("selectionApprovalText",e=>P.getState().setSelectionApprovalText(e))}),showTurnChangedFiles:h({scope:"profile",parse:R,ui:S("showTurnChangedFiles",e=>P.getState().setShowTurnChangedFiles(e))}),toolJsonViewMode:h({scope:"profile",parse:ne(["summary","formatted","raw"]),ui:S("toolJsonViewMode",e=>P.getState().setToolJsonViewMode(e))}),timeFormatPreference:h({scope:"profile",parse:ne(["auto","12h","24h"]),ui:S("timeFormatPreference",e=>P.getState().setTimeFormatPreference(e))}),weekStartPreference:h({scope:"profile",parse:ne(["auto","sunday","monday"]),ui:S("weekStartPreference",e=>P.getState().setWeekStartPreference(e))}),messageStreamTransport:h({scope:"profile",parse:ne(["auto","ws","sse"]),ui:Lt("settingsMessageStreamTransport")}),diffLayoutPreference:h({scope:"profile",parse:ne(["dynamic","inline","side-by-side"]),ui:S("diffLayoutPreference",e=>P.getState().setDiffLayoutPreference(e))}),diffWrapLines:h({scope:"profile",parse:R,ui:S("diffWrapLines",e=>P.getState().setDiffWrapLines(e))}),diffHideWhitespace:h({scope:"profile",parse:R,ui:S("diffHideWhitespace",e=>P.getState().setDiffHideWhitespace(e))}),gitChangesViewMode:h({scope:"profile",parse:ne(["flat","tree"]),ui:S("gitChangesViewMode",e=>P.getState().setGitChangesViewMode(e))}),gitmojiEnabled:h({scope:"profile",parse:R}),defaultFileViewerPreview:h({scope:"profile",parse:R}),directoryShowHidden:h({scope:"profile",parse:R,ui:{read:HT,write:e=>GT(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:h({scope:"profile",parse:R,ui:{read:JT,write:e=>QT(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:h({scope:"profile",parse:AI,ui:S("fileEditorKeymap",e=>P.getState().setFileEditorKeymap(e))}),fileEditorVimMappings:h({scope:"profile",parse:Aa(1e4),ui:S("fileEditorVimMappings",e=>P.getState().setFileEditorVimMappings(e))}),autoSaveEnabled:h({scope:"profile",parse:R,ui:S("autoSaveEnabled",e=>P.getState().setAutoSaveEnabled(e))}),fileEditorWrapLines:h({scope:"profile",parse:R,ui:S("fileEditorWrapLines",e=>P.getState().setFileEditorWrapLines(e))}),confirmFileTreeMove:h({scope:"profile",parse:R,ui:S("confirmFileTreeMove",e=>P.getState().setConfirmFileTreeMove(e))}),fileTreeSide:h({scope:"profile",surfaces:["web","desktop"],parse:ne(["left","right"]),ui:S("fileTreeSide",e=>P.getState().setFileTreeSide(e))}),layoutAnimations:h({scope:"profile",surfaces:["web","desktop"],parse:R,ui:S("layoutAnimations",e=>P.getState().setLayoutAnimations(e))}),openLinksInBrowserPanel:h({scope:"profile",surfaces:["desktop"],parse:R,ui:S("openLinksInBrowserPanel",e=>P.getState().setOpenLinksInBrowserPanel(e))}),liveBrowserTabLimit:h({scope:"profile",surfaces:["desktop"],parse:mc(Hh,Gh),ui:S("liveBrowserTabLimit",e=>P.getState().setLiveBrowserTabLimit(e))}),openTrackerLinksOnBoard:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:R,ui:S("openTrackerLinksOnBoard",e=>P.getState().setOpenTrackerLinksOnBoard(e))}),terminalCloseOnExit:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:R,ui:S("terminalCloseOnExit",e=>P.getState().setTerminalCloseOnExit(e))}),autoCreateWorktree:h({scope:"profile",parse:R}),sessionTabsEnabled:h({scope:"profile",surfaces:["web","desktop","vscode"],parse:R,ui:S("sessionTabsEnabled",e=>P.getState().setSessionTabsEnabled(e))}),sessionTabsPerWorkspace:h({scope:"profile",surfaces:["web","desktop"],parse:R,ui:S("sessionTabsPerWorkspace",e=>P.getState().setSessionTabsPerWorkspace(e))}),allowPromptingSubagentSessions:h({scope:"profile",parse:R,ui:S("allowPromptingSubagentSessions",e=>P.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:h({scope:"profile",parse:R,ui:S("inputSpellcheckEnabled",e=>P.getState().setInputSpellcheckEnabled(e))}),enterToSend:h({scope:"profile",parse:R,ui:S("enterToSend",e=>P.getState().setEnterToSend(e))}),enterToSendConfigured:h({scope:"profile",parse:R,ui:S("enterToSendConfigured",e=>P.getState().setEnterToSendConfigured(e))}),mobileReturnKeySends:h({scope:"profile",parse:R,ui:S("mobileReturnKeySends",e=>P.getState().setMobileReturnKeySends(e))}),largeTextPasteBehavior:h({scope:"profile",parse:zI,ui:S("largeTextPasteBehavior",e=>P.getState().setLargeTextPasteBehavior(e))}),savePastedImagesAsFiles:h({scope:"profile",parse:R,ui:S("savePastedImagesAsFiles",e=>P.getState().setSavePastedImagesAsFiles(e))}),followUpBehavior:h({scope:"profile",parse:pI,ui:{read:()=>vl.getState().followUpBehavior,write:e=>vl.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:h({scope:"profile",parse:R}),inputHistoryScope:h({scope:"profile",parse:CI,ui:{read:()=>Un.getState().scope,write:e=>Un.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:h({scope:"profile",parse:SI,ui:{read:()=>Un.getState().entryLimit,write:e=>Un.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:h({scope:"profile",parse:PI,ui:{read:()=>P.getState().globalDraftStarters??void 0,write:(e,t)=>P.getState().setGlobalDraftStarters(RI(e,t)),autoSave:!1}}),draftStartersVisible:h({scope:"profile",parse:R,ui:S("draftStartersVisible",e=>P.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:h({scope:"profile",parse:R}),draftStartersScheduleTaskAdded:h({scope:"profile",parse:R}),fontSize:h({scope:"profile",perSurface:!0,parse:vs,ui:S("fontSize",e=>P.getState().setFontSize(e))}),chatFontSize:h({scope:"profile",perSurface:!0,parse:vs,ui:S("chatFontSize",e=>P.getState().setChatFontSize(e))}),terminalFontSize:h({scope:"profile",perSurface:!0,parse:vs,ui:S("terminalFontSize",e=>P.getState().setTerminalFontSize(e))}),editorFontSize:h({scope:"profile",perSurface:!0,parse:vs,ui:S("editorFontSize",e=>P.getState().setEditorFontSize(e))}),uiFont:h({scope:"profile",parse:yI,ui:S("uiFont",e=>P.getState().setUiFont(e))}),monoFont:h({scope:"profile",parse:vI,ui:S("monoFont",e=>P.getState().setMonoFont(e))}),customUiFont:h({scope:"profile",parse:Aa(100),ui:S("customUiFont",e=>P.getState().setCustomUiFont(e))}),customMonoFont:h({scope:"profile",parse:Aa(100),ui:S("customMonoFont",e=>P.getState().setCustomMonoFont(e))}),uiFontWeight:h({scope:"profile",parse:ne(Vx),ui:S("uiFontWeight",e=>P.getState().setUiFontWeight(e))}),padding:h({scope:"profile",perSurface:!0,parse:vs,ui:S("padding",e=>P.getState().setPadding(e))}),cornerRadius:h({scope:"profile",perSurface:!0,parse:vs,ui:S("cornerRadius",e=>P.getState().setCornerRadius(e))}),shortcutOverrides:h({scope:"profile",parse:$R,ui:S("shortcutOverrides",Pt("shortcutOverrides"))}),defaultModel:h({scope:"profile",parse:Be}),defaultVariant:h({scope:"profile",parse:Be}),defaultAgent:h({scope:"profile",parse:Be}),smallModelUseDefault:h({scope:"profile",parse:R}),smallModelOverride:h({scope:"profile",parse:Be}),smallModelVariant:h({scope:"profile",parse:Be}),walkthroughModelOverride:h({scope:"profile",parse:Be}),walkthroughModelVariant:h({scope:"profile",parse:Be}),fallbackModel:h({scope:"profile",parse:Be}),fallbackVariant:h({scope:"profile",parse:Be}),accountSwitchProviders:h({scope:"profile",parse:Ia}),zenModel:h({scope:"profile",parse:Ys}),favoriteModels:h({scope:"profile",parse:wc(64),ui:S("favoriteModels",Pt("favoriteModels"),{autoSave:!1})}),hiddenModels:h({scope:"profile",parse:wc(1024),ui:S("hiddenModels",Pt("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:h({scope:"profile",parse:Ia,ui:S("collapsedModelProviders",Pt("collapsedModelProviders"),{autoSave:!1})}),customProviderIcons:h({scope:"profile",parse:KR,ui:S("customProviderIcons",Pt("customProviderIcons"),{autoSave:!1})}),recentModels:h({scope:"profile",parse:wc(16),ui:S("recentModels",Pt("recentModels"),{autoSave:!1})}),lastSelectedModel:h({scope:"profile",parse:Be,ui:S("lastSelectedModel",Pt("lastSelectedModel"))}),recentAgents:h({scope:"profile",parse:Ia,ui:S("recentAgents",Pt("recentAgents"),{autoSave:!1})}),favoriteAgents:h({scope:"profile",parse:Ia,ui:S("favoriteAgents",Pt("favoriteAgents"),{autoSave:!1})}),recentEfforts:h({scope:"profile",parse:JR,ui:S("recentEfforts",Pt("recentEfforts"),{autoSave:!1})}),lastUsedEfforts:h({scope:"profile",parse:QR,ui:S("lastUsedEfforts",Pt("lastUsedEfforts"),{autoSave:!1})}),providerOrder:h({scope:"profile",parse:Ia,ui:S("providerOrder",e=>P.getState().setProviderOrder(e))}),sessionRecapEnabled:h({scope:"profile",parse:R,ui:S("sessionRecapEnabled",e=>P.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:h({scope:"profile",parse:R,ui:S("sessionSuggestionEnabled",e=>P.getState().setSessionSuggestionEnabled(e))}),sessionWorkEnabled:h({scope:"profile",parse:R,ui:S("sessionWorkEnabled",e=>P.getState().setSessionWorkEnabled(e))}),sessionReviewOfferEnabled:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:R,ui:S("sessionReviewOfferEnabled",e=>P.getState().setSessionReviewOfferEnabled(e))}),sessionGoalEnabled:h({scope:"profile",parse:R,ui:S("sessionGoalEnabled",e=>P.getState().setSessionGoalEnabled(e))}),sessionGoalChecker:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:ne(["classifier","small-model"]),ui:S("sessionGoalChecker",e=>P.getState().setSessionGoalChecker(e))}),sessionGoalMaxAutoTurns:h({scope:"profile",surfaces:["web","desktop","mobile"],parse:V(v().refine(Dh)),ui:S("sessionGoalMaxAutoTurns",e=>P.getState().setSessionGoalMaxAutoTurns(e))}),sessionGoalDefaultBudgetEnabled:h({scope:"profile",parse:R,ui:S("sessionGoalDefaultBudgetEnabled",e=>P.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:h({scope:"profile",parse:UR,ui:S("sessionGoalDefaultBudget",e=>P.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:h({scope:"profile",parse:R,ui:S("summarizeLastMessage",e=>P.getState().setSummarizeLastMessage(e))}),summaryThreshold:h({scope:"profile",parse:hc(0),ui:S("summaryThreshold",e=>P.getState().setSummaryThreshold(e))}),summaryLength:h({scope:"profile",parse:hc(10),ui:S("summaryLength",e=>P.getState().setSummaryLength(e))}),maxLastMessageLength:h({scope:"profile",parse:hc(10),ui:S("maxLastMessageLength",e=>P.getState().setMaxLastMessageLength(e))}),showDeletionDialog:h({scope:"profile",parse:R,ui:S("showDeletionDialog",e=>P.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:h({scope:"profile",parse:R,ui:S("nativeNotificationsEnabled",e=>P.getState().setNativeNotificationsEnabled(e))}),notificationMode:h({scope:"profile",parse:ne(["always","hidden-only"]),ui:S("notificationMode",e=>P.getState().setNotificationMode(e))}),notifyOnSubtasks:h({scope:"profile",parse:R,ui:S("notifyOnSubtasks",e=>P.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:h({scope:"profile",parse:R,ui:S("notifyOnCompletion",e=>P.getState().setNotifyOnCompletion(e))}),notifyOnPullRequests:h({scope:"profile",parse:R,ui:S("notifyOnPullRequests",e=>P.getState().setNotifyOnPullRequests(e))}),notifyOnError:h({scope:"profile",parse:R,ui:S("notifyOnError",e=>P.getState().setNotifyOnError(e))}),notifyOnQuestion:h({scope:"profile",parse:R,ui:S("notifyOnQuestion",e=>P.getState().setNotifyOnQuestion(e))}),notificationTemplates:h({scope:"profile",parse:XR,ui:S("notificationTemplates",e=>P.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:h({scope:"profile",parse:R,ui:S("showOpenCodeUpdateNotifications",e=>P.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:h({scope:"profile",parse:R,ui:S("reportUsage",e=>P.getState().setReportUsage(e))}),usageDisplayMode:h({scope:"profile",parse:ne(["usage","remaining"])}),usageDropdownProviders:h({scope:"profile",parse:fc}),usageSelectedModels:h({scope:"profile",parse:bc}),usageCollapsedFamilies:h({scope:"profile",parse:bc}),usageExpandedFamilies:h({scope:"profile",parse:bc}),usageModelGroups:h({scope:"profile",parse:tI}),globalBehaviorPrompt:h({scope:"profile",parse:Aa(1024*1024)}),responseStyleEnabled:h({scope:"profile",parse:R}),responseStylePreset:h({scope:"profile",parse:ne(wI)}),responseStyleCustomInstructions:h({scope:"profile",parse:Aa(5e4)}),pwaAppName:h({scope:"instance",surfaces:["web"],parse:fI}),pwaOrientation:h({scope:"instance",surfaces:["web"],parse:ne(["system","portrait","landscape"])}),mobileKeyboardMode:h({scope:"device",surfaces:["mobile"],parse:xI,ui:S("mobileKeyboardMode",e=>P.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:h({scope:"device",surfaces:["desktop"],parse:hI,ui:S("desktopWindowControlsPosition",e=>P.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:h({scope:"device",surfaces:["desktop"],parse:ne(["classic","traffic-lights"]),ui:S("desktopWindowControlsStyle",e=>P.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:h({scope:"device",surfaces:["mobile","web"],parse:vs,ui:S("inputBarOffset",e=>P.getState().setInputBarOffset(e))})},II=e=>Object.prototype.hasOwnProperty.call(Oi,e),Di=Object.keys(Oi).filter(II),Gf=e=>Oi[e].scope==="device",Fi=e=>Oi[e],jI=e=>!Oi[e].computed&&!Gf(e),OI=kt(p(),ee()),DI=e=>{const t=OI.safeParse(e);if(!t.success)return null;const s=t.data,a={};for(const n of Di){const o=Fi(n).parse(s[n],s);o!==void 0&&Object.assign(a,{[n]:o})}return a},FI=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),BI=e=>{for(const t of Di){const s=Fi(t);if(!s.ui)continue;const a=e[t];a!==void 0&&(FI(s.ui.read(),a)||s.ui.write(a,e))}},NI=Di.filter(e=>Fi(e).ui?.autoSave===!0),uU=()=>{const e={};for(const t of NI){const a=Fi(t).ui?.read();a!==void 0&&Object.assign(e,{[t]:a})}return e},MI=Di.filter(e=>{const t=Fi(e);return t.scope!=="device"&&!t.secret&&!t.computed}),_f=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},Jg="openchamber.settingsMirror.v2.index",EI="openchamber.deviceSeeded.v1:",LI=e=>`${EI}${encodeURIComponent(e)}`,qI=(e,t)=>{const s=LI(t);let a=!1;try{a=localStorage.getItem(s)===null,a&&localStorage.setItem(s,String(Date.now()))}catch{a=!1}if(a)return e;const n={};for(const i of Di)e[i]===void 0||Gf(i)||Object.assign(n,{[i]:e[i]});return n},VI="openchamber.settingsMirror.v2:",UI=5,Cl=e=>`${VI}${encodeURIComponent(e)}`,Cs=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},WI=(e,t)=>{const s={};for(const i of MI)e[i]!==void 0&&Object.assign(s,{[i]:e[i]});localStorage.setItem(Cl(t),JSON.stringify(s));let a=[];try{const i=JSON.parse(localStorage.getItem(Jg)??"[]");Array.isArray(i)&&(a=i.filter(o=>typeof o=="string"))}catch{a=[]}const n=[t,...a.filter(i=>i!==t)].slice(0,UI);for(const i of a)n.includes(i)||localStorage.removeItem(Cl(i));localStorage.setItem(Jg,JSON.stringify(n))},HI=e=>{if(!(typeof window>"u")){if(WI(e,D()),Cs("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),_f(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(s=>s.sidebarCollapsed===!0).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"),Cs("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(Vh(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"),Cs("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),Cs("sttEndpointPath",e.sttEndpointPath??null),Cs("sttModel",typeof e.sttModel=="string"?e.sttModel:null),Cs("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),Cs("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null),Cs("sttCorrectTranscript",e.sttCorrectTranscript===void 0?null:String(e.sttCorrectTranscript))}},Sl=(e,t,s=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:s}}))};let xl="idle",mo=null;const Pl=new Set,GI=()=>xl,_I=e=>(Pl.add(e),()=>Pl.delete(e)),KI=e=>{ur(),Ft(e)},Ft=e=>{mo&&(clearTimeout(mo),mo=null);const t=e==="saved"?"idle":e;t!==xl&&(xl=t,Pl.forEach(s=>s())),t==="error"&&(mo=setTimeout(()=>Ft("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},Kf=()=>{const e=P.persist;if(e&&typeof e=="object")return e},Zf=()=>pn()?.settings??null,Jf=()=>`/api/config/settings?${df}=${dr()}`,ZI=e=>{BI(e)},Ko=e=>DI(e);class JI{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const s=this.mutations.at(-1),a=s?[...this.operations].some(n=>n.revision>=s.revision):!0;s&&!a?(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 a=t;for(const n of this.mutations)n.revision<=s.revision||(a={...a,...n.changes});return a}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const s=Math.min(...[...this.operations].map(({revision:a})=>a));this.mutations=this.mutations.filter(a=>a.revision>s)}reset(){this.mutations=[],this.operations.clear()}}let qd=0,Ds=null,nn={},Tl=!1;const QI=()=>Tl,zl=e=>{Tl=!0;try{ZI(e)}finally{Tl=!1}};let aa=null,Nt=null,Zt=null,at=null,ti=[],Qg=!1,Zo=0,zo=[];const dt=new JI,$I=2e3,YI=200,Vd=()=>({runtimeKey:D(),generation:qd}),gr=e=>Object.keys(e),Qf=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),Ao=e=>{nn={...nn,...e}},XI=e=>{const t={...nn};for(const s of e)delete t[s];nn=t},ej=e=>{const t={};for(const s of gr(e))Qf(e[s],nn[s])||Object.assign(t,{[s]:e[s]});return t},vi=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,$f=e=>{let t=null;for(const s of zo)vi(s.context,e)&&(t={...t??{},...s.changes});return Nt&&Zt&&vi(Zt,e)&&(t={...t??{},...Nt}),t},$g=(e,t)=>{const s=$f(t);return e&&s?{...e,...s}:e},je=e=>e.generation===qd&&e.runtimeKey===D(),Dn=()=>{Nt&&(at&&(clearTimeout(at),at=null),Jo({keepalive:!0}))},ur=()=>{if(!(Qg||typeof window>"u")){Qg=!0,er(e=>{e.runtimeKey!==e.previousRuntimeKey&&(at&&clearTimeout(at),Nt&&Jo())}),tr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(qd+=1,dt.reset(),Zo=0,Ds=null,aa=null,nn={},Ft("saved"))});try{window.addEventListener("pagehide",Dn,{capture:!0}),window.addEventListener("beforeunload",Dn,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Dn()}),document.addEventListener("freeze",Dn)),ma()&&qe(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([122,4,108])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||Dn()})).catch(()=>{})}catch{}}},Yf=async(e=Vd())=>{if(ur(),Ds&&vi(Ds.context,e)&&Date.now()-Ds.at<$I)return $g(Ds.value,e);if(aa&&vi(aa.context,e))return aa.promise;const t=dt.begin(),s=$f(e),a=i=>{if(!je(e)||!i)return null;const o=$g(dt.reconcile({...i,...s},t),e);Ds={value:o,at:Date.now(),context:e};const r={};for(const c of gr(i))Qf(i[c],o?.[c])&&Object.assign(r,{[c]:i[c]});return Ao(r),o},n={context:e,promise:(async()=>{const i=Zf();if(i)try{const o=await i.load();if(!je(e))return null;const r=Ko(o.settings);return a(r)}catch(o){if(!je(e))return null;console.warn("Failed to load shared settings from runtime settings API:",o)}if(!je(e))return null;try{const o=await C(Jf(),{method:"GET",headers:{Accept:"application/json"}});if(!je(e)||!o.ok)return null;const r=await o.json().catch(()=>null);if(!je(e))return null;const c=Ko(r);return a(c)}catch(o){return je(e)&&console.warn("Failed to load shared settings from server:",o),null}})()};return aa=n,n.promise.finally(()=>{dt.finish(t),aa===n&&(aa=null)}),n.promise},tj=async e=>{const t=e?.bootstrap!==!1,s=e?.adoptTheme??t;if(typeof window>"u")return;ur();const a=Vd(),n=dt.begin(),i=[Kf(),Ot.persist],o=d=>!d?.hasHydrated||d.hasHydrated()||!d.onFinishHydration?Promise.resolve():new Promise(u=>{let m=!1;const f=()=>{m||(m=!0,u())},b=d.onFinishHydration(()=>{b?.(),f()});d.hasHydrated?.()&&f()}),r=()=>Promise.all(i.map(o)).then(()=>{}),c=d=>!Nt||!Zt||!je(Zt)?d:{...d,...Nt},l=async d=>{if(!je(a))return;let u=c(dt.reconcile(d,n));if(await r(),!!je(a)){u=qI(c(dt.reconcile(d,n)),a.runtimeKey);try{HI(u)}catch(m){console.warn("persistToLocalStorage failed:",m)}try{zl(u)}catch(m){console.warn("applyDesktopUiPreferences failed:",m)}Sl(u,t,s)}};try{const d=await Yf(a);d&&je(a)?await l(d):je(a)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(d){je(a)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",d)}finally{dt.finish(n)}};async function Jo({keepalive:e=!1}={}){let t=!1;const s=Nt,a=Zt,n=Zo,i=ti;Nt=null,Zt=null,Zo=0,at=null,ti=[];try{if(!s||!a||Object.keys(s).length===0||!je(a)){t=!0,Ft("saved");return}const o=dt.begin(n),r={context:a,changes:{...s}};zo.push(r),Ao(s);const c=()=>XI(gr(s));try{const l=Zf();if(l)try{const d=Ko(await l.save(s));if(!je(a))return;if(d){Ao(d);const u=dt.reconcile(d,o);zl(u),Sl(u,!1),Ds=null}d||c(),t=!!d,Ft(d?"saved":"error");return}catch(d){if(!je(a))return;console.warn("Failed to update settings via runtime settings API:",d)}if(!je(a))return;try{const d=await C(Jf(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s),keepalive:e});if(!je(a))return;if(!d.ok){console.warn("Failed to update shared settings via API:",d.status,d.statusText),c(),Ft("error");return}const u=Ko(await d.json().catch(()=>null));if(!je(a))return;if(u){Ao(u);const m=dt.reconcile(u,o);zl(m),Sl(m,!1),t=!0,Ft("saved"),Ds=null}else c(),Ft("error")}catch(d){je(a)&&(console.warn("Failed to update shared settings via API:",d),c(),Ft("error"))}}finally{zo=zo.filter(l=>l!==r),dt.finish(o)}}finally{i.forEach(o=>o({ok:t}))}}const sj=()=>Yf(),Gt=async e=>{if(typeof window>"u")return{ok:!1};ur();const t=Vd();Zt&&!vi(Zt,t)&&(at&&clearTimeout(at),Jo());const s={};for(const o of gr(e))jI(o)&&Object.assign(s,{[o]:e[o]});const a=dt.record(s),n=ej({...Nt??{},...s});if(Object.keys(n).length===0){Nt=null,Zt=null,at&&(clearTimeout(at),at=null);const o=ti;return ti=[],o.forEach(r=>r({ok:!0})),Ft("saved"),{ok:!0}}Nt=n,Zt=t,Zo=a,Ft("saving"),at&&clearTimeout(at);const i=new Promise(o=>{ti.push(o)});return at=setTimeout(()=>{Jo()},YI),i},aj=async()=>{if(typeof window>"u")return;const e=Kf();try{const t=await rT();if(!t)return;const s=()=>oT(t);if(e?.hasHydrated?.()){s();return}if(s(),e?.onFinishHydration){const a=e.onFinishHydration(()=>{a?.(),s()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},mU=Object.freeze(Object.defineProperty({__proto__:null,applyPersistedHomeDirectoryToWindow:_f,getRuntimeSettingsMirrorStorageKey:Cl,getSettingsSaveState:GI,initializeAppearancePreferences:aj,isApplyingServerSettings:QI,loadDesktopSettings:sj,reportSettingsSaveState:KI,subscribeToSettingsSaveState:_I,syncDesktopSettings:tj,updateDesktopSettings:Gt},Symbol.toStringTag,{value:"Module"})),hU="openchamber:chats",yc=new Map,Xf=new Map,Al=new Set,eb=(e,...t)=>[e.replace(/[\\/]+$/,""),...t].join("/");function tb(e){const t=ze(e);return t?eb(t,".config","openchamber","chats"):null}function Ea(e,t){return!e.split("/").some(s=>s===".."||s===".")&&(e===t||e.startsWith(`${t}/`))}function sb(){return Xf.get(D())}function nj(e){const t=ze(e),s=sb();return!t||!s?null:Ea(t,s.configured)||Ea(t,s.canonicalConfigured)?s.configured:Ea(t,s.legacy)||Ea(t,s.canonicalLegacy)?s.legacy:null}function ij(e){return nj(e)!==null}function fU(e,t){if(ij(e))return!0;const s=ze(e),a=tb(t);return!!(s&&a&&Ea(s,a))}function oj(){return sb()?.configured??null}function bU(e){return Al.add(e),()=>Al.delete(e)}async function Bi(){const e=D(),t=yc.get(e);if(t)return t;const s=Je.getFilesystemHomeInfo().then(({home:a,chatsRoot:n,canonicalChatsRoot:i,canonicalLegacyChatsRoot:o})=>{const r=tb(a),c=ze(n)??r;if(!r||!c)throw new Error("Unable to resolve chat directories");const l={configured:c,legacy:r,canonicalConfigured:ze(i)??c,canonicalLegacy:ze(o)??r};Xf.set(e,l);for(const d of Al)d();return l}).catch(a=>{throw yc.delete(e),a});return yc.set(e,s),s}async function rj(){await Bi()}async function cj(){return(await Bi()).configured}function wU(){return rj().catch(()=>{})}async function kU(e=new Date){const t=D(),s=await Bi();if(D()!==t)throw new Error("Runtime changed while preparing chat directory");const a=[e.getFullYear(),String(e.getMonth()+1).padStart(2,"0"),String(e.getDate()).padStart(2,"0")].join("-"),n=globalThis.crypto?.randomUUID?.()??`${e.getTime()}-${Math.random().toString(36).slice(2)}`,i=eb(s.configured,a,`session-${n}`);return await Je.createDirectory(i),i}async function ab(e,t,s){const a=ze(e);if(!a)return;const n=[t.configured,t.legacy,t.canonicalConfigured,t.canonicalLegacy];if(n.includes(a)||!n.some(o=>Ea(a,o)))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 yU(e){if(!ze(e))return;const t=D(),s=await Bi();if(D()!==t)throw new Error("Runtime changed while deleting chat directory");await ab(e,s,C)}async function vU(e){const t=await $m(e),s=await Bi();if(D()!==e)throw new Error("Runtime changed while preparing chat cleanup");return async a=>{await t(async({fetch:n})=>{await ab(a,s,n)})}}const lj=3e4,dj=40,pj=60,gj=(e,t,s,a,n,i,o)=>{const r=t.trim(),c=s.trim().toLowerCase();return JSON.stringify([e,r,c,a,n,i,o])},Yg=(e,t)=>{try{const s=JSON.parse(e);return Array.isArray(s)&&s[1]===t}catch{return!1}},Xg=new WeakMap,eu=(e,t)=>{if(!t){e.waiters=1/0;return}e.waiters+=1,t.addEventListener("abort",()=>{e.waiters-=1,e.waiters===0&&e.abandon()},{once:!0})},uj=vt()(dn((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,a,n=pj,i){if(!s||s.trim().length===0)return[];const o=s.trim(),r=D(),c=typeof a=="string"?a.trim():"",l=!!i?.includeHidden,d=i?.respectGitignore??!0,u=i?.type==="directory"?"directory":"file",m=gj(r,o,c,n,l,d,u),f=Date.now(),b=t().cache[m];if(b&&f-b.timestamp<lj)return b.files;const w=t().inFlight[m];if(w){const U=Xg.get(w);return U&&eu(U,i?.signal),w}const y=u==="file"&&(l||!d)?pn()?.files:void 0,A=y?t().searchFiles(o,c,n,{type:u}):Je.searchFiles(c,{directory:o,limit:n,type:u});let x=!1;const M=new AbortController,Q=y?y.search({directory:o,query:c,maxResults:n,includeHidden:l,respectGitignore:d,signal:M.signal}).then(U=>U.map(Z=>{const ot=Z.path.replace(/\\/g,"/"),de=Z.preview?.[0]?Z.preview[0].replace(/\\/g,"/"):ot,st=de.split("/").filter(Boolean).pop()||ot.split("/").filter(Boolean).pop()||"";return{name:st,path:ot,relativePath:de,extension:st.includes(".")?st.split(".").pop()?.toLowerCase():void 0}})).catch(U=>(x=!0,M.signal.aborted||console.warn("Supplemental file search failed; keeping indexed results:",U),[])):Promise.resolve([]),he=Promise.all([A,Q]).then(([U,Z])=>{if(Z.length===0)return U;const ot=new Set(U.map(de=>de.path.replace(/\\/g,"/")));return[...U,...Z.filter(de=>ot.has(de.path)?!1:(ot.add(de.path),!0))].slice(0,n)}).then(U=>(x||e(Z=>{if(Z.inFlight[m]!==he)return Z;const ot={...Z.cache,[m]:{files:U,timestamp:Date.now()}},de=Z.cacheKeys.filter(st=>st!==m);for(de.push(m);de.length>dj;){const st=de.shift();st&&delete ot[st]}return{cache:ot,cacheKeys:de}}),U)).finally(L);function L(){e(U=>{if(U.inFlight[m]!==he)return U;const Z={...U.inFlight};return delete Z[m],{inFlight:Z}})}if(e(U=>({inFlight:{...U.inFlight,[m]:he}})),y){const U={controller:M,waiters:0,abandon:()=>{M.abort(),L()}};Xg.set(he,U),eu(U,i?.signal)}return he},invalidateDirectory(s){if(!s||s.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const a=s.trim();e(n=>{const i={...n.cache},o=n.cacheKeys.filter(l=>Yg(l,a)?(delete i[l],!1):!0),r=Object.entries(n.inFlight).filter(([l])=>!Yg(l,a)),c=Object.fromEntries(r);return{cache:i,cacheKeys:o,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),mj=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Rl="openchamber_stream_perf",hj=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Rl)==="1"}catch{return!1}};let nb=hj(),ib=!1;const ka=()=>nb||ib,ob=()=>{ka()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},tu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),rb=()=>{if(!ka()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},cb=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),Ud=(e,t)=>{const s=rb();if(!s)return;const a=s.counters.get(e)??{count:0,total:0,max:0,last:0};a.count+=1,a.total+=t,a.max=Math.max(a.max,t),a.last=t,s.counters.set(e,a),s.lastUpdatedAt=Date.now()},fj=e=>{if(nb=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(Rl,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Rl),ob()}catch{}},CU=e=>{if(ib=e,!(typeof window>"u")){if(e){rb();return}ob()}},bj=()=>{typeof window>"u"||(ka()&&(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()}))},wj=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!ka()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:cb(e.counters)}},SU=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!ka()||!e)return{enabled:!1,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:!0,startedAt:t,lastUpdatedAt:s,durationMs:t?Math.max(0,Date.now()-t):0,entries:cb(e.counters)}},xU=(e,t=1)=>{Ud(e,t)},PU=(e,t)=>{Ud(e,t)},TU=e=>{!ka()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},zU=(e,t)=>{if(!ka())return t();const s=tu();try{return t()}finally{Ud(e,tu()-s)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:fj,reset:bj,getSnapshot:wj});var kj={};const yj=e=>!e.isHomeReady&&(e.currentDirectory==="/"||e.currentDirectory===""),su=(e,t)=>ui()?t||"":!Oe()&&t||e,lb=async()=>{if(Oe()&&!ui())return null;const e=D();try{const t=await cj();return D()!==e?null:(ui()&&await Je.createDirectory(t),t)}catch{return null}};let ls=null,Il=0,db=!0;const ft=Ii(),au=ft.getItem("lastDirectory"),vj=typeof au=="string"&&au.length>0,ja=e=>{try{uj.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},on=e=>ze(e)??"",Cj=(e,t)=>{const s=e.trim();return s.startsWith("~")?s==="~"?t||s:(s.startsWith("~/")||s.startsWith("~\\"))&&t?`${t}${s.slice(1)}`:s:s},Ro=(e,t)=>{const s=Cj(e,t);return on(s)},Sj=()=>{const e=ft.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=on(e);return t.length>0?t:null},xj=()=>{const e=ft.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=on(e);return t.length>0?t:null},Pj=()=>{if(typeof process>"u")return null;const e=kj,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const a=on(t);return a.length>0?a:null}const s=process?.cwd?.();if(typeof s=="string"&&s.trim().length>0){const a=on(s);return a.length>0?a:null}return null},Wd=()=>{if(typeof window<"u"){if(ls)return ls;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ls=t,ft.setItem("homeDirectory",t),t;const s=Sj();if(s&&!Oe())return ls=s,s}const e=Pj();return e||"/"},Wn=e=>{const t=ze(e);return t&&t!=="/"?t:null},pb=async()=>{try{const s=await Je.getFilesystemHome(),a=Wn(s);if(a)return a}catch(s){console.warn("Failed to obtain filesystem home directory:",s)}if(!db)return"/";try{const s=await Je.getSystemInfo(),a=Wn(s?.homeDirectory);if(a)return a}catch(s){console.warn("Failed to get home directory from system info:",s)}try{const s=await wm(),a=Wn(s);if(a)return a}catch(s){console.warn("Failed to obtain desktop-integrated home directory:",s)}const e=Wd(),t=Wn(e);return t||e},Tj=()=>{if(!Oe())return null;const e=Ql()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=on(e);return t.length>0?t:null},Ci=Tj()||Wd(),Si=(()=>{const e=xj();return e&&!Oe()?Ro(e,Ci):Oe()&&!ui()?Ci:""})();Si&&Je.setDirectory(Si);const zj=!!(Ci&&Ci!=="/"&&Si),Hd=vt()(dn((e,t)=>({currentDirectory:Si,directoryHistory:[Si],historyIndex:0,homeDirectory:Ci,hasPersistedDirectory:vj,isHomeReady:zj,isSwitchingDirectory:!1,setDirectory:(s,a)=>{const n=ls||t().homeDirectory||ft.getItem("homeDirectory"),i=Ro(s,n);mj()&&console.log("[DirectoryStore] setDirectory called with path:",i),Je.setDirectory(i),ja(),e(o=>{const r=o.directoryHistory[o.historyIndex]===i,c=r?o.directoryHistory:[...o.directoryHistory.slice(0,o.historyIndex+1),i];return ft.setItem("lastDirectory",i),Gt({lastDirectory:i}),{currentDirectory:i,directoryHistory:c,historyIndex:r?o.historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const s=t();if(s.historyIndex>0){const a=s.historyIndex-1,n=s.directoryHistory[a];Je.setDirectory(n),ja(),ft.setItem("lastDirectory",n),Gt({lastDirectory:n}),e({currentDirectory:n,historyIndex:a,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const s=t();if(s.historyIndex<s.directoryHistory.length-1){const a=s.historyIndex+1,n=s.directoryHistory[a];Je.setDirectory(n),ja(),ft.setItem("lastDirectory",n),Gt({lastDirectory:n}),e({currentDirectory:n,historyIndex:a,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:a}=t(),n=ls||t().homeDirectory||Wd();if(s===n)return;const i=aC(s);i&&a(i)},goToNoProjectDirectory:async()=>{const s=D(),a=t().currentDirectory,[n,i]=await Promise.all([ls||t().homeDirectory||pb(),lb()]);if(D()!==s||t().currentDirectory!==a)return;const o=su(n,i);Je.setDirectory(o),ja(),ft.removeItem("lastDirectory"),Gt({lastDirectory:""}),e(r=>{const c=r.directoryHistory[r.historyIndex]===o,l=c?r.directoryHistory:[...r.directoryHistory.slice(0,r.historyIndex+1),o];return{currentDirectory:o,directoryHistory:l,historyIndex:c?r.historyIndex:l.length-1,hasPersistedDirectory:!1,isHomeReady:!0,isSwitchingDirectory:!1}})},synchronizeHomeDirectory:(s,a)=>{const n=t(),i=s;ls=i;const o=n.homeDirectory!==i,r=ft.getItem("lastDirectory"),c=typeof r=="string"&&r.length>0,l=su(i,a),d=yj(n)||!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||n.currentDirectory===oj()||!n.currentDirectory);if(!o&&!d){n.isHomeReady||e({isHomeReady:!0});return}const u=typeof i=="string"&&i!==""&&i!=="/",m=n.currentDirectory?Ro(n.currentDirectory,i):n.currentDirectory,f=n.directoryHistory.map(x=>Ro(x,i)),b=f.some((x,M)=>x!==n.directoryHistory[M]),w=!!(m&&m!==n.currentDirectory),y=d&&(!Oe()||ui())&&!a,A={homeDirectory:i,hasPersistedDirectory:c,isHomeReady:u&&!y};if(d?(A.currentDirectory=l,A.directoryHistory=[l],A.historyIndex=0,A.isSwitchingDirectory=!1):(w||b)&&(A.currentDirectory=m,A.directoryHistory=f,A.historyIndex=Math.min(n.historyIndex,f.length-1),A.isSwitchingDirectory=!1),e(()=>A),(d||w)&&u&&!y){const x=d?l:m;Je.setDirectory(x),ja(),d||(ft.setItem("lastDirectory",x),Gt({lastDirectory:x}))}Gt({homeDirectory:i})},resetForRuntimeSwitch:()=>{Je.setDirectory(void 0),ja(),e({currentDirectory:"/",directoryHistory:["/"],historyIndex:0,homeDirectory:"/",hasPersistedDirectory:!1,isHomeReady:!1,isSwitchingDirectory:!1})}}),{name:"directory-store"}));let si=null;const jl=()=>{const e=++Il,t=Promise.all([pb(),lb()]).then(([s,a])=>{if(e!==Il)return;const n=Wn(s);n&&ft.setItem("homeDirectory",n),Hd.getState().synchronizeHomeDirectory(s,a)}).finally(()=>{si===t&&(si=null)});return si=t,t},AU=async()=>{si&&await si,!Hd.getState().isHomeReady&&await jl()};typeof window<"u"&&(jl(),tr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(db=!1),ls=null,Il+=1,queueMicrotask(()=>{jl()})}));const Aj=ve("type",[g({id:p(),type:k("open")}),g({id:p(),type:k("message"),data:p(),binary:T()}),g({id:p(),type:k("error")}),g({id:p(),type:k("close"),code:v().int(),reason:p()})]),Rj=kw("RuntimeWebSocket"),Ij=(e,t,s)=>{const a=new URL(e),n=new URL(t);return a.protocol!=="ws:"&&a.protocol!=="wss:"||a.username||a.password?null:(a.protocol=a.protocol==="wss:"?"https:":"http:",a.origin===n.origin&&a.pathname.startsWith(n.pathname)?{...s}:null)},jj=e=>{const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let s="";for(let a=0;a<t.length;a+=8192)s+=String.fromCharCode(...t.subarray(a,a+8192));return btoa(s)},Oj=(e,t,s=[],a=Rj)=>{if(new Set(s).size!==s.length||s.some(b=>!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(b)))throw new SyntaxError("Invalid WebSocket protocols");const n=crypto.randomUUID();let i=0,o=null,r=!1,c=Promise.resolve(),l=0;const d=(b,w)=>{i!==3&&(i=3,o?.remove().catch(()=>{}),o=null,globalThis.window?.removeEventListener("pagehide",f),m.onclose?.({code:b,reason:w}))},u=()=>{i!==3&&(m.onerror?.(),d(1006,""),r&&a.close({id:n,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 w=b instanceof ArrayBuffer||ArrayBuffer.isView(b),y=w?b.byteLength:new TextEncoder().encode(b).byteLength;if(l+=y,l>16*1024*1024){u();return}const A=w?jj(b):b;c=c.then(async()=>{i!==3&&await a.send({id:n,data:A,binary:w})}).catch(u).finally(()=>{l-=y})},close(b=1e3,w=""){if(b!==1e3&&(b<3e3||b>4999||!Number.isInteger(b)))throw new DOMException("Invalid close code","InvalidAccessError");if(new TextEncoder().encode(w).byteLength>123)throw new SyntaxError("Close reason is too long");if(!(i>=2)){if(i=2,!r){d(1e3,"");return}c=c.then(()=>a.close({id:n,code:b,reason:w})).catch(u)}}},f=()=>m.close();return globalThis.window?.addEventListener("pagehide",f),a.addListener("socketEvent",b=>{const w=Aj.safeParse(b);if(!w.success||w.data.id!==n||i===3)return;const y=w.data;switch(y.type){case"open":if(i!==0)return;i=1,m.onopen?.();break;case"message":{if(i!==1)return;let A=y.data;if(y.binary)try{A=Uint8Array.from(atob(y.data),x=>x.charCodeAt(0)).buffer}catch{u();return}m.onmessage?.({data:A});break}case"error":u();break;case"close":d(y.code,y.reason);break}}).then(async b=>{if(i===3){await b.remove();return}o=b,r=!0,c=a.open({id:n,url:e,headers:{...t},protocols:s}),await c}).catch(u),m},Dj=(e,t)=>{const s=gn();if(s)return s.openWebSocket(sk(e),t);const a=un();if(Object.keys(a).length>0&&ma()){const n=Ij(e,ds().api("/"),a);if(n)return Oj(e,n,t)}return Hk(new WebSocket(e))},gb=1,La=512*1024,vc=8*1024,Fj=0,Oa=1,Bj=15e3,rn=new TextEncoder,Gd=new TextDecoder,_d=I(["interactive","command"]),ub=I(["running","exited","error"]),Nj=I(["node","bun"]),Kd=ve("type",[g({type:k("terminal")}),g({type:k("project-action"),actionId:p(),executionId:p()})]),Mj=g({sessionId:p(),cols:v(),rows:v(),status:ub,mode:_d.optional(),purpose:Kd.optional()}),Ej=g({sessionId:p(),cwd:p(),status:I(["running","exited"]),createdAt:v().nullable().optional().transform(e=>e??null),mode:_d.optional(),purpose:Kd.optional()}),nu={mode:_d.optional(),purpose:Kd.optional()},Lj=ve("t",[g({t:k("hello")}),g({t:k("pong")}),g({t:k("error"),s:p().optional(),message:p().optional(),code:p().optional(),fatal:T().optional()}),g({t:k("snapshot"),s:p(),q:v().int().nonnegative().default(0),history:p().default(""),status:ub,cols:v().int().positive().optional(),rows:v().int().positive().optional(),exitCode:v().nullish().transform(e=>e??void 0),signal:v().nullable().optional(),runtime:Nj.optional(),ptyBackend:p().optional(),...nu}),g({t:k("output"),s:p(),q:v().int().nonnegative(),d:p(),r:p().optional()}),g({t:k("exit"),s:p(),q:v().int().nonnegative(),exitCode:v().nullish().transform(e=>e??void 0),signal:v().nullable().optional()}),g({t:k("restarted"),s:p(),q:v().int().nonnegative(),history:p().default(""),...nu})]),qj=e=>{const t=rn.encode(JSON.stringify(e)),s=new Uint8Array(t.length+1);return s[0]=gb,s.set(t,1),s},Vj=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):rn.encode(e);t[0]===gb&&(t=t.subarray(1));try{return Lj.safeParse(JSON.parse(Gd.decode(t))).data??null}catch{return null}};class Uj extends Error{code;constructor(t,s){super(t),this.name="TerminalRequestError",this.code=s}}const RU=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,Wj=g({error:p().optional(),code:p().optional()}),mr=async(e,t)=>{const s=Wj.safeParse(await e.json().catch(()=>null)).data;return new Uj(s?.error??t,s?.code??null)},Hj=e=>{const t=rn.encode(e);if(t.byteLength<=La)return e;let s=t.byteLength-La;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;return Gd.decode(t.subarray(s))},Ol=e=>{for(let t=0;t<e.length;t+=1){const s=e.charCodeAt(t);if(s>=55296&&s<=56319){const a=e.charCodeAt(++t);if(a<56320||a>57343||Number.isNaN(a))return!1}else if(s>=56320&&s<=57343)return!1}return!0},Dl=e=>{if(e.malformed!==null)return e.malformed;const t=new Uint8Array(e.byteLength);let s=0;for(const a of e.parts)t.set(a.bytes.subarray(a.start,a.end),s),s+=a.end-a.start;return Gd.decode(t)},Fl=(e,t)=>{if(t.length>=La){let a=t.length-La;for(;a<t.length&&(t[a]&192)===128;)a+=1;const n=t.slice(a);e.parts=[{bytes:n,start:0,end:n.length}],e.byteLength=n.length;return}const s=e.parts.at(-1);if(s&&s.bytes.length===vc&&s.end+t.length<=s.bytes.length)s.bytes.set(t,s.end),s.end+=t.length;else if(t.length<vc){const a=new Uint8Array(vc);a.set(t),e.parts.push({bytes:a,start:0,end:t.length})}else e.parts.push({bytes:t,start:0,end:t.length});for(e.byteLength+=t.length;e.byteLength>La;){const a=e.parts[0],n=e.byteLength-La,i=a.start+n;if(i>=a.end){e.byteLength-=a.end-a.start,e.parts.shift();continue}let o=i;for(;o<a.end&&(a.bytes[o]&192)===128;)o+=1;e.byteLength-=o-a.start,a.start=o,a.start===a.end&&e.parts.shift()}},Gj=(e,t)=>{if(t){if(e.malformed!==null||!Ol(t)){const s=Hj(Dl(e)+t);if(e.parts=[],e.byteLength=0,!Ol(s)){e.malformed=s;return}e.malformed=null,Fl(e,rn.encode(s));return}Fl(e,rn.encode(t))}},iu=e=>{const t={parts:[],byteLength:0,malformed:null};return Ol(e)?e&&Fl(t,rn.encode(e)):t.malformed=e,t},_j=g({sessions:z(ee())});class Kj{constructor(t=mb(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=!1;subscribe(t,s){this.cancelIdleClose();const a={handlers:s,lastSequence:-1},n=this.subscribers.get(t)??new Set,i=n.size===0;n.add(a),this.subscribers.set(t,n);const o=this.projections.get(t);o&&(a.lastSequence=o.sequence,s.onEvent({type:"snapshot",sequence:o.sequence,data:Dl(o.history),cols:o.cols,rows:o.rows,status:o.status,mode:o.mode,purpose:o.purpose,exitCode:o.exitCode,signal:o.signal,runtime:o.runtime,ptyBackend:o.ptyBackend}));const r=this.socket?.readyState===Oa;return this.ensureConnected().then(()=>{const c=this.subscribers.get(t);i&&r&&c===n&&c.size>0&&this.send({t:"attach",v:3,s:t})}).catch(c=>{n.has(a)&&(s.onError?.(c,!1),this.scheduleReconnect())}),()=>{const c=this.subscribers.get(t);if(c?.delete(a),c?.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===Oa){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=!0,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,a){const n=this.projections.get(t);n&&this.projections.set(t,{...n,cols:s,rows:a})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===Oa)return;if(this.opening)return await this.opening,this.socket?.readyState===Oa?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((a,n)=>{let i=!1,o=!1,r=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,d=()=>{r||o||!l()||(r=!0,this.dependencies.clearUrlAuthToken?.())},u=f=>{i||(i=!0,clearTimeout(m),f?n(f):a())},m=setTimeout(()=>{d(),c?.close(),u(new Error("Terminal connection timed out"))},1e4);try{const f=this.dependencies.openSocket();c=f,f.binaryType="arraybuffer",this.socket=f,f.onopen=()=>{if(!l()){f.close(),u(new Error("Terminal runtime changed"));return}o=!0,this.failures=0,this.send({t:"hello",v:3});for(const b of this.subscribers.keys())this.send({t:"attach",v:3,s:b});this.startKeepalive(),u()},f.onmessage=b=>{this.handleMessage(b.data)},f.onerror=()=>{const b=l();b&&d(),u(new Error("Terminal WebSocket failed")),b&&this.subscribers.size>0&&this.scheduleReconnect()},f.onclose=()=>{const b=l();b&&(this.stopKeepalive(),d()),this.socket===f&&(this.socket=null),u(new Error("Terminal WebSocket closed")),b&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(f){u(f instanceof Error?f: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)}}handleMessage(t){const s=Vj(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 o=s.s?[s.s]:[...this.subscribers.keys()];for(const r of o)for(const c of this.subscribers.get(r)??[])c.handlers.onError?.(i,s.fatal===!0);return}if(!s.s)return;const a=this.subscribers.get(s.s);if(!a)return;if(s.t==="snapshot"){const i={sequence:s.q??0,history:iu(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 o=Dl(i.history);for(const r of a)r.lastSequence=i.sequence,r.handlers.onEvent({type:"snapshot",sequence:i.sequence,data:o,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 n=this.projections.get(s.s);n&&s.q>n.sequence&&(s.t==="output"?(Gj(n.history,s.r??s.d),this.projections.set(s.s,{...n,sequence:s.q})):s.t==="exit"?this.projections.set(s.s,{...n,sequence:s.q,status:"exited",exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&this.projections.set(s.s,{...n,sequence:s.q,history:iu(s.history??""),status:"running",mode:s.mode??n.mode,purpose:s.purpose??n.purpose,exitCode:void 0,signal:null}));for(const i of a)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??n?.mode,purpose:s.purpose??n?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==Oa)return!1;try{return this.socket.send(qj(t)),!0}catch{return!1}}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 n of this.subscribers.values())for(const i of n)i.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const a=()=>{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",a),typeof document<"u"&&document.addEventListener("visibilitychange",a),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",a),typeof document<"u"&&document.removeEventListener("visibilitychange",a)},this.reconnectTimer=setTimeout(a,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())},Bj))}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===Fj||t.readyState===Oa)&&t.close()}}const Zj="",Qo=new Map,Jj=e=>e===null?"/api/terminal/ws":`/api/terminal/ws?directory=${encodeURIComponent(Em(e))}`;function mb(e){return{refreshAuth:nr,openSocket:()=>Dj(ds().websocket(Jj(e))),clearUrlAuthToken:Ai}}function Ni(e){const t=yt(e),s=t??Zj,a=Qo.get(s);if(a)return a;const n=new Kj(mb(t));return Qo.set(s,n),n}async function Qj(e){const t=await C("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),directory:e.cwd});if(!t.ok)throw await mr(t,"Failed to create terminal session");const s=await t.json().catch(()=>null),a=Mj.safeParse(s).data;if(!a)throw new Error("Failed to create terminal session");return a}async function $j(e){const t=await C(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`,{directory:e});if(!t.ok)throw await mr(t,"Failed to list terminal sessions");const s=await t.json().catch(()=>null),a=_j.safeParse(s).data?.sessions;if(!Array.isArray(a))throw new Error("Failed to list terminal sessions");const n=[];for(const i of a){const o=Ej.safeParse(i).data;o&&n.push(o)}return n}async function Yj(e,t){e.length!==0&&await bn("/api/terminal/touch","POST",{sessionIds:e},t)}async function Xj(){const e=await C("/api/terminal/shells");if(!e.ok)throw await mr(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(s=>s&&typeof s=="object"&&Rd(s.id)&&typeof s.name=="string"&&typeof s.supportsLogin=="boolean"):[]}function eO(e,t,s,a){return Ni(a).subscribe(e,{onEvent:t,onError:s})}async function tO(e,t,s){await Ni(s).write(e,t)}async function bn(e,t,s,a){const n={method:t,directory:a};s!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(s));const i=await C(e,n);if(!i.ok)throw await mr(i,"Terminal command failed");return i}async function sO(e,t,s,a){await bn(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:s},a),Ni(a).noteResize(e,t,s)}async function aO(e,t,s){await bn(`/api/terminal/${e}/appearance`,"POST",t,s)}async function nO(e,t){await bn(`/api/terminal/${e}`,"DELETE",void 0,t),Ni(t).forget(e)}async function iO(e,t){return(await bn(`/api/terminal/${e}/restart`,"POST",t,t.cwd)).json()}async function oO(e){const s=await(await bn("/api/terminal/force-kill","POST",e,e.cwd)).json().catch(()=>null),a=Ni(e.cwd);if(Array.isArray(s?.killedSessionIds))for(const n of s.killedSessionIds)typeof n=="string"&&a.forget(n);else e.sessionId&&a.forget(e.sessionId)}function IU(){for(const e of Qo.values())e.dispose();Qo.clear()}const rO=()=>({async listShells(){return Xj()},async listSessions(e){return $j(e)},async touchSessions(e,t){await Yj(e,t)},async createSession(e){return Qj(e)},connect(e,t,s){const a=eO(e,t.onEvent,t.onError,s);return{close:()=>a()}},async sendInput(e,t,s){await tO(e,t,s)},async resize(e){await sO(e.sessionId,e.cols,e.rows,e.directory)},async updateAppearance(e,t,s){await aO(e,t,s)},async close(e,t){await nO(e,t)},async restartSession(e,t){return iO(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 oO(e)}});class Zd extends Error{code;status;constructor(t,s,a){super(s),this.name="GitNetworkOperationRequestError",this.code=t,this.status=a}}class Jd extends Error{code;status;remoteName;constructor(t,s,a,n){super(s),this.name="GitWorktreeRequestError",this.code=t,this.status=a,this.remoteName=n}}class cO extends Error{provider;constructor(t,s){super(t),this.name="SourceControlInstanceOtherProviderError",this.provider=s}}const lO=p().trim().min(1).max(200),ai=p().trim().min(1).max(512),ho=p().trim().max(512).nullable().optional(),dO=g({provider:Os,instance:ai,accountId:ai}).strict(),pO=I(["account","ssh","system","anonymous"]),cn=g({id:lO,name:ai,userName:ai,userEmail:ai,account:dO.nullable().optional(),transport:pO.optional(),sshCredentialId:ho,signCommits:T().optional(),signingKey:ho,color:ho,icon:ho}).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"})}),jU=e=>e?.transport??"system",gO=z(cn).max(256).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Git identity profile IDs must be unique"),hb=g({userName:p().max(512).nullable(),userEmail:p().max(512).nullable()}).strict(),uO=g({success:T(),profile:cn.nullable()}).strict(),OU=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),Bl=new Set,mO=e=>(Bl.add(e),()=>{Bl.delete(e)}),fb=e=>{for(const t of Bl)t(e)},Nl=new Set,hO=(e,t)=>JSON.stringify([t,ze(e)]);function DU(e){return Nl.add(e),()=>{Nl.delete(e)}}function fO(e,t){const s=hO(e,t);for(const a of Nl)a(s)}class bO extends Error{reason;constructor(t,s){super(t),this.name="GitPathUnavailableError",this.reason=s}}const wO=g({error:p(),code:I(["path_not_found","nested_repository","untracked_directory"])}),Qd=g({headCommit:p().nullable(),indexCommit:p().nullable(),worktreeCommit:p().nullable(),hasTrackedChanges:T(),hasUntrackedFiles:T(),hasConflict:T()}),$d="GIT_REPOSITORY_UNREADABLE";class bb extends Error{code=$d;constructor(t){super(t),this.name="GitRepositoryUnreadableError"}}const O="/api/git",kO=g({original:p(),modified:p()}),wb=g({diff:p()}),yO=g({files:z(g({path:p(),status:p(),revision:p().optional()}))}),vO=g({error:p()}),CO=g({error:p(),code:k($d)}),SO=g({files:z(g({path:p(),previousPath:p().optional(),changeType:p(),insertions:v(),deletions:v(),isBinary:T()}))}),ou=g({hash:p(),date:p(),message:p(),refs:p(),body:p(),author_name:p(),author_email:p(),filesChanged:v(),insertions:v(),deletions:v(),parents:z(p())}),xO=g({all:z(ou),latest:ou.nullable(),total:v()}),PO=g({diff:p(),submodule:Qd.nullable().default(null)}),TO=g({diffs:z(J([g({path:p(),diff:p(),submodule:Qd.nullable().default(null)}),g({path:p(),error:p(),code:I(["path_not_found","nested_repository","untracked_directory"]).nullable()})]))}),zO=g({original:p(),modified:p(),path:p(),isBinary:T().optional(),submodule:Qd.nullable().default(null)});async function Yd(e,t){const s=await e.json().catch(()=>null),a=g({code:k("not_repository"),error:p()}).safeParse(s);if(e.status===409&&a.success)return new Error(a.data.error);const n=wO.safeParse(s);return n.success&&(e.status===404||e.status===422)?new bO(n.data.error,n.data.code):new Error(`${t}: ${e.statusText}`)}async function Mi(e,t){const s=vO.safeParse(await e.json().catch(()=>null));return new Error(s.success?s.data.error:`${t}: ${e.statusText}`)}const kb=1200,yb=5e3,xi=new Map,qa=new Map,vb=new Map,$o=new Map,fo=new Map,AO=256,RO=900*1e3,IO=3600*1e3,Ei=8192,jO=/^[A-Za-z0-9_-]{1,200}$/,Ml=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i,OO=/^[A-Za-z0-9_-]{43}$/,DO=/^SHA256:[A-Za-z0-9+/]{43}=?$/,Yt=e=>p().trim().min(1).max(e),Cb=p().regex(jO),hr=p().regex(OO),Ts=Yt(1024),Xd=Yt(4096),Pe=Yt(512),Sb=p().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"),ru=p().max(4096).refine(e=>{if(!e)return!0;try{const t=new URL(e);return!t.username&&!t.password&&!t.search&&!t.hash}catch{return e.includes("://")?!1:!/[?#]/.test(e)}},"Git remote display URLs must not contain credentials, query parameters, or fragments"),FO=z(g({name:Pe,fetchUrl:ru,pushUrl:ru}).strict()).max(256),BO=g({selectionId:Cb,provenanceRevision:v().int().safe().positive(),sourceSha:p().regex(Ml),expiresInMs:v().int().safe().positive().max(900*1e3)}).strict(),NO=g({remote:g({name:Pe,endpoint:g({displayUrl:Xd,fingerprint:hr}).strict()}).strict(),transportMode:k("managed"),classification:I(["contributor-fork","own-fork","bound-repository","other"])}).strict(),MO=ve("kind",[g({kind:k("ordinary")}).strict(),g({kind:k("contributor"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,provenanceRevision:v().int().safe().positive(),candidates:z(NO).max(128)}).strict()]),EO=g({state:k("awaiting-trust"),digest:hr,actions:z(g({kind:I(["post-checkout-hook","project-start-command","setup-command"]),label:p().max(65536)}).strict()).max(3)}).strict(),Bt=new Map,LO=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(a=>a&&a!=="."&&a!=="..")}catch{return!1}},Va=g({displayUrl:Xd.refine(LO),fingerprint:hr}).strict(),qO=g({displayName:Yt(1024),fingerprint:hr}).strict(),VO=g({id:Pe,platform:I(["web","desktop","vscode"]),label:Yt(512).optional()}).strict(),UO=ve("kind",[g({kind:k("provider"),provider:Pe,instance:Xd,accountId:Pe,login:Pe.optional()}).strict(),g({kind:k("ssh-key"),fingerprint:p().regex(DO)}).strict()]),Cc=ve("mode",[g({mode:k("anonymous"),verification:g({status:k("anonymous")}).strict()}).strict(),g({mode:k("managed"),verification:g({status:k("verified"),method:I(["credential","git-identity"])}).strict(),actor:UO.optional()}).strict(),g({mode:k("system"),verification:g({status:k("unverified"),reason:k("system-credentials")}).strict()}).strict()]),WO=J([Cc,g({fetch:Cc,push:Cc}).strict()]),Io=g({name:Pe,endpoint:Va}).strict(),Sc={repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Io,sourceRef:Ts,destinationRef:Ts},HO=ve("operation",[g({operation:k("push"),...Sc,forceWithLease:g({expectedRemoteSha:p().regex(Ml)}).strict().optional(),configureUpstream:T().optional()}).strict(),ve("fetchScope",[g({operation:k("fetch"),fetchScope:k("ref").optional(),...Sc}).strict(),g({operation:k("fetch"),fetchScope:k("remote"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Io,force:T()}).strict()]),g({operation:k("pull"),...Sc}).strict(),g({operation:k("delete-remote-branch"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Io,destinationRef:Ts}).strict(),g({operation:k("checkout-hydration"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,remote:Io,requirements:z(g({kind:I(["submodule","lfs"]),path:Sb,endpoint:Va}).strict()).max(256)}).strict(),g({operation:k("sync"),repositoryId:Pe,bindingRevision:v().int().safe().nonnegative(),configRevision:Pe,fetch:g({name:Pe,endpoint:Va,sourceRef:Ts,destinationRef:Ts}).strict(),pull:g({destinationRef:Ts}).strict(),push:g({name:Pe,endpoint:Va,sourceRef:Ts,destinationRef:Ts,forceWithLease:g({expectedRemoteSha:p().regex(Ml)}).strict().optional()}).strict()}).strict(),g({operation:k("clone"),remote:Va,destination:qO}).strict()]),GO=I(["validated","authenticated","transferred","updated-local-repository","checked-out","cleaned-up"]),fr=I(["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","UNKNOWN"]),Fn=e=>g({code:I(e),message:Yt(Ei)}).strict(),_O=g({step:I(["fetch","pull","push"]),status:I(["succeeded","skipped","conflicted","failed","cancelled"]),error:g({code:fr,message:Yt(Ei)}).strict().optional()}).strict(),xb=I(["succeeded","authorization-required","invalid","client-missing","failed","cancelled","not-needed"]),KO=["cancelled","invalid","client-missing","authorization-required","failed"],cu=g({path:Sb,status:xb,endpoint:Va.optional(),error:g({code:fr,message:Yt(Ei)}).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"})}),Pb=g({status:xb,submodules:z(cu).max(256),lfs:z(cu).max(256)}).strict().superRefine((e,t)=>{const s=[...e.submodules,...e.lfs].map(n=>n.status);let a="succeeded";!s.length||s.every(n=>n==="not-needed")?a="not-needed":a=KO.find(n=>s.includes(n))??"succeeded",e.status!==a&&t.addIssue({code:"custom",message:"Git hydration summary does not match its results"})}),ZO=g({status:I(["pending","ready","failed"]),phase:I(["directory-created","git-ready","setup-ready"]).optional(),error:Yt(Ei).nullable(),errorCode:fr.optional(),updatedAt:v().int().safe().nonnegative(),hydration:Pb.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"})}),ep=g({error:Yt(Ei),code:fr}).strict(),Ss={operationId:Cb,runtimeIdentity:VO,transport:WO,target:HO,completedSteps:z(GO),stepResults:z(_O).length(3).optional(),hydration:Pb.optional()},JO=ve("state",[g({...Ss,state:k("planned")}).strict(),g({...Ss,state:k("running")}).strict(),g({...Ss,state:k("succeeded")}).strict(),g({...Ss,state:k("partial"),error:Fn(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),g({...Ss,state:k("failed"),error:Fn(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),g({...Ss,state:k("cancelled"),error:Fn(["CANCELLED","TIMEOUT"])}).strict(),g({...Ss,state:k("outcome-unknown"),error:Fn(["OUTCOME_UNKNOWN"])}).strict(),g({...Ss,state:k("conflicted"),error:Fn(["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",a=e.state!=="planned"&&e.state!=="running";s&&a&&e.stepResults===void 0&&t.addIssue({code:"custom",message:"Sync operation result is missing step results"});for(const n of e.stepResults??[])(n.status!=="succeeded"&&n.status!=="skipped")!==(n.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"})}),Tb=e=>e.trim(),Li=(e,t)=>JSON.stringify([e,Tb(t)]),br=(e,t,s)=>JSON.stringify([e,Tb(t),s??"full"]),Pi=(e,t)=>vb.get(Li(e,t))??0,tp=(e,t)=>{const s=Li(e,t);vb.set(s,Pi(e,t)+1);for(const a of[void 0,"light"]){const n=br(e,t,a);xi.delete(n),qa.delete(n)}},QO=(e,t,s)=>JSON.stringify([e,t,s]),sp=(e=Date.now())=>{for(const[t,s]of Bt){const a=s.terminalState?IO:RO;s.observedAt<=e-a&&Bt.delete(t)}for(;Bt.size>AO;){let t=null;for(const[s,a]of Bt)a.terminalState&&(!t||a.observedAt<t.observedAt)&&(t={key:s,observedAt:a.observedAt});if(!t)for(const[s,a]of Bt)(!t||a.observedAt<t.observedAt)&&(t={key:s,observedAt:a.observedAt});if(!t)return;Bt.delete(t.key)}},El=(e,t,s)=>{sp();for(const[a,n]of Bt)if(n.runtimeKey===e&&n.operationId===t&&(!s||n.runtimeIdentity.id===s))return{key:a,value:n};return null},$O=(e,t)=>{let s=null;for(const[a,n]of Bt)if(n.runtimeKey===e&&n.operationId===t){if(s)return;s=a}s&&Bt.delete(s)},YO=(e,t)=>{sp();const s=Date.now();for(const a of Bt.values())a.runtimeKey===e&&a.operationId===t&&!a.terminalState&&(a.observedAt=s)},_t=(e,t)=>JSON.stringify(e)===JSON.stringify(t),XO=e=>JSON.stringify(e,(t,s)=>{if(t==="forceWithLease")return;if(t!=="displayUrl")return s;const a=p().safeParse(s);if(!a.success||a.data.includes("://"))return s;const n=a.data.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/);return n?`${n[1]}:${n[2]}`:a.data}),eD=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(/[?#].*$/,"")}},tD=(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 n={...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:n};if(!_t(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 n=t.target;if(n.operation!=="checkout-hydration"||!_t({repositoryId:n.repositoryId,bindingRevision:n.bindingRevision,configRevision:n.configRevision,remote:n.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 n=t.target;if(n.operation!=="clone")throw new Error("Malformed Git network operation plan response");const i=e.destinationPath.trim().split(/[\\/]/).filter(Boolean).at(-1);if(n.remote.displayUrl!==eD(e.remoteUrl)||n.destination.displayName!==i)throw new Error("Malformed Git network operation plan response");return}if(e.operation==="delete-remote-branch"){if(!_t(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 n=t.target;if(n.operation!=="fetch"||n.fetchScope!=="remote"||!_t(n,{operation:"fetch",fetchScope:"remote",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,force:n.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},a=e.operation==="fetch"?{operation:"fetch",fetchScope:e.fetchScope,...s}:{operation:e.operation,...s};if(e.operation==="push"&&e.forceWithLease&&Object.assign(a,{forceWithLease:e.forceWithLease}),e.operation==="push"&&e.configureUpstream&&Object.assign(a,{configureUpstream:!0}),!_t(t.target,a))throw new Error("Malformed Git network operation plan response")},sD=e=>e.target.operation==="clone"?!1:e.state==="succeeded"?!0:e.completedSteps.includes("transferred")||e.completedSteps.includes("updated-local-repository"),Ll=(e,t,s=!1)=>"fetch"in e||"fetch"in t?"fetch"in e&&"fetch"in t&&Ll(e.fetch,t.fetch,s)&&Ll(e.push,t.push,s):e.mode===t.mode&&_t(e.verification,t.verification)&&(e.mode!=="managed"||t.mode==="managed"&&(!e.actor||s&&!t.actor||_t(e.actor,t.actor)));mO(e=>{tp(D(),e),$o.delete(Li(D(),e))});const wn=e=>{fb(e)},Ae=async(e,t)=>{const s=await t.json();return wn(e),s};function F(e,t,s){const a={...s};return t&&(a.directory=t),ds().api(e,a)}const aD=15,lu=200,nD=e=>e==="worktrees"?`${O}/project-worktrees`:`${O}/projects`,iD=(e,t)=>JSON.stringify(e==="status"||e==="root"?{directories:t,fields:[e]}:{directories:t}),oD=(e,t)=>`${e}\0${yt(t)??""}`,ni=new Map,du=async e=>{const t=ni.get(e);if(ni.delete(e),!t)return;if(t.runtimeKey!==D()){const r=new Error("Runtime changed before project repository batch was sent");for(const c of t.waiters.values())for(const l of c)l.reject(r);return}const s=[...t.waiters.keys()],a=new Map;for(const r of s)a.set(r,Pi(t.runtimeKey,r));const n=nD(t.field),i=new Map,o=[];for(let r=0;r<s.length;r+=lu)o.push(s.slice(r,r+lu));await Promise.all(o.map(async r=>{try{const c=await C(F(n,r[0]),{method:"POST",headers:{"Content-Type":"application/json"},body:iD(t.field,r)});if(!c.ok)throw new Error(`Failed to read project repositories: ${c.statusText}`);const l=await c.json();for(const d of l?.projects??[])i.set(d.directory,d)}catch(c){const l=c instanceof Error?c.message:"Failed to read project repositories";for(const d of r)i.set(d,{directory:d,error:l})}}));for(const[r,c]of i)typeof c.isGitRepository=="boolean"&&$o.set(Li(t.runtimeKey,r),{value:c.isGitRepository,expiresAt:Date.now()+yb}),c.status&&Pi(t.runtimeKey,r)===a.get(r)&&xi.set(br(t.runtimeKey,r,void 0),{value:c.status,expiresAt:Date.now()+kb});for(const[r,c]of t.waiters){const l=i.get(r)??null;for(const d of c)l?l.error?d.reject(l.code===$d?new bb(l.error):new Error(l.error)):l.errors?.includes(t.field)?d.reject(new Error(`Failed to read project ${t.field}`)):d.resolve(l):d.reject(new Error("Project repository read missing from batch response"))}},wr=(e,t)=>{const s=D(),a=oD(t,e),n=ni.get(a);n&&n.runtimeKey!==s&&du(a);let i=ni.get(a);i||(i={runtimeKey:s,field:t,waiters:new Map,timer:null},ni.set(a,i));const o=i;return new Promise((r,c)=>{const l=o.waiters.get(e)??[];l.push({resolve:r,reject:c}),o.waiters.set(e,l),o.timer===null&&(o.timer=setTimeout(()=>{du(a)},aD))})};async function rD(e){const t=D(),s=Date.now(),a=e.filter(n=>{const i=br(t,n,void 0),o=xi.get(i);return!(o&&o.expiresAt>s)&&!qa.has(i)});await Promise.allSettled(a.map(n=>wr(n,"status")))}async function cD(e){const t=Li(D(),e),s=Date.now(),a=$o.get(t);if(a&&a.expiresAt>s)return a.value;const n=fo.get(t);if(n)return n;const i=(async()=>{const r=(await wr(e,"repo")).isGitRepository===!0;return $o.set(t,{value:r,expiresAt:Date.now()+yb}),r})();fo.set(t,i);try{return await i}finally{fo.get(t)===i&&fo.delete(t)}}class lD extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function FU(e){const t=await C("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new lD;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(a=>ze(a?.path??null)).filter(a=>a!==null)}async function dD(e,t){const s=t?.mode,a=D();t?.fresh&&tp(a,e);const n=br(a,e,s),i=Date.now(),o=xi.get(n);if(o&&o.expiresAt>i)return o.value;const r=qa.get(n);if(r)return r;const c=(async()=>{const l=Pi(a,e),d=await C(F(`${O}/status`,e,s?{mode:s}:void 0));if(!d.ok){const m=CO.safeParse(await d.json().catch(()=>null));throw m.success?new bb(m.data.error):new Error(`Failed to get git status: ${d.statusText}`)}const u=await d.json();return Pi(a,e)===l&&xi.set(n,{value:u,expiresAt:Date.now()+kb}),u})();qa.set(n,c);try{return await c}finally{qa.get(n)===c&&qa.delete(n)}}async function BU(e){const t=await wr(e,"root");return{root:t.root?t.root:e}}async function NU(e){const t=await C(F(`${O}/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 MU(e){const t=await C(F(`${O}/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 EU(e,t){const s=await C(F(`${O}/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 a=await s.json().catch(()=>({}));return{commits:Array.isArray(a.commits)?a.commits.map(n=>({sha:typeof n.sha=="string"?n.sha:"",short:typeof n.short=="string"?n.short:"",subject:typeof n.subject=="string"?n.subject:""})).filter(n=>n.sha&&n.short):[]}}async function pD(e,t){const{path:s,staged:a,contextLines:n}=t;if(!s)throw new Error("path is required to fetch git diff");const i=await C(F(`${O}/diff`,e,{path:s,staged:a?"true":void 0,context:n}));if(!i.ok)throw await Yd(i,"Failed to get git diff");return PO.parse(await i.json())}const pu=1e3;async function gD(e,t){const{paths:s,staged:a,contextLines:n}=t,i=[];for(let o=0;o<s.length;o+=pu){const r=await C(F(`${O}/diffs`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s.slice(o,o+pu),staged:a===!0,context:n})});if(!r.ok)throw await Yd(r,"Failed to get git diffs");for(const c of TO.parse(await r.json()).diffs)i.push("diff"in c?{path:c.path,ok:!0,diff:{diff:c.diff,submodule:c.submodule}}:{path:c.path,ok:!1,error:c.error,reason:c.code})}return i}async function uD(e,t){const{base:s,head:a,path:n,contextLines:i,includeWorkingTree:o}=t;if(!s||!a)throw new Error("base and head are required to fetch git range diff");const r=await C(F(`${O}/range-diff`,e,{base:s,head:a,path:n||void 0,context:i,includeWorkingTree:o}));if(!r.ok)throw await Mi(r,"Failed to get git range diff");return wb.parse(await r.json())}async function mD(e,t){const s=await C(F(`${O}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!s.ok)throw await Mi(s,"Failed to get commit diff");return wb.parse(await s.json())}async function hD(e,t){const{base:s,head:a,includeWorkingTree:n}=t;if(!s||!a)throw new Error("base and head are required to fetch git range files");const i=await C(F(`${O}/range-files`,e,{base:s,head:a,includeWorkingTree:n}));if(!i.ok)throw await Mi(i,"Failed to get git range files");return yO.parse(await i.json()).files}async function fD(e,t){if(!t)throw new Error("branch is required to get branch base");const s=await C(F(`${O}/branch-base`,e,{branch:t}));if(!s.ok)throw new Error(`Failed to get branch base: ${s.statusText}`);return s.json()}async function bD(e,t){const{path:s,staged:a}=t;if(!s)throw new Error("path is required to fetch git file diff");const n=await C(F(`${O}/file-diff`,e,{path:s,staged:a?"true":void 0}));if(!n.ok)throw await Yd(n,"Failed to get git file diff");return zO.parse(await n.json())}async function wD(e,t,s){if(!t)throw new Error("path is required to revert git changes");const a=await C(F(`${O}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:s?.scope})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to revert git changes")}wn(e)}async function kD(e,t){await zb(e,[t])}async function zb(e,t){const s=t.map(n=>n.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to stage git changes");const a=await C(F(`${O}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to stage git changes")}wn(e)}async function yD(e,t){await Ab(e,[t])}async function Ab(e,t){const s=t.map(n=>n.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to unstage git changes");const a=await C(F(`${O}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to unstage git changes")}wn(e)}async function vD(e,t,s){await ap(e,t,s,"stage")}async function CD(e,t,s){await ap(e,t,s,"unstage")}async function SD(e,t,s){await ap(e,t,s,"discard")}async function ap(e,t,s,a){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 n=await C(F(`${O}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:s,action:a})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to apply git hunk")}wn(e)}async function xD(e){if(!e)return!1;const t=await C(F(`${O}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function PD(e,t){const s=await C(F(`${O}/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 TD(e,t){const s=await C(F(`${O}/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 zD(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const s=await C(F(`${O}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to delete branch")}return Ae(e,s)}async function AD(e,t){const s=t?.remote?.trim();if(!s)throw new Error("remote is required to remove a remote");const a=await C(F(`${O}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to remove remote")}return Ae(e,a)}async function RD(e,t,s){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const a={files:t};s?.zenModel&&(a.zenModel=s.zenModel),s?.providerId&&(a.providerId=s.providerId),s?.modelId&&(a.modelId=s.modelId);const n=await C(F(`${O}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok){const c=await n.json().catch(()=>({error:n.statusText}));console.error("[git-generation][browser] http error",{status:n.status,statusText:n.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const i=await n.json();if(!i?.message||typeof i.message!="object")throw new Error("Malformed commit generation response");const o=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(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:o,highlights:r}}}async function ID(e,t){const{base:s,head:a,context:n,zenModel:i,providerId:o,modelId:r}=t;if(!s||!a)throw new Error("base and head are required");const c={base:s,head:a};n?.trim()&&(c.context=n.trim()),i&&(c.zenModel=i),o&&(c.providerId=o),r&&(c.modelId=r);const l=await C(F(`${O}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const f=await l.json().catch(()=>({error:l.statusText}));throw new Error(f.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),u=typeof d?.title=="string"?d.title:"",m=typeof d?.body=="string"?d.body:"";if(!u&&!m)throw new Error("Malformed PR description response");return{title:u,body:m}}async function gu(e){return(await wr(e,"worktrees")).worktrees??[]}async function uu(e,t){const s=await C(F(`${O}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to validate worktree")}return s.json()}async function jD(e){const t=await C(F(`${O}/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 ZO.parse(await t.json())}async function OD(e,t){const s=await C(F(`${O}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to preview worktree")}return s.json()}async function mu(e,t){const s=await C(F(`${O}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const a=g({error:p().optional(),code:p().optional(),remoteName:p().optional()}).strict().parse(await s.json().catch(()=>({error:s.statusText})));throw new Jd(a.code||"UNKNOWN",a.error||"Failed to create worktree",s.status,a.remoteName)}return s.json()}async function hu(e,t){const s=await C(F(`${O}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});return s.ok||await Rb(s,"Failed to delete worktree"),s.json()}async function DD(e,t){const s=await C(F(`${O}/worktrees/teardown`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return s.ok||await Rb(s,"Failed to tear down worktree"),s.json()}const Rb=async(e,t)=>{const s=g({error:p().optional(),code:p().optional()}).catch({}).parse(await e.json().catch(()=>null)),a=s.error||e.statusText||t;throw s.code?new Jd(s.code,a,e.status):new Error(a)},FD=g({title:p(),branch:p()});async function BD(e,t,s="user"){const a=await C(F(`${O}/worktrees/title`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t,by:s})}),n=await a.json().catch(()=>null);if(!a.ok){const o=g({error:p()}).safeParse(n).data?.error;throw new Error(o||"Failed to rename the task")}const i=FD.safeParse(n);if(!i.success)throw new Error("Malformed task title response");return i.data}const ND=g({pinned:T(),branch:p()});async function MD(e,t,s=null){const a=await C(F(`${O}/worktrees/pin`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s?{pinned:t,list:s}:{pinned:t})}),n=await a.json().catch(()=>null);if(!a.ok){const o=g({error:p()}).safeParse(n).data?.error;throw new Error(o||"Failed to pin the task")}const i=ND.safeParse(n);if(!i.success)throw new Error("Malformed pin response");return i.data}const Ib=g({id:p().min(1),ref:p().min(1),commit:p().min(1),head:p(),path:p().min(1),branch:p(),branchExists:T(),title:p(),archivedAt:v(),sessionIds:z(p())}),kr=async(e,t,s,a,n)=>{const i=await C(F(`${O}/worktrees/archives${e}`,t),{...s,headers:s.body?{"Content-Type":"application/json"}:void 0});if(!i.ok){const o=g({error:p().optional(),code:p().optional()}).catch({}).parse(await i.json().catch(()=>null)),r=o.error||i.statusText||n;throw o.code?new Jd(o.code,r,i.status):new Error(r)}return a.parse(await i.json())},ED=(e,t)=>kr("",e,{method:"POST",body:JSON.stringify(t)},Ib,"Failed to archive worktree"),LD=async e=>(await kr("",e,{method:"GET"},g({archives:z(Ib)}),"Failed to list worktree archives")).archives,qD=(e,t)=>kr("/restore",e,{method:"POST",body:JSON.stringify({id:t})},g({id:p(),conflicts:T()}),"Failed to restore worktree archive"),VD=(e,t)=>kr("",e,{method:"DELETE",body:JSON.stringify(t)},g({id:p(),branchDeleted:T()}),"Failed to delete worktree archive"),UD=g({ref:p(),commit:p().min(1),head:p().min(1)});async function WD(e,t){const s=await C(F(`${O}/worktrees/snapshot`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to snapshot worktree")}return UD.parse(await s.json())}async function HD(e,t,s={}){const a=await C(F(`${O}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:s.addAll??!1,files:s.files,stageFiles:s.stageFiles})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to create commit")}return Ae(e,a)}async function GD(e,t={}){const s=D(),a=await C(F(`${O}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){const i=await a.json().catch(()=>({error:a.statusText}));throw new Error(i.error||"Failed to push")}const n=await Ae(e,a);return n.success&&fO(e,s),n}async function _D(e,t={}){const s=await C(F(`${O}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to pull")}return Ae(e,s)}async function KD(e,t={}){const s=await C(F(`${O}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to fetch")}return Ae(e,s)}const jb=async(e,t,s)=>{const a=await C(e,t);if(!a.ok){const n=ep.parse(await a.json());throw n.code==="NOT_FOUND"&&s&&$O(s.runtimeKey,s.operationId),new Zd(n.code,n.error,a.status)}return JO.parse(await a.json())},ZD=(e,t,s)=>{if(s.operationId!==e)throw new Error("Malformed Git network operation response");const a=El(t,e,s.runtimeIdentity.id);if(!a&&El(t,e))throw new Error("Malformed Git network operation response");if(a){const n=a.value.transport,i=s.state!=="planned"&&s.state!=="running",o=_t(a.value.target,s.target)||i&&XO(a.value.target)===JSON.stringify(s.target);if(!_t(a.value.runtimeIdentity,s.runtimeIdentity)||!o||!Ll(n,s.transport,i))throw new Error("Malformed Git network operation response");if(a.value.terminalState&&(s.state==="planned"||s.state==="running"||s.state!==a.value.terminalState))throw new Error("Malformed Git network operation response");_t(n,s.transport)===!1&&(a.value.transport=s.transport),s.state!=="planned"&&s.state!=="running"?a.value.terminalState||(sD(s)&&(tp(a.value.runtimeKey,a.value.directory),a.value.runtimeKey===D()&&fb(a.value.directory)),a.value.terminalState=s.state,a.value.observedAt=Date.now()):a.value.observedAt=Date.now()}if(D()!==t)throw new Error("Git network operation response belongs to a stale runtime");return s};async function JD(e){const t=D(),s=await jb(`${O}/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(D()!==t)throw new Error("Git network operation response belongs to a stale runtime");tD(e,s);const a=QO(t,s.runtimeIdentity.id,s.operationId);if(El(t,s.operationId,s.runtimeIdentity.id)?.value.terminalState)throw new Error("Malformed Git network operation plan response");return Bt.set(a,{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()}),sp(),s}async function QD(e){const t=await C(`${O}/contributor-destinations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const s=ep.parse(await t.json());throw new Zd(s.code,s.error,t.status)}return BO.parse(await t.json())}async function $D(e){const t=D(),s=await C(F(`${O}/contributor-destinations`,e));if(!s.ok){const n=ep.parse(await s.json());throw new Zd(n.code,n.error,s.status)}const a=MO.parse(await s.json());if(D()!==t)throw new Error("Contributor destinations belong to a stale runtime");return a}async function YD(e){const t=await C(F(`${O}/worktrees/checkout-trust`,e));if(!t.ok)throw new Error((await t.json()).error||"Failed to inspect checkout actions");return EO.parse(await t.json())}async function XD(e,t,s){const a=await C(F(`${O}/worktrees/checkout-trust`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({digest:t,decision:s})});if(!a.ok)throw new Error((await a.json()).error||"Failed to apply checkout trust decision");return g({state:p().min(1)}).passthrough().parse(await a.json())}const np=async(e,t)=>{const s=D();YO(s,e);const a=t?`/${t}`:"",n=t?{method:"POST"}:void 0,i=await jb(`${O}/network-operations/${encodeURIComponent(e)}${a}`,n,{runtimeKey:s,operationId:e});return ZD(e,s,i)};async function eF(e){return np(e,"execute")}async function tF(e){return np(e)}async function sF(e){return np(e,"cancel")}async function aF(e){const t=await C(F(`${O}/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 nF(e,t){const s=await C(F(`${O}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to count stash files")}return s.json()}async function Ob(e,t={}){const s=await C(F(`${O}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to stash changes")}return Ae(e,s)}const ip=async(e,t,s)=>{const a=await C(F(`${O}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||`Failed to ${t}`)}return Ae(e,a)},iF=(e,t)=>ip(e,"stash/apply",t),Db=(e,t)=>ip(e,"stash/pop",t),oF=(e,t)=>ip(e,"stash/drop",t);async function rF(e,t){const s=await C(F(`${O}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to checkout branch")}return Ae(e,s)}async function cF(e,t,s){const a=await C(F(`${O}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to create branch")}return Ae(e,a)}async function lF(e,t,s){const a=await C(F(`${O}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to rename branch")}return Ae(e,a)}async function dF(e,t={}){const s=await C(F(`${O}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(`Failed to get git log: ${a.error||s.statusText}`)}return xO.parse(await s.json())}const pF=g({sha:p().regex(/^[0-9a-f]{40}$/),changeId:p().regex(/^I[0-9a-f]{40}$/)});async function gF(e,t){const s=await C(F(`${O}/change-id`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedHead:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to add a Change-Id")}return wn(e),pF.parse(await s.json())}async function uF(e,t){const s=await C(F(`${O}/commit-files`,e,{hash:t}));if(!s.ok)throw await Mi(s,"Failed to get commit files");return SO.parse(await s.json())}async function LU(e,t){const{base:s,head:a,path:n,previousPath:i,includeWorkingTree:o}=t,r=await C(F(`${O}/range-file-versions`,e,{base:s,head:a,path:n,previousPath:i,includeWorkingTree:o?"true":void 0}));if(!r.ok)throw await Mi(r,"Failed to read file versions");return kO.parse(await r.json())}async function mF(e,t,s,a,n){const i=await C(F(`${O}/commit-file-diff`,e,{hash:t,path:s,binary:a?"true":void 0,previousPath:n}));if(!i.ok)throw new Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function hF(){const e=await C(F(`${O}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return gO.parse(await e.json())}async function fF(e){const t=cn.parse(e),s=await C(F(`${O}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to create git identity")}return cn.parse(await s.json())}async function bF(e,t){const s=cn.parse(t);if(s.id!==e)throw new Error("Git identity profile ID does not match the update target");const a=await C(F(`${O}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to update git identity")}return cn.parse(await a.json())}async function wF(e){const t=await C(F(`${O}/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 kF(e){if(!e)return null;const t=await C(F(`${O}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const s=await t.json();return s?hb.parse(s):null}async function yF(e){if(!e)return!1;const t=await C(F(`${O}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function vF(){const e=await C(F(`${O}/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=hb.parse(t);return s.userName||s.userEmail?s:null}async function CF(e,t){const s=await C(F(`${O}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to set git identity")}return uO.parse(await s.json())}async function SF(e){const t=await C(F(`${O}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return FO.parse(await t.json())}async function xF(e,t){const s=await C(F(`${O}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to rebase")}return Ae(e,s)}async function PF(e){const t=await C(F(`${O}/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 Ae(e,t)}async function TF(e,t){const s=await C(F(`${O}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to merge")}return Ae(e,s)}async function zF(e,t){const s=await C(F(`${O}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to checkout commit")}return Ae(e,s)}async function AF(e,t){const s=await C(F(`${O}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to cherry-pick")}return Ae(e,s)}async function RF(e,t){const s=await C(F(`${O}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to revert commit")}return Ae(e,s)}async function IF(e,t,s,a){const n=await C(F(`${O}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:s,force:a})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to reset")}return Ae(e,n)}async function jF(e){const t=await C(F(`${O}/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 Ae(e,t)}async function OF(e){const t=await C(F(`${O}/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 Ae(e,t)}async function DF(e){const t=await C(F(`${O}/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 Ae(e,t)}async function FF(e,t){return await Ob(e,{message:t?.message}),{success:!0}}async function BF(e){return await Db(e,{ref:"stash@{0}"}),{success:!0}}async function NF(e){const t=await C(F(`${O}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function MF(e,t){const s=await C(`${O}/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 EF(e){const t=await C(`${O}/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 LF=/^[a-z][a-z0-9-]{0,31}$/,Fb=e=>Object.prototype.toString.call(e)==="[object String]"&&LF.test(e),qF=e=>Object.prototype.toString.call(e)==="[object String]"&&/^[\x20-\x39\x3b-\x7e]{1,256}$/.test(e)&&e.trim()===e,Bb=e=>e!==null&&Object.prototype.toString.call(e)==="[object Object]"&&Object.getPrototypeOf(e)===Object.prototype,VF=e=>Object.prototype.toString.call(e)==="[object String]",ht=e=>VF(e)&&e.length>0,fu=(e,t=512)=>ht(e)&&e.length<=t&&e.trim()===e&&!/[\0\r\n]/.test(e),UF=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/,WF=e=>{const t=e.toLowerCase();return t==="localhost"||t==="::1"||t==="[::1]"||UF.test(t)},HF=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=WF(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!1}},GF=e=>e.providerUserId.startsWith(`${e.instance}#`)&&/^\d+$/.test(e.providerUserId.slice(e.instance.length+1)),rs=(e,t,s=[])=>Bb(e)&&t.every(a=>Object.hasOwn(e,a))&&Object.keys(e).every(a=>t.includes(a)||s.includes(a)),bu=e=>{let t;try{t=decodeURIComponent(e)}catch{return!1}const s=t.replace(/^\/+|\/+$/g,"");return!!(s&&!/[\0\r\n]/.test(s)&&!s.split("/").some(a=>!a||a==="."||a===".."))},_F=e=>{if(!ht(e)||e.trim()!==e||e.length>4096||/[\0\r\n]/.test(e))return!1;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("-")&&bu(`/${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&&bu(t.pathname)}catch{return!1}},ql=e=>rs(e,["displayUrl","fingerprint"])&&_F(e.displayUrl)&&ht(e.fingerprint)&&e.fingerprint.length<=128&&/^[A-Za-z0-9_-]+$/.test(e.fingerprint),bo=ql,wu=e=>["managed","system","anonymous"].includes(e.mode)&&(e.mode==="managed"?ht(e.credentialId):!Object.hasOwn(e,"credentialId")),KF=e=>Bb(e)&&Object.hasOwn(e,"status")&&(e.status==="unavailable"&&rs(e,["status"])||e.status==="available"&&(rs(e,["status","transport","fingerprint"])&&e.transport==="ssh"&&/^SHA256:[A-Za-z0-9+/]{43}=?$/.test(e.fingerprint)||rs(e,["status","transport","provider","instance","source","username","providerUserId"])&&e.transport==="https"&&Fb(e.provider)&&["oauth","pat","cli"].includes(e.source)&&fu(e.instance,2048)&&qF(e.username)&&fu(e.providerUserId)&&HF(e)&&GF(e))),xc=(e,t)=>new Set(e.map(t)).size===e.length,Bn=()=>Object.assign(new Error("Source control binding storage is invalid"),{code:"INVALID_SOURCE_CONTROL_BINDINGS"}),ZF=(e,t=!1)=>{if(!rs(e,["repositoryId","revision","state","configRevision","providers","remotes"],["auxiliary"])||!ht(e.repositoryId)||!Number.isSafeInteger(e.revision)||e.revision<1||!ht(e.configRevision)||!["bound","needs-attention"].includes(e.state)||!Array.isArray(e.providers)||!Array.isArray(e.remotes)||!Array.isArray(e.auxiliary))throw Bn();for(const s of e.providers)if(!rs(s,["provider","instance","accountId","primaryRemote","readiness","endpoint"],["repository"])||!Fb(s.provider)||!ht(s.instance)||!ht(s.accountId)||!ht(s.primaryRemote)||s.repository!==void 0&&(!rs(s.repository,["owner","name"])||!ht(s.repository.owner)||!ht(s.repository.name))||!["ready","confirmation-required","account-unavailable","config-changed"].includes(s.readiness)||!(s.endpoint===null&&s.readiness!=="ready"||bo(s.endpoint)))throw Bn();for(const s of e.remotes)if(!rs(s,["name","fetch","push","mode","readiness"],["credentialId",...t&&s.mode==="managed"?["presentation"]:[],...t?["inherited"]:[]])||!ht(s.name)||!bo(s.fetch)||!bo(s.push)||!wu(s)||s.presentation!==void 0&&!KF(s.presentation)||s.inherited!==void 0&&(s.inherited!==!0||s.readiness!=="ready")||s.mode==="anonymous"&&!s.fetch.displayUrl.startsWith("https://")||!["ready","confirmation-required","config-changed"].includes(s.readiness))throw Bn();for(const s of e.auxiliary??[])if(!rs(s,["kind","endpoint","mode","readiness"],["credentialId"])||!["submodule","lfs"].includes(s.kind)||!bo(s.endpoint)||!wu(s)||s.mode==="anonymous"&&!s.endpoint.displayUrl.startsWith("https://")||!["ready","confirmation-required"].includes(s.readiness))throw Bn();if((e.auxiliary?.length??0)>256||!xc(e.remotes,s=>s.name)||!xc(e.providers,s=>`${s.provider}\0${s.instance}\0${s.primaryRemote}`)||!xc(e.auxiliary??[],s=>`${s.kind}\0${s.endpoint.fingerprint}`))throw Bn()},JF=e=>[...e.providers,...e.remotes,...e.auxiliary].some(t=>t.readiness!=="ready")?"needs-attention":"bound",QF=e=>(ZF(e,!0),structuredClone(e)),$F=(e,t)=>{const s=new Map(t.remotes.map(o=>[o.name,o])),a=e.providers.map(o=>o.readiness==="ready"&&o.endpoint?.fingerprint!==s.get(o.primaryRemote)?.fetch.fingerprint?{...o,readiness:"config-changed"}:o),n=e.remotes.map(o=>{const r=s.get(o.name);return o.readiness==="ready"&&(!r||o.fetch.fingerprint!==r.fetch.fingerprint||o.push.fingerprint!==r.push.fingerprint)?{...o,readiness:"config-changed"}:o}),i={...e,providers:a,remotes:n};return i.state=JF(i),i},ku={referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1},Nb=[{id:"github",label:"GitHub",order:0,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"github",filledSprite:"github-fill"},repository:{nestedNamespaces:!1},instances:{format:"host",defaultInstance:"github.com",multiple:!0,allowLoopbackHttp:!1,allowPort:!1,reserved:["github.com"],placeholder:"https://github.example.com",legacyFlow:{instance:"github.com",kind:"github-com-device"}},auth:{methods:["device","pat","cli"],cliName:"gh",cliTransport:!0,token:{scopes:["repo","read:org","workflow","read:user","user:email"],createPath:"/settings/tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:!1},{id:"token",kind:"personal-access-token",secret:!0}]},urls:{changeRequest:["/{owner}/{repo}/pull/{number}"],issue:["/{owner}/{repo}/issues/{number}"],commit:["/{owner}/{repo}/commit/{sha}"],user:["/{user}"]},features:{...ku,referenceSearch:!0,referenceDetail:!0,listStatuses:!0,referencesAcross:!0,issueCloseReason:!0,changeRequestPatch:!0}},{id:"gitlab",label:"GitLab",order:1,terminology:{changeRequest:"mergeRequest",changeRequestPrefix:"!",issuePrefix:"#",sharedNumberSpace:!1,abbreviation:"MR",promptNoun:"merge request",ci:"pipeline"},icon:{sprite:"gitlab"},repository:{nestedNamespaces:!0},instances:{format:"origin",defaultInstance:"https://gitlab.com",multiple:!0,allowLoopbackHttp:!0,allowPort:!0,reserved:[],placeholder:"https://gitlab.example.com"},auth:{methods:["device","pat","cli"],cliName:"glab",cliTransport:!1,token:{scopes:["api"],createPath:"/-/user_settings/personal_access_tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:!1},{id:"token",kind:"personal-access-token",secret:!0}]},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:{...ku,startThread:!0,authorCanReview:!0,projectUploads:!0,changeRequestPatch:!0,changeRequestTemplates:[".gitlab/merge_request_templates/Default.md"]}}],kn=(e,t)=>`/api/source-control/${e.provider}${t}`,YF=g({providers:z(ee())}),XF=g({error:p()}),eB=async e=>{const t=await e("/api/source-control/providers",{headers:{Accept:"application/json"}});if(t.status===404)return wl.parse(Nb);const s=await t.json().catch(()=>null);if(!t.ok){const i=XF.safeParse(s);throw new Error(i.success&&i.data.error||t.statusText||"Failed to load source control providers")}const a=YF.parse(s).providers,n=wl.parse(a);if(a.length>0&&n.length===0)throw new Error("Source control providers response contained no readable provider");return n},Mb=g({state:I(["success","failure","pending","unknown"]),total:v(),success:v(),failure:v(),pending:v(),inProgress:v().optional(),queued:v().optional(),startedAt:p().optional()}),Pc={number:v(),title:p(),url:p(),body:p(),bodyTruncated:T(),createdAt:p().nullable(),updatedAt:p().nullable(),author:g({login:p(),avatarUrl:p().optional()}).nullable(),labels:z(g({name:p(),color:p().optional()})),commentCount:v(),sourceRepo:g({owner:p(),repo:p(),source:p()})},Eb=ve("kind",[g({kind:k("issue"),...Pc,state:I(["open","completed","not_planned"])}),g({kind:k("pull"),...Pc,state:I(["open","closed","merged"]),draft:T(),head:p(),base:p(),headSha:p(),headRepo:g({owner:p(),repo:p(),url:p(),cloneUrl:p().optional(),sshUrl:p().optional()}).nullable()}),g({kind:k("discussion"),...Pc,state:I(["open","resolved","outdated","duplicate"]),answered:T().nullable(),upvotes:v(),locked:T(),category:g({name:p(),emoji:p().nullable(),answerable:T()})})]),tB=ve("connected",[g({connected:k(!1)}),g({connected:k(!0),repo:g({owner:p(),repo:p(),url:p()}).nullable(),items:z(Eb),cursor:p().nullable(),hasMore:T(),total:v()})]),yu={author:g({login:p(),avatarUrl:p().optional()}).nullable(),body:p(),createdAt:p().nullable(),url:p(),path:p().nullable(),line:v().nullable(),review:I(["approved","changes_requested","commented","dismissed"]).nullable(),excerpt:g({startLine:v().int().positive(),lines:z(p()).max(200)}).optional().catch(void 0)},sB=ve("connected",[g({connected:k(!1)}),g({connected:k(!0),detail:g({number:v(),comments:z(g({...yu,thread:g({id:p().min(1),resolved:T(),canResolve:T(),canReply:T(),replies:z(g(yu))}).optional(),answer:g({chosen:T(),canChange:T()}).optional()})),commentTotal:v(),pull:g({reviewDecision:I(["approved","changes_requested","review_required"]).nullable(),reviewers:z(g({id:p(),login:p(),avatarUrl:p().optional()})).default([]),checks:Mb.nullable().optional(),additions:v(),deletions:v(),changedFiles:v(),commits:z(g({sha:p(),headline:p(),author:g({login:p(),avatarUrl:p().optional()}).nullable(),authorName:p().nullable(),committedAt:p().nullable(),url:p().nullable()})).default([]),commitTotal:v().nullable().default(null),stack:g({number:v().nullable(),base:p(),layers:z(g({number:v(),title:p(),url:p(),state:I(["open","closed","merged"]),draft:T(),head:p()}))}).nullable().optional().catch(void 0)}).nullable(),discussion:g({canComment:T(),canClose:T(),canReopen:T()}).optional()}).nullable()})]),aB=Ui({items:z(Eb.and(g({directory:p().min(1)}))),cursor:p().nullable(),hasMore:T(),total:v().int().nonnegative(),repositories:z(J([Ui({directory:p().min(1),status:k("included"),repo:Ui({owner:p(),repo:p(),url:p(),host:p().optional()})}),Ui({directory:p().min(1),status:I(["no-repo","disconnected","invalid-context","error"])})]))}),nB=ve("connected",[g({connected:k(!1)}),g({connected:k(!0),statuses:z(g({owner:p(),repo:p(),number:v(),checks:Mb.nullable(),mergeable:T().nullable(),mergeableState:p().nullable()}))})]),iB=g({error:p()}),yr=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},qi=async(e,t,s)=>{const a=await e.json().catch(()=>null);if(!e.ok){const n=iB.safeParse(a);throw new Error(n.success&&n.data.error||e.statusText||s)}return t.parse(a)},oB=async(e,t,s)=>{const a=yr(t);a.set("kind",s.kind),s.state&&a.set("state",s.state),s.people&&a.set("people",s.people),s.query?.trim()&&a.set("query",s.query.trim()),s.cursor&&a.set("cursor",s.cursor);const n=await e(kn(t,"/references"),{query:a,headers:{Accept:"application/json"}}),i=await qi(n,tB,"Failed to load issues and pull requests");return i.connected?{...i,items:i.items.map(o=>({...o,provider:t.provider}))}:i},rB=async(e,t,s)=>{const a=yr(t);a.set("owner",s.owner),a.set("repo",s.repo),a.set("number",String(s.number)),s.kind==="discussion"&&a.set("kind","discussion");const n=s.host?.trim();n&&n!=="github.com"&&a.set("host",n);const i=await e(kn(t,"/references/detail"),{query:a,headers:{Accept:"application/json"}});return qi(i,sB,"Failed to load issue or pull request detail")},vu=g({login:p(),avatarUrl:p().optional()}).nullable(),Cu=I(["old","new"]),cB=ve("connected",[g({connected:k(!1)}),g({connected:k(!0),viewerIsAuthor:T(),headSha:p(),draft:g({id:p(),body:p(),comments:z(g({id:p(),path:p(),side:Cu,line:v().int().nullable(),startLine:v().int().nullable(),body:p(),author:vu}))}).nullable(),threads:z(g({id:p(),path:p(),side:Cu,line:v().int().nullable(),startLine:v().int().nullable(),resolved:T(),canReply:T(),canResolve:T(),comments:z(g({id:p(),body:p(),createdAt:p(),url:p(),author:vu}))})),truncated:T()})]),lB=async(e,t,s)=>{const a=yr(t);a.set("owner",s.owner),a.set("repo",s.repo),a.set("number",String(s.number));const n=await e(kn(t,"/pr/review/state"),{query:a,headers:{Accept:"application/json"}});return qi(n,cB,"Failed to load the review")},dB=async(e,t,s)=>{const[a]=t;if(!a||t.some(o=>o.provider!==a.provider))throw new Error("A search across repositories needs contexts of one provider");const n=await e(kn(a,"/references/across"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({contexts:t,...s,query:s.query?.trim()})}),i=await qi(n,aB,"Failed to load issues and pull requests");return{...i,items:i.items.map(o=>({...o,provider:a.provider}))}},pB=async(e,t,s)=>{const a=yr(t);a.set("pulls",s.map(i=>{const o=i.host?.trim().toLowerCase();return`${i.owner}/${i.repo}#${i.number}${o&&o!=="github.com"?`@${o}`:""}`}).join(","));const n=await e(kn(t,"/references/status"),{query:a,headers:{Accept:"application/json"}});return qi(n,nB,"Failed to load pull request statuses")};class Es extends Error{constructor(t,s){super(t),this.code=s}code}const vr=new Map,Lb=e=>{for(const t of e)vr.set(t.id,{format:t.instances.format,label:t.label,pathStyle:t.repository.pathStyle==="path"})},op=(e,t)=>K(t)&&(t.trim().length>0||t===""&&vr.get(e.provider)?.pathStyle!==!1);Lb(Nb);const Ti=e=>vr.get(e.provider)?.label??e.provider,gB=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 a=["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:"&&a))throw new Error(`Invalid ${Ti(e)} instance: ${e.instance}`);return{provider:e.provider,instance:s.origin}},uB=e=>{const t=e.instance.trim().toLowerCase().replace(/\.$/,"");let s=t;if(t.includes("://"))try{const a=new URL(t);if(a.protocol!=="https:"||a.username||a.password||a.port||a.search||a.hash||a.pathname&&a.pathname!=="/")throw new Error(`Invalid ${Ti(e)} instance: ${e.instance}`);s=a.hostname.toLowerCase().replace(/\.$/,"")}catch{throw new Error(`Invalid ${Ti(e)} instance: ${e.instance}`)}return{provider:e.provider,instance:s}},H=e=>{const t=(vr.get(e.provider)?.format??"origin")==="host"?uB(e):gB(e);return e.instanceSshUrl?.trim()?{...t,instanceSshUrl:e.instanceSshUrl.trim()}:t},qb=e=>{if(!e||!K(e.repositoryId)||!e.repositoryId||!K(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||!K(s.name)||!s.name||!ql(s.fetch)||!ql(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}},Ja=e=>{const t=qb(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=QF(e.binding);if(!s||s.repositoryId!==t.repositoryId||s.revision!==e.revision||!K(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 a=$F({...s,providers:s.providers.map(n=>({...n,...H(n)}))},t);return{status:a.state,repository:t,revision:e.revision,binding:a}},Su=async(e,t,s)=>{const a=await e(t,{query:new URLSearchParams({directory:s}),headers:{Accept:"application/json"}}),n=await a.json();if(!a.ok)throw new Es(n.error||a.statusText||"Source control repository request failed",n.code);return n},mB=async(e,t=C)=>{const s=await t("/api/source-control/binding/transport",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),a=await s.json();if(!s.ok)throw new Es(a.error||"Git transport configuration failed",a.code);return{status:"configured",binding:Ja(a)}},hB=async(e,t=C)=>{const s=await t("/api/source-control/binding/transport/remove",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),a=await s.json();if(!s.ok)throw new Es(a.error||"Git transport removal failed",a.code);return{status:"removed",binding:Ja(a)}},fB=async(e,t=C)=>{const s=await t("/api/source-control/binding/auxiliary",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),a=await s.json();if(!s.ok)throw new Es(a.error||"Git auxiliary transport configuration failed",a.code);return{status:"configured",binding:Ja(a)}},_e=async(e,t,s,a={},n)=>{const i=H(t),o=await e(kn(i,s),{...a,query:new URLSearchParams([["instance",i.instance],...n?Array.from(n.entries()):[]]),headers:{Accept:"application/json",...a.headers}}),r=await o.json();if(!o.ok){const c=r?.error||o.statusText||"Source control request failed";throw r?.code==="SOURCE_CONTROL_INSTANCE_OTHER_PROVIDER"&&j(r.provider)?new cO(c,r.provider):new Es(c,r?.code)}return r},ss=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},bB=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!j(t)))throw new Error("Source control response contained invalid incomplete projects");return[...e]}},le=(e,t,s,a)=>_e(e,t,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),Jt=(e,t)=>{const s=Object.keys(e);return s.length===t.length&&s.every(a=>t.includes(a))};function be(e,t,s){const a=e.target;if(!j(e.directory)||!j(e.repositoryId)||!j(e.accountId)||!Wb(e.bindingRevision)||!j(e.primaryRemote)||!j(e.idempotencyKey)||!a||!op(t,a.project?.owner)||!j(a.project?.name)||s==="create"&&("number"in a||"headSha"in a)||s==="create"&&(!j(a.head)||!j(a.base))||s==="existing"&&!$t(a.number)||a.number!==void 0&&!$t(a.number)||a.head!==void 0&&!j(a.head)||a.base!==void 0&&!j(a.base)||a.headSha!==void 0&&!j(a.headSha))throw new Error("Source control mutation context is invalid");const n={...t,directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:e.bindingRevision,primaryRemote:e.primaryRemote,idempotencyKey:e.idempotencyKey};if(s==="create"){if(!j(a.head)||!j(a.base))throw new Error("Source control mutation context is invalid");return{...n,target:{project:{owner:a.project.owner,name:a.project.name},head:a.head,base:a.base}}}if(!$t(a.number))throw new Error("Source control mutation context is invalid");const i={project:{owner:a.project.owner,name:a.project.name},number:a.number};return a.head!==void 0&&(i.head=a.head),a.base!==void 0&&(i.base=a.base),a.headSha!==void 0&&(i.headSha=a.headSha),{...n,target:i}}const wB=(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),kB=(e,t)=>t.startsWith(`${e.instance}#`)&&/^\d+$/.test(t.slice(e.instance.length+1)),we=(e,t,s,a)=>{const n=e?.actor,i=e?.target,o=i?.project;if(!e||!Jt(e,["status","actor","target","replayed","result"])||e.status!=="succeeded"||!Te(e.replayed)||!n||!Jt(n,["provider","instance","providerAccountId"])||n.provider!==s.provider||n.instance!==s.instance||!j(n.providerAccountId)||!kB(s,n.providerAccountId)||!i||!Jt(i,["repositoryId","bindingRevision","primaryRemote","project",...["number","head","base","headSha"].filter(c=>i[c]!==void 0)])||!j(i.repositoryId)||!Wb(i.bindingRevision)||!j(i.primaryRemote)||!o||!Jt(o,["id","owner","name"])||!j(o.id)||!op(s,o.owner)||!j(o.name)||i.number!==void 0&&!$t(i.number)||i.head!==void 0&&!j(i.head)||i.base!==void 0&&!j(i.base)||i.headSha!==void 0&&!j(i.headSha)||!wB(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:o.id,owner:o.owner,name:o.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:n.providerAccountId},target:r,replayed:e.replayed,result:a(e.result)}},Ge=e=>{if(!Jt(e,[]))throw new Error("Source control response contained an invalid mutation result");return{}},yB=["queued","merging","auto-merge","cancelled"],vB=e=>yB.find(t=>t===e)??null,CB=e=>{if(!Jt(e,e.stacked===void 0?[]:["stacked"])||e.stacked!==void 0&&!Te(e.stacked))throw new Error("Source control response contained an invalid create result");return e.stacked===void 0?{}:{stacked:e.stacked}},SB=e=>{const t=["merged",...e.message===void 0?[]:["message"],...e.outcome===void 0?[]:["outcome"]],s=e.outcome===void 0?void 0:vB(e.outcome);if(!Jt(e,t)||!Te(e.merged)||e.message!==void 0&&!K(e.message)||s===null)throw new Error("Source control response contained an invalid merge result");const a={merged:e.merged};return e.message!==void 0&&(a.message=e.message),s!==void 0&&(a.outcome=s),a},xB=e=>{if(!Jt(e,["commented"])||!Te(e.commented))throw new Error("Source control response contained an invalid review result");return{commented:e.commented}},xu=async(e,t,s,a)=>{const n=H(t),i=ss(t);i.set("owner",s.owner),i.set("repo",s.repo);const o=await _e(e,n,a,{},i);if(o.connected!==!0)throw new Error(`${Ti(n)} is not connected`);if(!Array.isArray(o.items))throw new Error("Source control response contained an invalid list");return o.items},PB=e=>e.map(t=>{if(!j(t.name)||t.color!==void 0&&!K(t.color))throw new Error("Source control response contained an invalid label");return t.color?{name:t.name,color:t.color}:{name:t.name}}),TB=e=>e.map(t=>{if(!j(t.id)||!j(t.login)||t.avatarUrl!==void 0&&!fs(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}}),Tc=e=>{if(!Jt(e,["state"])||e.state!=="open"&&e.state!=="closed")throw new Error("Source control response contained an invalid state result");return{state:e.state}},zB=e=>{if(!Jt(e,["ready"])||!Te(e.ready))throw new Error("Source control response contained an invalid ready result");return{ready:e.ready}},pt=(e,t)=>{const s=e?.username||e?.login;if(!e||!gs(e.id)||!j(s)||!VB(e,t)||e.avatarUrl!==void 0&&!fs(e.avatarUrl)||e.name!==void 0&&!K(e.name)||e.email!==void 0&&!K(e.email))throw new Error("Source control response contained an invalid user");const a={...t,id:String(e.id),username:s};return e.avatarUrl&&(a.avatarUrl=e.avatarUrl),e.name&&(a.name=e.name),e.email&&(a.email=e.email),a},ln=(e,t)=>{if(!e||!gs(e.id)||!op(t,e.owner)||!j(e.name)||!fs(e.url)||!bt(e,t)||e.cloneUrl!==void 0&&!j(e.cloneUrl)||e.sshUrl!==void 0&&!j(e.sshUrl)||e.defaultBranch!==void 0&&!j(e.defaultBranch)||e.defaultBranchSha!==void 0&&e.defaultBranchSha!==null&&!j(e.defaultBranchSha)||e.remoteName!==void 0&&e.remoteName!==null&&!j(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},Vb=(e,t)=>{if(e==null)return null;if(!e.summary)throw new Error("Source control response contained an invalid CI summary");if(HB(e.summary),e.runs!==void 0){if(!Array.isArray(e.runs)||e.runs.some(s=>!s||!gs(s.id)||!j(s.name)||!bt(s,t)||s.detailsUrl!==void 0&&!fs(s.detailsUrl)))throw new Error("Source control response contained invalid CI runs");for(const s of e.runs){if(s.startedAt!==void 0&&!j(s.startedAt)||s.completedAt!==void 0&&!j(s.completedAt)||s.status!==void 0&&!j(s.status)||s.conclusion!==void 0&&s.conclusion!==null&&!K(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&&!K(s.application.name)||s.application.slug!==void 0&&!K(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&&!gs(s.job.runId)||s.job.jobId!==void 0&&!gs(s.job.jobId)||s.job.url!==void 0&&!fs(s.job.url)||s.job.name!==void 0&&!K(s.job.name)||s.job.workflowName!==void 0&&!K(s.job.workflowName)||s.job.conclusion!==void 0&&s.job.conclusion!==null&&!K(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(a=>!a||!j(a.name)||a.status!==void 0&&!K(a.status)||a.conclusion!==void 0&&a.conclusion!==null&&!K(a.conclusion)||a.number!==void 0&&(!Number.isInteger(a.number)||a.number<0)||a.startedAt!==void 0&&!j(a.startedAt)||a.completedAt!==void 0&&!j(a.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&&!K(s.output.title)||s.output.summary!==void 0&&!K(s.output.summary)||s.output.text!==void 0&&!K(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(a=>!a||!j(a.message)||a.path!==void 0&&!K(a.path)||a.startLine!==void 0&&(!Number.isInteger(a.startLine)||a.startLine<0)||a.endLine!==void 0&&(!Number.isInteger(a.endLine)||a.endLine<0)||a.level!==void 0&&!K(a.level)||a.title!==void 0&&!K(a.title)||a.rawDetails!==void 0&&!K(a.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}))}},Vl=(e,t)=>{if(!e||!gs(e.id)||!Number.isInteger(e.number)||e.number<1||!j(e.title)||!fs(e.url)||!["open","closed","merged"].includes(e.state)||!Te(e.draft)||!j(e.base)||!j(e.head)||!bt(e,t)||e.body!==void 0&&!K(e.body)||e.headSha!==void 0&&!j(e.headSha)||e.author!==void 0&&e.author!==null&&!bt(e.author,t)||e.createdAt!==void 0&&!j(e.createdAt)||e.updatedAt!==void 0&&!j(e.updatedAt)||e.headLabel!==void 0&&!j(e.headLabel)||e.mergeable!==void 0&&e.mergeable!==null&&!Te(e.mergeable)||e.mergeableState!==void 0&&e.mergeableState!==null&&!K(e.mergeableState)||e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(a=>!a||!j(a.name)||a.color!==void 0&&!K(a.color)))||e.workInProgress!==void 0&&!Te(e.workInProgress)||e.private!==void 0&&!Te(e.private)||e.topic!==void 0&&!K(e.topic)||e.hashtags!==void 0&&(!Array.isArray(e.hashtags)||e.hashtags.some(a=>!j(a)))||e.revisionNumber!==void 0&&!$t(e.revisionNumber))throw new Error("Source control response contained an invalid change request");const s={...t,id:String(e.id),number:e.number,project:ln(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=pt(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=ln(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(a=>({name:a.name,color:a.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},Pu=(e,t)=>{if(!e||!gs(e.id)||!Number.isInteger(e.number)||e.number<1||!j(e.title)||!fs(e.url)||e.state!=="open"&&e.state!=="closed"||!bt(e,t)||e.body!==void 0&&!K(e.body)||e.author!==void 0&&e.author!==null&&!bt(e.author,t)||e.createdAt!==void 0&&!j(e.createdAt)||e.updatedAt!==void 0&&!j(e.updatedAt))throw new Error("Source control response contained an invalid issue");if(e.assignees!==void 0&&(!Array.isArray(e.assignees)||e.assignees.some(a=>!bt(a,t))))throw new Error("Source control response contained invalid issue assignees");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(a=>!a||!j(a.name)||a.color!==void 0&&!K(a.color))))throw new Error("Source control response contained invalid issue labels");const s={...t,id:String(e.id),number:e.number,project:ln(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?pt(e.author,t):null),e.assignees!==void 0&&(s.assignees=e.assignees.map(a=>pt(a,t))),e.labels!==void 0&&(s.labels=e.labels.map(a=>({name:a.name,color:a.color}))),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),s},AB=e=>{if(!e||!j(e.sha)||!K(e.headline)||e.authorName!==null&&!K(e.authorName)||e.committedAt!==null&&!j(e.committedAt)||e.url!==null&&!fs(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}},RB=["open","closed","merged"],IB=e=>{if(!e||!j(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=RB.find(a=>a===t?.state);if(!t||!Number.isSafeInteger(t.number)||!K(t.title)||!fs(t.url)||!s||!Te(t.draft)||!j(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}})}},Ub=e=>{try{return IB(e)}catch{return}},jB=(e,t)=>{if(!e||e.state!=="approved"&&e.state!=="changes_requested"||!j(e.url)||e.createdAt!==null&&!j(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=pt(e.author,t)),s},OB=["approved","rejected","recommended","disliked","neutral"],DB=["satisfied","unsatisfied","overridden","not-applicable","error","forced"],FB=["rework","trivial-rebase","merge-first-parent-update","no-code-change","no-change"],ii=e=>Cr(e)&&Number.isInteger(e)&&e>=-10&&e<=10,BB=(e,t)=>{if(!e||!ii(e.value)||e.revision!==void 0&&!$t(e.revision))throw new Error("Source control response contained an invalid vote");const s={user:pt(e.user,t),value:e.value};return e.revision!==void 0&&(s.revision=e.revision),s},NB=(e,t)=>{const s=OB.find(a=>a===e?.status);if(!e||!j(e.name)||!s||!ii(e.defaultValue)||!Te(e.blocking)||!Array.isArray(e.values)||e.values.some(a=>!a||!ii(a.value)||!K(a.description))||!Array.isArray(e.permitted)||e.permitted.some(a=>!ii(a))||!Array.isArray(e.votes))throw new Error("Source control response contained an invalid vote label");return{name:e.name,values:e.values.map(a=>({value:a.value,description:a.description})),defaultValue:e.defaultValue,permitted:[...e.permitted],blocking:e.blocking,status:s,votes:e.votes.map(a=>BB(a,t))}},MB=e=>{const t=DB.find(a=>a===e?.status);if(!e||!j(e.name)||!t||e.description!==void 0&&!K(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},EB=(e,t)=>{const s=e?.kind===void 0?void 0:FB.find(n=>n===e.kind);if(!e||!$t(e.number)||!j(e.sha)||!j(e.ref)||e.createdAt!==null&&!j(e.createdAt)||e.kind!==void 0&&!s)throw new Error("Source control response contained an invalid revision");const a={number:e.number,sha:e.sha,createdAt:e.createdAt,ref:e.ref};return e.uploader&&(a.uploader=pt(e.uploader,t)),s&&(a.kind=s),a},LB=e=>{if(!e||!j(e.sha)||e.changeId!==null&&!j(e.changeId)||e.uploadedAs!==null&&!$t(e.uploadedAs))throw new Error("Source control response contained an invalid local revision");return{sha:e.sha,changeId:e.changeId,uploadedAs:e.uploadedAs}},qB=(e,t)=>{if(e?.revision!==void 0&&!$t(e.revision))throw new Error("Source control response contained an invalid review comment");const s={...Ul(e,t),path:e.path,line:e.line,position:e.position};return e.revision!==void 0&&(s.revision=e.revision),s},Ul=(e,t)=>{if(!e||!gs(e.id)||!j(e.url)||!K(e.body)||!bt(e,t)||e.author!==void 0&&e.author!==null&&!bt(e.author,t)||e.createdAt!==void 0&&!j(e.createdAt)||e.updatedAt!==void 0&&!j(e.updatedAt))throw new Error("Source control response contained an invalid comment");const s=e.thread;if(s!==void 0&&(!s||!gs(s.id)||!Te(s.resolved)||!Te(s.resolvable)||!Te(s.first)||s.canResolve!==void 0&&!Te(s.canResolve)||s.canReply!==void 0&&!Te(s.canReply)))throw new Error("Source control response contained an invalid comment thread");const a={...t,id:String(e.id),url:e.url,body:e.body};return s&&(a.thread={id:String(s.id),resolved:s.resolved,resolvable:s.resolvable,first:s.first},s.canResolve!==void 0&&(a.thread.canResolve=s.canResolve),s.canReply!==void 0&&(a.thread.canReply=s.canReply)),e.author&&(a.author=pt(e.author,t)),e.createdAt&&(a.createdAt=e.createdAt),e.updatedAt&&(a.updatedAt=e.updatedAt),a},K=e=>Object.prototype.toString.call(e)==="[object String]",Te=e=>Object.prototype.toString.call(e)==="[object Boolean]",Cr=e=>Object.prototype.toString.call(e)==="[object Number]",j=e=>K(e)&&e.trim().length>0,$t=e=>Cr(e)&&Number.isSafeInteger(e)&&e>=1,Wb=e=>Cr(e)&&Number.isSafeInteger(e)&&e>=0,gs=e=>j(e)||Number.isFinite(e),fs=e=>{if(!j(e))return!1;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"}catch{return!1}},bt=(e,t)=>e?.provider===t.provider&&e.instance===t.instance,VB=(e,t)=>e.provider===void 0&&e.instance===void 0?!0:bt(e,t),UB=(e,t)=>{if(!Cr(e)||!Number.isInteger(e)||e<1||!Te(t))throw new Error("Source control response contained invalid pagination");return{page:e,hasMore:t}},Tu=(e,t)=>{const s={items:t,...UB(e.page,e.hasMore)},a=bB(e.incompleteProjectIds);return a?.length&&(s.incompleteProjectIds=a),s},WB=e=>{if(!e||!Array.isArray(e.branches)||e.branches.some(t=>!j(t)))throw new Error("Source control response contained invalid branches");return[...e.branches]},HB=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&&!j(e.startedAt))throw new Error("Source control response contained an invalid CI summary")},GB=(e,t,s)=>{if(!e||!bt(e.identity,t)||!j(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&&!Te(e.canMerge)||e.defaultBranch!==void 0&&e.defaultBranch!==null&&!j(e.defaultBranch)||e.resolvedRemoteName!==void 0&&e.resolvedRemoteName!==null&&!j(e.resolvedRemoteName))throw new Error("Source control response contained an invalid change request status");const a={identity:t,project:e.project===null?null:ln(e.project,t),branch:e.branch,changeRequest:e.changeRequest===null?null:Vl(e.changeRequest,t)};if(e.ci!==void 0&&(a.ci=Vb(e.ci,t)),e.canMerge!==void 0&&(a.canMerge=e.canMerge),e.defaultBranch!==void 0&&(a.defaultBranch=e.defaultBranch),e.resolvedRemoteName!==void 0&&(a.resolvedRemoteName=e.resolvedRemoteName),e.fetchedAt!==void 0&&(a.fetchedAt=e.fetchedAt),e.localRevision!==void 0&&(a.localRevision=LB(e.localRevision)),e.stack===null)a.stack=null;else if(e.stack!==void 0){const n=Ub(e.stack);n&&(a.stack=n)}return a},zc=(e,t)=>(e??[]).map(s=>{if(!j(s.id)||s.id!==s.credentialId||!$t(s.credentialRevision)||!j(s.providerUserId)||!["available","unavailable"].includes(s.providerUserStatus)||!Te(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:pt(s.user,t),scope:s.scope,current:s.current,source:s.source,status:s.status}}),Ac=(e,t)=>{if(!e.connected){if(!e.status){const s={...t,status:"disconnected",connected:!1};return e.cli&&(s.cli={available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?pt(e.cli.user,t):void 0}),s.accounts=zc(e.accounts,t),s}return{...e,...t,connected:!1,accounts:zc(e.accounts,t)}}return{...t,status:"connected",connected:!0,user:pt(e.user,t),scope:e.scope,accounts:zc(e.accounts,t),cli:e.cli?{available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?pt(e.cli.user,t):void 0}:void 0}},_B=(e={})=>{const t=e.fetch??C;return{repositoryContext:async s=>qb(await Su(t,"/api/source-control/repository-context",s)),repositoryBinding:async s=>Ja(await Su(t,"/api/source-control/binding",s)),resetRepositoryBinding:async s=>{const a=await t("/api/source-control/binding/reset",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),n=await a.json();if(!a.ok)throw new Es(n.error||a.statusText||"Source control binding reset failed",n.code);return Ja(n)},repositoryProviderBindingMutate:async s=>{const a=await t("/api/source-control/binding/provider",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),n=await a.json();if(!a.ok)throw new Es(n.error||a.statusText||"Source control binding request failed",n.code);return Ja(n)},providers:async()=>{const s=await eB(t);return Lb(s),s},authInstances:async()=>{const s=await t("/api/source-control/instances",{headers:{Accept:"application/json"}}),a=await s.json();if(!s.ok)throw new Error(a.error||s.statusText||"Failed to list source control instances");return a.instances.map(H)},capabilities:async s=>{const a=await _e(t,s,"/capabilities");return{identity:H(a.identity),authentication:a.authentication,authenticationMethods:a.authenticationMethods,multipleAccounts:a.multipleAccounts,projects:a.projects,issues:a.issues,changeRequests:a.changeRequests,draftChangeRequests:a.draftChangeRequests,mergeChangeRequests:a.mergeChangeRequests,mergeMethods:a.mergeMethods?[...a.mergeMethods]:void 0,ci:a.ci}},authStatus:async s=>{const a=H(s);return Ac(await _e(t,a,"/auth/status"),a)},authStart:async s=>{const a=await _e(t,s,"/auth/start",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),n={flowId:a.flowId,userCode:a.userCode,verificationUri:a.verificationUri,expiresIn:a.expiresIn,interval:a.interval};return a.verificationUriComplete&&(n.verificationUriComplete=a.verificationUriComplete),a.scope&&(n.scope=a.scope),n},authComplete:async(s,a)=>{let n;try{n=await le(t,s,"/auth/complete",{flowId:a})}catch(o){if(o instanceof Es&&o.code==="SOURCE_CONTROL_OAUTH_FLOW_UNAVAILABLE")return{status:"error",code:"expired",message:o.message};throw o}if(n.connected){const o={status:"connected",user:pt(n.user,H(s))};return n.scope&&(o.scope=n.scope),o}if(n.status==="authorization_pending"||n.status==="slow_down"){const o={status:"pending"};return n.status==="slow_down"&&(o.slowDown=!0),o}let i="provider-error";return n.status==="access_denied"?i="access-denied":n.status==="expired_token"&&(i="expired"),{status:"error",code:i,message:n.error||n.status||`${Ti(s)} authentication failed`}},authSetToken:async(s,a,n)=>{const i=H(s);return await le(t,i,"/auth/token",n?.username?{token:a,username:n.username}:{token:a}),Ac(await _e(t,i,"/auth/status"),i)},authSetSshUrl:async(s,a)=>{const n=H(s),i=await le(t,n,"/auth/ssh-url",{sshUrl:a});if(i.sshUrl!==null&&!j(i.sshUrl))throw new Error("Source control response contained an invalid SSH URL");return{sshUrl:i.sshUrl??null}},authDisconnect:async(s,a)=>{if(!j(a)||a.trim()!==a)throw new Error("Source control credential accountId is required");const n=new URLSearchParams({accountId:a}),i=await _e(t,s,"/auth",{method:"DELETE"},n);if(!Te(i.removed))throw new Error("Source control response contained an invalid account removal result");return{removed:i.removed}},authActivate:async(s,a)=>{const n=H(s);return Ac(await le(t,n,"/auth/activate",{accountId:a}),n)},authSetCliDisabled:async(s,a)=>{const n=H(s);return{disabled:!!(await le(t,n,"/auth/cli",{disabled:a})).disabled}},changeRequestStatus:async(s,a,n)=>{const i=H(s),o=ss(s);o.set("branch",a),n?.force&&o.set("force","true");const r=await _e(t,i,"/pr/status",{},o);return GB(r,i,a)},changeRequestCreate:async s=>{const a=H(s),i={...be(s,a,"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 o=await le(t,a,"/pr/create",i);return we(o,s,a,CB)},changeRequestUpdate:async s=>{const a=H(s),n={...be(s,a,"existing"),title:s.title};s.body!==void 0&&(n.body=s.body);const i=await le(t,a,"/pr/update",n);return we(i,s,a,Ge)},changeRequestMerge:async s=>{const a=H(s),n=await le(t,a,"/pr/merge",{...be(s,a,"existing"),method:s.method,cancel:s.cancel});return we(n,s,a,SB)},changeRequestReady:async s=>{const a=H(s),n=await le(t,a,"/pr/ready",be(s,a,"existing"));return we(n,s,a,zB)},changeRequestComment:async s=>{const a=H(s),n=await le(t,a,"/pr/comment",{...be(s,a,"existing"),body:s.body});return we(n,s,a,Ge)},changeRequestStartThread:async s=>{const a=H(s),n=await le(t,a,"/pr/thread/start",{...be(s,a,"existing"),body:s.body});return we(n,s,a,Ge)},changeRequestReplyToThread:async s=>{const a=H(s),n=await le(t,a,"/pr/thread/reply",{...be(s,a,"existing"),threadId:s.threadId,body:s.body});return we(n,s,a,Ge)},changeRequestResolveThread:async s=>{const a=H(s),n=await le(t,a,"/pr/thread/resolve",{...be(s,a,"existing"),threadId:s.threadId,resolved:s.resolved});return we(n,s,a,Ge)},changeRequestReview:async s=>{const a=H(s),n=be(s,a,"existing");let i;if(s.votes!==void 0){const r=Object.entries(s.votes);if(s.verdict!==void 0||r.length===0&&s.publishDrafts!==!0||r.some(([c,l])=>!j(c)||!ii(l)))throw new Error("Source control review input is invalid");i={...n,votes:Object.fromEntries(r),publishDrafts:s.publishDrafts}}else i={...n,verdict:s.verdict};s.body!==void 0&&(i.body=s.body);const o=await le(t,a,"/pr/review",i);return we(o,s,a,xB)},changeRequestReviewState:(s,a)=>lB(t,s,a),changeRequestReviewComment:async s=>{const a=H(s),n=s.line===void 0?{path:s.path}:{path:s.path,side:s.side,line:s.line,startLine:s.startLine},i=await le(t,a,"/pr/review/comment",{...be(s,a,"existing"),...n,body:s.body});return we(i,s,a,Ge)},changeRequestReviewCommentUpdate:async s=>{const a=H(s),n=await le(t,a,"/pr/review/comment/update",{...be(s,a,"existing"),commentId:s.commentId,body:s.body});return we(n,s,a,Ge)},changeRequestReviewCommentDelete:async s=>{const a=H(s),n=await le(t,a,"/pr/review/comment/delete",{...be(s,a,"existing"),commentId:s.commentId});return we(n,s,a,Ge)},changeRequestReviewDiscard:async s=>{const a=H(s),n=await le(t,a,"/pr/review/discard",be(s,a,"existing"));return we(n,s,a,Ge)},changeRequestSetState:async s=>{const a=H(s),n=await le(t,a,"/pr/state",{...be(s,a,"existing"),state:s.state});return we(n,s,a,Tc)},issueSetState:async s=>{const a=H(s),n=await le(t,a,"/issues/state",{...be(s,a,"existing"),state:s.state});return we(n,s,a,Tc)},changeRequestSetLabels:async s=>{const a=H(s),n=await le(t,a,"/pr/labels",{...be(s,a,"existing"),labels:s.labels});return we(n,s,a,Ge)},issueSetLabels:async s=>{const a=H(s),n=await le(t,a,"/issues/labels",{...be(s,a,"existing"),labels:s.labels});return we(n,s,a,Ge)},changeRequestSetReviewers:async s=>{const a=H(s),n=await le(t,a,"/pr/reviewers",{...be(s,a,"existing"),reviewers:s.reviewers});return we(n,s,a,Ge)},refreshProviderReads:async(s,a)=>{const n="item"in a?new URLSearchParams({scope:"item",owner:a.item.owner,repo:a.item.repo,number:String(a.item.number)}):new URLSearchParams({scope:"lists"});await _e(t,s,"/read-cache/refresh",{method:"POST"},n)},referenceLabels:async(s,a)=>PB(await xu(t,s,a,"/references/labels")),referenceReviewers:async(s,a)=>TB(await xu(t,s,a,"/references/reviewers")),issueComment:async s=>{const a=H(s),n=await le(t,a,"/issues/comment",{...be(s,a,"existing"),body:s.body});return we(n,s,a,Ge)},discussionComment:async s=>{const a=H(s),n={...be(s,a,"existing"),body:s.body};s.replyTo&&(n.replyTo=s.replyTo);const i=await le(t,a,"/discussions/comment",n);return we(i,s,a,Ge)},discussionSetState:async s=>{const a=H(s),n=be(s,a,"existing"),i=await le(t,a,"/discussions/state",s.state==="closed"?{...n,state:"closed",reason:s.reason}:{...n,state:"open"});return we(i,s,a,Tc)},discussionSetAnswer:async s=>{const a=H(s),n=await le(t,a,"/discussions/answer",{...be(s,a,"existing"),commentId:s.commentId,answer:s.answer});return we(n,s,a,Ge)},discussionSetLabels:async s=>{const a=H(s),n=await le(t,a,"/discussions/labels",{...be(s,a,"existing"),labels:s.labels});return we(n,s,a,Ge)},changeRequestsList:async(s,a)=>{const n=H(s),i=ss(s);i.set("page",String(a?.page??1)),a?.query&&i.set("query",a.query),a?.state&&i.set("state",a.state),a?.people&&i.set("people",a.people);const o=await _e(t,n,"/pulls/list",{},i);if(!o||!Array.isArray(o.items))throw new Error("Source control response contained invalid change requests");return Tu(o,o.items.map(r=>Vl(r,n)))},changeRequestContext:async(s,a,n)=>{const i=H(s),o=ss(s);o.set("number",String(a)),n?.includeDiff&&o.set("diff","1"),n?.includeCIDetails&&o.set("checkDetails","1"),n?.includeTimeline&&o.set("timeline","1"),n?.revision&&o.set("revision",n.revision),n?.project&&(o.set("owner",n.project.owner),o.set("repo",n.project.name));const r=await _e(t,i,"/pulls/context",{},o),c={identity:i,project:r.project?ln(r.project,i):null,changeRequest:r.changeRequest?Vl(r.changeRequest,i):null,issueComments:r.issueComments.map(l=>Ul(l,i)),reviewComments:r.reviewComments.map(l=>qB(l,i)),files:r.files.map(l=>({...l})),diff:r.diff,ci:Vb(r.ci,i),fetchedAt:r.fetchedAt};if(r.commits&&(c.commits=r.commits.map(AB),c.commitsComplete=r.commitsComplete!==!1,c.verdicts=(r.verdicts??[]).map(l=>jB(l,i)),r.reviewers&&(c.reviewers=r.reviewers.map(l=>pt(l,i)))),r.stack===null)c.stack=null;else if(r.stack!==void 0){const l=Ub(r.stack);l&&(c.stack=l)}if(r.voteLabels!==void 0){if(!Array.isArray(r.voteLabels))throw new Error("Source control response contained invalid vote labels");c.voteLabels=r.voteLabels.map(l=>NB(l,i))}if(r.submitRequirements!==void 0){if(!Array.isArray(r.submitRequirements))throw new Error("Source control response contained invalid submit requirements");c.submitRequirements=r.submitRequirements.map(MB)}if(r.revisions!==void 0){if(!Array.isArray(r.revisions))throw new Error("Source control response contained invalid revisions");c.revisions=r.revisions.map(l=>EB(l,i))}return c},issuesList:async(s,a)=>{const n=H(s),i=ss(s);i.set("page",String(a?.page??1)),a?.query&&i.set("query",a.query),a?.state&&i.set("state",a.state),a?.people&&i.set("people",a.people);const o=await _e(t,n,"/issues/list",{},i);if(!o||!Array.isArray(o.items))throw new Error("Source control response contained invalid issues");return Tu(o,o.items.map(r=>Pu(r,n)))},issueGet:async(s,a,n)=>{const i=H(s),o=ss(s);o.set("number",String(a)),n&&(o.set("owner",n.owner),o.set("repo",n.name));const r=await _e(t,i,"/issues/get",{},o);return r===null?null:Pu(r,i)},issueComments:async(s,a,n)=>{const i=H(s),o=ss(s);o.set("number",String(a)),n&&(o.set("owner",n.owner),o.set("repo",n.name));const r=await _e(t,i,"/issues/comments",{},o);if(!Array.isArray(r))throw new Error("Source control response contained invalid comments");return r.map(c=>Ul(c,i))},projectUpstream:async s=>{const a=H(s),n=ss(s),i=await _e(t,a,"/repo/upstream",{},n);if(!i||!bt(i.identity,a)||!Te(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:a,isFork:i.isFork,upstream:i.upstream?ln(i.upstream,a):null}},projectBranches:async(s,a,n)=>{const i=H(s),o=ss(s);o.set("owner",a),o.set("repo",n);const r=await _e(t,i,"/repo/branches",{},o);return WB(r)},references:(s,a)=>oB(t,s,a),referencesAcross:(s,a)=>dB(t,s,a),referenceDetail:(s,a)=>rB(t,s,a),changeRequestListStatuses:(s,a)=>pB(t,s,a)}},KB=g({status:k("unsupported"),reason:k("host-setup-required")}).strict(),Hb=p().regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/),Wl=g({credentialId:p().regex(/^ocgit:v1:ssh:[A-Za-z0-9_-]{1,267}$/),label:k("SSH"),fingerprint:Hb,capability:J([g({status:k("ready")}).strict(),g({status:k("unavailable"),reason:I(["unreadable","encrypted-or-unverifiable","fingerprint-mismatch"])}).strict()])}).strict(),ZB=Wl.extend({capability:g({status:k("ready")}).strict()}),zu=p().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),JB=J([g({candidateId:p().regex(/^[A-Za-z0-9_-]{1,200}$/),label:zu,fingerprint:Hb,capability:g({status:k("ready")}).strict()}).strict(),g({label:zu,capability:g({status:k("unavailable"),reason:I(["unreadable","encrypted-or-unverifiable","insecure-permissions"])}).strict()}).strict()]),QB=J([KB,g({status:k("available"),credentials:z(Wl).max(256)}).strict(),g({status:k("discovered"),candidates:z(JB).max(128),truncated:T()}).strict(),g({status:k("imported"),credentials:z(Wl).max(256),selectedCredential:ZB}).strict(),g({status:k("rejected"),reason:I(["candidate-expired","candidate-changed","fingerprint-mismatch","candidate-unavailable","inventory-full"])}).strict()]),$B=async(e,t=C)=>{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 a=QB.parse(await s.json());if(a.status==="imported"&&!a.credentials.some(n=>n.credentialId===a.selectedCredential.credentialId&&n.fingerprint===a.selectedCredential.fingerprint&&n.capability.status==="ready"))throw new Error("Managed SSH import response is inconsistent");return a},YB=()=>({managedSshCredentials:$B,configureTransportBinding:mB,removeTransportBinding:hB,configureAuxiliaryBinding:fB,checkIsGitRepository:cD,getGitStatus:dD,prefetchProjectStatuses:rD,getGitDiff:pD,getGitDiffs:gD,getGitFileDiff:bD,getGitRangeDiff:uD,getGitRangeFiles:hD,getBranchBase:fD,revertGitFile:wD,stageGitFile:kD,stageGitFiles:zb,unstageGitFile:yD,unstageGitFiles:Ab,stageGitHunk:vD,unstageGitHunk:CD,revertGitHunk:SD,isLinkedWorktree:xD,getGitBranches:PD,getGitUnpushedBranchCounts:TD,deleteGitBranch:zD,removeRemote:AD,generateCommitMessage:RD,generatePullRequestDescription:ID,listGitWorktrees:gu,validateGitWorktree:uu,createGitWorktree:mu,deleteGitWorktree:hu,validateWorktreeDirectory:MF,canonicalizeWorktreeState:EF,createGitCommit(e,t,s){return HD(e,t,s)},gitPush:GD,gitPull:_D,gitFetch:KD,planNetworkOperation:JD,issueContributorDestination:QD,listContributorDestinations:$D,inspectCheckoutTrust:YD,decideCheckoutTrust:XD,executeNetworkOperation:eF,getNetworkOperation:tF,cancelNetworkOperation:sF,listGitStashes:aF,countGitStashFiles:nF,stashGitChanges:Ob,applyGitStash:iF,popGitStash:Db,dropGitStash:oF,checkoutBranch:rF,createBranch:cF,renameBranch:lF,getGitLog(e,t){return dF(e,t)},addChangeIdToHead:gF,getCommitFiles:uF,getCommitFileDiff:mF,getGitCommitDiff:mD,getCurrentGitIdentity:kF,hasLocalIdentity:yF,setGitIdentity:CF,getGitIdentities:hF,createGitIdentity:fF,updateGitIdentity:bF,deleteGitIdentity:wF,getGlobalGitIdentity:vF,getRemotes:SF,rebase:xF,abortRebase:PF,continueRebase:OF,merge:TF,abortMerge:jF,continueMerge:DF,checkoutCommit:zF,cherryPick:AF,revertCommit:RF,resetToCommit:IF,stash:FF,stashPop:BF,getConflictDetails:NF,worktree:{list:gu,validate:uu,bootstrapStatus:jD,preview:OD,create:mu,remove:hu,teardown:DD,setTitle:BD,setPinned:MD,snapshot:WD,archive:ED,listArchives:LD,restoreArchive:qD,deleteArchive:VD}});let Au=null;const XB=()=>window.Capacitor,eN=e=>e.getPlatform?.()!=="android"||!e.registerPlugin?null:(Au??=e.registerPlugin("FileShare"),Au),tN=async e=>{const t=new Uint8Array(await e.arrayBuffer());let s="";for(let a=0;a<t.length;a+=32768)s+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(s)},sN=async e=>{const t=XB(),s=t?eN(t):null;if(s){await s.share({fileName:e.name,mimeType:e.type||"application/octet-stream",data:await tN(e)});return}if(!navigator.canShare?.({files:[e]}))throw new Error("File sharing is unavailable in this mobile runtime");await navigator.share({files:[e]})},ye=e=>e.replace(/\\/g,"/"),aN=(e,t)=>Je.searchFiles(e,t),nN=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new jt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:ye(t?.directory||t?.path||e),entries:t.entries.filter(a=>!!(a&&typeof a.name=="string"&&typeof a.path=="string")).map(a=>({name:a.name,path:ye(a.path),isDirectory:!!a.isDirectory}))}},mt=(e,t,s)=>{const a=e?.(),n=yt(s),i=t||(n!==null&&yt(a)!==n?Em(n):a);return i?{"x-opencode-directory":i}:void 0},iN=g({matches:z(g({path:p(),relativePath:p(),line:v().int().positive(),column:v().int().positive(),text:p(),ranges:z(jo([v().int().nonnegative(),v().int().nonnegative()])),cutStart:T()})),stopped:I(["limit","deadline"]).nullable()}),oN=g({error:p().optional(),reason:p().optional()}),rN=g({files:z(g({path:p(),relativePath:p()}))}),cN=({getDirectory:e,searchFiles:t=aN})=>({async listDirectory(s,a){const n=ye(s),i=new URLSearchParams;n&&i.set("path",n),a?.respectGitignore&&i.set("respectGitignore","true");const o=await C("/api/fs/list",{query:i,headers:mt(e,void 0,n)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new jt(c.error||"Failed to list directory",{reason:Zn(c.reason),status:o.status})}const r=await o.json();return nN(n,r)},async search(s){const a=ye(s.directory),n=!!s.includeHidden,i=s.respectGitignore!==!1;if(n||!i){const r=new URLSearchParams;r.set("query",s.query),a&&r.set("directory",a),typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)&&r.set("limit",String(s.maxResults)),n&&r.set("includeHidden","true"),i||r.set("respectGitignore","false");const c=await C("/api/fs/search",{query:r,signal:s.signal,headers:mt(e,a)});if(!c.ok){const d=await c.json().catch(()=>({error:c.statusText}));throw new Error(d.error||"Failed to search files")}const l=rN.safeParse(await c.json().catch(()=>null));if(!l.success)throw new jt("File search returned an invalid response",{reason:"invalid-response"});return l.data.files.map(d=>({path:ye(d.path),preview:[ye(d.relativePath)]}))}return(await t(s.query,{directory:a,limit:typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)?s.maxResults:void 0,type:"file"})).map(r=>({path:ye(r.path),preview:[ye(r.relativePath)]}))},async searchContents(s){const a=ye(s.directory),n=new URLSearchParams({query:s.query,regex:s.regex?"true":"false"});s.limit!==void 0&&n.set("limit",String(s.limit)),s.includeHidden&&n.set("includeHidden","true"),s.respectGitignore===!1&&n.set("respectGitignore","false");const i=await C("/api/fs/find-in-files",{query:n,cache:"no-store",signal:s.signal,headers:mt(e,a)});if(i.ok){const c=iN.safeParse(await i.json().catch(()=>null));if(!c.success)throw new jt("Content search returned an invalid response",{reason:"invalid-response"});return{status:"ok",matches:c.data.matches.map(l=>({...l,path:ye(l.path)})),stopped:c.data.stopped}}const o=oN.safeParse(await i.json().catch(()=>null)),r=o.success?o.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:o.success&&o.data.error?o.data.error:"Invalid regular expression"};throw new jt(o.success&&o.data.error||i.statusText||"Failed to search file contents",{status:i.status})},async createDirectory(s){const a=ye(s),n=await C("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...mt(e,void 0,a)},body:JSON.stringify({path:a})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create directory")}const i=await n.json();return{success:!!i?.success,path:typeof i?.path=="string"?ye(i.path):a}},async statFile(s,a){const n=ye(s),i=new URLSearchParams({path:n});a?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),a?.outsideFileGrant&&i.set("outsideFileGrant",a.outsideFileGrant);const o=await C("/api/fs/stat",{query:i,signal:AbortSignal.timeout(3e4),headers:mt(e,a?.directory,n)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new Error(c.error||"Failed to stat file")}const r=await o.json().catch(()=>({}));return{path:typeof r.path=="string"?ye(r.path):n,isFile:!!r.isFile,size:typeof r.size=="number"?r.size:0,mtimeMs:typeof r.mtimeMs=="number"?r.mtimeMs:void 0}},async readFile(s,a){const n=ye(s),i=new URLSearchParams({path:n});a?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),a?.outsideFileGrant&&i.set("outsideFileGrant",a.outsideFileGrant),a?.optional&&i.set("optional","true");const o=await C("/api/fs/read",{query:i,signal:AbortSignal.timeout(3e4),cache:a?.optional||a?.fresh?"no-store":"default",headers:mt(e,a?.directory,n)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new Error(c.error||"Failed to read file")}return{content:await o.text(),path:n}},async writeFile(s,a){const n=ye(s),i=await C("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...mt(e,void 0,n)},body:JSON.stringify({path:n,content:a})});if(!i.ok){const r=await i.json().catch(()=>({error:i.statusText}));throw new Error(r.error||"Failed to write file")}const o=await i.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?ye(o.path):n}},async uploadFile(s,a,n){const i=ye(s),o=await C("/api/fs/upload",{method:"POST",query:{path:i,overwrite:n?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...mt(e,n?.directory,i)},body:a});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));throw new jt(c.error||"Failed to upload file",{reason:Zn(c.reason),status:o.status,maxBytes:c.maxBytes})}const r=await o.json().catch(()=>({}));return{success:!!r.success,path:r.path?ye(r.path):i}},async delete(s){const a=ye(s),n=await C("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...mt(e,void 0,a)},body:JSON.stringify({path:a})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to delete file")}return{success:!!(await n.json().catch(()=>({}))).success}},async rename(s,a){const n=await C("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...mt(e,void 0,s)},body:JSON.stringify({oldPath:s,newPath:a})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new jt(o.error||"Failed to rename file",{reason:Zn(o.reason),status:n.status})}const i=await n.json().catch(()=>({}));return{success:!!i.success,path:i.path?ye(i.path):a}},async revealPath(s){const a=await C("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...mt(e,void 0,s)},body:JSON.stringify({path:ye(s)})});if(!a.ok){const i=await a.json().catch(()=>({error:a.statusText}));throw new Error(i.error||"Failed to reveal path")}return{success:!!(await a.json().catch(()=>({}))).success}},async downloadFile(s,a){const n=ye(s),i=new URLSearchParams({path:n,download:"true"});a?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),a?.outsideFileGrant&&i.set("outsideFileGrant",a.outsideFileGrant);const o=await C("/api/fs/raw",{query:i,headers:mt(e,a?.directory,n)});if(!o.ok)throw new Error(`Download failed (${o.status})`);const r=await o.blob(),c=n.split("/").pop()||"file";if(window.Capacitor?.isNativePlatform?.()===!0){await sN(new File([r],c,{type:r.type||"application/octet-stream"}));return}const d=URL.createObjectURL(r),u=document.createElement("a");u.href=d,u.download=c,document.body.appendChild(u),u.click(),document.body.removeChild(u),setTimeout(()=>URL.revokeObjectURL(d),100)}}),lN="/api/config/settings",Ru=()=>`${lN}?${df}=${dr()}`,dN="/api/config/reload",Iu=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},pN=()=>({async load(){const e=await C(Ru(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:Iu(await e.json()),source:"web"}},async save(e){const t=await C(Ru(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const a=await t.json().catch(()=>({error:t.statusText}));throw new Error(a.error||"Failed to save settings")}return Iu(await t.json())},async restartOpenCode(){const e=await C(dN,{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:!0}}}),gN=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),uN=g({type:k("openchamber:notification-navigation"),url:p().url(),expiresAt:v().finite()});let oi=null;function Gb(e){if(!oi)return!1;try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin&&t.pathname===window.location.pathname&&oi(t)}catch{return!1}}function qU(e){oi=e;const t="serviceWorker"in navigator?navigator.serviceWorker:null,s=a=>{const n=uN.safeParse(a.data),i=a.ports[0];if(!(!n.success||!i))try{const o=a.origin===window.location.origin&&Date.now()<n.data.expiresAt&&Gb(n.data.url);i.postMessage(o)}catch{i.postMessage(!1)}finally{i.close()}};return t?.addEventListener("message",s),()=>{t?.removeEventListener("message",s),oi===e&&(oi=null)}}const mN=1500,Hl=5e3,hN="openchamber-notification-claim:",ri=new Map,fN=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),bN=e=>{if(typeof e!="string")return null;const t=e.trim();return t?`/?session=${encodeURIComponent(t)}`:null},_b=e=>{const t=typeof e?.sessionId=="string"?e.sessionId.trim():"";if(!t)return;const s=bN(t);if(s)return{url:s,sessionId:t}},Kb=(e,t)=>{const s={body:e?.body,tag:e?.tag};return t&&(s.data=t),s},wN=e=>{try{if(typeof window>"u"||(typeof window.focus=="function"&&window.focus(),!e)||`${window.location.pathname}${window.location.search}`===e.url||Gb(e.url))return;window.location.assign(e.url)}catch{}},kN=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("|")},yN=e=>{for(const[t,s]of ri)e-s>Hl&&ri.delete(t)},vN=e=>{const t=kN(e);if(!t)return!0;const s=Date.now();yN(s);const a=ri.get(t)??0;if(s-a<Hl)return!1;try{if(typeof window<"u"&&window.localStorage){const n=`${hN}${t}`,i=Number(window.localStorage.getItem(n)??"0");if(Number.isFinite(i)&&s-i<Hl)return ri.set(t,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(n),window.localStorage.setItem(n,String(s))}}catch{}return ri.set(t,s),!0},Zb=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),mN)})])??e}catch{return e}},CN=async e=>{const t=await Zb();if(!t||typeof t.showNotification!="function")return!1;try{const s=_b(e);return await t.showNotification(e?.title??"OpenChamber",Kb(e,s)),!0}catch(s){return console.warn("Failed to send notification via service worker",s),!1}},SN=async()=>{const e=await Zb();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},xN=async e=>{if(e?.requireHidden&&typeof document<"u"&&document.hasFocus())return!0;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",e),!1;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),!1;if(!fN()&&await SN()||!vN(e))return!0;try{if(await CN(e))return!0;const t=_b(e),s=new Notification(e?.title??"OpenChamber",Kb(e,t));return s.onclick=a=>{a.preventDefault(),wN(t),s.close()},!0}catch(t){return console.warn("Failed to send notification",t),!1}},PN=async e=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;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}}),!0}catch(s){return console.warn("Failed to send native notification (desktop)",s),!1}},TN=()=>({async notifyAgentCompletion(e){return await PN(e)||await xN(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),Da=async(e,t)=>{try{const s=await C(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return s.ok?await s.json():null}catch{return null}},zN=()=>({async getVapidPublicKey(){return Da("/api/push/vapid-public-key")},async subscribe(e){return Da("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return Da("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return Da("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return Da("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return Da("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),AN=new Set(Df),RN=p().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!AN.has(e),{message:"Reserved tracker id"}),IN=e=>{try{return new RegExp(e),!0}catch{return!1}},ju=p().min(1).max(2048).refine(IN),qt=T().catch(!1),jN=g({id:RN,name:p().min(1).max(64),authMethods:z(p()).transform(e=>e.filter(t=>t==="oauth"||t==="token")),capabilities:g({multipleAccounts:qt,stateUpdate:qt,children:qt,labels:qt,priority:qt,filters:g({people:qt,priority:qt}).catch({people:!1,priority:!1}),projectMapping:qt,sessionComments:qt,hostAccess:qt}),stateFilters:z(p().min(1).max(32)).max(32),urlPatterns:z(g({host:p().min(1).max(256),path:ju,query:g({name:p().min(1).max(64)}).optional().catch(void 0)}).nullable().catch(null)).max(8).transform(e=>e.filter(t=>t!==null)),identifierPattern:ju}),ON=z(jN.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const a of e)!a||t.has(a.id)||(t.add(a.id),s.push(a));return s}),Ou=new Map,VU=e=>{const t=Ou.get(e);if(t)return t;const s={id:e,name:e,authMethods:[],capabilities:{multipleAccounts:!1,stateUpdate:!1,children:!1,labels:!1,priority:!1,filters:{people:!1,priority:!1},projectMapping:!1,sessionComments:!1,hostAccess:!1},stateFilters:["open","all"],urlPatterns:[],identifierPattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$"};return Ou.set(e,s),s},DN=g({error:p()}),Jb=async(e,t)=>{const s=DN.safeParse(await e.json().catch(()=>null));return new Error(s.success&&s.data.error.trim()||e.statusText||t)};async function Qb(e,t,s,a,n){const i=new Headers({Accept:"application/json"});s.body!==void 0&&i.set("Content-Type","application/json");const o=await e(t,{method:s.method,body:s.body,headers:i});if(!o.ok)throw await Jb(o,n);const r=a.safeParse(await o.json().catch(()=>null));if(!r.success)throw new Error(`${n}: unreadable answer`);return r.data}const Ze=p().trim().min(1),wt=p().trim().nullish().catch(null).transform(e=>e||null),$b=I(["triage","backlog","todo","in-progress","done","canceled"]),FN=I(["none","urgent","high","medium","low"]),Ls=e=>z(ee()).catch([]).transform(t=>t.flatMap(s=>{const a=e.safeParse(s);return a.success?[a.data]:[]})),rp=g({name:wt,avatarUrl:wt}).nullish().catch(null).transform(e=>e&&(e.name||e.avatarUrl)?e:null),BN=p().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null}),NN=g({id:wt,name:p().trim().catch(""),category:$b.nullable().catch(null)}).nullish().catch(null).transform(e=>e??null),MN=g({total:v().int().positive(),done:v(),more:T().catch(!1)}).nullish().catch(null).transform(e=>e?{...e,done:Math.min(Math.max(e.done,0),e.total)}:null),Yb={provider:Ze,id:Ze,identifier:Ze,title:Ze,url:Ze,state:NN,priority:FN.nullish().catch(null),assignee:rp.optional(),container:g({id:Ze,key:wt,name:Ze}).nullish().catch(null),updatedAt:wt.optional()},Xb=g(Yb),ew=g({...Yb,labels:Ls(g({id:Ze,name:Ze,color:BN})).optional(),parent:Xb.nullish().catch(null),progress:MN.optional()}),EN=ew,LN=g({id:Ze,body:p().catch(""),createdAt:wt,author:rp}),qN=ew.extend({description:p().nullish().catch(null).transform(e=>e??null),comments:Ls(LN),children:Ls(Xb),childrenMore:T().catch(!1)}),yn=g({connected:k(!1)}).transform(()=>({connected:!1})),VN=J([yn,g({connected:k(!0),items:Ls(EN),cursor:wt,hasMore:T().catch(!1)})]),Du=J([yn,g({connected:k(!0),item:qN.nullish().catch(null).transform(e=>e??null)})]),UN=g({id:Ze,name:Ze,category:$b.nullable().catch(null),position:v().catch(0)}),WN=J([yn,g({connected:k(!0),states:Ls(UN)})]),Rc=g({id:Ze,name:wt,user:rp.optional(),current:T().catch(!1),authorizedAt:v().nullish().catch(null),status:I(["valid","invalid"]).optional().catch(void 0),invalidReason:p().trim().min(1).max(256).optional().catch(void 0),method:I(["oauth","token"]).optional().catch(void 0)}),Fu=g({instance:p().trim().min(1).max(2048).nullable().catch(null),instances:J([g({kind:k("fixed"),origin:p().trim().min(1).max(2048)}),g({kind:k("user"),label:p().trim().min(1).max(64),placeholder:p().trim().min(1).max(256).optional()})]),hasClient:T().catch(!1),redirectUri:p().trim().min(1).max(2048).nullable().catch(null)}),Bu=J([g({connected:k(!1),accounts:Ls(Rc).optional(),connect:Fu.optional().catch(void 0)}),g({connected:k(!0),account:Rc.nullish().catch(null),accounts:Ls(Rc),connect:Fu.optional().catch(void 0)})]),HN=["UNSUPPORTED","INSTANCE_REQUIRED","INSTANCE_MISMATCH","UNSUPPORTED_INSTANCE","TOKEN_REQUIRED","TOKEN_REFUSED","USERNAME_REQUIRED","USERNAME_INVALID","CLIENT_MISSING","CONNECT_SUPERSEDED","TRACKER_UNAVAILABLE"],GN=g({error:p().optional(),code:p().optional()}),Nu=async e=>{if(e.ok)return{ok:!0};const t=GN.safeParse(await e.json().catch(()=>null));if(!t.success)return{ok:!1,code:"failed",message:null};const s=I(HN).safeParse(t.data.code);return{ok:!1,code:s.success?s.data:"failed",message:t.data.error?.trim()||null}},_N=g({authorizationUrl:Ze,expiresIn:v().positive()}),Mu=J([yn,g({connected:k(!0),defaultProjectPath:wt,containers:Ls(g({id:Ze,key:wt,name:Ze,projectPath:wt}))})]),Yo=g({sessionComments:T()}),tw=J([yn,g({connected:k(!0),posted:k(!0),commentId:wt}),g({connected:k(!0),posted:k(!1),skipped:I(["already-posted","issue-not-found","not-started","disabled","origin-not-public"])})]),KN=new Map([["triage","triage"],["backlog","backlog"],["unstarted","todo"],["started","in-progress"],["completed","done"],["canceled","canceled"],["duplicate","canceled"]]),sw=e=>e?KN.get(e)??null:null,ZN=new Map([["linear","linear"]]),UU=e=>ZN.get(e)??"tracker",aw={id:"linear",name:"Linear",authMethods:["oauth"],capabilities:{multipleAccounts:!0,stateUpdate:!0,children:!0,labels:!0,priority:!0,filters:{people:!0,priority:!0},projectMapping:!0,sessionComments:!0,hostAccess:!0},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+$"},JN=["none","urgent","high","medium","low"],QN=new Map([["in-progress","started"],["done","completed"]]),Qe=p().trim().min(1),$e=p().trim().nullish().catch(null).transform(e=>e||null),la=e=>z(ee()).catch([]).transform(t=>t.flatMap(s=>{const a=e.safeParse(s);return a.success?[a.data]:[]})),Sr=g({name:$e,displayName:$e,avatarUrl:$e}).nullish().catch(null).transform(e=>{const t=e?.displayName||e?.name||null,s=e?.avatarUrl??null;return t||s?{name:t,avatarUrl:s}:null}),$N=g({id:$e,name:$e,type:$e}).nullish().catch(null).transform(e=>e&&(e.id||e.name||e.type)?{id:e.id,name:e.name??"",category:sw(e.type)}:null),nw={id:Qe,identifier:Qe,title:Qe,url:Qe,state:$N,assignee:Sr,team:g({id:Qe,key:$e,name:Qe}).nullish().catch(null),priority:v().int().nullish().catch(null),updatedAt:$e},Gl=(e,t)=>({provider:t,id:e.id,identifier:e.identifier,title:e.title,url:e.url,state:e.state,priority:e.priority!=null?JN[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}),iw=g(nw),ow=g({...nw,labels:la(g({id:Qe,name:Qe,color:p().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null})})),parent:iw.nullish().catch(null),subIssueProgress:g({total:v().int().positive(),done:v(),more:T().catch(!1)}).nullish().catch(null)}),rw=(e,t)=>({...Gl(e,t),labels:e.labels,parent:e.parent?Gl(e.parent,t):null,progress:e.subIssueProgress?{...e.subIssueProgress,done:Math.min(Math.max(e.subIssueProgress.done,0),e.subIssueProgress.total)}:null}),YN=ow.extend({description:p().nullish().catch(null),comments:la(g({id:Qe,body:p().catch(""),createdAt:$e,user:Sr})),subIssues:la(iw),subIssuesMore:T().catch(!1)}),XN=(e,t)=>({...rw(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=>Gl(s,t)),childrenMore:e.subIssuesMore}),eM=g({id:Qe,name:$e,current:T().catch(!1),user:Sr,authorizedAt:v().nullish().catch(null)}),Eu=g({connected:T(),user:Sr,organization:g({id:Qe,name:$e}).nullish().catch(null),workspaces:la(eM)}).transform(e=>{if(!e.connected)return{connected:!1};const t=[...e.workspaces];return t.length===0&&e.organization&&t.push({id:e.organization.id,name:e.organization.name,user:e.user,current:!0,authorizedAt:null}),{connected:!0,account:t.find(s=>s.current)??null,accounts:t}}),tM=e=>{const t=new URLSearchParams,s=(i,o)=>{const r=o?.trim();r&&t.set(i,r)},a=e?.state?.trim();s("query",e?.query),s("cursor",e?.cursor),s("status",a?QN.get(a)??a:void 0),s("assignee",e?.people),s("teamId",e?.containerId),s("priority",e?.priority);const n=t.toString();return n?`?${n}`:""},sM=e=>{const t=async(o,r,c,l,d)=>{if(o!==aw.id)throw new Error(`Unknown tracker: ${o}`);return Qb(e,`/api/linear${r}`,c,l,d)},s={method:"GET"},a=o=>J([yn,o]),n=o=>a(g({connected:k(!0),issue:YN.nullish().catch(null)}).transform(({issue:r})=>({connected:!0,item:r?XN(r,o):null}))),i=a(g({connected:k(!0),defaultProjectPath:$e,teams:la(g({id:Qe,key:$e,name:Qe,projectPath:$e}))}).transform(({defaultProjectPath:o,teams:r})=>({connected:!0,defaultProjectPath:o,containers:r})));return{authStatus:o=>t(o,"/auth/status",s,Eu,"Failed to load Linear status"),authStart:(o,r)=>t(o,"/auth/start",{method:"POST",body:JSON.stringify({origin:r})},g({authorizationUrl:Qe,expiresIn:v().positive()}),"Failed to start Linear auth"),authConnectToken:async()=>({ok:!1,code:"UNSUPPORTED",message:null}),authSaveOAuthClient:async()=>({ok:!1,code:"UNSUPPORTED",message:null}),authDisconnect:o=>t(o,"/auth",{method:"DELETE"},g({removed:T().catch(!1)}),"Failed to disconnect Linear").then(({removed:r})=>({removed:r})),authActivate:(o,r)=>t(o,"/auth/activate",{method:"POST",body:JSON.stringify({organizationId:r})},Eu,"Failed to switch Linear workspace"),list:(o,r)=>t(o,`/issues/list${tM(r)}`,s,a(g({connected:k(!0),issues:la(ow),cursor:$e,hasMore:T().catch(!1)}).transform(({issues:c,cursor:l,hasMore:d})=>({connected:!0,items:c.map(u=>rw(u,o)),cursor:l,hasMore:d}))),"Failed to load Linear issues"),refreshListReads:async o=>{await t(o,"/read-cache/refresh?scope=lists",{method:"POST"},ee(),"Failed to refresh Linear lists")},get:(o,r)=>t(o,`/issues/get?${new URLSearchParams({id:r}).toString()}`,s,n(o),"Failed to load Linear issue"),states:(o,r)=>t(o,`/issues/states?${new URLSearchParams({teamId:r}).toString()}`,s,a(g({connected:k(!0),states:la(g({id:Qe,name:Qe,type:$e,position:v().catch(0)}).transform(({id:c,name:l,type:d,position:u})=>({id:c,name:l,category:sw(d),position:u})))})),"Failed to load Linear workflow states"),updateState:(o,r)=>t(o,"/issues/update",{method:"POST",body:JSON.stringify({id:r.id,stateId:r.stateId})},n(o),"Failed to update Linear issue"),mappingGet:o=>t(o,"/mapping",s,i,"Failed to load Linear mapping"),mappingSet:(o,r)=>t(o,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:r.defaultProjectPath,teamProjectPaths:r.containerProjectPaths})},i,"Failed to save Linear mapping"),sessionStatusPost:(o,r)=>t(o,"/session-status",{method:"POST",body:JSON.stringify({kind:r.kind,sessionId:r.sessionId,issueIdentifier:r.identifier,sessionOrigin:r.sessionOrigin})},tw,"Failed to post Linear session status"),preferencesGet:o=>t(o,"/preferences",s,Yo,"Failed to load Linear preferences"),preferencesSet:(o,r)=>t(o,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:r.sessionComments})},Yo,"Failed to save Linear preferences")}},aM=g({providers:z(ee())}),nM=e=>{const t=e?.split(";")[0]?.trim().toLowerCase()??"";return t==="application/json"||t.endsWith("+json")};async function iM(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 Jb(t,"Failed to load trackers");if(!nM(t.headers.get("content-type")))return{kind:"legacy-linear"};const s=aM.parse(await t.json().catch(()=>null)).providers,a=ON.parse(s);if(s.length>0&&a.length===0)throw new Error("Trackers response contained no readable tracker");return{kind:"tracker",descriptors:a}}const Ic=(e,t)=>`/api/tracker/${encodeURIComponent(e)}${t}`,oM=({fetch:e=C,runtimeKey:t=D}={})=>{const s=sM(e);let a=null;const n=()=>{const l=iM(e),d={runtimeKey:t(),request:l};return a=d,l.catch(()=>{a===d&&(a=null)}),l},i=async()=>(await((a?.runtimeKey===t()?a.request:null)??n())).kind==="legacy-linear",o=(l,d,u,m,f)=>Qb(e,Ic(l,d),u,m,f),r={method:"GET"},c=l=>{const d=new URLSearchParams,u=(f,b)=>{const w=b?.trim();w&&d.set(f,w)};u("query",l?.query),u("cursor",l?.cursor),u("state",l?.state),u("people",l?.people),u("priority",l?.priority),u("containerId",l?.containerId);const m=d.toString();return m?`?${m}`:""};return{async providers(){const l=await n();return l.kind==="legacy-linear"?[aw]:l.descriptors},async authStatus(l){return await i()?s.authStatus(l):o(l,"/auth/status",r,Bu,"Failed to load tracker status")},async authStart(l,d,u){if(await i())return s.authStart(l,d);const m=u?.instance?{origin:d,instance:u.instance}:{origin:d};return o(l,"/auth/start",{method:"POST",body:JSON.stringify(m)},_N,"Failed to start tracker sign-in")},async authConnectToken(l,d){if(await i())return s.authConnectToken(l,d);try{const u=await e(Ic(l,"/auth/token"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(d)});return await Nu(u)}catch{return{ok:!1,code:"failed",message:null}}},async authSaveOAuthClient(l,d){if(await i())return s.authSaveOAuthClient(l,d);try{const u=await e(Ic(l,"/auth/oauth-client"),{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(d)});return await Nu(u)}catch{return{ok:!1,code:"failed",message:null}}},async authDisconnect(l){return await i()?s.authDisconnect(l):o(l,"/auth",{method:"DELETE"},g({removed:T().catch(!1)}),"Failed to disconnect tracker").then(({removed:d})=>({removed:d}))},async authActivate(l,d){return await i()?s.authActivate(l,d):o(l,"/auth/activate",{method:"POST",body:JSON.stringify({accountId:d})},Bu,"Failed to switch tracker account")},async list(l,d){return await i()?s.list(l,d):o(l,`/items/list${c(d)}`,r,VN,"Failed to load tracker items")},async refreshListReads(l){if(await i())return s.refreshListReads(l);await o(l,"/read-cache/refresh?scope=lists",{method:"POST"},ee(),"Failed to refresh tracker lists")},async get(l,d){return await i()?s.get(l,d):o(l,`/items/get?${new URLSearchParams({id:d}).toString()}`,r,Du,"Failed to load tracker item")},async states(l,d){return await i()?s.states(l,d):o(l,`/states?${new URLSearchParams({containerId:d}).toString()}`,r,WN,"Failed to load workflow states")},async updateState(l,d){return await i()?s.updateState(l,d):o(l,"/items/update",{method:"POST",body:JSON.stringify({id:d.id,stateId:d.stateId})},Du,"Failed to update tracker item")},async mappingGet(l){return await i()?s.mappingGet(l):o(l,"/mapping",r,Mu,"Failed to load project mapping")},async mappingSet(l,d){return await i()?s.mappingSet(l,d):o(l,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:d.defaultProjectPath,containerProjectPaths:d.containerProjectPaths})},Mu,"Failed to save project mapping")},async sessionStatusPost(l,d){return await i()?s.sessionStatusPost(l,d):o(l,"/session-status",{method:"POST",body:JSON.stringify({kind:d.kind,sessionId:d.sessionId,identifier:d.identifier,sessionOrigin:d.sessionOrigin})},tw,"Failed to post session status")},async preferencesGet(l){return await i()?s.preferencesGet(l):o(l,"/preferences",r,Yo,"Failed to load tracker preferences")},async preferencesSet(l,d){return await i()?s.preferencesSet(l,d):o(l,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:d.sessionComments})},Yo,"Failed to save tracker preferences")}}},xs=async e=>await e.json().catch(()=>null),rM=g({identityConflict:T().catch(!1)}),Lu=async(e,t)=>{const s=await C(e,{method:t,headers:{Accept:"application/json"}}),a=await s.json().catch(()=>null),n=rM.safeParse(a);if(!s.ok||!n.success)throw new Error(s.statusText||"Failed to read relay status");return n.data},cM=()=>({async listClients(){const e=await C("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await xs(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 C("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),s=await xs(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 C("/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 xs(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 C("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await xs(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 C("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await xs(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!==!1}},async cancelPairing(e){const t=await C(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await xs(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to cancel pairing");return{cancelled:s.cancelled===!0}},async revokeClient(e){const t=await C(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await xs(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to revoke remote client");return s},getRelayHostStatus:()=>Lu("/api/openchamber/relay/status","GET"),resetRelayIdentity:()=>Lu("/api/openchamber/relay/reset-identity","POST"),async purgeRevokedClients(){const e=await C("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await xs(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),lM=(e={})=>{const t=e.urls??Zl();return kk(t),{clipboard:Ak(),themeFiles:Rk(),runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:rO(),git:YB(),files:cN({getDirectory:()=>Hd.getState().currentDirectory}),settings:pN(),permissions:gN(),notifications:TN(),sourceControl:_B(),trackers:oM(),push:zN(),clientAuth:cM()}},dM=3e3,qu=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},pM=()=>{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__===!0}};let _l=Promise.resolve();const WU=()=>_l,HU=()=>{const{apiBaseUrl:e,clientToken:t,localOrigin:s,runtimeHeaders:a,relayHostId:n,explicitRuntime:i}=pM(),o=om(),r=n||(o?.target==="remote"?o.hostId:""),c=cm({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});Sk({apiBaseUrl:e,runtimeKey:qu(e,s)?"local":r?`host:${r}`:null});const l=u=>{const m=u.trim(),f=window.__OPENCHAMBER_DESKTOP__?.invoke;!m||!f||f("desktop_set_window_runtime_key",{runtimeKey:m}).catch(()=>{})};l(D()),tr(u=>l(u.runtimeKey)),zm(t||null),Am(a||null),Je.reconnectToRuntimeBaseUrl(),nr(e||void 0).catch(()=>{}),s&&!qu(e,s)&&Object.keys(un()).length>0&&Fm(s).catch(()=>{}),Gm();const d=()=>n?Ip(n,{reconnectActive:!0}):i?Promise.resolve():Ip();return _l=Promise.race([d().catch(()=>{}),new Promise(u=>{window.setTimeout(u,1e4)})]).then(()=>{Je.reconnectToRuntimeBaseUrl()}),_l.then(()=>{window.setTimeout(()=>{dv().catch(()=>{})},dM)}),lM({urls:c})},Vu="openchamber:chunk-import-reload",gM=250,uM=3e4,mM=[/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 cw(e){if(e instanceof Error)return`${e.name}
|
|
86
86
|
${e.message}
|
|
87
|
-
${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Uu(e){const t=cw(e);return mM.some(s=>s.test(t))}function hM(e){return`2.7.
|
|
87
|
+
${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Uu(e){const t=cw(e);return mM.some(s=>s.test(t))}function hM(e){return`2.7.1-canary.20261108.12:${cw(e).slice(0,500)}`}function fM(e){if(typeof window>"u"||Oe())return;const t=Date.now(),s=hM(e);let a=null;try{const i=window.sessionStorage.getItem(Vu);if(i)try{a=JSON.parse(i)}catch{a=null}}catch{return}const n=typeof a?.timestamp=="number"?a.timestamp:0;if(!(a?.signature===s&&t-n<uM)){try{window.sessionStorage.setItem(Vu,JSON.stringify({signature:s,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function bM(e,t={}){const s=t.retries??1;let a;for(let n=0;n<=s;n+=1)try{return await e()}catch(i){if(a=i,!Uu(i)||n>=s)break;await new Promise(o=>setTimeout(o,gM*(n+1)))}throw Uu(a)&&fM(a),a}const GU=e=>hw.lazy(()=>bM(e));export{hA as $,Gt as A,ST as B,CT as C,vT as D,xT as E,yT as F,kT as G,AT as H,RT as I,gU as J,wj as K,SU as L,bj as M,qL as N,EL as O,HU as P,bM as Q,sz as R,Ur as S,az as T,nz as U,cz as V,rz as W,oz as X,iz as Y,bA as Z,fA as _,aj as a,iL as a$,mA as a0,uA as a1,gA as a2,pA as a3,dA as a4,lA as a5,cA as a6,rA as a7,oA as a8,iA as a9,jz as aA,Iz as aB,Rz as aC,Az as aD,zz as aE,Tz as aF,Pz as aG,xz as aH,Sz as aI,Cz as aJ,vz as aK,yz as aL,kz as aM,wz as aN,bz as aO,fz as aP,hz as aQ,mz as aR,uz as aS,gz as aT,pz as aU,dz as aV,Lz as aW,D as aX,hU as aY,tr as aZ,SV as a_,nA as aa,aA as ab,sA as ac,tA as ad,eA as ae,Xz as af,Yz as ag,$z as ah,Qz as ai,Jz as aj,Zz as ak,Kz as al,_z as am,Gz as an,Hz as ao,Wz as ap,Uz as aq,Vz as ar,qz as as,Ez as at,Mz as au,Nz as av,Bz as aw,Fz as ax,Dz as ay,Oz as az,Xe as b,qE as b$,VV as b0,_r as b1,Se as b2,kE as b3,ZV as b4,_V as b5,iU as b6,DU as b7,hO as b8,Ai as b9,cE as bA,ij as bB,qV as bC,ua as bD,jM as bE,sE as bF,SE as bG,Jq as bH,fv as bI,FM as bJ,BM as bK,NM as bL,_h as bM,ia as bN,MP as bO,fi as bP,ME as bQ,ir as bR,Gy as bS,bE as bT,NE as bU,sj as bV,rE as bW,pE as bX,Km as bY,Ue as bZ,LE as b_,nr as ba,Dj as bb,ds as bc,rV as bd,kv as be,ph as bf,aU as bg,RC as bh,pd as bi,Xr as bj,eq as bk,yV as bl,vV as bm,WU as bn,Ih as bo,GV as bp,jd as bq,XA as br,Co as bs,cV as bt,uT as bu,uj as bv,gt as bw,Y as bx,EM as by,Ye as bz,TL as c,Yq as c$,qg as c0,bO as c1,KV as c2,uR as c3,OU as c4,jU as c5,er as c6,lE as c7,Nk as c8,EV as c9,vd as cA,pn as cB,wa as cC,yk as cD,en as cE,TE as cF,Kh as cG,OL as cH,fU as cI,gV as cJ,vE as cK,vo as cL,xU as cM,Hc as cN,JV as cO,hS as cP,GU as cQ,Cd as cR,nt as cS,ra as cT,DP as cU,pV as cV,UP as cW,ol as cX,Zh as cY,Xq as cZ,IP as c_,QT as ca,us as cb,IV as cc,CE as cd,ZE as ce,Qq as cf,$q as cg,JP as ch,Jk as ci,Zq as cj,rr as ck,km as cl,Ii as cm,ma as cn,qc as co,Gk as cp,gn as cq,AE as cr,$l as cs,as as ct,zE as cu,td as cv,My as cw,BE as cx,RV as cy,lV as cz,SL as d,Kx as d$,wd as d0,yt as d1,Mh as d2,NL as d3,So as d4,eV as d5,tV as d6,aV as d7,nV as d8,kP as d9,OM as dA,DM as dB,WM as dC,hT as dD,_S as dE,Eq as dF,Jp as dG,HL as dH,Lq as dI,lx as dJ,Ky as dK,qy as dL,DE as dM,FE as dN,Yy as dO,wE as dP,KI as dQ,Hf as dR,tE as dS,cO as dT,wS as dU,bm as dV,dE as dW,oE as dX,Gq as dY,qh as dZ,Wx as d_,sV as da,iV as db,oV as dc,ga as dd,dV as de,RU as df,cr as dg,aE as dh,$i as di,Ha as dj,qx as dk,iE as dl,Ip as dm,nv as dn,It as dp,VL as dq,gk as dr,om as ds,AM as dt,CU as du,_q as dv,RM as dw,nE as dx,IM as dy,UM as dz,mL as e,cU as e$,Hx as e0,Zx as e1,Vx as e2,or as e3,eL as e4,aL as e5,oL as e6,lL as e7,nL as e8,tL as e9,GT as eA,Gh as eB,Hh as eC,Rd as eD,LM as eE,fE as eF,mE as eG,hE as eH,sU as eI,_I as eJ,GI as eK,qU as eL,nj as eM,oj as eN,TT as eO,zT as eP,MT as eQ,ta as eR,fT as eS,av as eT,sv as eU,WE as eV,Bs as eW,nC as eX,Kq as eY,dr as eZ,DL as e_,sL as ea,Qv as eb,Jv as ec,LL as ed,yL as ee,vL as ef,ZM as eg,JM as eh,QM as ei,$M as ej,qM as ek,HM as el,YM as em,_M as en,VM as eo,GM as ep,XM as eq,KM as er,Fx as es,Bx as et,vl as eu,Un as ev,Ad as ew,CA as ex,vA as ey,kV as ez,zL as f,yU as f$,TU as f0,RL as f1,fL as f2,zV as f3,ML as f4,ui as f5,TV as f6,PV as f7,Ck as f8,Em as f9,IS as fA,rk as fB,WL as fC,Hr as fD,DS as fE,TS as fF,Rq as fG,Iq as fH,ES as fI,mR as fJ,Os as fK,sR as fL,GL as fM,fb as fN,sq as fO,QL as fP,kq as fQ,aC as fR,UU as fS,yl as fT,Ps as fU,DA as fV,X as fW,ck as fX,lk as fY,jp as fZ,lU as f_,bP as fa,un as fb,tt as fc,eP as fd,_x as fe,Zd as ff,Wt as fg,IU as fh,um as fi,Ql as fj,Ys as fk,VR as fl,mj as fm,Av as fn,jL as fo,cj as fp,hv as fq,UL as fr,qq as fs,fS as ft,bS as fu,JE as fv,JL as fw,KL as fx,Xi as fy,Yc as fz,gL as g,BS as g$,_a as g0,Zp as g1,rj as g2,LV as g3,PL as g4,UV as g5,$T as g6,jD as g7,KT as g8,cD as g9,uD as gA,mD as gB,mF as gC,LU as gD,pD as gE,TD as gF,dF as gG,iF as gH,zF as gI,AF as gJ,nF as gK,cF as gL,oF as gM,fD as gN,NF as gO,EU as gP,aF as gQ,TF as gR,Db as gS,xF as gT,IF as gU,MU as gV,RF as gW,MD as gX,BD as gY,Ob as gZ,MM as g_,PD as ga,dD as gb,DD as gc,WD as gd,hu as ge,mu as gf,uu as gg,gu as gh,VD as gi,qD as gj,LD as gk,ED as gl,BU as gm,MF as gn,NU as go,wF as gp,bF as gq,fF as gr,vF as gs,hF as gt,zb as gu,kD as gv,Ab as gw,yD as gx,hD as gy,uF as gz,AL as h,$A as h$,Qp as h0,QS as h1,JS as h2,tx as h3,rd as h4,Mv as h5,jE as h6,Cq as h7,wU as h8,RN as h9,iv as hA,lv as hB,EE as hC,KE as hD,_E as hE,UE as hF,VE as hG,_y as hH,mv as hI,AU as hJ,OE as hK,fO as hL,pU as hM,mO as hN,FU as hO,lD as hP,bb as hQ,tq as hR,XL as hS,md as hT,et as hU,bU as hV,eU as hW,nU as hX,tU as hY,jt as hZ,QA as h_,sw as ha,ER as hb,dU as hc,lC as hd,Lc as he,eE as hf,Tq as hg,FL as hh,pC as hi,BL as hj,dC as hk,kU as hl,yj as hm,vU as hn,IL as ho,Sq as hp,Vq as hq,Eh as hr,PE as hs,lT as ht,uU as hu,QI as hv,NI as hw,CV as hx,HE as hy,GE as hz,kA as i,NV as i$,JA as i0,ON as i1,VU as i2,to as i3,aq as i4,sN as i5,mh as i6,zq as i7,wq as i8,hq as i9,RE as iA,YV as iB,QV as iC,$V as iD,XV as iE,YL as iF,jC as iG,E as iH,kh as iI,fq as iJ,ZL as iK,KC as iL,Gx as iM,tS as iN,aS as iO,QC as iP,pr as iQ,ut as iR,SR as iS,IE as iT,jV as iU,DV as iV,MV as iW,FV as iX,OV as iY,BV as iZ,Cf as i_,gq as ia,pq as ib,oq as ic,$L as id,xq as ie,lq as ig,Aq as ih,Dq as ii,Fq as ij,Nq as ik,mq as il,Pq as im,dq as io,uq as ip,$c as iq,yq as ir,vq as is,VC as it,PU as iu,Bq as iv,wR as iw,bR as ix,yE as iy,uh as iz,C as j,oU as j0,rU as j1,Mk as j2,CL as j3,xL as j4,kL as j5,wL as j6,bL as j7,hL as j8,dL as j9,bV as jA,LP as jB,uV as jC,fV as jD,_L as jE,wV as jF,Uq as jG,Mq as jH,$E as jI,QE as jJ,YE as jK,xE as jL,sa as jM,Jd as jN,Hq as jO,Wq as jP,WV as jQ,mU as jR,cL as ja,rL as jb,cC as jc,pL as jd,lO as je,cn as jf,hb as jg,gO as jh,gE as ji,uE as jj,NA as jk,HV as jl,Dd as jm,Oq as jn,jq as jo,$C as jp,nq as jq,iq as jr,zU as js,cq as jt,rq as ju,bq as jv,rR as jw,FP as jx,mV as jy,hV as jz,gm as k,Hd as l,Oe as m,ze as n,uL as o,XE as p,yA as q,rC as r,tj as s,_o as t,P as u,Je as v,Ot as w,xV as x,PT as y,AV as z};
|