@openchamber/web 1.15.0 → 1.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/assets/{DiagramView-HR2xZxJ8.js → DiagramView-Elkp8b4l.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-sm01Q7R7.js → MarkdownRendererImpl-DLhrL6oX.js} +3 -3
- package/dist/assets/{MultiRunWindow-DlFUaNQK.js → MultiRunWindow-DVpNCqnE.js} +1 -1
- package/dist/assets/{OnboardingScreen-DVRz82mJ.js → OnboardingScreen-CpcR0gyq.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-DHO5Je6v.js +1 -0
- package/dist/assets/{SettingsWindow-CkInZcj7.js → SettingsWindow-Bewo7vwh.js} +1 -1
- package/dist/assets/{TerminalView-D_9BAjtv.js → TerminalView-D9C7fNLm.js} +3 -3
- package/dist/assets/es-D9nOo8Wx.js +15 -0
- package/dist/assets/fr-DEF71lgt.js +13 -0
- package/dist/assets/index-BklNmnVr.js +2 -0
- package/dist/assets/index-C3uMIExE.css +1 -0
- package/dist/assets/ja-CpNfaEje.js +15 -0
- package/dist/assets/ko-DLS_rnE-.js +15 -0
- package/dist/assets/main-B0CxEOP5.js +237 -0
- package/dist/assets/{main-DzNa8r0N.js → main-Ck3ZNw8-.js} +2 -2
- package/dist/assets/miniChat-BAJj2Ome.js +2 -0
- package/dist/assets/mobile-CJoX4Cdj.js +2 -0
- package/dist/assets/pl-BjtFn5-n.js +15 -0
- package/dist/assets/pt-BR-C0_4Rnzn.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-D4-OXCXM.js +2 -0
- package/dist/assets/renderMobileApp-DHWdI195.js +16 -0
- package/dist/assets/runtimeEndpointReset-B0P2DED1.js +167 -0
- package/dist/assets/uk-BDu4E0s0.js +15 -0
- package/dist/assets/{useAppFontEffects-DzBg8hrC.js → useAppFontEffects-9LFMCKYW.js} +195 -136
- package/dist/assets/zh-CN-BcwMqxIR.js +15 -0
- package/dist/assets/zh-TW-bNDQjKEu.js +15 -0
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +106 -1
- package/server/lib/notifications/DOCUMENTATION.md +1 -1
- package/server/lib/notifications/apns-runtime.js +3 -1
- package/server/lib/notifications/runtime.js +135 -33
- package/server/lib/opencode/DOCUMENTATION.md +1 -0
- package/server/lib/opencode/agents.js +3 -0
- package/server/lib/opencode/bootstrap-runtime.js +5 -0
- package/server/lib/opencode/core-routes.js +75 -2
- package/server/lib/opencode/core-routes.test.js +81 -0
- package/server/lib/opencode/feature-routes-runtime.js +6 -0
- package/server/lib/opencode/settings-helpers.js +30 -0
- package/server/lib/opencode/settings-helpers.test.js +14 -0
- package/server/lib/opencode/settings-normalization-runtime.js +19 -4
- package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
- package/server/lib/opencode/settings-runtime.js +25 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/opencode/tunnel-auth.js +4 -9
- package/server/lib/package-manager.js +1 -1
- package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
- package/server/lib/permission-auto-accept/runtime.js +263 -0
- package/server/lib/permission-auto-accept/runtime.test.js +137 -0
- package/server/lib/projects/project-config.js +8 -0
- package/server/lib/quota/DOCUMENTATION.md +5 -2
- package/server/lib/quota/credentials/providers.js +43 -0
- package/server/lib/quota/credentials/store.js +48 -0
- package/server/lib/quota/credentials/store.test.js +26 -0
- package/server/lib/quota/opencode-go-credentials.js +11 -0
- package/server/lib/quota/opencode-go-credentials.test.js +32 -0
- package/server/lib/quota/providers/codex.js +7 -4
- package/server/lib/quota/providers/codex.test.js +48 -0
- package/server/lib/quota/providers/cursor.js +28 -39
- package/server/lib/quota/providers/index.js +7 -0
- package/server/lib/quota/providers/ollama-cloud.js +23 -42
- package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
- package/server/lib/quota/providers/opencode-go.js +70 -0
- package/server/lib/quota/providers/opencode-go.test.js +17 -0
- package/server/lib/quota/routes.js +78 -7
- package/server/lib/quota/routes.test.js +40 -0
- package/server/lib/relay/DOCUMENTATION.md +20 -0
- package/server/lib/relay/host-lock.js +101 -0
- package/server/lib/relay/host-lock.test.js +129 -0
- package/server/lib/relay/identity.js +24 -4
- package/server/lib/relay/service.js +95 -8
- package/server/lib/relay/signing-key.js +30 -7
- package/server/lib/scheduled-tasks/runtime.js +104 -0
- package/server/lib/session-goal/DOCUMENTATION.md +176 -0
- package/server/lib/session-goal/objectives.js +61 -0
- package/server/lib/session-goal/routes.js +36 -0
- package/server/lib/session-goal/runtime.js +764 -0
- package/server/lib/small-model/DOCUMENTATION.md +3 -1
- package/server/lib/small-model/call.js +45 -8
- package/server/lib/small-model/call.test.js +338 -0
- package/server/lib/small-model/index.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-DvoOalMY.js +0 -1
- package/dist/assets/es-cjUissX4.js +0 -15
- package/dist/assets/fr-DqbXnTdK.js +0 -13
- package/dist/assets/index-Dg0nmvQU.css +0 -1
- package/dist/assets/index-ltrmNGAf.js +0 -2
- package/dist/assets/ja-Cetyq6Eg.js +0 -15
- package/dist/assets/ko-DtunWisP.js +0 -15
- package/dist/assets/main-BC0m8s1v.js +0 -236
- package/dist/assets/miniChat-BRYDE-Se.js +0 -2
- package/dist/assets/mobile-C3QJVA97.js +0 -2
- package/dist/assets/pl-DctGLgve.js +0 -15
- package/dist/assets/pt-BR-CXPhf78S.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +0 -2
- package/dist/assets/renderMobileApp-wkBjh5WR.js +0 -16
- package/dist/assets/runtimeEndpointReset-C42u8PvG.js +0 -167
- package/dist/assets/uk-Bdrc-kqF.js +0 -15
- package/dist/assets/zh-CN-CeCVKrHP.js +0 -15
- package/dist/assets/zh-TW-CoqiQING.js +0 -15
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{_ as qs,c as Ks,a as er,d as tr,p as To,b as Eo,R as Ht}from"./vendor-.bun-BE757pvp.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(o){if(o.ep)return;o.ep=!0;const s=r(o);fetch(o.href,s)}})();const it=1,Vs="openchamber-relay-v1",ko=1,vo=12,at=1+vo,dt=64*1024,ut=5,ft=128,Ao=0,Po=1,Ke=4,Js=1+Ke,xr=dt-ut-Js,D={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Ys=new Set(Object.values(D)),Qs=e=>Ys.has(e),Ie={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},we=globalThis.crypto.subtle,Do={name:"ECDH",namedCurve:"P-256"},Mo=16,mr=32,Xs=16,Lr=4,Co=8;class Ee extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Zs=()=>we.generateKey(Do,!0,["deriveBits"]),ei=async e=>{const t=await we.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},ti=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Ee("invalid ECDH public key JWK");try{return await we.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Do,!0,[])}catch{throw new Ee("invalid ECDH public key JWK")}},ri=()=>{const e=new Uint8Array(Mo);return globalThis.crypto.getRandomValues(e),e},ni=async(e,t,r)=>{if(r.length!==Mo)throw new Ee("invalid handshake nonce length");const n=await we.deriveBits({name:"ECDH",public:t},e,256),o=await we.importKey("raw",n,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await we.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(Vs)},o,mr*2*8)),i=(a,c)=>we.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(s.slice(0,mr),["encrypt","decrypt"]),hostToClient:await i(s.slice(mr),["encrypt","decrypt"])}},oi=(e,t,r)=>{for(let n=Co-1;n>=0;n-=1)e[t+n]=Number(r&0xffn),r>>=8n},si=(e,t)=>{let r=0n;for(let n=0;n<Co;n+=1)r=r<<8n|BigInt(e[t+n]);return r},ii=e=>{const t=new Uint8Array(Lr);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(n){if(n.length>dt)throw new Ee("plaintext frame exceeds maximum size");r+=1n;const o=new Uint8Array(vo);o.set(t,0),oi(o,Lr,r);const s=new Uint8Array(await we.encrypt({name:"AES-GCM",iv:o},e,n)),i=new Uint8Array(at+s.length);return i[0]=ko,i.set(o,1),i.set(s,at),i}}},ai=e=>{let t=0n;return{async decrypt(r){if(r.length<at+Xs)throw new Ee("encrypted frame too short");if(r[0]!==ko)throw new Ee("unsupported encrypted frame version");const n=r.slice(1,at),o=si(n,Lr);if(o<=t)throw new Ee("frame counter regression");let s;try{s=await we.decrypt({name:"AES-GCM",iv:n},e,r.slice(at))}catch{throw new Ee("frame decryption failed")}return t=o,new Uint8Array(s)}}},vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",ci=e=>{let t="";for(let r=0;r<e.length;r+=3){const n=e[r],o=r+1<e.length?e[r+1]:void 0,s=r+2<e.length?e[r+2]:void 0;t+=vt[n>>2],t+=vt[(n&3)<<4|(o??0)>>4],o!==void 0&&(t+=vt[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=vt[s&63])}return t},Dn=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const r=t;if(r.v!==it)return null;const n=r.batch===!0;return r.t==="ready"?{t:"ready",v:it,batch:n}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:it,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:n}:null},li=e=>({type:"fail",closeCode:Ie.ChannelFailure,reason:e}),di=async(e,t={})=>{const r=t.batch!==!1,n=await ti(e),o=await Zs(),s=ri(),i={t:"hello",v:it,clientPubJwk:await ei(o.publicKey),nonce:ci(s),...r?{batch:!0}:{}};let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return Dn(c)?.t==="ready"?{type:"ignore"}:li("plaintext frame on established channel");const l=Dn(c);if(l?.t!=="ready")return{type:"ignore"};const d=await ni(o.privateKey,n,s);return a=!0,{type:"established",batch:r&&l.batch===!0,channel:{encryptor:ii(d.clientToHost),decryptor:ai(d.hostToClient)}}}}},Ro=4294967295;class q extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const pe=(e,t,r,n=!1)=>{if(!Number.isInteger(t)||t<0||t>Ro)throw new q("invalid stream id");if(r.length>xr)throw new q("tunnel payload exceeds maximum size");const o=new Uint8Array(ut+r.length);return o[0]=n?e|ft:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(r,ut),o},ui=e=>{if(e.length<ut)throw new q("tunnel frame too short");const t=e[0],r=(t&ft)!==0,n=t&~ft;if(!Qs(n))throw new q(`unknown tunnel frame type ${n}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:n,streamId:o,payload:e.slice(ut),hasMoreFragments:r}},fi=new TextEncoder,hi=new TextDecoder,At=e=>fi.encode(JSON.stringify(e)),Pt=(e,t)=>{let r;try{r=JSON.parse(hi.decode(e))}catch{throw new q("malformed JSON tunnel payload")}if(!t(r))throw new q("unexpected JSON tunnel payload shape");return r},Oo=(e,t=xr)=>{if(t<=0||t>xr)throw new q("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r},Mn=(e,t,r)=>{const n=Oo(r);return n.map((o,s)=>pe(e,t,o,s<n.length-1))},pi=(e=16*1024*1024)=>{const t=new Map;return{push(r){const n=`${r.streamId}:${r.frameType}`,o=t.get(n);if(!r.hasMoreFragments&&!o)return r.payload;const s=o?.chunks??[],i=(o?.totalBytes??0)+r.payload.length;if(i>e)throw t.delete(n),new q("fragmented message exceeds maximum size");if(s.push(r.payload),r.hasMoreFragments)return t.set(n,{chunks:s,totalBytes:i}),null;t.delete(n);const a=new Uint8Array(i);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a},dropStream(r){for(const n of t.keys())n.startsWith(`${r}:`)&&t.delete(n)}}},mi=e=>{if(e.length===0)throw new q("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=Ao,s.set(o,1),s.length>dt)throw new q("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=Ke+o.length;if(t>dt)throw new q("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=Po;let n=1;for(const o of e)r[n]=o.length>>>24&255,r[n+1]=o.length>>>16&255,r[n+2]=o.length>>>8&255,r[n+3]=o.length&255,n+=Ke,r.set(o,n),n+=o.length;return r},yi=e=>{if(e.length<1)throw new q("empty batch plaintext");const t=e[0];if(t===Ao)return[e.slice(1)];if(t!==Po)throw new q(`unknown batch container tag ${t}`);const r=[];let n=1;for(;n<e.length;){if(n+Ke>e.length)throw new q("truncated batch frame length");const o=(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0;if(n+=Ke,n+o>e.length)throw new q("truncated batch frame body");r.push(e.slice(n,n+o)),n+=o}if(r.length===0)throw new q("empty frame batch");return r},gi=new Set([D.HttpBody,D.WsText,D.WsBinary]),Io=150,wi=24*1024,bi=32,Si=e=>{const t=e.windowMs??Io,r=e.maxBatchBytes??wi,n=e.maxBatchFrames??bi,o=e.now??(()=>Date.now()),s=e.setTimer??((b,T)=>setTimeout(b,T)),i=e.clearTimer??(b=>clearTimeout(b));let a=[],c=0,l=null,d=0,f=!1;const w=()=>{l!==null&&(i(l),l=null)},p=()=>{if(w(),a.length===0)return;const b=a;a=[],c=0,d=o(),e.sendBatch(mi(b))};return{enqueue:b=>{if(f)return;const T=b[0]&~ft;if(!gi.has(T)){a.push(b),p();return}const S=o();if(a.length===0&&S-d>=t){a.push(b),p();return}const R=Ke+b.length;if(a.length>0&&1+c+R>dt&&p(),a.push(b),c+=R,c>=r||a.length>=n){p();return}l===null&&(l=s(p,t))},flush:p,dispose(){f=!0,w(),a=[],c=0}}},Ti=()=>{let e=1;return{next(){if(e>Ro)throw new q("stream id space exhausted");const t=e;return e+=2,t}}},rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ei=e=>rr(e)&&Object.values(e).every(t=>typeof t=="string"),ki=e=>rr(e)&&typeof e.status=="number"&&Ei(e.headers),Cn=e=>rr(e)&&typeof e.reason=="string",vi=e=>rr(e)&&typeof e.code=="number"&&typeof e.reason=="string",_o=/^[a-z][a-z\d+.-]*:\/\//i,tn="http://tunnel.invalid",Ai=e=>{try{const t=_o.test(e)?new URL(e):new URL(e,tn);return`${t.pathname}${t.search}`}catch{return e}},Dt=e=>({async*[Symbol.asyncIterator](){yield e}}),Pi=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:r,value:n}=await t.read();if(r)return;n&&(yield n)}}finally{t.releaseLock()}}}),Di=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Mi=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Pi(e)};if(typeof e=="string")return{body:Dt(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Dt(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Dt(Di(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,n=new Uint8Array(await t.arrayBuffer());return{body:Dt(n),contentType:r}},Ci=async(e,t)=>{let r;const n=new Headers;let o="GET",s=null,i;e instanceof Request?(r=e.url,o=e.method,e.headers.forEach((f,w)=>n.set(w,f)),i=e.signal,s=e.body):r=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((f,w)=>n.set(w,f)),t.body!==void 0&&(s=t.body),t.signal&&(i=t.signal));const a=_o.test(r)?new URL(r):new URL(r,tn),{body:c,contentType:l}=await Mi(s);l&&!n.has("content-type")&&n.set("content-type",l);const d={};return n.forEach((f,w)=>{d[w]=f}),{method:o.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:d,body:c,signal:i}},yr=new Uint8Array(0),Ri=new TextEncoder,Oi=new TextDecoder,oe=e=>e instanceof Error?e:new Error(String(e)),Mt=()=>new DOMException("The operation was aborted.","AbortError"),Ii=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(r){e.send(r)},close(r,n){e.close(r,n)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>t.onmessage?.({data:r.data}),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),e.onerror=()=>t.onerror?.(),t},_i=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(r){r&&(e.binaryType=r)},onopen:null,onmessage:null,onerror:null,onclose:null,send(r){e.send(r)},close(r,n){e.close(r,n)}};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>{const n=r.data;(typeof n=="string"||n instanceof ArrayBuffer)&&t.onmessage?.({data:n})},e.onerror=()=>t.onerror?.(),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),t},Rn=0,gr=1,On=2,In=3,Fi=new Set([Ie.AuthFailed,Ie.DuplicateClient,Ie.LimitExceeded]),xi={[Ie.AuthFailed]:"relay authentication failed",[Ie.DuplicateClient]:"relay connection replaced by another client",[Ie.LimitExceeded]:"relay connection limit reached"},_n=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Fo=e=>{const t=e.helloRetryMs??1e3,r=e.helloTimeoutMs??3e4,n=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??Io,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(g=>Ii(new WebSocket(g)));let f=!1,w={state:"idle"};const p=new Set;let h=null,b=null,T=null,S=0,R=0,E=null,C=[],be=!1;const ne=g=>{if(!(w.state===g.state&&w.lastError===g.lastError)){w=g;for(const M of p)try{M(w)}catch{}}},et=g=>{const M=C;C=[];for(const k of M)k.reject(g)},dr=g=>{const M=C;C=[];for(const k of M)k.resolve(g)},kn=(g,M)=>{g.dead=!0;const k=Array.from(g.streams.values());g.streams.clear();for(const v of k)try{v.fail(M)}catch{}},ur=()=>{E!==null&&(clearTimeout(E),E=null)},fr=()=>{f||E===null||_n()||(ur(),hr(),pr())},vn=()=>{typeof document<"u"&&document.visibilityState==="visible"&&fr()},js=()=>{be||typeof window>"u"||(be=!0,window.addEventListener("online",fr),typeof document<"u"&&document.addEventListener("visibilitychange",vn))},hr=()=>{!be||typeof window>"u"||(be=!1,window.removeEventListener("online",fr),typeof document<"u"&&document.removeEventListener("visibilitychange",vn))},An=()=>{if(f||E!==null)return;const g=Math.max(0,R-1),M=a*2**Math.min(g,10),k=_n()?l:c,v=Math.min(k,M);js(),E=setTimeout(()=>{E=null,hr(),pr()},v)},Hs=()=>{const g=new URL(e.relayUrl);return g.searchParams.set("v",String(it)),g.searchParams.set("role","client"),g.searchParams.set("serverId",e.serverId),e.grant&&g.searchParams.set("grant",e.grant),g.toString()},pr=async()=>{if(f)return;ur(),S+=1;const g=S;ne({state:R>0?"reconnecting":"connecting",lastError:w.lastError});let M;try{M=await di(e.hostEncPubJwk,{batch:i})}catch(_){if(g!==S||f)return;tt(g,oe(_),!0);return}if(g!==S||f)return;let k;try{k=d(Hs())}catch(_){tt(g,oe(_));return}b=k;let v=!1,A=null,O=null,ee=null,z=null,P=Promise.resolve(),I=null,L=null,fe=!1,N=null,$=Date.now();const K=()=>{A!==null&&(clearInterval(A),A=null),O!==null&&(clearTimeout(O),O=null),ee!==null&&(clearInterval(ee),ee=null),z!==null&&(clearTimeout(z),z=null),N!==null&&(N.dispose(),N=null)};T=K;function G(_,F=!1,U=!1){if(!(v||g!==S)){v=!0,K(),I&&(h=null,kn(I,new Error(`relay tunnel reset: ${_.message}`))),et(_);try{k.close()}catch{}if(b===k&&(b=null),!f){if(R+=1,U){ne({state:"error",lastError:_.message});return}ne({state:F?"error":"reconnecting",lastError:_.message}),An()}}}const x=()=>{try{k.send(M.helloText)}catch{}},Ae=(_,F)=>{L=_,fe=F,A!==null&&(clearInterval(A),A=null),O!==null&&(clearTimeout(O),O=null);const U=new Map,B=Ti(),Pe=pi();let re=Promise.resolve();const he=Ne=>{re=re.then(async()=>{if(Ue.dead)return;const kt=await _.encryptor.encrypt(Ne);k.send(kt)}).catch(()=>{})},De=F?Si({windowMs:s,sendBatch:he}):null;N=De;const Ue={streams:U,assembler:Pe,nextStreamId:()=>B.next(),dead:!1,send(Ne){if(Ue.dead)return;const kt=Ne[0]&~ft;kt!==D.Ping&&kt!==D.Pong&&($=Date.now()),De?De.enqueue(Ne):he(Ne)}};I=Ue,h=Ue,R=0,$=Date.now(),ne({state:"connected"}),dr(Ue),ee=setInterval(()=>{Date.now()-$<n||(Ue.send(pe(D.Ping,0,yr)),z===null&&(z=setTimeout(()=>{z=null,G(new Error("relay keepalive timeout"))},o)))},n)},te=(_,F)=>{let U;try{U=ui(F)}catch(re){G(oe(re));return}if(z!==null&&(clearTimeout(z),z=null),U.frameType===D.Ping){_.send(pe(D.Pong,U.streamId,yr));return}if(U.frameType===D.Pong)return;$=Date.now();let B=U.payload;if(U.frameType===D.WsText||U.frameType===D.WsBinary){let re;try{re=_.assembler.push(U)}catch(he){G(oe(he));return}if(re===null)return;B=re}else if(U.hasMoreFragments){G(new Error("unexpected fragmented tunnel frame"));return}const Pe=_.streams.get(U.streamId);Pe&&Pe.handleFrame(U.frameType,B)};k.onopen=()=>{v||g!==S||(x(),A=setInterval(x,t))},k.onmessage=_=>{if(v||g!==S)return;const F=_.data;if(typeof F=="string"){P=P.then(async()=>{if(v||g!==S)return;const B=await M.handleText(F);if(B.type==="established"){if(L)return;Ae(B.channel,B.batch)}else B.type==="fail"&&G(new Error(`relay handshake failed: ${B.reason}`))}).catch(B=>{G(oe(B))});return}const U=F instanceof ArrayBuffer?new Uint8Array(F):F instanceof Uint8Array?F:null;U&&(P=P.then(async()=>{if(v||g!==S)return;const B=I,Pe=L;if(!B||!Pe){G(new Error("encrypted frame before handshake completed"));return}let re;try{re=await Pe.decryptor.decrypt(U)}catch(he){G(oe(he));return}if(fe){let he;try{he=yi(re)}catch(De){G(oe(De));return}for(const De of he){if(v||g!==S||B.dead)return;te(B,De)}return}te(B,re)}).catch(B=>{G(oe(B))}))},k.onclose=_=>{const F=Fi.has(_.code);G(new Error(xi[_.code]??`relay socket closed (code ${_.code})`),F,F)},k.onerror=()=>{},O=setTimeout(()=>{O=null,G(new Error("relay handshake timeout"),!0)},r);function tt(_,F,U=!1){_!==S||f||(et(F),R+=1,ne({state:U?"error":"reconnecting",lastError:F.message}),An())}},Pn=g=>f?Promise.reject(new Error("relay tunnel closed")):g?.aborted?Promise.reject(Mt()):h&&!h.dead?Promise.resolve(h):new Promise((M,k)=>{let v=null;const A={resolve(O){v&&g&&g.removeEventListener("abort",v),M(O)},reject(O){v&&g&&g.removeEventListener("abort",v),k(O)}};g&&(v=()=>{C=C.filter(O=>O!==A),k(Mt())},g.addEventListener("abort",v,{once:!0})),C.push(A)}),zs=async(g,M)=>{const k=await Ci(g,M),v=k.signal;if(v?.aborted)throw Mt();const A=await Pn(v),O=A.nextStreamId();return await new Promise((ee,z)=>{let P=!1,I=!1,L=null,fe=null;const N=()=>{A.streams.delete(O),A.assembler.dropStream(O),fe&&v&&v.removeEventListener("abort",fe)},$=x=>{if(!I){if(I=!0,N(),!P){z(x);return}try{L?.error(x)}catch{}}},K=x=>{A.dead||A.send(pe(D.StreamAbort,O,At({reason:x})))};fe=()=>{K("aborted"),$(Mt())},A.streams.set(O,{handleFrame(x,Ae){if(x===D.HttpResponse){if(P||I)return;let te;try{te=Pt(Ae,ki)}catch(F){K("malformed response head"),$(oe(F));return}const tt=te.status===204||te.status===205||te.status===304;let _=null;tt||(_=new ReadableStream({start(F){L=F},cancel(){I||(I=!0,N(),K("response body cancelled"))}})),P=!0,ee(new Response(_,{status:te.status,headers:te.headers})),tt&&(I=!0,N());return}if(x===D.HttpBody){if(!P||I)return;try{L?.enqueue(Ae)}catch{}return}if(x===D.StreamEnd){if(I)return;if(!P){$(new Error("tunnel stream ended before response head"));return}I=!0,N();try{L?.close()}catch{}return}if(x===D.StreamAbort){let te="stream aborted by host";try{te=Pt(Ae,Cn).reason}catch{}$(new Error(te))}},fail(x){$(x)}}),v&&v.addEventListener("abort",fe,{once:!0});const G={method:k.method,path:k.path,query:k.query,headers:k.headers};A.send(pe(D.HttpRequest,O,At(G))),(async()=>{try{if(k.body)for await(const x of k.body){if(I||A.dead)return;for(const Ae of Oo(x))A.send(pe(D.HttpBody,O,Ae))}!I&&!A.dead&&A.send(pe(D.StreamEnd,O,yr))}catch(x){K("request body failed"),$(oe(x))}})()})},$s=g=>{const M=g.indexOf("?");return M===-1?{path:g,query:""}:{path:g.slice(0,M),query:g.slice(M+1)}},Gs=(g,M)=>{let k=Rn,v=null,A=0,O=!1;const ee={get readyState(){return k},onopen:null,onmessage:null,onerror:null,onclose:null,send(P){if(k!==gr||!v||v.dead)throw new Error("relay tunnel socket is not open");if(typeof P=="string"){for(const L of Mn(D.WsText,A,Ri.encode(P)))v.send(L);return}const I=P instanceof ArrayBuffer?new Uint8Array(P.slice(0)):(()=>{const L=new Uint8Array(P.byteLength);return L.set(new Uint8Array(P.buffer,P.byteOffset,P.byteLength)),L})();for(const L of Mn(D.WsBinary,A,I))v.send(L)},close(P=1e3,I=""){k===In||k===On||(k===gr&&v&&!v.dead&&(k=On,v.send(pe(D.WsClose,A,At({code:P,reason:I})))),z(P,I))}},z=(P,I,L=!1)=>{if(!O){if(O=!0,v&&(v.streams.delete(A),v.assembler.dropStream(A)),k=In,L)try{ee.onerror?.()}catch{}try{ee.onclose?.({code:P,reason:I})}catch{}}};return(async()=>{let P;try{P=await Pn()}catch(N){z(1006,oe(N).message,!0);return}if(O)return;v=P,A=P.nextStreamId(),P.streams.set(A,{handleFrame(N,$){if(N===D.WsOpened){if(k===Rn){k=gr;try{ee.onopen?.()}catch{}}return}if(N===D.WsText){try{ee.onmessage?.({data:Oi.decode($)})}catch{}return}if(N===D.WsBinary){const K=new ArrayBuffer($.byteLength);new Uint8Array(K).set($);try{ee.onmessage?.({data:K})}catch{}return}if(N===D.WsClose){let K=1e3,G="";try{const x=Pt($,vi);K=x.code,G=x.reason}catch{}z(K,G);return}if(N===D.StreamAbort){let K="stream aborted";try{K=Pt($,Cn).reason}catch{}z(1006,K,!0)}},fail(N){z(1012,N.message,!0)}});const{path:I,query:L}=$s(g),fe=M&&M.length>0?{path:I,query:L,protocols:M}:{path:I,query:L};P.send(pe(D.WsOpen,A,At(fe)))})(),ee},Ws=()=>{if(f)return;f=!0,S+=1,ur(),hr(),T?.(),T=null;const g=h;h=null;const M=new Error("relay tunnel closed");g&&kn(g,M),et(M);try{b?.close()}catch{}b=null,ne({state:"idle"})};return pr(),{fetch:zs,openWebSocket:Gs,getStatus:()=>w,subscribeStatus(g){return p.add(g),()=>{p.delete(g)}},close:Ws}};let ye=null,Lt=null;const Li=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),nr=()=>ye,ou=()=>ye!==null,Ui=e=>(ye&&Lt&&Li(Lt,e)||(ye?.close(),Lt=e,ye=Fo(e)),ye),Ni=()=>{ye?.close(),ye=null,Lt=null};let xo=()=>null,Lo="",zt={},Fe="",ht=0,Re=null,qe="",pt=0,Be=null,Ut=0;const rn=1e4,Bi=e=>e.toLowerCase()==="authorization",Uo=e=>{const t={};for(const[r,n]of Object.entries(e||{})){const o=r.trim(),s=n.trim();o&&s&&!Bi(o)&&(t[o]=s)}return t},ji=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([n,o])=>t[n]===o)},or=e=>typeof e!="string"?"":e.trim(),Hi=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return or(e)},zi=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},No=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():zi();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},sr=()=>{Fe="",ht=0,qe="",pt=0},Bo=()=>{Ut+=1,Re=null,sr(),on()},jo=e=>{const t=or(e);Lo=t,Bo(),xo=()=>t?{type:"bearer",token:t}:null},Ho=e=>{const t=Uo(e);ji(zt,t)||(zt=t,Bo())},ir=()=>{if(Object.keys(zt).length>0)return zt;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Uo(e):{}},zo=()=>Lo||Hi(),$i=(e,t)=>{const r=or(e);if(!r||typeof t!="number"||!Number.isFinite(t)){sr();return}const n=Fe;Fe=r,ht=t,n&&n!==r&&Vi()},$o=()=>!Fe||ht<=Date.now()+rn?(sr(),""):Fe,Go=()=>!qe||pt<=Date.now()+rn?(qe="",pt=0,""):qe,Gi=()=>{const e=$o();return!e&&(zo()||typeof window<"u")&&nn().catch(()=>{}),e},Wi=e=>{const t=Go();return!t&&e&&typeof window<"u"&&Ko(e).catch(()=>{}),t},Wo=async()=>{const e=await xo(),t=e?.type==="bearer"?or(e.token):zo();return t?{type:"bearer",token:t}:null},qo=e=>{if(Re)return Re;const t=Ut,n=(async()=>{const o=await Wo(),s=new Headers;for(const[f,w]of Object.entries(ir()))s.set(f,w);o?.type==="bearer"&&s.set("Authorization",`Bearer ${o.token}`);const i=nr(),a=i?await i.fetch("/auth/url-token",{method:"POST",headers:s}):await fetch(No(e,"/auth/url-token"),{method:"POST",headers:s,credentials:"include"});if(!a.ok)throw t===Ut&&sr(),new Error(`Failed to mint runtime URL auth token (${a.status})`);const c=await a.json().catch(()=>null),l=typeof c?.token=="string"?c.token.trim():"",d=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==Ut)throw new Error("Runtime URL auth token response is stale");if($i(l,d),!Fe)throw new Error("Runtime URL auth token response was invalid");return Fe})().finally(()=>{Re===n&&(Re=null)});return Re=n,Re},qi=e=>{if(Be)return Be;const r=(async()=>{const n=await fetch(No(e,"/auth/url-token"),{method:"POST",credentials:"include"});if(!n.ok)throw qe="",pt=0,new Error(`Failed to mint local runtime URL auth token (${n.status})`);const o=await n.json().catch(()=>null),s=typeof o?.token=="string"?o.token.trim():"",i=typeof o?.expiresAt=="number"?o.expiresAt:0;if(!s||!Number.isFinite(i))throw new Error("Local runtime URL auth token response was invalid");return qe=s,pt=i,s})().finally(()=>{Be===r&&(Be=null)});return Be=r,Be},nn=async e=>{const t=$o();return t||qo(e)},Ko=async e=>{const t=Go();return t||qi(e)};let $e=0,ct=null,Vo=null;const Ur=new Set,Ki=5e3,Vi=()=>{for(const e of Ur)try{e()}catch{}},Jo=()=>{ct!==null&&(clearTimeout(ct),ct=null)},on=()=>{if(Jo(),$e<=0||typeof window>"u")return;const e=ht-rn-Ki,t=ht>0?Math.max(0,e-Date.now()):0;ct=setTimeout(()=>{ct=null,!($e<=0)&&qo(Vo).catch(()=>{}).finally(()=>{on()})},t)},su=e=>{typeof e=="string"&&e.trim()&&(Vo=e.trim()),$e+=1,on();let t=!1;return()=>{t||(t=!0,$e=Math.max(0,$e-1),$e===0&&Jo())}},iu=e=>(Ur.add(e),()=>{Ur.delete(e)}),Ji=async e=>{const t=new Headers(e);for(const[n,o]of Object.entries(ir()))t.has(n)||t.set(n,o);if(t.has("Authorization"))return t;const r=await Wo();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},$t=/^[a-z][a-z\d+.-]*:\/\//i,Yi=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Gt=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Qi=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Gt(e)},Xi=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Gt(e)},Zi=()=>Object.keys(ir()).length>0,ea=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Nr=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of r)o!=null&&e.searchParams.set(n,String(o))},ta=(e,t)=>{if(!t)return e;const r=new URLSearchParams;Nr({searchParams:r},t);const n=r.toString();return n?e.includes("?")?`${e}&${n}`:`${e}?${n}`:e},Fn=(e,t,r)=>{if($t.test(t)){const s=new URL(t);return Nr(s,r),s.toString()}const n=Yi(t);if(!e)return ta(n,r);const o=new URL(n,`${e}/`);return Nr(o,r),o.toString()},wr=e=>{const t=Gi();if(!t)return e;const r=$t.test(e)?new URL(e):new URL(e,"http://openchamber.local");return r.searchParams.set("oc_url_token",t),$t.test(e)?r.toString():`${r.pathname}${r.search}${r.hash}`},Yo=(e,t)=>{const r=$t.test(e)?new URL(e):new URL(e,ea(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},xn=(e,t,r)=>{if(!Zi())return null;const n=Xi();if(!n)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${n}/`);o.searchParams.set("url",t);const s=Wi(n);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Yo(o.toString(),r)):o.toString()}catch{return null}},sn=(e={})=>{const t=Gt(e.apiBaseUrl),r=Gt(e.realtimeBaseUrl),n=()=>t||Qi(),o=()=>r||n(),s=(a,c)=>Fn(n(),a,c),i=(a,c)=>Fn(o(),a,c);return{api:s,authenticatedAsset:(a,c)=>wr(s(a,c)),auth:s,health:a=>s("/health",a),rawFile:(a,c)=>s("/api/fs/raw",{path:a,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(a,c)=>{const l=wr(i(a,c));return xn("sse",l,e)||l},websocket:(a,c)=>{const l=Yo(wr(i(a,c)),e);return xn("ws",l,e)||l}}};let Wt=sn();const X=()=>Wt,ra=e=>{Wt=e},Qo=e=>(Wt=sn(e),Wt),xe=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",na=()=>typeof window>"u"?"":window.location.origin||"",an=e=>{if(typeof window>"u")return!1;const t=na();if(t&&e.origin===t)return!0;try{const r=new URL(window.location.href||t);return e.protocol===r.protocol&&e.host===r.host}catch{return!1}},cn=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),ln=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of r)o!=null&&e.searchParams.set(n,String(o))},Nt=e=>{try{const t=X().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const r=new URL(t);return e.origin!==r.origin?!1:xe(e.pathname)}catch{return!1}},br=e=>{if(xe(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return an(t)&&xe(t.pathname)}catch{return!1}},oa=(e,t)=>{try{const r=new URL(e);if(!an(r))return e;const n=_e(`${r.pathname}${r.search}`,t);return!cn(n)&&(r.protocol==="http:"||r.protocol==="https:")?(ln(r,t),r.toString()):r.hash?`${n}${r.hash}`:n}catch{return e}},_e=(e,t)=>e==="/health"?X().health(t):e.startsWith("/auth/")||e==="/auth"?X().auth(e,t):xe(e)?X().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?oa(e,t):e,sa=e=>{const t=e instanceof Request?e.url:e.toString();if(!cn(t))return xe(t);try{return Nt(new URL(t))}catch{return!1}},ia=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},aa=(e,t)=>!ia(t),Ln=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const r=[];let n=!1,o=!1;for(const[s,i]of t)aa(s,i)?(r.push([s,encodeURIComponent(i)]),n=!0,s.toLowerCase()==="x-opencode-directory"&&(o=!0)):r.push([s,i]);return o&&r.push(["x-opencode-directory-encoding","uri"]),n?r:void 0},me=async(e,t,r=!0)=>{const n=new Headers(Ln(e)??e);return t&&new Headers(Ln(t)??t).forEach((o,s)=>n.set(s,o)),r?Ji(n):n},ca=(e,t)=>{if(!t)return e;const r=new URL(e,tn);return ln(r,t),`${r.pathname}${r.search}`},Xo=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!cn(r))return xe(r)?ca(r,t):null;try{const n=new URL(r);return!an(n)||!xe(n.pathname)?null:(ln(n,t),`${n.pathname}${n.search}`)}catch{return null}},la=async(e,t,r)=>{const n=nr();if(!n)return null;const o=Xo(e,r);if(o===null)return null;const s=e instanceof Request?e.headers:void 0,i=await me(s,t.headers,!0);return e instanceof Request?n.fetch(e,{...t,headers:i}):n.fetch(o,{...t,headers:i})},da=(e,t)=>{if(typeof e=="string")return _e(e,t);if(e instanceof URL)return _e(e.toString(),t);const r=_e(e.url,t);return r===e.url?e:new Request(r,e)},ua=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Ct=new Map,fa=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!ua.test(t)?null:`GET ${t}`,u=async(e,t={})=>{const{query:r,...n}=t,o=nr(),s=o?Xo(e,r):null;let i,a,c;if(o&&s!==null){const p=e instanceof Request?e.headers:void 0,h=await me(p,n.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...n,headers:h}):()=>o.fetch(s,{...n,headers:h}),a=s,c=String(n.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const p=da(e,r),h=p instanceof Request?p.headers:void 0,b=await me(h,n.headers,sa(p));i=p instanceof Request?()=>fetch(new Request(p,{...n,headers:b})):()=>fetch(p,{...n,headers:b}),a=p instanceof Request?p.url:p instanceof URL?p.toString():String(p),c=String(n.method??(p instanceof Request?p.method:"GET")).toUpperCase()}const l=n.signal!=null||e instanceof Request,d=fa(c,a,l);if(!d)return i();const f=Ct.get(d);if(f)return f.then(p=>p.clone());const w=i();return Ct.set(d,w),w.then(()=>Ct.delete(d),()=>Ct.delete(d)),w.then(p=>p.clone())};let Un=!1;const ha=()=>{if(Un||typeof window>"u")return;Un=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const n=await la(t,r??{});if(n)return n;if(typeof t=="string"){if(!br(t)){try{const s=new URL(t);if(Nt(s)){const i=await me(void 0,r?.headers);return e(t,{...r,headers:i})}}catch{}return e(t,r)}const o=await me(void 0,r?.headers);return e(_e(t),{...r,headers:o})}if(t instanceof URL){const o=t.toString();if(!br(o)){if(Nt(t)){const i=await me(void 0,r?.headers);return e(t,{...r,headers:i})}return e(t,r)}const s=await me(void 0,r?.headers);return e(_e(o),{...r,headers:s})}if(t instanceof Request){if(!br(t.url)){try{const a=new URL(t.url);if(Nt(a)){const c=await me(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const o=await me(t.headers,r?.headers),s=_e(t.url),i=s===t.url?t:new Request(s,t);return e(new Request(i,{...r,headers:o}))}return e(t,r)}},Br="openchamber:runtime-endpoint-changed";let qt="",mt="";const Sr=(e,t,r)=>{try{e[t]=r}catch{}},dn=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"}`}},Zo=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},es=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},ts=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},un=()=>qt||Zo(),St=()=>{if(mt)return mt;const e=un();return ts(e,es())?"local":dn(e)},pa=(e={})=>{if(qt||mt)return;const t=e.apiBaseUrl?.trim()||Zo();t&&(qt=t,mt=e.runtimeKey?.trim()||(ts(t,es())?"local":dn(t)))},Nn=e=>{const t=e.apiBaseUrl.trim(),r=un(),n=St(),o=e.runtimeKey?.trim()||dn(t);if(qt=t,mt=o,typeof window<"u"){const s=window;Sr(s,"__OPENCHAMBER_API_BASE_URL__",t),Sr(s,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Sr(s,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Qo({apiBaseUrl:t,realtimeBaseUrl:t}),Ho(e.requestHeaders||null),jo(e.clientToken||null),e.relay?Ui(e.relay):Ni(),nn(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Br,{detail:{apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:o,previousRuntimeKey:n}}))},ma=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(Br,t),()=>window.removeEventListener(Br,t)},ya=["local","remote",null],ga=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function rs(e){if(!e||typeof e!="object")return{valid:!1};const t=e,r=t.target,n=t.status;if(r!==null&&(typeof r!="string"||!ya.includes(r)))return{valid:!1};if(typeof n!="string"||!ga.includes(n))return{valid:!1};if(r==="remote"||r==="local"){if(n==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok"}};if(n==="ok"&&r==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url}};if(n==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable"}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url}};if(n==="incompatible"||n==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url}};if(n==="missing")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId}}}if(r===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured"}};if(n==="missing")return{valid:!1}}return{valid:!1}}function au(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;if(t.status==="ok"){if(t.target==="local")return{screen:"main"};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser"};if(t.target==="local"&&t.status==="unreachable")return{screen:"recovery",variant:"local-unavailable"};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId}}return null}function cu(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function lu(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function wa(){if(ba()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,r=rs(t);return r.valid?r.outcome:null}function ba(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":rs(e).valid?"valid":"malformed"}let jr=null;const du=e=>{jr=e},ar=()=>jr||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Sa=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Xe=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,fn=()=>Sa()?.runtime==="electron",Y=()=>typeof Xe()?.invoke=="function",Ze=()=>fn()&&Y(),H=async(e,t)=>{const r=Xe();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},uu=async()=>{if(!Ze()||!Q())return null;try{const e=await H("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},fu=async e=>{if(!Ze()||!Q())return null;try{const t=await H("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},hu=async()=>{if(!Ze()||!Q())return null;try{const e=await H("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},pu=async e=>{if(!Ze()||!Q())return null;try{const t=await H("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},mu=async()=>{if(!Ze()||!Q())return null;try{const e=await H("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},yu=async e=>{if(!Ze()||!Q())return null;try{const t=await H("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},Bn=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}}},Tr=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}}},Ta=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),rt=e=>{const t=Ta(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Q=()=>{if(typeof window>"u"||!ns())return!1;if(St()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Tr(e),r=Tr(un());if(!r&&t&&wa()?.target==="local")return!0;if(t&&r){if(t.origin===r.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&i===a&&rt(t.hostname)&&rt(r.hostname)}const n=Tr(window.location.origin);if(t&&n){if(t.origin===n.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&i===a&&rt(t.hostname)&&rt(n.hostname)}const o=Bn(e),s=Bn(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(n&&rt(n.hostname))},ns=()=>typeof window>"u"?!1:fn(),gu=async()=>{if(!ns())return!1;try{return await H("desktop_start_window_drag"),!0}catch{return!1}},cr=()=>ar()?.runtime?.isVSCode===!0,wu=()=>{const t=ar()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!cr()},os=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},bu=async e=>{if(Y()&&Q())try{const t=await Xe()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory"});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:!0,path:e}},ss=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Su=async e=>{if(Y()&&Q())try{const t=await Xe()?.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(!ss(t))return{success:!1,error:"File selection cancelled"};const r=typeof t.path=="string"?t.path:"";return r?{success:!0,path:r,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},Tu=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!Y()||!Q())return{success:!1,error:"Native file access not available"};try{const r=await Xe()?.grantFileAccess?.(t);if(!ss(r))return{success:!1,error:"File access was not granted"};const n=typeof r.path=="string"?r.path:"",o=typeof r.outsideFileGrant=="string"?r.outsideFileGrant:"";return!n||!o?{success:!1,error:"File access was not granted"}:{success:!0,path:n,outsideFileGrant:o}}catch(r){return console.warn("Failed to request existing file access",r),{success:!1,error:r instanceof Error?r.message:String(r)}}},Eu=async e=>({success:!0}),ku=async e=>({success:!0}),vu=async()=>{if(!Y())return null;try{return await H("desktop_check_for_updates")}catch(e){return console.warn("Failed to check for updates",e),null}},Au=async e=>{if(!Y())return!1;const t=Xe();let r=null,n=0,o;try{return typeof e=="function"&&t?.listen&&(r=await t.listen("openchamber:update-progress",s=>{const i=s?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){n=0,o=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:n,total:o});return}if(c==="Progress"){const d=l?.downloaded,f=l?.total;typeof d=="number"&&(n=d),typeof f=="number"&&(o=f),e({downloaded:n,total:o});return}c==="Finished"&&e({downloaded:n,total:o})})),await H("desktop_download_and_install_update"),!0}catch(s){return console.warn("Failed to download update",s),!1}finally{if(r)try{const s=r();s instanceof Promise&&await s}catch{}}},Pu=async()=>Y()?Ea():!1,Ea=async()=>{if(!Y())return!1;try{return await H("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},Du=async()=>{if(!Y()||!Q())return null;try{const e=await H("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},ka=async(e,t)=>{if(!Y()||!Q())return!1;const r=e?.trim();if(!r)return!1;try{return await H("desktop_open_path",{path:r,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(n){return console.warn("Failed to open path",n),!1}},Mu=async e=>{if(!Y()||!Q())return!1;const t=e?.trim();if(!t)return!1;try{return await H("desktop_reveal_path",{path:t}),!0}catch{return ka(t)}},Cu=async(e,t)=>{if(!Y()||!Q())return null;const r=e?.trim();if(!r)return null;try{const n=await H("desktop_save_markdown_file",{defaultFileName:r,content:t});return typeof n=="string"&&n.trim().length>0?n:null}catch(n){return console.warn("Failed to save markdown file",n),null}},Ru=async(e,t,r)=>{if(!Y()||!Q())return!1;const n=e?.trim(),o=t?.trim(),s=r?.trim();if(!n||!o||!s)return!1;try{return await H("desktop_open_in_app",{projectPath:n,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},Ou=async(e,t,r)=>{if(!Y()||!Q())return!1;const n=e?.trim(),o=t?.trim(),s=r?.trim();if(!n||!o||!s)return!1;try{return await H("desktop_open_file_in_app",{filePath:n,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},Iu=async(e,t)=>{if(!Y()||!Q())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const r=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];if(r.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const n=await H("desktop_get_installed_apps",{apps:r,force:t===!0?!0:void 0});if(!n||typeof n!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const o=n;return Array.isArray(o.apps)?{apps:o.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:o.hasCache===!0,isCacheStale:o.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(n){return console.warn("Failed to fetch installed apps",n),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Ve=e=>typeof e=="object"&&e!==null,va=e=>e.trim().toLowerCase()==="authorization",Aa=e=>{if(!Ve(e))return;const t={};for(const[r,n]of Object.entries(e)){const o=r.trim(),s=typeof n=="string"?n.trim():"";!o||!s||/[\r\n:]/.test(o)||/[\r\n]/.test(s)||va(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},_u=e=>`relay://${e}`,Pa=e=>{if(!Ve(e))return null;const t=J(e,"relayUrl")||J(e,"relay_url"),r=J(e,"serverId")||J(e,"server_id"),n=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!r||!Ve(n)?null:{relayUrl:t,serverId:r,hostEncPubJwk:n}},Da=/^(t|.*(?:token|auth|secret|api).*)$/i,Je=e=>{const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},Fu=e=>{const t=Je(e);if(!t)return null;try{const r=new URL(t);if((r.pathname.replace(/\/+$/,"")||"/")==="/connect"&&r.searchParams.has("t"))return{persistedUrl:r.origin,redeemUrl:r.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},xu=e=>{const t=Je(e);if(!t)return e;try{const r=new URL(t);(r.username||r.password)&&(r.username="",r.password="");const n=Array.from(new Set(Array.from(r.searchParams.keys())));for(const o of n)Da.test(o)&&r.searchParams.set(o,"[REDACTED]");return r.toString()}catch{return t}},Lu=(e,t)=>{const r=Je(e),n=Je(t);if(!r||!n)return!1;try{const o=new URL(r),s=new URL(n);if(o.origin!==s.origin||s.search&&o.search!==s.search)return!1;const i=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname,a=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},J=(e,t)=>{const r=e[t];return typeof r=="string"?r:null},jn=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},Ma=e=>{if(!Ve(e))return null;const t=J(e,"id"),r=J(e,"label"),n=J(e,"url"),o=J(e,"apiUrl")||J(e,"api_url"),s=J(e,"clientToken")||J(e,"client_token"),i=Aa(e.requestHeaders),a=Pa(e.relay);return!t||!r||!n?null:{id:t,label:r,url:n,...o?{apiUrl:o}:{},...s?{clientToken:s}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Ca=e=>Je(e.apiUrl||e.url)||e.apiUrl||e.url,Le=()=>Y()?(e,t)=>H(e,t):null,Ra=async()=>{const e=Le();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Ve(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const r=t.hosts,n=Array.isArray(r)?r.map(Ma).filter(a=>!!a):[],o=J(t,"defaultHostId")||J(t,"default_host_id")||J(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=J(t,"localOrigin")||J(t,"local_origin");return{hosts:n,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},Uu=async e=>{const t=Le();if(!t)return;const r={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(r.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:r})},Nu=async()=>{const e=Le();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Bu=async()=>{const e=Le();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Oa=8e3,ju=async e=>{const t=Fo({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now();try{const n=await Promise.race([t.fetch("/health"),new Promise(o=>{const s=window.setTimeout(()=>o(null),Oa);typeof s!="number"&&typeof s.unref=="function"&&s.unref()})]);return n?{status:n.ok?"ok":"unreachable",latencyMs:Math.max(0,Date.now()-r)}:{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{t.close()}},Ia=async(e,t)=>{const r=Le();if(!r)return{status:"unreachable",latencyMs:0};const n=await r("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0});if(!Ve(n))return{status:"unreachable",latencyMs:0};const o=n.status,s=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",i=jn(n,"latencyMs")??jn(n,"latency_ms")??0;return{status:s,latencyMs:i}},Hu=async(e,t)=>{const r=Le();r&&await r("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},zu=async e=>{const t=Le();t&&await t("desktop_new_window_for_host",{hostId:e})},_a=async e=>{if(!fn())return;const t=await Ra().catch(()=>null);if(!t)return;const r=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!r)return;const n=t.hosts.find(i=>i.id===r);if(!n?.relay)return;const o=`host:${n.id}`;if(St()===o)return;const s=n.apiUrl?Je(Ca(n)):null;if(s){const i=await Ia(s,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(i.status!=="unreachable"&&i.status!=="wrong-service"&&i.status!=="incompatible"){Nn({apiBaseUrl:s,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:o});return}}Nn({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:n.clientToken||null,runtimeKey:o,relay:n.relay})},Hn=500,is=()=>{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}},$u=()=>is(),se=(e,t)=>{if(!is())return;const r=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=r,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(r-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>Hn&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Hn)},Fa=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(n=>n.name==="ModelControls:ready"),r=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,r).filter(n=>n.name.includes("checkConnection")||n.name.includes("checkHealth")||n.name.includes("initializeApp")||n.name.includes("initApp")||n.name.includes("loadProviders")||n.name.includes("loadAgents")||n.name.includes("config.defaults")||n.name.includes("modelsMetadata")||n.name.includes("ModelControls")||n.name.includes("activateDirectory")||n.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=Fa);const Gu=async(e,t,r)=>{const n=typeof performance<"u"?performance.now():Date.now();se(`${e}:start`,r);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return se(`${e}:end`,{durationMs:Math.round(s-n)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw se(`${e}:error`,{durationMs:Math.round(s-n),error:o instanceof Error?o.message:String(o)}),o}},xa=3,La=3e4,Ua=32e3,Na=3600*1e3,Ba=600*1e3,ja=new Set([429,502,503,504]),Ye=new Map;function Ha(){const e=Date.now();for(const[t,r]of Ye)r.consecutiveErrors===0&&e-r.lastErrorAt>Na&&Ye.delete(t)}typeof setInterval<"u"&&setInterval(Ha,Ba).unref?.();function za(e){let t=Ye.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:La},Ye.set(e,t)),t}function $a(e){if(!e)return;const t=Ye.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function zn(e,t){if(!e)return;const r=za(e);r.consecutiveErrors+=1,r.lastErrorAt=Date.now(),Ga(t)&&r.consecutiveErrors>=xa&&(r.circuitOpen=!0,r.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${r.consecutiveErrors} consecutive errors`))}function Ga(e){return e!==void 0&&ja.has(e)}function Wa(e){const t=Ye.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Ua*4),!1):!0:!1}function qa(e){if(!(!e||!Wa(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const $n="/api",Ka=1e4,Va=4e3;function Ge(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object"&&"message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function Z(e,t){if(e.error){const r=e.response?.status,n=new Error(`${t} failed${r?` (${r})`:""}: ${Ge(e.error)}`);throw r!==void 0&&(n.status=r),n}if(e.data===void 0||e.data===null)throw new Error(`${t} failed: empty response`);return e.data}function je(e,t){if(e.error){const r=e.response?.status,n=new Error(`${t} failed${r?` (${r})`:""}: ${Ge(e.error)}`);throw r!==void 0&&(n.status=r),n}return e.data}const Ja=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Gn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ya=14;let Wn=0,Er=0;const Qa=e=>{const t=new Uint8Array(e);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let n=0;n<e;n+=1)t[n]=Math.floor(Math.random()*256);let r="";for(let n=0;n<e;n+=1)r+=Gn[t[n]%Gn.length];return r},qn=e=>{const t=Date.now();t!==Wn&&(Wn=t,Er=0),Er+=1;const r=BigInt(t)*BigInt(4096)+BigInt(Er),n=new Uint8Array(6);for(let s=0;s<6;s+=1)n[s]=Number(r>>BigInt(40-8*s)&BigInt(255));const o=Array.from(n,s=>s.toString(16).padStart(2,"0")).join("");return`${e}_${o}${Qa(Ya)}`},Kn=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(Ja.test(t)||typeof window>"u")return t;const r=window.location?.href||window.location?.origin;if(!r)return t;try{return new URL(t,r).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),t}},Vn=()=>{try{return X().api("/api")}catch{return null}},Xa=e=>{const t=typeof AbortSignal<"u"?AbortSignal:void 0;if(typeof t?.timeout=="function")return{signal:t.timeout(e),cleanup:()=>{}};const r=new AbortController,n=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>clearTimeout(n)}},kr=e=>Ks({...e,fetch:u}),He=e=>e.replace(/\\/g,"/"),Jn=400,Yn=()=>{const e=ar();return e&&e.runtime?.isDesktop&&e.files?e.files:null};class Za{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;constructor(t=$n){const n=Vn()||t;this.baseUrl=Kn(n),this.client=kr({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=Vn(),r=Kn(t||$n);r!==this.baseUrl&&(this.baseUrl=r,this.client=kr({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear())}getSdkClient(){return this.client}getScopedSdkClient(t){return this.getScopedApiClient(t)}getScopedApiClient(t){const r=this.normalizeCandidatePath(t)??t,n=r||"",o=this.scopedClients.get(n);if(o)return o;const s=kr({baseUrl:this.baseUrl,directory:r});return this.scopedClients.set(n,s),s}normalizeCandidatePath(t){if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const n=r.replace(/\\/g,"/").replace(/^([a-z]):/,(s,i)=>i.toUpperCase()+":");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(t){const r=t.match(/^([A-Za-z]:)(?:\/|$)/);if(r){const s=r[1],a=t.slice(s.length+(t.charAt(s.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${s}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${s}/${a[0]}`,username:a[0]}:{homeDirectory:s,username:void 0}}const n=t.startsWith("/"),o=t.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const r=this.normalizeCandidatePath(t)??t;this.currentDirectory!==r&&se("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:r??null}),this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(t,r){const n=async()=>{if(t==null)return r();const s=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await r()}finally{this.currentDirectory===i&&(this.currentDirectory=s)}},o=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const t=new Set,r=o=>{const s=this.normalizeCandidatePath(o);s&&t.add(s)};try{const s=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;s&&(r(s.directory),r(s.worktree),r(s.state))}catch(o){console.debug("Failed to load path info:",o)}if(!t.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);r(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!t.size)try{(await this.listSessions()).forEach(s=>r(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(r(this.currentDirectory),typeof window<"u")try{r(window.localStorage.getItem("lastDirectory")),r(window.localStorage.getItem("homeDirectory"))}catch{}if(!t.size&&typeof process<"u"&&typeof process.cwd=="function"&&r(process.cwd()),!t.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(t);return this.deriveHomeDirectory(n)}async probeDirectory(t){const r=this.normalizeCandidatePath(t);if(!r)return!1;try{const o=(await this.client.path.get({directory:r})).data,s=typeof o?.directory=="string"?o.directory:null;return!!(s&&s.trim().length>0)}catch{return!1}}async listSessions(){const t=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(t.data)?t.data:[]}async createSession(t,r){const n=this.normalizeCandidatePath(r)??this.currentDirectory,o=await this.client.session.create({...n?{directory:n}:{},parentID:t?.parentID,title:t?.title,metadata:t?.metadata});return Z(o,"session.create")}async getSession(t,r){const n=this.normalizeCandidatePath(r)??this.currentDirectory,o=await this.client.session.get({sessionID:t,...n?{directory:n}:{}});return Z(o,"session.get")}async deleteSession(t,r){const n=this.normalizeCandidatePath(r)??this.currentDirectory,o=await this.client.session.delete({sessionID:t,...n?{directory:n}:{}});return je(o,"session.delete")===!0}async updateSession(t,r,n){const o=this.normalizeCandidatePath(n)??this.currentDirectory,s={...r.title!==void 0?{title:r.title}:{},...r.metadata!==void 0?{metadata:r.metadata}:{},...r.time?.archived!==void 0&&r.time.archived!==null?{time:{archived:r.time.archived}}:{}},i=await this.client.session.update({sessionID:t,...o?{directory:o}:{},...s});return Z(i,"session.update")}async getSessionMessages(t,r){const n=await this.client.session.messages({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof r=="number"?{limit:r}:{}});return Z(n,"session.messages")}async getSessionTodos(t){try{const r=await this.client.session.todo({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(r.error)return[];const n=r.data;return!n||!Array.isArray(n)?[]:n}catch{return[]}}shouldNormalizeToTextPlain(t){if(!t)return!1;const r=t.toLowerCase();return r.startsWith("text/")&&r!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(r)}isHeicMime(t){if(!t)return!1;const r=t.toLowerCase();return r==="image/heic"||r==="image/heif"}async convertHeicToJpeg(t){try{const r=(await qs(async()=>{const{default:f}=await import("./vendor-.bun-BE757pvp.js").then(w=>w.h);return{default:f}},[])).default,n=t.url.indexOf(",");if(n===-1)return t;const o=t.url.substring(n+1),s=atob(o),i=new Uint8Array(s.length);for(let f=0;f<s.length;f++)i[f]=s.charCodeAt(f);const a=new Blob([i],{type:t.mime}),c=await r({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((f,w)=>{const p=new FileReader;p.onload=()=>f(p.result),p.onerror=w,p.readAsDataURL(c)});let d=t.filename;return d&&(d=d.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:d,url:l}}catch(r){return console.warn("Failed to convert HEIC to JPEG:",r),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let r=t.url;if(t.url.startsWith("data:")){const n=t.url.indexOf(",");if(n!==-1){const o=t.url.substring(5,n),s=t.url.substring(n);r=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:t.filename,url:r}}async toNormalizedFilePartInput(t){const r=await this.normalizeFilePart(t);return{...t.id?{id:t.id}:{},type:"file",mime:r.mime,filename:r.filename,url:r.url}}async sendMessage(t){const r=t.messageId??qn("msg"),n=[];if(t.prefaceText&&t.prefaceText.trim()&&n.push({type:"text",text:t.prefaceText,synthetic:t.prefaceTextSynthetic!==!1}),t.text&&t.text.trim()){const l={type:"text",text:t.text};n.push(l)}if(t.files&&t.files.length>0)for(const l of t.files){const d=await this.toNormalizedFilePartInput(l);n.push(d)}if(t.additionalParts&&t.additionalParts.length>0){for(const l of t.additionalParts)if(l.text&&l.text.trim()&&n.push({type:"text",text:l.text,...l.synthetic?{synthetic:!0}:{}}),l.files&&l.files.length>0)for(const d of l.files){const f=await this.toNormalizedFilePartInput(d);n.push(f)}}if(t.agentMentions&&t.agentMentions.length>0)for(const l of t.agentMentions)l?.name&&n.push({type:"agent",name:l.name,...l.source?{source:l.source}:{}});if(n.length===0)throw new Error("Message must have at least one part (text or file)");const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;t.format&&console.info("[git-generation][browser] send structured message",{sessionId:t.id,providerID:t.providerID,modelID:t.modelID,agent:t.agent,variant:t.variant,directory:o,baseUrl:this.baseUrl,formatType:t.format.type}),qa(t.providerID);let s;try{const l=await this.client.session.promptAsync({sessionID:t.id,...o?{directory:o}:{},model:{providerID:t.providerID,modelID:t.modelID},agent:t.agent,variant:t.variant,messageID:r,...t.delivery?{delivery:t.delivery}:{},...t.format?{format:t.format}:{},parts:n});if(l.response instanceof Response)s=l.response;else if(l.error){const d=l.response?.status;if(!d)throw new Error(`Message send transport failure: ${Ge(l.error)}`);s=new Response(JSON.stringify(l.error),{status:d})}else s=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){throw zn(t.providerID),l}if(s.ok)return $a(t.providerID),r;let i="";try{i=await s.text()}catch{}const a=i&&i.trim().length>0?`: ${i.trim()}`:"",c=new Error(`Failed to send message (${s.status})${a}`);throw c.status=s.status,zn(t.providerID,s.status),c}async sendCommand(t){const r=t.messageId??qn("msg"),n=[];if(t.files&&t.files.length>0)for(const i of t.files)n.push(await this.toNormalizedFilePartInput(i));const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,s=await this.client.session.command({sessionID:t.id,...o?{directory:o}:{},command:t.command,arguments:t.arguments??"",model:`${t.providerID}/${t.modelID}`,agent:t.agent,variant:t.variant,...n.length>0?{parts:n}:{},messageID:r});return je(s,"session.command"),r}async abortSession(t){return!!(await this.client.session.abort({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(t){const r=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,n=await this.client.session.shell({sessionID:t.sessionId,...r?{directory:r}:{},messageID:t.messageId,agent:t.agent,model:t.model,command:t.command});return Z(n,"session.shell")}async revertSession(t,r,n,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.revert({sessionID:t,...s?{directory:s}:{},messageID:r,partID:n});return Z(i,"session.revert")}async summarizeSession(t,r,n,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.summarize({sessionID:t,...s?{directory:s}:{},providerID:r,modelID:n});return je(i,"session.summarize")===!0}async unrevertSession(t){const r=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Z(r,"session.unrevert")}async forkSession(t,r,n){const o=this.normalizeCandidatePath(n)??this.currentDirectory,s=await this.client.session.fork({sessionID:t,...o?{directory:o}:{},messageID:r});return Z(s,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(t){try{const r=typeof t=="string"?t.trim():"",n=await this.client.session.status(r?{directory:r}:void 0);return n.error||!n.data||typeof n.data!="object"?null:n.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const t=await u("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const r=await t.json().catch(()=>null);return!r||typeof r!="object"?null:r}catch{return null}}async listToolIds(t){try{const r=typeof t?.directory=="string"?t.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(r?{directory:r}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(t,r,n){const o=this.normalizeCandidatePath(n?.directory??null)??this.currentDirectory,s=await this.client.permission.reply({requestID:t,...o?{directory:o}:{},reply:r,...n?.message?{message:n.message}:{}});return je(s,"permission.reply")===!0}async listPendingPermissions(t){const r=[],n=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.permission.list(l?{directory:l}:void 0);if(d.error)throw new Error(`permission.list failed: ${Ge(d.error)}`);return d.data||[]};r.push(n(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)r.push(n(c));const s=await Promise.all(r),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}async replyToQuestion(t,r,n){const o=!Array.isArray(r)||r.length===0?[]:Array.isArray(r[0])?r:[r],s=this.normalizeCandidatePath(n)??this.currentDirectory,i=await this.client.question.reply({requestID:t,...s?{directory:s}:{},answers:o});return je(i,"question.reply")===!0}async rejectQuestion(t){const r=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return je(r,"question.reject")===!0}async listPendingQuestions(t){const r=[],n=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.question.list(l?{directory:l}:void 0);if(d.error)throw new Error(`question.list failed: ${Ge(d.error)}`);return d.data||[]};r.push(n(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)r.push(n(c));const s=await Promise.all(r),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const r=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,n=r??"",o=this.configCache.get(n);if(o&&o.expiresAt>Date.now())return se("opencodeClient.getConfig:cacheHit",{directory:r??null}),o.config;const s=this.configInFlight.get(n);if(s)return se("opencodeClient.getConfig:deduped",{directory:r??null}),s;const i=this.configCacheGeneration,a=(async()=>{se("opencodeClient.getConfig:start",{directory:r??null});const c=typeof performance<"u"?performance.now():Date.now(),d=await(r?this.getScopedApiClient(r):this.client).config.get();if(!d.data)throw new Error("Failed to get config");const f=typeof performance<"u"?performance.now():Date.now();return se("opencodeClient.getConfig:end",{directory:r??null,durationMs:Math.round(f-c)}),i===this.configCacheGeneration&&this.configCache.set(n,{config:d.data,expiresAt:Date.now()+Ka}),d.data})();this.configInFlight.set(n,a);try{return await a}finally{this.configInFlight.get(n)===a&&this.configInFlight.delete(n)}}async updateConfig(t){const r=await this.client.config.update({config:t}),n=Z(r,"global.config.update");return this.clearConfigCache(),n}async updateConfigPartial(t){const r=await this.getConfig(),n=t(r);return await this.updateConfig(n)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const r=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,n=r??"",o=this.configProvidersInFlight.get(n);if(o)return o;const s=(async()=>{const i=await this.client.config.providers(r?{directory:r}:void 0);return Z(i,"config.providers")})();this.configProvidersInFlight.set(n,s);try{return await s}finally{this.configProvidersInFlight.delete(n)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(t){const r=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,n=r??"",o=this.listAgentsInFlight.get(n);if(o)return o;const s=(async()=>{const i=r?{directory:r}:void 0,a=await this.client.app.agents(i);if(!a.error&&Array.isArray(a.data)&&a.data.length>0)return a.data;const c=await u("/api/agent",{...r?{query:{directory:r}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${Ge(a.error)}`):new Error(`agent.list failed (${c.status})`);const l=await c.json().catch(()=>null);if(!Array.isArray(l))throw new Error("agent.list failed: invalid response");return l})();this.listAgentsInFlight.set(n,s);try{return await s}finally{this.listAgentsInFlight.delete(n)}}async readFile(t){try{const r=await this.client.file.read({path:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(Z(r,"file.read"))}catch{return`// Content of ${t}
|
|
2
|
-
// This would be loaded from the server`}}async listFiles(t){try{const r=t||this.currentDirectory||"/",n=await this.client.file.list({path:r,...this.currentDirectory?{directory:this.currentDirectory}:{}}),o=Z(n,"file.list");return Array.isArray(o)?o:[]}catch{return[]}}async listCommands(){const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(Z(t,"command.list")||[]).map(n=>({name:n.name,description:n.description,agent:n.agent,model:n.model,source:n.source}))}async listCommandsWithDetails(){const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(Z(t,"command.list")||[]).map(n=>({name:n.name,description:n.description,agent:n.agent,model:n.model,source:n.source,template:n.template}))}async listSkillsWithDetails(){try{const r=(await this.client.app.skills(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;if(!Array.isArray(r))return[];const n=[];for(const o of r){const s=typeof o.name=="string"?o.name.trim():"",i=typeof o.location=="string"?o.location:"";if(!s||!i)continue;const a={name:s,location:i};typeof o.description=="string"&&(a.description=o.description),typeof o.content=="string"&&(a.content=o.content),n.push(a)}return n}catch{return[]}}async getCommandDetails(t){try{const r=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(r.data){const n=r.data.find(o=>o.name===t);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,r=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;se("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:r});const n=Xa(Va),o=await u(r,{signal:n.signal}).finally(n.cleanup);if(se("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return se("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,r){const n=Yn();if(n?.createDirectory)try{return await n.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}const o={path:t,...r?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await u(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const a=await s.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await s.json()}async cloneRepository(t){const r=await u(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(n.error||"Failed to clone repository")}return await r.json()}async listLocalDirectory(t,r){const o=`${typeof t=="string"?He(t.trim()):""}|${r?.respectGitignore?"1":"0"}`,s=Date.now(),i=this.listDirectoryCache.get(o);if(i&&i.expiresAt>s)return i.entries;const a=this.listDirectoryInFlight.get(o);if(a)return a;const l=(async()=>{const d=Yn();if(d)try{const f=await d.listDirectory(t||"",r);if(!f||!Array.isArray(f.entries))return[];const w=f.entries.map(p=>({name:p.name,path:He(p.path),isDirectory:!!p.isDirectory,isFile:!p.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:w,expiresAt:Date.now()+Jn}),w}catch(f){throw console.error("Failed to list directory contents:",f),f}try{const f=new URLSearchParams;t&&t.trim().length>0&&f.set("path",t),r?.respectGitignore&&f.set("respectGitignore","true");const w=f.toString(),p=await u(`${this.baseUrl}/fs/list${w?`?${w}`:""}`);if(!p.ok){const T=await p.json().catch(()=>({})),S=typeof T.error=="string"?T.error:"Failed to list directory";throw new Error(S)}const h=await p.json();if(!h||!Array.isArray(h.entries))return[];const b=h.entries;return this.listDirectoryCache.set(o,{entries:b,expiresAt:Date.now()+Jn}),b}catch(f){throw console.error("Failed to list directory contents:",f),f}})().finally(()=>{this.listDirectoryInFlight.get(o)===l&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,l),l}async searchFiles(t,r){const n=typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():this.currentDirectory,o=n?He(n):null,s=n?this.getScopedApiClient(n):this.client;try{const i=await s.find.files({query:t,limit:typeof r?.limit=="number"&&Number.isFinite(r.limit)?r.limit:void 0,dirs:r?.dirs===!1||r?.type==="file"?"false":"true",type:r?.type});return(Array.isArray(i?.data)?i.data:[]).map(c=>{const l=He(c),d=l.split("/").filter(Boolean).pop()||l,f=He(o?`${o}/${l}`:l);return{name:d,path:f,relativePath:l,extension:d.includes(".")?d.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const t=St();if(!t||t==="local"){const r=await os();if(r)return r}try{const r=await u(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){const o=await r.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}const n=await r.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(r){return console.warn("Failed to resolve filesystem home directory:",r),null}}async setOpenCodeWorkingDirectory(t){if(!t||typeof t!="string"||!t.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",t),null;const r=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",r,"with path:",t);try{const n=await u(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),o=await n.json().catch(()=>null);if(!n.ok){const s=o??{},i=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:t}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const ke=new Za,ec=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const r=new TextEncoder().encode(t);let n="";for(const s of r)n+=String.fromCharCode(s);return`path_${typeof btoa=="function"?btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`};let vr=null,Ar=null,Pr=null;const Qn=new Set;let Xn=!1;const as=e=>{if(Qn.add(e),Xn||typeof window>"u")return;Xn=!0;const t=()=>{for(const r of Qn)r()};try{window.addEventListener("pagehide",t,{capture:!0}),window.addEventListener("beforeunload",t,{capture:!0}),window.addEventListener("visibilitychange",()=>{typeof document<"u"&&document.visibilityState==="hidden"&&t()}),window.addEventListener("freeze",t)}catch{}},tc=(e,t)=>{let r;try{r=e()}catch{return}const n=new Map,o=new Set;let s;const i=()=>{if(s=void 0,n.size===0&&o.size===0)return;const c=Array.from(n.entries()),l=Array.from(o);n.clear(),o.clear();for(const[d,f]of c)try{r.setItem(d,JSON.stringify(f,t?.replacer))}catch(w){console.error("Failed to persist deferred storage value",w)}for(const d of l)try{r.removeItem(d)}catch(f){console.error("Failed to remove deferred storage value",f)}},a=()=>{s===void 0&&(s=setTimeout(i,0))};return as(i),{getItem:c=>{if(n.has(c))return n.get(c)??null;if(o.has(c))return null;const l=f=>f===null?null:JSON.parse(f,t?.reviver),d=r.getItem(c);return d instanceof Promise?d.then(l):l(d)},setItem:(c,l)=>{n.set(c,l),o.delete(c),a()},removeItem:c=>{n.delete(c),o.add(c),a()}}},cs=e=>tc(()=>ds(),e),rc=e=>{const t=new Map,r=new Set;let n;const o=()=>{if(n=void 0,t.size===0&&r.size===0)return;const i=Array.from(t.entries()),a=Array.from(r);t.clear(),r.clear();for(const[c,l]of i)try{e.setItem(c,l)}catch(d){console.error("Failed to persist deferred storage value",d)}for(const c of a)try{e.removeItem(c)}catch(l){console.error("Failed to remove deferred storage value",l)}},s=()=>{n===void 0&&(n=setTimeout(o,0))};return as(o),{getItem:i=>t.has(i)?t.get(i)??null:r.has(i)?null:e.getItem(i),setItem:(i,a)=>{t.set(i,a),r.delete(i),s()},removeItem:i=>{t.delete(i),r.add(i),s()},clear:()=>{t.clear(),r.clear(),n!==void 0&&(clearTimeout(n),n=void 0),e.clear()},key:i=>e.key(i),get length(){return e.length}}},ls=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},Kt=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,r)=>{e.set(t,r)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},nc=()=>{const e=ls("localStorage");if(!e)return Kt();const t=Kt();let r=!0;const n=()=>{r=!1};return{getItem:l=>{if(r)try{const d=e.getItem(l);if(d!==null)return d}catch{n()}return t.getItem(l)},setItem:(l,d)=>{if(r)try{e.setItem(l,d),t.removeItem(l);return}catch{n();try{e.removeItem(l)}catch{}}t.setItem(l,d)},removeItem:l=>{try{e.removeItem(l)}catch{n()}t.removeItem(l)},clear:()=>{try{e.clear()}catch{n()}t.clear()},key:l=>{if(r)try{return e.key(l)}catch{n()}return t.key(l)},get length(){if(r)try{return e.length+t.length}catch{n()}return t.length}}},ds=()=>(vr||(vr=nc()),vr),Tt=()=>(Pr||(Pr=rc(ds())),Pr),oc=()=>{const e=ls("sessionStorage");if(!e)return Kt();const t=Kt();let r=!0;const n=()=>{r=!1};return{getItem:l=>{if(r)try{const d=e.getItem(l);if(d!==null)return d}catch{n()}return t.getItem(l)},setItem:(l,d)=>{if(r)try{e.setItem(l,d),t.removeItem(l);return}catch{n();try{e.removeItem(l)}catch{}}t.setItem(l,d)},removeItem:l=>{try{e.removeItem(l)}catch{n()}t.removeItem(l)},clear:()=>{try{e.clear()}catch{n()}t.clear()},key:l=>{if(r)try{return e.key(l)}catch{n()}return t.key(l)},get length(){if(r)try{return e.length+t.length}catch{n()}return t.length}}},Wu=()=>(Ar||(Ar=oc()),Ar),sc={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},qu={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Zn(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Rt={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Dr={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Rt.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Dr.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Rt.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Dr.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Rt.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Dr.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Rt.tool.inline})},ic=[{id:"inter",label:"Inter",description:"Modern UI sans with excellent readability at small sizes.",stack:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Inter",packageName:"@fontsource/inter",filePrefix:"inter",weights:[400,500,600]}},{id:"geist-sans",label:"Geist Sans",description:"Crisp sans-serif with a technical interface feel.",stack:'"Geist Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Geist Sans",packageName:"@fontsource/geist-sans",filePrefix:"geist-sans",weights:[400,500,600]}},{id:"atkinson-hyperlegible",label:"Atkinson Hyperlegible",description:"Accessibility-focused sans-serif optimized for character distinction.",stack:'"Atkinson Hyperlegible", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Atkinson Hyperlegible",packageName:"@fontsource/atkinson-hyperlegible",filePrefix:"atkinson-hyperlegible",weights:[400,700]}},{id:"source-sans-3",label:"Source Sans 3",description:"Adobe sans-serif tuned for clean, readable interfaces.",stack:'"Source Sans 3", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Source Sans 3",packageName:"@fontsource/source-sans-3",filePrefix:"source-sans-3",weights:[400,500,600]}},{id:"roboto",label:"Roboto",description:"Familiar Material-style sans-serif with broad UI usage.",stack:'"Roboto", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Roboto",packageName:"@fontsource/roboto",filePrefix:"roboto",weights:[400,500,600]}},{id:"noto-sans",label:"Noto Sans",description:"Readable sans-serif with strong international coverage.",stack:'"Noto Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Noto Sans",packageName:"@fontsource/noto-sans",filePrefix:"noto-sans",weights:[400,500,600]}},{id:"dm-sans",label:"DM Sans",description:"Modern product UI sans-serif with friendly proportions.",stack:'"DM Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"DM Sans",packageName:"@fontsource/dm-sans",filePrefix:"dm-sans",weights:[400,500,600]}},{id:"manrope",label:"Manrope",description:"Polished geometric sans-serif for modern app interfaces.",stack:'"Manrope", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Manrope",packageName:"@fontsource/manrope",filePrefix:"manrope",weights:[400,500,600]}},{id:"system",label:"System",description:"Native operating system interface font.",stack:'"SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'}],ac=[{id:"jetbrains-mono",label:"JetBrains Mono",description:"Developer-focused monospace with strong punctuation clarity.",stack:'"JetBrains Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"JetBrains Mono",packageName:"@fontsource/jetbrains-mono",filePrefix:"jetbrains-mono",weights:[400,500,600]}},{id:"fira-code",label:"Fira Code",description:"Readable coding font with ligature support.",stack:'"Fira Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Fira Code",packageName:"@fontsource/fira-code",filePrefix:"fira-code",weights:[400,500,600]}},{id:"geist-mono",label:"Geist Mono",description:"Sharp monospace pair for Geist Sans.",stack:'"Geist Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Geist Mono",packageName:"@fontsource/geist-mono",filePrefix:"geist-mono",weights:[400,500,600]}},{id:"commit-mono",label:"Commit Mono",description:"Code-oriented monospace with polished editor ergonomics.",stack:'"Commit Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Commit Mono",packageName:"@fontsource/commit-mono",filePrefix:"commit-mono",weights:[400,500,600]}},{id:"source-code-pro",label:"Source Code Pro",description:"Adobe monospace designed for source code readability.",stack:'"Source Code Pro", "SFMono-Regular", "Menlo", monospace',source:{family:"Source Code Pro",packageName:"@fontsource/source-code-pro",filePrefix:"source-code-pro",weights:[400,500,600]}},{id:"cascadia-code",label:"Cascadia Code",description:"Microsoft coding font popular in terminals and editors.",stack:'"Cascadia Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Cascadia Code",packageName:"@fontsource/cascadia-code",filePrefix:"cascadia-code",weights:[400,500,600]}},{id:"roboto-mono",label:"Roboto Mono",description:"Neutral monospace companion to Roboto.",stack:'"Roboto Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Roboto Mono",packageName:"@fontsource/roboto-mono",filePrefix:"roboto-mono",weights:[400,500,600]}},{id:"iosevka",label:"Iosevka",description:"Compact monospace for dense code and terminal layouts.",stack:'"Iosevka", "SFMono-Regular", "Menlo", monospace',source:{family:"Iosevka",packageName:"@fontsource/iosevka",filePrefix:"iosevka",weights:[400,500,600]}},{id:"system-mono",label:"System Mono",description:"Native operating system monospace font.",stack:'ui-monospace, "SFMono-Regular", "Menlo", "Cascadia Mono", "Segoe UI Mono", monospace'}],us=e=>Object.fromEntries(e.map(t=>[t.id,t])),cc=us(ic),lc=us(ac),dc="system",uc="system-mono",fs=e=>typeof e=="string"&&e in cc,hs=e=>typeof e=="string"&&e in lc,Hr="openchamber.mobileKeyboardMode",fc='meta[name="viewport"]',eo="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Ku=()=>!0;function lr(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const hc=e=>lr(e)==="resize-content"?`${eo}, interactive-widget=resizes-content`:eo,pc=()=>{if(typeof window>"u")return"resize-content";try{return lr(localStorage.getItem(Hr))}catch{return"resize-content"}},ps=e=>{const t=lr(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Hr):localStorage.setItem(Hr,t)}catch{}return t},Vu=e=>{const t=ps(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const r=document.querySelector(fc);if(r instanceof HTMLMetaElement){const n=hc(t);r.getAttribute("content")!==n&&r.setAttribute("content",n)}return t};function to(e){return e==="vim"?"vim":"default"}const Ot={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},Se={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},It=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,mc=e=>{if(!e||typeof e!="object")return!1;const t=e;return It(t.completion,Ot.completion)&&It(t.error,Ot.error)&&It(t.question,Ot.question)&&It(t.subtask,Ot.subtask)},hn=380,yc=380,gc=1400,ms=12,ro=120,nt=280,ot=360,wc=860,Mr=new Map,Cr=e=>(e??St()).trim()||"default",V=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),r=t.startsWith("//");let n=t.replace(/\/+$/g,"");return n=n.replace(/\/+/g,"/"),r&&!n.startsWith("//")&&(n=`/${n}`),n===""?t.startsWith("/")?"/":"":n},ys=e=>Number.isFinite(e)?Math.min(gc,Math.max(yc,Math.round(e))):hn,Vt=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Jt=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>ro?t.slice(0,ro):t:null},pn=e=>e==="working"||e==="staged"||e==="turn"?e:null,bc=(e,t)=>(e==="file"||e==="preview")&&t||e,gs=(e,t,r)=>{if(e==="diff")return e;if(typeof r=="string"){const n=r.trim();if(n)return n}return bc(e,t)},ws=(e,t)=>t===e?e:`${e}:${t}`,bs=e=>{const t=Vt(e.targetPath),r=gs(e.mode,t,e.dedupeKey);return{id:ws(e.mode,r),mode:e.mode,targetPath:t,dedupeKey:r,label:Jt(e.label),sessionTitleFallback:Jt(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:pn(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Ss=(e,t,r)=>{if(e.length<=t)return e;const o=[...e].sort((a,c)=>a.touchedAt-c.touchedAt).filter(a=>a.id!==r),s=e.length-t;if(s<=0||o.length===0)return e.slice(-t);const i=new Set(o.slice(0,s).map(a=>a.id));return e.filter(a=>!i.has(a.id))},Ts=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const n of e){if(!n||typeof n!="object")continue;const o=n;if(o.mode!=="diff"&&o.mode!=="file"&&o.mode!=="context"&&o.mode!=="plan"&&o.mode!=="chat"&&o.mode!=="preview"&&o.mode!=="browser")continue;const s=Vt(typeof o.targetPath=="string"?o.targetPath:null),i=gs(o.mode,s,typeof o.dedupeKey=="string"?o.dedupeKey:null),a=ws(o.mode,i);!a||r.has(a)||(r.add(a),t.push({id:a,mode:o.mode,targetPath:s,dedupeKey:i,label:Jt(typeof o.label=="string"?o.label:null),sessionTitleFallback:Jt(typeof o.sessionTitleFallback=="string"?o.sessionTitleFallback:null),readOnly:o.readOnly===!0,stagedDiff:o.stagedDiff===!0,diffScope:pn(o.diffScope)??(o.stagedDiff===!0?"staged":"working"),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return t},yt=(e,t)=>t&&e.some(r=>r.id===t)?t:e.length===0?null:e[e.length-1].id,Me=e=>{if(e){const t=Ts(e.tabs),r=yt(t,e.activeTabId);return{...e,tabs:t,activeTabId:r,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:hn,touchedAt:Date.now()}},Sc=(e,t)=>{const r=bs(t),n=e.tabs.findIndex(a=>a.id===r.id),o=n===-1?[...e.tabs,r]:e.tabs.map((a,c)=>c===n?{...a,mode:r.mode,targetPath:r.targetPath||a.targetPath,dedupeKey:r.dedupeKey,label:r.label,sessionTitleFallback:r.sessionTitleFallback||a.sessionTitleFallback,stagedDiff:r.stagedDiff,diffScope:r.diffScope,readOnly:r.readOnly,touchedAt:Date.now()}:a),s=r.id,i=Ss(o,ms,s);return{...e,isOpen:!0,tabs:i,activeTabId:yt(i,s),touchedAt:Date.now()}},Tc=(e,t)=>{const r=e.tabs.filter(o=>o.id!==t),n=e.activeTabId===t?r[r.length-1]?.id??null:yt(r,e.activeTabId);return{...e,tabs:r,activeTabId:n,isOpen:r.length>0?e.isOpen:!1,touchedAt:Date.now()}},Ec=(e,t,r)=>{if(t===r)return e;const n=e.tabs.findIndex(a=>a.id===t),o=e.tabs.findIndex(a=>a.id===r);if(n===-1||o===-1)return e;const s=[...e.tabs],[i]=s.splice(n,1);return i?(s.splice(o,0,i),{...e,tabs:s,touchedAt:Date.now()}):e},kc=(e,t,r)=>({...e,tabs:e.tabs.map(n=>n.id===t?{...n,targetPath:r}:n)}),Rr=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[n,o]of Object.entries(t)){const s=V(n);if(!s||!o||typeof o!="object")continue;const i=o;let a=Ts(i.tabs),c=typeof i.activeTabId=="string"?i.activeTabId:null;a.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat")&&(a=[bs({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=a[0]?.id??null);const l=yt(a,c),d=Ss(a,ms,l);r[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:d,activeTabId:yt(d,l),width:ys(typeof i.width=="number"?i.width:hn),touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return r},Ce=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;r.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const n={};for(const[o,s]of r.slice(0,t))n[o]=s;return n},de=er()(tr(To((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:nt,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:ot,hasManuallyResizedRightSidebar:!1,rightSidebarTab:"git",contextPanelByDirectory:{},isBottomTerminalOpen:!1,isBottomTerminalExpanded:!1,bottomTerminalHeight:300,hasManuallyResizedBottomTerminal:!1,notesPanelHeight:112,todoPanelHeight:259,isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingDiagramFile:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:13,uiFont:dc,monoFont:uc,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:pc(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!0,inputSpellcheckEnabled:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,expandedEditorToolbar:!1,showSplitAssistantMessageActions:!1,isMobileSessionStatusBarCollapsed:!1,mobileSessionPanelOpen:!1,mobileSessionFilterProjectId:null,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:r=>{e({theme:r}),t().applyTheme()},toggleSidebar:()=>{e(r=>{const n=!r.isSidebarOpen;return n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:nt}:{isSidebarOpen:n}})},setSidebarOpen:r=>{e(n=>n.isSidebarOpen===r?r&&!n.hasManuallyResizedLeftSidebar&&n.sidebarWidth!==nt?{isSidebarOpen:r,sidebarWidth:nt}:n:r&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:nt}:{isSidebarOpen:r})},setSidebarWidth:r=>{e({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{e(r=>{const n=!r.isRightSidebarOpen;return n&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:n,rightSidebarWidth:ot}:{isRightSidebarOpen:n}})},setRightSidebarOpen:r=>{e(n=>{if(n.isRightSidebarOpen===r)return n;const o=r&&!n.hasManuallyResizedRightSidebar&&n.rightSidebarWidth!==ot;return{isRightSidebarOpen:r,rightSidebarWidth:o?ot:n.rightSidebarWidth}})},setRightSidebarWidth:r=>{const n=Math.min(wc,Math.max(ot,r));e({rightSidebarWidth:n,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:r=>{e({rightSidebarTab:r})},openContextPanelTab:(r,n)=>{const o=V((r||"").trim());o&&e(s=>{const i=s.contextPanelByDirectory[o],a=Me(i),c={...s.contextPanelByDirectory,[o]:Sc(a,n)};return{contextPanelByDirectory:Ce(c,20)}})},openContextDiff:(r,n,o=!1,s=null)=>{const i=V((r||"").trim()),a=(n||"").trim();if(!i||!a)return;const c=pn(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(r,n)=>{const o=V((r||"").trim()),s=Vt(n);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(r,n,o,s)=>{const i=V((r||"").trim()),a=Vt(n),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,l=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:r=>{const n=V((r||"").trim());n&&t().openContextPanelTab(n,{mode:"context"})},openContextPlan:r=>{const n=V((r||"").trim());n&&t().openContextPanelTab(n,{mode:"plan"})},openContextPreview:(r,n)=>{const o=V((r||"").trim()),s=(n||"").trim();if(!o||!s)return;let i=null;try{const a=new URL(s);(a.protocol==="http:"||a.protocol==="https:")&&(i=a.host||a.hostname||"Preview")}catch{}t().openContextPanelTab(o,{mode:"preview",targetPath:s,dedupeKey:s,label:i})},openContextBrowser:(r,n="")=>{const o=V((r||"").trim());if(!o)return;const s=typeof n=="string"&&n.trim().length>0?n.trim():"";t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:"desktop-browser",label:"Browser"})},setContextPanelTabTargetPath:(r,n,o)=>{const s=V((r||"").trim()),i=(n||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:kc(c,i,o)}}:a})},setActiveContextPanelTab:(r,n)=>{const o=V((r||"").trim()),s=(n||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Me(a);if(!c.tabs.some(d=>d.id===s)||c.activeTabId===s&&c.isOpen)return i;const l={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:s,touchedAt:Date.now(),tabs:c.tabs.map(d=>d.id===s?{...d,touchedAt:Date.now()}:d)}};return{contextPanelByDirectory:Ce(l,20)}})},reorderContextPanelTabs:(r,n,o)=>{const s=V((r||"").trim()),i=(n||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],d=Me(l);if(!d.tabs.some(p=>p.id===i)||!d.tabs.some(p=>p.id===a))return c;const f=Ec(d,i,a);if(f.tabs===d.tabs)return c;const w={...c.contextPanelByDirectory,[s]:f};return{contextPanelByDirectory:Ce(w,20)}})},closeContextPanelTab:(r,n)=>{const o=V((r||"").trim()),s=(n||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Me(a);if(!c.tabs.some(d=>d.id===s))return i;const l={...i.contextPanelByDirectory,[o]:Tc(c,s)};return{contextPanelByDirectory:Ce(l,20)}})},closeContextPanel:r=>{const n=V((r||"").trim());n&&e(o=>{const s=o.contextPanelByDirectory[n];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[n]:{...Me(s),isOpen:!1}};return{contextPanelByDirectory:Ce(i,20)}})},toggleContextPanelExpanded:r=>{const n=V((r||"").trim());n&&e(o=>{const s=o.contextPanelByDirectory[n],i=Me(s),a={...o.contextPanelByDirectory,[n]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Ce(a,20)}})},setContextPanelWidth:(r,n)=>{const o=V((r||"").trim());o&&e(s=>{const i=s.contextPanelByDirectory[o],a=Me(i),c={...s.contextPanelByDirectory,[o]:{...a,width:ys(n)}};return{contextPanelByDirectory:Ce(c,20)}})},toggleBottomTerminal:()=>{e(r=>{const n=!r.isBottomTerminalOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:n}})},setBottomTerminalOpen:r=>{e(n=>{if(n.isBottomTerminalOpen===r){if(!r)return n;if(!n.hasManuallyResizedBottomTerminal&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return n.bottomTerminalHeight===o&&n.hasManuallyResizedBottomTerminal===!1?n:{isBottomTerminalOpen:r,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return n}if(r&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:r,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:r}})},setBottomTerminalExpanded:r=>{e({isBottomTerminalExpanded:r})},setBottomTerminalHeight:r=>{e({bottomTerminalHeight:r,hasManuallyResizedBottomTerminal:!0})},setNotesPanelHeight:r=>{e({notesPanelHeight:r})},setTodoPanelHeight:r=>{e({todoPanelHeight:r})},setSessionSwitcherOpen:r=>{t().isSessionSwitcherOpen!==r&&e({isSessionSwitcherOpen:r})},setSessionDropdownOpen:r=>{t().isSessionDropdownOpen!==r&&e({isSessionDropdownOpen:r})},setMainTabGuard:r=>{t().mainTabGuard!==r&&e({mainTabGuard:r})},setActiveMainTab:r=>{const n=t().mainTabGuard;n&&!n(r)||(Mr.set(Cr(),r),e({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{Mr.set(Cr(r),t().activeMainTab)},restoreForRuntimeSwitch:r=>{const n=Mr.get(Cr(r))??"chat";e({activeMainTab:n})},setPendingDiffFile:(r,n=!1,o=null)=>{e({pendingDiffFile:r,pendingDiffStaged:r?n:!1,pendingDiffScope:r?o:null})},setPendingDiagramFile:r=>{e({pendingDiagramFile:r})},setPendingFileNavigation:r=>{e({pendingFileNavigation:r})},setPendingFileFocusPath:r=>{e({pendingFileFocusPath:r})},navigateToDiff:(r,n=!1,o=null)=>{const s=t().mainTabGuard;s&&!s("diff")||e({pendingDiffFile:r,pendingDiffStaged:n,pendingDiffScope:o,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:r}=t();return r&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),r},navigateToDiagram:r=>{const n=t().mainTabGuard;n&&!n("diagram")||e({pendingDiagramFile:r,activeMainTab:"diagram"})},consumePendingDiagramFile:()=>{const{pendingDiagramFile:r}=t();return r&&e({pendingDiagramFile:null}),r},setIsMobile:r=>{e({isMobile:r})},toggleCommandPalette:()=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen}))},setCommandPaletteOpen:r=>{e({isCommandPaletteOpen:r})},toggleHelpDialog:()=>{e(r=>({isHelpDialogOpen:!r.isHelpDialogOpen}))},setHelpDialogOpen:r=>{e({isHelpDialogOpen:r})},setAboutDialogOpen:r=>{e({isAboutDialogOpen:r})},setOpenCodeStatusDialogOpen:r=>{e({isOpenCodeStatusDialogOpen:r})},setOpenCodeStatusText:r=>{e({openCodeStatusText:r})},setSessionCreateDialogOpen:r=>{e({isSessionCreateDialogOpen:r})},setScheduledTasksDialogOpen:r=>{e({isScheduledTasksDialogOpen:r})},setSettingsDialogOpen:r=>{e(n=>r?n.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:r=>{e({isNewWorktreeDialogOpen:r})},setModelSelectorOpen:r=>{e({isModelSelectorOpen:r})},setSidebarSection:r=>{e({sidebarSection:r})},setSettingsPage:r=>{e({settingsPage:r})},setSettingsProjectsSelectedId:r=>{e({settingsProjectsSelectedId:r})},setSettingsRemoteInstancesSelectedId:r=>{e({settingsRemoteInstancesSelectedId:r})},setEventStreamStatus:(r,n)=>{e({eventStreamStatus:r,eventStreamHint:n??null})},setShowReasoningTraces:r=>{e({showReasoningTraces:r})},setSessionRecapEnabled:r=>{e({sessionRecapEnabled:r})},setSessionSuggestionEnabled:r=>{e({sessionSuggestionEnabled:r})},setCollapsibleThinkingBlocks:r=>{e({collapsibleThinkingBlocks:r})},setChatRenderMode:r=>{e({chatRenderMode:r})},setActivityRenderMode:r=>{e({activityRenderMode:r})},setShowDeletionDialog:r=>{e({showDeletionDialog:r})},setAutoDeleteEnabled:r=>{e({autoDeleteEnabled:r})},setAutoDeleteAfterDays:r=>{const n=Math.max(1,Math.min(365,r));e({autoDeleteAfterDays:n})},setSessionRetentionAction:r=>{e({sessionRetentionAction:r})},setAutoDeleteLastRunAt:r=>{e({autoDeleteLastRunAt:r})},setMessageLimit:r=>{const n=Math.max(10,Math.min(500,Math.round(r)));e({messageLimit:n})},setFontSize:r=>{const n=Math.max(50,Math.min(200,r));e({fontSize:n}),t().applyTypography()},setGlobalDraftStarters:r=>{e({globalDraftStarters:r})},setTerminalFontSize:r=>{const n=Math.round(r),o=Math.max(9,Math.min(52,n));e({terminalFontSize:o})},setUiFont:r=>{e({uiFont:r})},setMonoFont:r=>{e({monoFont:r})},setPadding:r=>{const n=Math.max(50,Math.min(200,r));e({padding:n}),t().applyPadding()},setCornerRadius:r=>{e({cornerRadius:r})},applyTypography:()=>{const{fontSize:r}=t(),n=document.documentElement,o=r/100,s=Object.entries(sc);if(o===1){for(const[i]of s)n.style.removeProperty(Zn(i));return}for(const[i,a]of s){const c=parseFloat(a);Number.isFinite(c)&&n.style.setProperty(Zn(i),`${c*o}rem`)}},applyPadding:()=>{const{padding:r}=t(),n=document.documentElement,o=r/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const s=Math.sqrt(o);n.style.setProperty("--padding-scale",s.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:r=>{e({diffLayoutPreference:r})},setDiffFileLayout:(r,n)=>{e(o=>({diffFileLayout:{...o.diffFileLayout,[r]:n}}))},setDiffWrapLines:r=>{e({diffWrapLines:r})},setGitChangesViewMode:r=>{e({gitChangesViewMode:r})},setInputBarOffset:r=>{e({inputBarOffset:r})},setMobileKeyboardMode:r=>{e(n=>n.mobileKeyboardMode===r?n:{mobileKeyboardMode:r})},toggleFavoriteModel:(r,n)=>{e(o=>o.favoriteModels.some(i=>i.providerID===r&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===r&&i.modelID===n))}:{favoriteModels:[{providerID:r,modelID:n},...o.favoriteModels]})},reorderFavoriteModel:(r,n,o,s)=>{e(i=>{const a=i.favoriteModels.findIndex(f=>f.providerID===r&&f.modelID===n),c=i.favoriteModels.findIndex(f=>f.providerID===o&&f.modelID===s);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[d]=l.splice(a,1);return d?(l.splice(c,0,d),{favoriteModels:l}):i})},setProviderOrder:r=>{e(n=>{const o=r.filter(i=>typeof i=="string"&&i.length>0),s=n.providerOrder;return s.length===o.length&&s.every((i,a)=>i===o[a])?n:{providerOrder:o}})},toggleHiddenModel:(r,n)=>{e(o=>o.hiddenModels.some(i=>i.providerID===r&&i.modelID===n)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===r&&i.modelID===n))}:{hiddenModels:[{providerID:r,modelID:n},...o.hiddenModels]})},isHiddenModel:(r,n)=>{const{hiddenModels:o}=t();return o.some(s=>s.providerID===r&&s.modelID===n)},hideAllModels:(r,n)=>{e(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==r);return{hiddenModels:[...n.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:r,modelID:a})),...s]}})},showAllModels:r=>{e(n=>({hiddenModels:n.hiddenModels.filter(o=>o.providerID!==r)}))},toggleModelProviderCollapsed:r=>{const n=typeof r=="string"?r.trim():"";n&&e(o=>o.collapsedModelProviders.includes(n)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==n)}:{collapsedModelProviders:[...o.collapsedModelProviders,n]})},setModelProvidersCollapsed:(r,n)=>{const o=Array.from(new Set(r.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean)));o.length!==0&&e(s=>{const i=new Set(o),a=s.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:n?[...a,...o]:a}})},isFavoriteModel:(r,n)=>{const{favoriteModels:o}=t();return o.some(s=>s.providerID===r&&s.modelID===n)},addRecentModel:(r,n)=>{e(o=>{const s=o.recentModels.filter(i=>!(i.providerID===r&&i.modelID===n));return{recentModels:[{providerID:r,modelID:n},...s].slice(0,5)}})},addRecentAgent:r=>{const n=typeof r=="string"?r.trim():"";n&&e(o=>{if(o.recentAgents.includes(n))return o;const s=o.recentAgents;return{recentAgents:[n,...s].slice(0,5)}})},addRecentEffort:(r,n,o)=>{const s=typeof r=="string"?r.trim():"",i=typeof n=="string"?n.trim():"";if(!s||!i)return;const a=`${s}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.trim():"default";e(l=>{const d=l.recentEfforts[a]??[];if(d.includes(c))return l;const f=d;return{recentEfforts:{...l.recentEfforts,[a]:[c,...f].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||e(r=>{const n={};if(r.isBottomTerminalOpen&&!r.hasManuallyResizedBottomTerminal){const o=Math.floor(window.innerHeight*.32);r.bottomTerminalHeight!==o&&(n.bottomTerminalHeight=o)}return Object.keys(n).length>0?n:r})},applyTheme:()=>{const{theme:r}=t(),n=document.documentElement;if(n.classList.remove("light","dark"),r==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(r)},setMultiRunLauncherOpen:r=>{e(n=>({isMultiRunLauncherOpen:r,multiRunLauncherPrefillPrompt:r?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:r=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:r,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:r=>{e({isTimelineDialogOpen:r})},setImagePreviewOpen:r=>{e({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{e({nativeNotificationsEnabled:r})},setNotificationMode:r=>{e({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{e({showTerminalQuickKeysOnDesktop:r})},setNotifyOnSubtasks:r=>{e({notifyOnSubtasks:r})},setDockBadgeEnabled:r=>{e({dockBadgeEnabled:r})},setNotifyOnCompletion:r=>{e({notifyOnCompletion:r})},setNotifyOnError:r=>{e({notifyOnError:r})},setNotifyOnQuestion:r=>{e({notifyOnQuestion:r})},setNotificationTemplates:r=>{e({notificationTemplates:r})},setSummarizeLastMessage:r=>{e({summarizeLastMessage:r})},setSummaryThreshold:r=>{e({summaryThreshold:r})},setSummaryLength:r=>{e({summaryLength:r})},setMaxLastMessageLength:r=>{e({maxLastMessageLength:r})},setPersistChatDraft:r=>{e({persistChatDraft:r})},setShowOpenCodeUpdateNotifications:r=>{e({showOpenCodeUpdateNotifications:r})},setInputSpellcheckEnabled:r=>{e({inputSpellcheckEnabled:r})},setWideChatLayoutEnabled:r=>{e({wideChatLayoutEnabled:r})},setCodeBlockLineWrap:r=>{e({codeBlockLineWrap:r})},setShowToolFileIcons:r=>{e({showToolFileIcons:r})},setShowTurnChangedFiles:r=>{e({showTurnChangedFiles:r})},setShowExpandedBashTools:r=>{e({showExpandedBashTools:r})},setShowExpandedEditTools:r=>{e({showExpandedEditTools:r})},setTimeFormatPreference:r=>{e({timeFormatPreference:r})},setWeekStartPreference:r=>{e({weekStartPreference:r})},setMermaidRenderingMode:r=>{e({mermaidRenderingMode:r})},setUserMessageRenderingMode:r=>{e({userMessageRenderingMode:r})},setCollapsibleUserMessages:r=>{e({collapsibleUserMessages:r})},setStickyUserHeader:r=>{e({stickyUserHeader:r})},setExpandedEditorToolbar:r=>{e({expandedEditorToolbar:r})},setShowSplitAssistantMessageActions:r=>{e({showSplitAssistantMessageActions:r})},setIsMobileSessionStatusBarCollapsed:r=>{e({isMobileSessionStatusBarCollapsed:r})},setMobileSessionPanelOpen:r=>{e({mobileSessionPanelOpen:r})},setMobileSessionFilterProjectId:r=>{e({mobileSessionFilterProjectId:r})},setReportUsage:r=>{e({reportUsage:r})},viewPagerPage:"center",setViewPagerPage:r=>{e({viewPagerPage:r}),e(r==="left"?{isSessionSwitcherOpen:!0,isRightSidebarOpen:!1}:r==="right"?{isRightSidebarOpen:!0,isSessionSwitcherOpen:!1}:{isSessionSwitcherOpen:!1,isRightSidebarOpen:!1})},setShortcutOverride:(r,n)=>{e(o=>({shortcutOverrides:{...o.shortcutOverrides,[r]:n}}))},clearShortcutOverride:r=>{e(n=>{const o={...n.shortcutOverrides};return delete o[r],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:r=>{e({fileEditorKeymap:to(r)})},toggleExpandedInput:()=>{e(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{e({isExpandedInput:r})}}),{name:"ui-store",storage:cs(),version:10,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const r=e;if(t<10&&delete r.diffViewMode,t<9&&((typeof r.notesPanelHeight!="number"||!Number.isFinite(r.notesPanelHeight))&&(r.notesPanelHeight=112),(typeof r.todoPanelHeight!="number"||!Number.isFinite(r.todoPanelHeight))&&(r.todoPanelHeight=259)),t<1&&mc(r.notificationTemplates)&&(r.notificationTemplates={completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}}),t<3){const n=new Set([90,120,180,220]),o=r.memoryLimitHistorical,s=r.memoryLimitActiveSession;typeof o=="number"&&!n.has(o)?r.messageLimit=o:typeof s=="number"&&!n.has(s)&&(r.messageLimit=s),delete r.memoryLimitHistorical,delete r.memoryLimitViewport,delete r.memoryLimitActiveSession}if((typeof r.rightSidebarTab!="string"||r.rightSidebarTab!=="git"&&r.rightSidebarTab!=="files"&&r.rightSidebarTab!=="context")&&(r.rightSidebarTab="git"),r.contextPanelByDirectory=Rr(r.contextPanelByDirectory),t<5)if(!r.shortcutOverrides||typeof r.shortcutOverrides!="object")r.shortcutOverrides={};else{const n=r.shortcutOverrides,o={};for(const[s,i]of Object.entries(n))typeof s=="string"&&typeof i=="string"&&(o[s]=i);r.shortcutOverrides=o}return t<6&&(r.contextPanelByDirectory=Rr(r.contextPanelByDirectory)),t<7&&(r.contextPanelByDirectory=Rr(r.contextPanelByDirectory)),t<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=to(r.fileEditorKeymap),r},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,isRightSidebarOpen:e.isRightSidebarOpen,rightSidebarWidth:e.rightSidebarWidth,rightSidebarTab:e.rightSidebarTab,contextPanelByDirectory:e.contextPanelByDirectory,isBottomTerminalOpen:e.isBottomTerminalOpen,isBottomTerminalExpanded:e.isBottomTerminalExpanded,bottomTerminalHeight:e.bottomTerminalHeight,notesPanelHeight:e.notesPanelHeight,todoPanelHeight:e.todoPanelHeight,isSessionSwitcherOpen:e.isSessionSwitcherOpen,activeMainTab:e.activeMainTab,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,chatRenderMode:e.chatRenderMode,activityRenderMode:e.activityRenderMode,showDeletionDialog:e.showDeletionDialog,autoDeleteEnabled:e.autoDeleteEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,providerOrder:e.providerOrder,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,diffWrapLines:e.diffWrapLines,gitChangesViewMode:e.gitChangesViewMode,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,inputSpellcheckEnabled:e.inputSpellcheckEnabled,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,expandedEditorToolbar:e.expandedEditorToolbar,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,isMobileSessionStatusBarCollapsed:e.isMobileSessionStatusBarCollapsed,mobileSessionFilterProjectId:e.mobileSessionFilterProjectId,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Es="queue",mn=e=>e==="steer"||e==="queue",yn=(e,t)=>e==="immediate"?"steer":mn(e)?e:t===!1?"steer":t===!0?"queue":Es,vc=er()(tr(To((e,t)=>({queuedMessages:{},followUpBehavior:Es,addToQueue:(r,n)=>{const s={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now(),sendConfig:n.sendConfig};e(i=>{const a=i.queuedMessages[r]??[];return{queuedMessages:{...i.queuedMessages,[r]:[...a,s]}}})},removeFromQueue:(r,n)=>{e(o=>{const i=(o.queuedMessages[r]??[]).filter(a=>a.id!==n);if(i.length===0){const{[r]:a,...c}=o.queuedMessages;return{queuedMessages:c}}return{queuedMessages:{...o.queuedMessages,[r]:i}}})},reorderQueue:(r,n,o)=>{n!==o&&e(s=>{const i=s.queuedMessages[r];if(!i)return s;const a=i.findIndex(f=>f.id===n),c=i.findIndex(f=>f.id===o);if(a===-1||c===-1)return s;const l=i.slice(),[d]=l.splice(a,1);return l.splice(c,0,d),{queuedMessages:{...s.queuedMessages,[r]:l}}})},popToInput:(r,n)=>{const i=(t().queuedMessages[r]??[]).find(a=>a.id===n);return i?(e(a=>{const l=(a.queuedMessages[r]??[]).filter(d=>d.id!==n);if(l.length===0){const{[r]:d,...f}=a.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...a.queuedMessages,[r]:l}}}),i):null},clearQueue:r=>{e(n=>{const{[r]:o,...s}=n.queuedMessages;return{queuedMessages:s}})},clearAllQueues:()=>{e({queuedMessages:{}})},setFollowUpBehavior:r=>{e({followUpBehavior:r}),ge({followUpBehavior:r})},getQueueForSession:r=>t().queuedMessages[r]??[]}),{name:"message-queue-store",version:1,storage:cs(),partialize:e=>({queuedMessages:e.queuedMessages,followUpBehavior:e.followUpBehavior}),migrate:e=>{const t=e??{};return{queuedMessages:t.queuedMessages??{},followUpBehavior:yn(t.followUpBehavior,t.queueModeEnabled??null)}}}),{name:"message-queue-store"})),ks="directoryTreeShowHidden",zr="directory-show-hidden-change",no=()=>{if(typeof window>"u")return!0;try{const e=Tt().getItem(ks);return e===null?!0:e==="true"}catch{return!0}},Ac=()=>{typeof window>"u"||window.dispatchEvent(new Event(zr))},Pc=(e,t={})=>{if(!(typeof window>"u")){try{Tt().setItem(ks,e?"true":"false"),Ac()}catch{}t.persist!==!1&&ge({directoryShowHidden:e})}},Ju=()=>{const e=Eo.c(2),[t,r]=Ht.useState(no);let n,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{if(typeof window>"u")return;const s=()=>{r(no())};return window.addEventListener("storage",s),window.addEventListener(zr,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(zr,s)}},o=[],e[0]=n,e[1]=o):(n=e[0],o=e[1]),Ht.useEffect(n,o),t},vs="filesViewShowGitignored",$r="files-view-show-gitignored-change",oo=()=>{if(typeof window>"u")return!1;try{return Tt().getItem(vs)==="true"}catch{return!1}},Dc=()=>{typeof window>"u"||window.dispatchEvent(new Event($r))},Mc=(e,t={})=>{if(!(typeof window>"u")){try{Tt().setItem(vs,e?"true":"false"),Dc()}catch{}t.persist!==!1&&ge({filesViewShowGitignored:e})}},Yu=()=>{const e=Eo.c(2),[t,r]=Ht.useState(oo);let n,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{if(typeof window>"u")return;const s=()=>{r(oo())};return window.addEventListener("storage",s),window.addEventListener($r,s),()=>{window.removeEventListener("storage",s),window.removeEventListener($r,s)}},o=[],e[0]=n,e[1]=o):(n=e[0],o=e[1]),Ht.useEffect(n,o),t},Cc=e=>{if(!e||typeof e!="object")return null;const t={};return typeof e.showReasoningTraces=="boolean"&&(t.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&(t.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),Object.keys(t).length>0?t:null},Rc=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Oc=e=>{const t=de.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Ic=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),r=Rc(t);return Cc(r)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},As=[{name:"explore",icon:"compass-3",labelKey:"chat.draftPresets.explore.label",command:"/explore"},{name:"catch-up",icon:"history",labelKey:"chat.draftPresets.catchup.label",command:"/catch-up"},{name:"weigh",icon:"scales-3",labelKey:"chat.draftPresets.weigh.label",command:"/weigh"},{name:"plan-feature",icon:"survey",labelKey:"chat.draftPresets.plan.label",command:"/plan-feature"},{name:"debug",icon:"bug",labelKey:"chat.draftPresets.debug.label",command:"/debug"},{name:"review",icon:"search-eye",labelKey:"chat.draftPresets.review.label",command:"/workspace-review"}],_c=new Map(As.map(e=>[e.name,e])),Qu=e=>_c.get(e),Xu=As.map(e=>({type:"command",name:e.name})),Zu="terminal-box",ef="book-open",tf=e=>`${e.type}:${e.name}`,rf=(e,t)=>e.type===t.type&&e.name===t.name,nf=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Ps=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const n of e){if(!n||typeof n!="object")continue;const o=n,s=o.type==="command"||o.type==="skill"?o.type:null,i=typeof o.name=="string"?o.name.trim():"";if(!s||!i)continue;const a=`${s}:${i}`;r.has(a)||(r.add(a),t.push({type:s,name:i}))}return t},Fc=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},Gr=e=>{if(!(typeof window>"u")){if(e.themeId&&localStorage.setItem("selectedThemeId",e.themeId),e.themeVariant&&localStorage.setItem("selectedThemeVariant",e.themeVariant),e.lightThemeId&&localStorage.setItem("lightThemeId",e.lightThemeId),e.darkThemeId&&localStorage.setItem("darkThemeId",e.darkThemeId),typeof e.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(e.useSystemTheme)),e.lastDirectory&&localStorage.setItem("lastDirectory",e.lastDirectory),e.homeDirectory&&(localStorage.setItem("homeDirectory",e.homeDirectory),Fc(e.homeDirectory)),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(r=>r.sidebarCollapsed===!0).map(r=>r.id).filter(r=>typeof r=="string"&&r.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}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"),typeof e.filesViewShowGitignored=="boolean"&&localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"),typeof e.openInAppId=="string"&&e.openInAppId.length>0&&localStorage.setItem("openInAppId",e.openInAppId),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")}if(typeof e.mobileKeyboardMode=="string"&&ps(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")}typeof e.dictationEnabled=="boolean"&&localStorage.setItem("dictationEnabled",String(e.dictationEnabled)),(e.sttProvider==="local"||e.sttProvider==="openai-compatible")&&localStorage.setItem("sttProvider",e.sttProvider),typeof e.sttServerUrl=="string"&&localStorage.setItem("sttServerUrl",e.sttServerUrl),typeof e.sttModel=="string"&&localStorage.setItem("sttModel",e.sttModel),typeof e.sttLocalModel=="string"&&localStorage.setItem("sttLocalModel",e.sttLocalModel),typeof e.sttLanguage=="string"&&localStorage.setItem("sttLanguage",e.sttLanguage)}},Wr=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:e}))},xc=e=>{if(!Array.isArray(e))return;const t=[],r=new Set;for(const n of e){if(!n||typeof n!="object")continue;const o=n,s=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",a=typeof o.source=="string"?o.source.trim():"",c=typeof o.subpath=="string"?o.subpath.trim():"",l=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!s||!i||!a||r.has(s)||(r.add(s),t.push({id:s,label:i,source:a,...c?{subpath:c}:{},...l?{gitIdentityId:l}:{}}))}return t},Lc=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e)){const o=typeof r=="string"?r.trim():"",s=typeof n=="string"?n.trim():"";!o||!s||(t[o]=s)}return t},Uc=(e,t)=>{const r=Object.entries(e),n=Object.entries(t);return r.length!==n.length?!1:r.every(([o,s])=>t[o]===s)},Or=(e,t)=>e.length===t.length&&e.every((r,n)=>r.providerID===t[n]?.providerID&&r.modelID===t[n]?.modelID),qr=(e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]),Kr=e=>{if(Array.isArray(e))return Array.from(new Set(e.filter(t=>typeof t=="string"&&t.length>0)))},Nc=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e)){if(!r||!Array.isArray(n))continue;const o=Kr(n);o&&o.length>0&&(t[r]=o.slice(0,5))}return Object.keys(t).length>0?t:void 0},Bc=(e,t)=>{const r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>Array.isArray(t[n])&&qr(e[n],t[n]))},jc=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Hc=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&jc.test(t)?t.toLowerCase():null},zc=e=>{if(!Array.isArray(e))return;const t=[],r=new Set,n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.path=="string"?s.path.trim():"";if(!i)continue;const a=i==="/"?i:i.replace(/\\/g,"/").replace(/\/+$/,"");if(!a)continue;const c=ec(a);if(!c||r.has(c)||n.has(a))continue;r.add(c),n.add(a);const l={id:c,path:a};if(typeof s.label=="string"&&s.label.trim().length>0&&(l.label=s.label.trim()),typeof s.icon=="string"&&s.icon.trim().length>0&&(l.icon=s.icon.trim()),s.iconImage===null)l.iconImage=null;else if(s.iconImage&&typeof s.iconImage=="object"){const d=s.iconImage,f=typeof d.mime=="string"?d.mime.trim():"",w=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,p=d.source==="custom"||d.source==="auto"?d.source:null;f&&w>0&&p&&(l.iconImage={mime:f,updatedAt:w,source:p})}if(typeof s.color=="string"&&s.color.trim().length>0&&(l.color=s.color.trim()),s.iconBackground===null)l.iconBackground=null;else{const d=Hc(s.iconBackground);d&&(l.iconBackground=d)}typeof s.addedAt=="number"&&Number.isFinite(s.addedAt)&&s.addedAt>=0&&(l.addedAt=s.addedAt),typeof s.lastOpenedAt=="number"&&Number.isFinite(s.lastOpenedAt)&&s.lastOpenedAt>=0&&(l.lastOpenedAt=s.lastOpenedAt),typeof s.sidebarCollapsed=="boolean"&&(l.sidebarCollapsed=s.sidebarCollapsed),t.push(l)}return t.length>0?t:void 0},$c=e=>{if(!Array.isArray(e))return;const t=[],r=new Set,n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.id=="string"?s.id.trim():"",a=typeof s.name=="string"?s.name.trim():"",c=typeof s.hostname=="string"?s.hostname.trim().toLowerCase():"";!i||!a||!c||r.has(i)||n.has(c)||(r.add(i),n.add(c),t.push({id:i,name:a,hostname:c}))}return t},Gc=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r={};for(const[n,o]of Object.entries(t)){const s=n.trim(),i=typeof o=="string"?o.trim():"";!s||!i||(r[s]=i)}return Object.keys(r).length>0?r:void 0},Ir=(e,t)=>{if(!Array.isArray(e))return;const r=[],n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.providerID=="string"?s.providerID.trim():"",a=typeof s.modelID=="string"?s.modelID.trim():"";if(!i||!a)continue;const c=`${i}/${a}`;if(!n.has(c)&&(n.add(c),r.push({providerID:i,modelID:a}),r.length>=t))break}return r},Ds=()=>{const e=de.persist;if(e&&typeof e=="object")return e},Ms=()=>ar()?.settings??null,Vr=e=>{const t=de.getState(),r=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,n=typeof window<"u"?window.__zustand_config_store__??null:null,o=vc.getState();if(typeof e.showReasoningTraces=="boolean"&&e.showReasoningTraces!==t.showReasoningTraces&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.sessionRecapEnabled=="boolean"&&e.sessionRecapEnabled!==t.sessionRecapEnabled&&t.setSessionRecapEnabled(e.sessionRecapEnabled),typeof e.sessionSuggestionEnabled=="boolean"&&e.sessionSuggestionEnabled!==t.sessionSuggestionEnabled&&t.setSessionSuggestionEnabled(e.sessionSuggestionEnabled),typeof e.collapsibleThinkingBlocks=="boolean"&&e.collapsibleThinkingBlocks!==t.collapsibleThinkingBlocks&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled=="boolean"&&e.autoDeleteEnabled!==t.autoDeleteEnabled&&t.setAutoDeleteEnabled(e.autoDeleteEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)){const i=Math.max(1,Math.min(365,e.autoDeleteAfterDays));i!==t.autoDeleteAfterDays&&t.setAutoDeleteAfterDays(i)}(e.sessionRetentionAction==="archive"||e.sessionRetentionAction==="delete")&&e.sessionRetentionAction!==t.sessionRetentionAction&&t.setSessionRetentionAction(e.sessionRetentionAction);let s=null;if(mn(e.followUpBehavior)?s=e.followUpBehavior:typeof e.queueModeEnabled=="boolean"&&(s=yn(void 0,e.queueModeEnabled)),s&&s!==o.followUpBehavior&&o.setFollowUpBehavior(s),typeof e.showDeletionDialog=="boolean"&&e.showDeletionDialog!==t.showDeletionDialog&&t.setShowDeletionDialog(e.showDeletionDialog),typeof e.nativeNotificationsEnabled=="boolean"&&e.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&t.setNativeNotificationsEnabled(e.nativeNotificationsEnabled),typeof e.notificationMode=="string"&&(e.notificationMode==="always"||e.notificationMode==="hidden-only")&&e.notificationMode!==t.notificationMode&&t.setNotificationMode(e.notificationMode),typeof e.notifyOnSubtasks=="boolean"&&e.notifyOnSubtasks!==t.notifyOnSubtasks&&t.setNotifyOnSubtasks(e.notifyOnSubtasks),typeof e.notifyOnCompletion=="boolean"&&e.notifyOnCompletion!==t.notifyOnCompletion&&t.setNotifyOnCompletion(e.notifyOnCompletion),typeof e.notifyOnError=="boolean"&&e.notifyOnError!==t.notifyOnError&&t.setNotifyOnError(e.notifyOnError),typeof e.notifyOnQuestion=="boolean"&&e.notifyOnQuestion!==t.notifyOnQuestion&&t.setNotifyOnQuestion(e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates=="object"&&t.setNotificationTemplates(e.notificationTemplates),typeof e.summarizeLastMessage=="boolean"&&e.summarizeLastMessage!==t.summarizeLastMessage&&t.setSummarizeLastMessage(e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&t.setSummaryThreshold(e.summaryThreshold),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&t.setSummaryLength(e.summaryLength),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&t.setMaxLastMessageLength(e.maxLastMessageLength),typeof e.inputSpellcheckEnabled=="boolean"&&e.inputSpellcheckEnabled!==t.inputSpellcheckEnabled&&t.setInputSpellcheckEnabled(e.inputSpellcheckEnabled),typeof e.showOpenCodeUpdateNotifications=="boolean"&&e.showOpenCodeUpdateNotifications!==t.showOpenCodeUpdateNotifications&&t.setShowOpenCodeUpdateNotifications(e.showOpenCodeUpdateNotifications),typeof e.showToolFileIcons=="boolean"&&e.showToolFileIcons!==t.showToolFileIcons&&t.setShowToolFileIcons(e.showToolFileIcons),typeof e.codeBlockLineWrap=="boolean"&&e.codeBlockLineWrap!==t.codeBlockLineWrap&&t.setCodeBlockLineWrap(e.codeBlockLineWrap),typeof e.showTurnChangedFiles=="boolean"&&e.showTurnChangedFiles!==t.showTurnChangedFiles&&t.setShowTurnChangedFiles(e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&e.showExpandedBashTools!==t.showExpandedBashTools&&t.setShowExpandedBashTools(e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&e.showExpandedEditTools!==t.showExpandedEditTools&&t.setShowExpandedEditTools(e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&e.timeFormatPreference!==t.timeFormatPreference&&t.setTimeFormatPreference(e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&e.weekStartPreference!==t.weekStartPreference&&t.setWeekStartPreference(e.weekStartPreference),typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&e.chatRenderMode!==t.chatRenderMode&&t.setChatRenderMode(e.chatRenderMode),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&e.activityRenderMode!==t.activityRenderMode&&t.setActivityRenderMode(e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&e.mermaidRenderingMode!==t.mermaidRenderingMode&&t.setMermaidRenderingMode(e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&e.userMessageRenderingMode!==t.userMessageRenderingMode&&t.setUserMessageRenderingMode(e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&e.collapsibleUserMessages!==t.collapsibleUserMessages&&t.setCollapsibleUserMessages(e.collapsibleUserMessages),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&r&&e.messageStreamTransport!==r.settingsMessageStreamTransport&&r.setSettingsMessageStreamTransport(e.messageStreamTransport),typeof e.stickyUserHeader=="boolean"&&e.stickyUserHeader!==t.stickyUserHeader&&t.setStickyUserHeader(e.stickyUserHeader),typeof e.expandedEditorToolbar=="boolean"&&e.expandedEditorToolbar!==t.expandedEditorToolbar&&t.setExpandedEditorToolbar(e.expandedEditorToolbar),typeof e.wideChatLayoutEnabled=="boolean"&&e.wideChatLayoutEnabled!==t.wideChatLayoutEnabled&&t.setWideChatLayoutEnabled(e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&e.showSplitAssistantMessageActions!==t.showSplitAssistantMessageActions&&t.setShowSplitAssistantMessageActions(e.showSplitAssistantMessageActions),typeof e.reportUsage=="boolean"&&e.reportUsage!==t.reportUsage&&t.setReportUsage(e.reportUsage),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize!==t.fontSize&&t.setFontSize(e.fontSize),Array.isArray(e.draftStarters)){const i=Ps(e.draftStarters);JSON.stringify(t.globalDraftStarters)!==JSON.stringify(i)&&t.setGlobalDraftStarters(i)}if(typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&e.terminalFontSize!==t.terminalFontSize&&t.setTerminalFontSize(e.terminalFontSize),fs(e.uiFont)&&e.uiFont!==t.uiFont&&t.setUiFont(e.uiFont),hs(e.monoFont)&&e.monoFont!==t.monoFont&&t.setMonoFont(e.monoFont),typeof e.padding=="number"&&Number.isFinite(e.padding)&&e.padding!==t.padding&&t.setPadding(e.padding),typeof e.cornerRadius=="number"&&Number.isFinite(e.cornerRadius)&&e.cornerRadius!==t.cornerRadius&&t.setCornerRadius(e.cornerRadius),typeof e.inputBarOffset=="number"&&Number.isFinite(e.inputBarOffset)&&e.inputBarOffset!==t.inputBarOffset&&t.setInputBarOffset(e.inputBarOffset),e.shortcutOverrides&&!Uc(e.shortcutOverrides,t.shortcutOverrides)&&de.setState({shortcutOverrides:e.shortcutOverrides}),typeof e.mobileKeyboardMode=="string"){const i=lr(e.mobileKeyboardMode,t.mobileKeyboardMode);i!==t.mobileKeyboardMode&&t.setMobileKeyboardMode(i)}if(n&&r){const i={};typeof e.dictationEnabled=="boolean"&&e.dictationEnabled!==r.dictationEnabled&&(i.dictationEnabled=e.dictationEnabled),(e.sttProvider==="local"||e.sttProvider==="openai-compatible")&&e.sttProvider!==r.sttProvider&&(i.sttProvider=e.sttProvider),typeof e.sttServerUrl=="string"&&e.sttServerUrl!==r.sttServerUrl&&(i.sttServerUrl=e.sttServerUrl),typeof e.sttModel=="string"&&e.sttModel!==r.sttModel&&(i.sttModel=e.sttModel),typeof e.sttLocalModel=="string"&&e.sttLocalModel!==r.sttLocalModel&&(i.sttLocalModel=e.sttLocalModel),typeof e.sttLanguage=="string"&&e.sttLanguage!==r.sttLanguage&&(i.sttLanguage=e.sttLanguage),Object.keys(i).length>0&&n.setState(i)}if(Array.isArray(e.favoriteModels)){const i=t.favoriteModels,a=e.favoriteModels;Or(i,a)||de.setState({favoriteModels:a})}if(Array.isArray(e.hiddenModels)){const i=t.hiddenModels,a=e.hiddenModels;Or(i,a)||de.setState({hiddenModels:a})}if(Array.isArray(e.collapsedModelProviders)){const i=t.collapsedModelProviders,a=e.collapsedModelProviders;qr(i,a)||de.setState({collapsedModelProviders:a})}if(Array.isArray(e.recentModels)){const i=t.recentModels,a=e.recentModels;Or(i,a)||de.setState({recentModels:a})}if(Array.isArray(e.recentAgents)){const i=t.recentAgents,a=e.recentAgents;qr(i,a)||de.setState({recentAgents:a})}if(e.recentEfforts&&typeof e.recentEfforts=="object"){const i=t.recentEfforts,a=e.recentEfforts;Bc(i,a)||de.setState({recentEfforts:a})}typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&e.diffLayoutPreference!==t.diffLayoutPreference&&t.setDiffLayoutPreference(e.diffLayoutPreference),typeof e.gitChangesViewMode=="string"&&(e.gitChangesViewMode==="flat"||e.gitChangesViewMode==="tree")&&e.gitChangesViewMode!==t.gitChangesViewMode&&t.setGitChangesViewMode(e.gitChangesViewMode),typeof e.directoryShowHidden=="boolean"&&Pc(e.directoryShowHidden,{persist:!1}),typeof e.filesViewShowGitignored=="boolean"&&Mc(e.filesViewShowGitignored,{persist:!1})},so=e=>{if(!e||typeof e!="object")return null;const t=e,r={};if(typeof t.themeId=="string"&&t.themeId.length>0&&(r.themeId=t.themeId),(t.useSystemTheme===!0||t.useSystemTheme===!1)&&(r.useSystemTheme=t.useSystemTheme),typeof t.themeVariant=="string"&&(t.themeVariant==="light"||t.themeVariant==="dark")&&(r.themeVariant=t.themeVariant),typeof t.lightThemeId=="string"&&t.lightThemeId.length>0&&(r.lightThemeId=t.lightThemeId),typeof t.darkThemeId=="string"&&t.darkThemeId.length>0&&(r.darkThemeId=t.darkThemeId),typeof t.lastDirectory=="string"&&t.lastDirectory.length>0&&(r.lastDirectory=t.lastDirectory),typeof t.homeDirectory=="string"&&t.homeDirectory.length>0&&(r.homeDirectory=t.homeDirectory),typeof t.opencodeBinary=="string"){const h=t.opencodeBinary.trim();r.opencodeBinary=h.length>0?h:void 0}typeof t.desktopLanAccessEnabled=="boolean"&&(r.desktopLanAccessEnabled=t.desktopLanAccessEnabled),typeof t.desktopKeepAwakeEnabled=="boolean"&&(r.desktopKeepAwakeEnabled=t.desktopKeepAwakeEnabled),typeof t.desktopMinimizeToTrayEnabled=="boolean"&&(r.desktopMinimizeToTrayEnabled=t.desktopMinimizeToTrayEnabled);const n=zc(t.projects);if(n&&(r.projects=n),typeof t.activeProjectId=="string"&&t.activeProjectId.length>0&&(r.activeProjectId=t.activeProjectId),Array.isArray(t.securityScopedBookmarks)&&(r.securityScopedBookmarks=t.securityScopedBookmarks.filter(h=>typeof h=="string"&&h.length>0)),Array.isArray(t.pinnedDirectories)&&(r.pinnedDirectories=Array.from(new Set(t.pinnedDirectories.filter(h=>typeof h=="string"&&h.length>0)))),Array.isArray(t.draftStarters)&&(r.draftStarters=Ps(t.draftStarters)),typeof t.showReasoningTraces=="boolean"&&(r.showReasoningTraces=t.showReasoningTraces),typeof t.sessionRecapEnabled=="boolean"&&(r.sessionRecapEnabled=t.sessionRecapEnabled),typeof t.sessionSuggestionEnabled=="boolean"&&(r.sessionSuggestionEnabled=t.sessionSuggestionEnabled),typeof t.collapsibleThinkingBlocks=="boolean"&&(r.collapsibleThinkingBlocks=t.collapsibleThinkingBlocks),typeof t.autoDeleteEnabled=="boolean"&&(r.autoDeleteEnabled=t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)&&(r.autoDeleteAfterDays=t.autoDeleteAfterDays),(t.sessionRetentionAction==="archive"||t.sessionRetentionAction==="delete")&&(r.sessionRetentionAction=t.sessionRetentionAction),typeof t.tunnelProvider=="string"){const h=t.tunnelProvider.trim().toLowerCase();h.length>0&&(r.tunnelProvider=h)}if(typeof t.tunnelMode=="string"){const h=t.tunnelMode.trim().toLowerCase();(h==="quick"||h==="managed-remote"||h==="managed-local")&&(r.tunnelMode=h)}if(t.tunnelBootstrapTtlMs===null?r.tunnelBootstrapTtlMs=null:typeof t.tunnelBootstrapTtlMs=="number"&&Number.isFinite(t.tunnelBootstrapTtlMs)&&(r.tunnelBootstrapTtlMs=t.tunnelBootstrapTtlMs),typeof t.tunnelSessionTtlMs=="number"&&Number.isFinite(t.tunnelSessionTtlMs)&&(r.tunnelSessionTtlMs=t.tunnelSessionTtlMs),t.managedLocalTunnelConfigPath===null)r.managedLocalTunnelConfigPath=null;else if(typeof t.managedLocalTunnelConfigPath=="string"){const h=t.managedLocalTunnelConfigPath.trim();r.managedLocalTunnelConfigPath=h.length>0?h:null}typeof t.managedRemoteTunnelHostname=="string"&&(r.managedRemoteTunnelHostname=t.managedRemoteTunnelHostname.trim()),t.managedRemoteTunnelToken===null?r.managedRemoteTunnelToken=null:typeof t.managedRemoteTunnelToken=="string"&&(r.managedRemoteTunnelToken=t.managedRemoteTunnelToken.trim());const o=$c(t.managedRemoteTunnelPresets);if(o&&(r.managedRemoteTunnelPresets=o),typeof t.managedRemoteTunnelSelectedPresetId=="string"){const h=t.managedRemoteTunnelSelectedPresetId.trim();r.managedRemoteTunnelSelectedPresetId=h.length>0?h:void 0}const s=Gc(t.managedRemoteTunnelPresetTokens);if(s&&(r.managedRemoteTunnelPresetTokens=s),typeof t.defaultModel=="string"&&t.defaultModel.length>0&&(r.defaultModel=t.defaultModel),typeof t.defaultVariant=="string"&&t.defaultVariant.length>0&&(r.defaultVariant=t.defaultVariant),typeof t.defaultAgent=="string"&&t.defaultAgent.length>0&&(r.defaultAgent=t.defaultAgent),typeof t.smallModelUseDefault=="boolean"&&(r.smallModelUseDefault=t.smallModelUseDefault),typeof t.smallModelOverride=="string"&&t.smallModelOverride.length>0&&(r.smallModelOverride=t.smallModelOverride),typeof t.autoCreateWorktree=="boolean"&&(r.autoCreateWorktree=t.autoCreateWorktree),typeof t.gitmojiEnabled=="boolean"&&(r.gitmojiEnabled=t.gitmojiEnabled),mn(t.followUpBehavior)?r.followUpBehavior=t.followUpBehavior:typeof t.queueModeEnabled=="boolean"&&(r.followUpBehavior=yn(void 0,t.queueModeEnabled)),typeof t.showDeletionDialog=="boolean"&&(r.showDeletionDialog=t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&(r.nativeNotificationsEnabled=t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&(r.notificationMode=t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&(r.notifyOnSubtasks=t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&(r.notifyOnCompletion=t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&(r.notifyOnError=t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&(r.notifyOnQuestion=t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"){const h=t.notificationTemplates,b=C=>{const be=h[C];if(!be||typeof be!="object")return;const ne=be,et=typeof ne.title=="string"?ne.title:"",dr=typeof ne.message=="string"?ne.message:"";return{title:et,message:dr}},T=b("completion"),S=b("error"),R=b("question"),E=b("subtask");(T||S||R||E)&&(r.notificationTemplates={completion:T??{title:"Task Complete",message:"Your task has finished."},error:S??{title:"Error Occurred",message:"An error occurred while processing your task."},question:R??{title:"Input Needed",message:"Please provide input to continue."},subtask:E??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof t.summarizeLastMessage=="boolean"&&(r.summarizeLastMessage=t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&(r.summaryThreshold=Math.max(0,Math.round(t.summaryThreshold))),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&(r.summaryLength=Math.max(10,Math.round(t.summaryLength))),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&(r.maxLastMessageLength=Math.max(10,Math.round(t.maxLastMessageLength))),typeof t.usageAutoRefresh=="boolean"&&(r.usageAutoRefresh=t.usageAutoRefresh),typeof t.usageRefreshIntervalMs=="number"&&Number.isFinite(t.usageRefreshIntervalMs)&&(r.usageRefreshIntervalMs=t.usageRefreshIntervalMs),(t.usageDisplayMode==="usage"||t.usageDisplayMode==="remaining")&&(r.usageDisplayMode=t.usageDisplayMode),typeof t.usageShowPredValues=="boolean"&&(r.usageShowPredValues=t.usageShowPredValues),Array.isArray(t.usageDropdownProviders)&&(r.usageDropdownProviders=t.usageDropdownProviders.filter(h=>typeof h=="string"&&h.length>0)),t.usageSelectedModels&&typeof t.usageSelectedModels=="object"){const h={};for(const[b,T]of Object.entries(t.usageSelectedModels))Array.isArray(T)&&(h[b]=T.filter(S=>typeof S=="string"));Object.keys(h).length>0&&(r.usageSelectedModels=h)}if(t.usageCollapsedFamilies&&typeof t.usageCollapsedFamilies=="object"){const h={};for(const[b,T]of Object.entries(t.usageCollapsedFamilies))Array.isArray(T)&&(h[b]=T.filter(S=>typeof S=="string"));Object.keys(h).length>0&&(r.usageCollapsedFamilies=h)}if(t.usageExpandedFamilies&&typeof t.usageExpandedFamilies=="object"){const h={};for(const[b,T]of Object.entries(t.usageExpandedFamilies))Array.isArray(T)&&(h[b]=T.filter(S=>typeof S=="string"));Object.keys(h).length>0&&(r.usageExpandedFamilies=h)}if(t.usageModelGroups&&typeof t.usageModelGroups=="object"){const h={};for(const[b,T]of Object.entries(t.usageModelGroups))if(T&&typeof T=="object"){const S=T,R={};Array.isArray(S.customGroups)&&(R.customGroups=S.customGroups.filter(E=>E&&typeof E=="object").map(E=>({id:String(E.id??""),label:String(E.label??""),models:Array.isArray(E.models)?E.models.filter(C=>typeof C=="string"):[],order:typeof E.order=="number"?E.order:0}))),S.modelAssignments&&typeof S.modelAssignments=="object"&&(R.modelAssignments=Object.fromEntries(Object.entries(S.modelAssignments).filter(([,E])=>typeof E=="string").map(([E,C])=>[E,String(C)]))),S.renamedGroups&&typeof S.renamedGroups=="object"&&(R.renamedGroups=Object.fromEntries(Object.entries(S.renamedGroups).filter(([,E])=>typeof E=="string").map(([E,C])=>[E,String(C)]))),Object.keys(R).length>0&&(h[b]=R)}Object.keys(h).length>0&&(r.usageModelGroups=h)}typeof t.inputSpellcheckEnabled=="boolean"&&(r.inputSpellcheckEnabled=t.inputSpellcheckEnabled),typeof t.showOpenCodeUpdateNotifications=="boolean"&&(r.showOpenCodeUpdateNotifications=t.showOpenCodeUpdateNotifications),typeof t.openCodeUpdateToastDismissedVersion=="string"&&(r.openCodeUpdateToastDismissedVersion=t.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof t.showToolFileIcons=="boolean"&&(r.showToolFileIcons=t.showToolFileIcons),typeof t.codeBlockLineWrap=="boolean"&&(r.codeBlockLineWrap=t.codeBlockLineWrap),typeof t.showTurnChangedFiles=="boolean"&&(r.showTurnChangedFiles=t.showTurnChangedFiles),typeof t.showExpandedBashTools=="boolean"&&(r.showExpandedBashTools=t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&(r.showExpandedEditTools=t.showExpandedEditTools),typeof t.timeFormatPreference=="string"&&(t.timeFormatPreference==="auto"||t.timeFormatPreference==="12h"||t.timeFormatPreference==="24h")&&(r.timeFormatPreference=t.timeFormatPreference),typeof t.weekStartPreference=="string"&&(t.weekStartPreference==="auto"||t.weekStartPreference==="sunday"||t.weekStartPreference==="monday")&&(r.weekStartPreference=t.weekStartPreference),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&(r.chatRenderMode=t.chatRenderMode),typeof t.messageStreamTransport=="string"&&(t.messageStreamTransport==="auto"||t.messageStreamTransport==="ws"||t.messageStreamTransport==="sse")&&(r.messageStreamTransport=t.messageStreamTransport),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&(r.activityRenderMode=t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&(r.mermaidRenderingMode=t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&(r.userMessageRenderingMode=t.userMessageRenderingMode),typeof t.collapsibleUserMessages=="boolean"&&(r.collapsibleUserMessages=t.collapsibleUserMessages),typeof t.stickyUserHeader=="boolean"&&(r.stickyUserHeader=t.stickyUserHeader),typeof t.wideChatLayoutEnabled=="boolean"&&(r.wideChatLayoutEnabled=t.wideChatLayoutEnabled),typeof t.showSplitAssistantMessageActions=="boolean"&&(r.showSplitAssistantMessageActions=t.showSplitAssistantMessageActions),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&(r.fontSize=t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&(r.terminalFontSize=t.terminalFontSize),fs(t.uiFont)&&(r.uiFont=t.uiFont),hs(t.monoFont)&&(r.monoFont=t.monoFont),typeof t.padding=="number"&&Number.isFinite(t.padding)&&(r.padding=t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&(r.cornerRadius=t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&(r.inputBarOffset=t.inputBarOffset);const i=Lc(t.shortcutOverrides);i&&(r.shortcutOverrides=i),typeof t.mobileKeyboardMode=="string"&&(t.mobileKeyboardMode==="native"||t.mobileKeyboardMode==="resize-content")&&(r.mobileKeyboardMode=t.mobileKeyboardMode);const a=Ir(t.favoriteModels,64);a&&(r.favoriteModels=a);const c=Ir(t.hiddenModels,1024);c&&(r.hiddenModels=c);const l=Kr(t.collapsedModelProviders);l&&(r.collapsedModelProviders=l);const d=Ir(t.recentModels,16);d&&(r.recentModels=d);const f=Kr(t.recentAgents);f&&(r.recentAgents=f);const w=Nc(t.recentEfforts);if(w&&(r.recentEfforts=w),typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&(r.diffLayoutPreference=t.diffLayoutPreference),typeof t.gitChangesViewMode=="string"&&(t.gitChangesViewMode==="flat"||t.gitChangesViewMode==="tree")&&(r.gitChangesViewMode=t.gitChangesViewMode),typeof t.directoryShowHidden=="boolean"&&(r.directoryShowHidden=t.directoryShowHidden),typeof t.filesViewShowGitignored=="boolean"&&(r.filesViewShowGitignored=t.filesViewShowGitignored),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&(r.openInAppId=t.openInAppId),typeof t.pwaAppName=="string"){const h=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);r.pwaAppName=h.length>0?h:""}const p=xc(t.skillCatalogs);return p&&(r.skillCatalogs=p),typeof t.reportUsage=="boolean"&&(r.reportUsage=t.reportUsage),typeof t.globalBehaviorPrompt=="string"&&(r.globalBehaviorPrompt=t.globalBehaviorPrompt),typeof t.responseStyleEnabled=="boolean"&&(r.responseStyleEnabled=t.responseStyleEnabled),typeof t.responseStylePreset=="string"&&(t.responseStylePreset==="concise"||t.responseStylePreset==="detailed"||t.responseStylePreset==="mentor"||t.responseStylePreset==="pushback"||t.responseStylePreset==="noFiller"||t.responseStylePreset==="matchEnergy"||t.responseStylePreset==="warmPeer"||t.responseStylePreset==="custom")&&(r.responseStylePreset=t.responseStylePreset),typeof t.responseStyleCustomInstructions=="string"&&(r.responseStyleCustomInstructions=t.responseStyleCustomInstructions),typeof t.dictationEnabled=="boolean"&&(r.dictationEnabled=t.dictationEnabled),t.sttProvider==="local"||t.sttProvider==="openai-compatible"?r.sttProvider=t.sttProvider:t.sttProvider==="server"?r.sttProvider="openai-compatible":(t.sttProvider==="browser"||t.sttProvider==="wasm")&&(r.sttProvider="local"),typeof t.sttServerUrl=="string"&&(r.sttServerUrl=t.sttServerUrl.trim()),typeof t.sttModel=="string"&&(r.sttModel=t.sttModel.trim()),typeof t.sttLocalModel=="string"&&(r.sttLocalModel=t.sttLocalModel.trim()),typeof t.sttLanguage=="string"&&(r.sttLanguage=t.sttLanguage.trim()),r};let Oe=null,st=null;const Wc=2e3,qc=async()=>Oe&&Date.now()-Oe.at<Wc?Oe.value:st||(st=(async()=>{const e=Ms();if(e)try{const t=await e.load(),r=so(t.settings);return Oe={value:r,at:Date.now()},r}catch(t){console.warn("Failed to load shared settings from runtime settings API:",t)}try{const t=await u("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const r=await t.json().catch(()=>null),n=so(r);return Oe={value:n,at:Date.now()},n}catch(t){return console.warn("Failed to load shared settings from server:",t),null}})().finally(()=>{st=null}),st),of=async()=>{if(typeof window>"u")return;const e=Ds(),t=()=>!e?.hasHydrated||e.hasHydrated()||!e.onFinishHydration?Promise.resolve():new Promise(n=>{let o=!1;const s=()=>{o||(o=!0,n())},i=e.onFinishHydration(()=>{i?.(),s()});e.hasHydrated?.()&&s()}),r=async n=>{try{Gr(n)}catch(o){console.warn("persistToLocalStorage failed:",o)}await t();try{Vr(n)}catch(o){console.warn("applyDesktopUiPreferences failed:",o)}Wr(n)};try{const n=await qc();n&&await r(n)}catch(n){console.warn("Failed to synchronise settings:",n)}};let Yt=null,Bt=null,Jr=[];const Kc=200,Vc=async()=>{const e=Yt,t=Jr;if(Yt=null,Bt=null,Jr=[],!e||Object.keys(e).length===0){t.forEach(n=>n());return}const r=Ms();if(r)try{const n=await r.save(e);n&&(Gr(n),Vr(n),Wr(n),Oe=null),t.forEach(o=>o());return}catch(n){console.warn("Failed to update settings via runtime settings API:",n)}try{const n=await u("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!n.ok){console.warn("Failed to update shared settings via API:",n.status,n.statusText);return}const o=await n.json().catch(()=>null);o&&(Gr(o),Vr(o),Wr(o),Oe=null)}catch(n){console.warn("Failed to update shared settings via API:",n)}finally{t.forEach(n=>n())}},ge=async e=>{if(typeof window>"u")return;Yt={...Yt??{},...e},Bt&&clearTimeout(Bt);const t=new Promise(r=>{Jr.push(r)});return Bt=setTimeout(()=>{Vc()},Kc),t},sf=async()=>{if(typeof window>"u")return;const e=Ds();try{const t=await Ic();if(!t)return;const r=()=>Oc(t);if(e?.hasHydrated?.()){r();return}if(r(),e?.onFinishHydration){const n=e.onFinishHydration(()=>{n?.(),r()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},Jc=3e4,Yc=40,Qc=60,Xc=(e,t,r,n,o,s)=>{const i=e.trim(),a=t.trim().toLowerCase();return JSON.stringify([i,a,r,n,o,s])},io=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r)&&r[0]===t}catch{return!1}},Zc=er()(tr((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(r,n,o=Qc,s){if(!r||r.trim().length===0)return[];const i=r.trim(),a=typeof n=="string"?n.trim():"",c=!!s?.includeHidden,l=s?.respectGitignore??!0,d=s?.type==="directory"?"directory":"file",f=Xc(i,a,o,c,l,d),w=Date.now(),p=t().cache[f];if(p&&w-p.timestamp<Jc)return p.files;const h=t().inFlight[f];if(h)return h;const b=ke.searchFiles(a,{directory:i,limit:o,includeHidden:c,respectGitignore:l,dirs:d!=="file",type:d}).then(T=>(e(S=>{if(S.inFlight[f]!==b)return S;const R={...S.cache,[f]:{files:T,timestamp:Date.now()}},E=S.cacheKeys.filter(C=>C!==f);for(E.push(f);E.length>Yc;){const C=E.shift();C&&delete R[C]}return{cache:R,cacheKeys:E}}),T)).finally(()=>{e(T=>{if(T.inFlight[f]!==b)return T;const S={...T.inFlight};return delete S[f],{inFlight:S}})});return e(T=>({inFlight:{...T.inFlight,[f]:b}})),b},invalidateDirectory(r){if(!r||r.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const n=r.trim();e(o=>{const s={...o.cache},i=o.cacheKeys.filter(l=>io(l,n)?(delete s[l],!1):!0),a=Object.entries(o.inFlight).filter(([l])=>!io(l,n)),c=Object.fromEntries(a);return{cache:s,cacheKeys:i,inFlight:c}})}}),{name:"file-search-store"})),el=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Yr="openchamber_stream_perf",Et=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Yr)==="1"}catch{return!1}},ao=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),tl=()=>{if(!Et()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},Cs=e=>Array.from(e.entries()).map(([t,r])=>({metric:t,count:r.count,avg:r.count>0?Number((r.total/r.count).toFixed(3)):0,max:Number(r.max.toFixed(3)),total:Number(r.total.toFixed(3)),last:Number(r.last.toFixed(3))})).sort((t,r)=>r.total-t.total||r.count-t.count),gn=(e,t)=>{const r=tl();if(!r)return;const n=r.counters.get(e)??{count:0,total:0,max:0,last:0};n.count+=1,n.total+=t,n.max=Math.max(n.max,t),n.last=t,r.counters.set(e,n),r.lastUpdatedAt=Date.now()},af=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Yr,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Yr),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},cf=()=>{typeof window>"u"||(Et()&&(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()}))},lf=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!Et()||!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:Cs(e.counters)}},df=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!Et()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,r=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:r,durationMs:t?Math.max(0,Date.now()-t):0,entries:Cs(e.counters)}},uf=(e,t=1)=>{gn(e,t)},ff=(e,t)=>{gn(e,t)},hf=(e,t)=>{if(!Et())return t();const r=ao();try{return t()}finally{gn(e,ao()-r)}};var rl={};let ae=null,co=0;const ie=Tt(),lo=ie.getItem("lastDirectory"),nl=typeof lo=="string"&&lo.length>0,_t=e=>{try{Zc.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Qe=e=>{const t=e.trim();if(!t)return t;const r=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,o)=>o.toUpperCase()+":");return r.length>1?r.replace(/\/+$/,""):r},ol=(e,t)=>{const r=e.trim();return r.startsWith("~")?r==="~"?t||r:(r.startsWith("~/")||r.startsWith("~\\"))&&t?`${t}${r.slice(1)}`:r:r},jt=(e,t)=>{const r=ol(e,t);return Qe(r)},sl=()=>{const e=ie.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Qe(e);return t.length>0?t:null},il=()=>{const e=ie.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Qe(e);return t.length>0?t:null},al=()=>{if(typeof process>"u")return null;const e=rl,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const n=Qe(t);return n.length>0?n:null}const r=process?.cwd?.();if(typeof r=="string"&&r.trim().length>0){const n=Qe(r);return n.length>0?n:null}return null},Qt=()=>{if(typeof window<"u"){if(ae)return ae;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ae=t,ie.setItem("homeDirectory",t),t;const r=sl();if(r&&!cr())return ae=r,r}const e=al();return e||"/"},cl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const r=t.replace(/\\/g,"/");if(r.length>1){const n=r.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return r==="/"||r.length===0?null:r},ll=e=>(ae=e,typeof window<"u"&&ie.setItem("homeDirectory",e),ge({homeDirectory:e}),e),Qr=async()=>{const e=n=>{const o=cl(n);return o?ll(o):null};try{const n=await ke.getFilesystemHome(),o=e(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await ke.getSystemInfo(),o=e(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await os(),o=e(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const t=Qt(),r=e(t);return r||t},dl=()=>{if(!cr())return null;const e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Qe(e);return t.length>0?t:null},gt=dl()||Qt(),Xt=(()=>{const e=il();return e&&!cr()?jt(e,gt):gt})();Xt&&ke.setDirectory(Xt);const ul=!!(gt&>!=="/"),Xr=er()(tr((e,t)=>({currentDirectory:Xt,directoryHistory:[Xt],historyIndex:0,homeDirectory:gt,hasPersistedDirectory:nl,isHomeReady:ul,isSwitchingDirectory:!1,setDirectory:(r,n)=>{const o=ae||t().homeDirectory||ie.getItem("homeDirectory"),s=jt(r,o);el()&&console.log("[DirectoryStore] setDirectory called with path:",s),ke.setDirectory(s),_t(),e(i=>{const a=[...i.directoryHistory.slice(0,i.historyIndex+1),s];return ie.setItem("lastDirectory",s),ge({lastDirectory:s}),{currentDirectory:s,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const r=t();if(r.historyIndex>0){const n=r.historyIndex-1,o=r.directoryHistory[n];ke.setDirectory(o),_t(),ie.setItem("lastDirectory",o),ge({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const r=t();if(r.historyIndex<r.directoryHistory.length-1){const n=r.historyIndex+1,o=r.directoryHistory[n];ke.setDirectory(o),_t(),ie.setItem("lastDirectory",o),ge({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:r,setDirectory:n}=t(),o=ae||t().homeDirectory||Qt();if(r===o||r==="/")return;const s=r.endsWith("/")?r.slice(0,-1):r,i=s.lastIndexOf("/");if(i===-1){const a=ae||Qt();n(a)}else n(i===0?"/":s.substring(0,i))},goHome:async()=>{const r=ae||t().homeDirectory||await Qr();t().setDirectory(r)},synchronizeHomeDirectory:r=>{const n=t(),o=r;ae=o;const s=n.homeDirectory!==o,i=ie.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!s&&!c){n.isHomeReady||e({isHomeReady:!0});return}const l=typeof o=="string"&&o!==""&&o!=="/",d=n.currentDirectory?jt(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(b=>jt(b,o)),w=f.some((b,T)=>b!==n.directoryHistory[T]),p=!!(d&&d!==n.currentDirectory),h={homeDirectory:o,hasPersistedDirectory:a,isHomeReady:l};if(c?(h.currentDirectory=o,h.directoryHistory=[o],h.historyIndex=0,h.isSwitchingDirectory=!1):(p||w)&&(h.currentDirectory=d,h.directoryHistory=f,h.historyIndex=Math.min(n.historyIndex,f.length-1),h.isSwitchingDirectory=!1),e(()=>h),(c||p)&&l){const b=c?o:d;ke.setDirectory(b),_t(),ie.setItem("lastDirectory",b),ge({lastDirectory:b})}ge({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&(Qr().then(e=>{Xr.getState().synchronizeHomeDirectory(e)}),ma(()=>{ae=null;const e=++co;Qr().then(t=>{e===co&&Xr.getState().synchronizeHomeDirectory(t)})}));const fl=(e,t)=>{const r=nr();return r?r.openWebSocket(Ai(e),t):_i(new WebSocket(e))},Rs=1,ce=1,Ft=0,Os="/api/terminal/ws",hl=1200,pl=250,ml=2e4,yl=5e3,_r="__openchamberTerminalTransportState",gl=new TextEncoder,uo=new TextDecoder,wn=e=>X().websocket(e),Fr=e=>{const t=gl.encode(JSON.stringify(e)),r=new Uint8Array(t.length+1);return r[0]=Rs,r.set(t,1),r},wt=e=>e?((e.transports??[]).includes("ws")||e.preferred==="ws")&&typeof e.ws?.path=="string"&&e.ws.path.length>0:!1,bn=e=>e.streamCapability?.ws?.path??e.inputCapability?.ws?.path??Os,wl=e=>{switch(e){case"SESSION_NOT_FOUND":return new Error("Terminal session not found");case"NOT_BOUND":return new Error("Terminal session is not bound");case"WRITE_FAIL":return new Error("Failed to write to terminal");case"RATE_LIMIT":return new Error("Terminal websocket is rate limited");case"BAD_FRAME":return new Error("Terminal websocket protocol violation");default:return new Error("Terminal websocket error")}};class bl{socket=null;socketUrl="";boundSessionId=null;requestedSessionId=null;openPromise=null;reconnectTimeout=null;keepaliveInterval=null;closed=!1;subscriptions=new Map;activeSubscriptionToken=null;replayCursorBySession=new Map;configure(t){if(t){if(this.socketUrl===t){this.closed=!1,this.isConnectedOrConnecting()||this.ensureConnected();return}this.socketUrl=t,this.closed=!1,this.resetConnection(),this.ensureConnected()}}subscribe(t,r,n,o){const s=Symbol(t),i={token:s,sessionId:t,onEvent:r,onError:n,maxRetries:o?.maxRetries??3,initialRetryDelay:o?.initialRetryDelay??1e3,maxRetryDelay:o?.maxRetryDelay??8e3,connectionTimeout:o?.connectionTimeout??1e4,retryCount:0,connected:!1,connectionTimeoutId:null};return this.subscriptions.set(s,i),this.activeSubscriptionToken=s,this.boundSessionId=null,this.requestedSessionId=t,this.ensureConnected(),this.startConnectionTimeout(i),this.bindActiveSession(),()=>{this.clearConnectionTimeout(i),this.subscriptions.delete(s),this.activeSubscriptionToken===s&&(this.activeSubscriptionToken=null),this.boundSessionId===t&&(this.boundSessionId=null),this.requestedSessionId===t&&(this.requestedSessionId=null),this.subscriptions.size===0&&(this.clearReconnectTimeout(),this.resetConnection())}}async sendInput(t,r){if(!t||!r||this.closed||!this.socketUrl)return!1;const n=await this.getOpenSocket(hl);if(!n||n.readyState!==ce)return!1;try{return this.boundSessionId!==t&&(this.requestedSessionId=t,n.send(Fr({t:"b",s:t,r:this.replayCursorBySession.get(t)??0,v:2}))),n.send(r),!0}catch{return this.handleSocketFailure(new Error("Terminal websocket send failed")),!1}}unbindSession(t){t&&(this.boundSessionId===t&&(this.boundSessionId=null),this.requestedSessionId===t&&(this.requestedSessionId=null))}close(){this.closed=!0,this.clearReconnectTimeout();for(const t of this.subscriptions.values())this.clearConnectionTimeout(t);this.resetConnection(),this.socketUrl="",this.subscriptions.clear(),this.activeSubscriptionToken=null,this.replayCursorBySession.clear()}prime(){this.closed||!this.socketUrl||this.isConnectedOrConnecting()||this.ensureConnected()}isConnectedOrConnecting(t){return this.closed||t&&this.socketUrl!==t?!1:this.socket&&(this.socket.readyState===ce||this.socket.readyState===Ft)?!0:this.openPromise!==null}getActiveSubscription(){return this.activeSubscriptionToken?this.subscriptions.get(this.activeSubscriptionToken)??null:null}startConnectionTimeout(t){this.clearConnectionTimeout(t),t.connectionTimeoutId=setTimeout(()=>{this.getActiveSubscription()?.token!==t.token||t.connected||this.handleSocketFailure(new Error("Connection timeout"))},t.connectionTimeout)}clearConnectionTimeout(t){t.connectionTimeoutId&&(clearTimeout(t.connectionTimeoutId),t.connectionTimeoutId=null)}async getOpenSocket(t){if(this.socket&&this.socket.readyState===ce)return this.socket;if(this.ensureConnected(),this.socket&&this.socket.readyState===ce)return this.socket;const r=await Promise.race([this.openPromise??Promise.resolve(null),new Promise(n=>{setTimeout(()=>n(null),t)})]);return r&&r.readyState===ce?r:this.socket&&this.socket.readyState===ce?this.socket:null}ensureConnected(){this.closed||!this.socketUrl||this.socket&&(this.socket.readyState===ce||this.socket.readyState===Ft)||this.openPromise||(this.clearReconnectTimeout(),this.openPromise=new Promise(t=>{let r=!1,n=null;const o=s=>{r||(r=!0,n&&(clearTimeout(n),n=null),this.openPromise=null,t(s))};try{const s=fl(this.socketUrl);s.binaryType="arraybuffer",s.onopen=()=>{this.socket=s,this.startKeepalive(),o(s)},s.onmessage=i=>{this.handleSocketMessage(i.data)},s.onerror=()=>{!this.closed&&!this.getActiveSubscription()&&this.scheduleReconnect(new Error("Terminal websocket error"))},s.onclose=()=>{this.socket===s&&(this.socket=null,this.boundSessionId=null,this.stopKeepalive(),this.closed||this.scheduleReconnect(new Error("Terminal stream connection error"))),o(null)},this.socket=s,n=setTimeout(()=>{s.readyState===Ft&&(s.close(),o(null))},yl)}catch{o(null),this.closed||this.scheduleReconnect(new Error("Terminal websocket open failed"))}}))}bindActiveSession(){const t=this.getActiveSubscription();if(!(!t||!this.socket||this.socket.readyState!==ce)){this.requestedSessionId=t.sessionId;try{this.socket.send(Fr({t:"b",s:t.sessionId,r:this.replayCursorBySession.get(t.sessionId)??0,v:2}))}catch{this.handleSocketFailure(new Error("Terminal websocket bind failed"))}}}scheduleReconnect(t){if(this.closed||!this.socketUrl||this.reconnectTimeout)return;const r=this.getActiveSubscription();if(!r)return;const n=r.retryCount+1,o=r.initialRetryDelay,s=r.maxRetryDelay,i=r.maxRetries;if(n>i){this.clearConnectionTimeout(r),r.onError?.(t,!0);return}r.retryCount=n,r.connected=!1,r.onEvent({type:"reconnecting",attempt:n,maxAttempts:i}),this.startConnectionTimeout(r);const a=Math.min(o*Math.pow(2,Math.max(n-1,0)),s),c=Math.floor(Math.random()*pl),l=a+c;this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},l)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}sendControl(t){if(!this.socket||this.socket.readyState!==ce)return!1;try{return this.socket.send(Fr(t)),!0}catch{return this.handleSocketFailure(new Error("Terminal websocket control send failed")),!1}}startKeepalive(){this.stopKeepalive(),this.keepaliveInterval=setInterval(()=>{this.closed||this.sendControl({t:"p",v:2})},ml)}stopKeepalive(){this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null)}async handleSocketMessage(t){const r=await this.asUint8Array(t);if(r&&r.length>0&&r[0]===Rs){this.handleControlMessage(r);return}const n=await this.asText(t);if(!n)return;const o=this.getActiveSubscription();o&&o.onEvent({type:"data",data:n})}handleControlMessage(t){if(t.length<2)return;let r;try{r=JSON.parse(uo.decode(t.subarray(1)))}catch{this.handleSocketFailure(new Error("Terminal websocket control parse failed"));return}const n=this.getActiveSubscription();switch(r.t){case"ok":this.bindActiveSession();return;case"po":return;case"d":{const o=r.s??this.boundSessionId??this.requestedSessionId;if(!n||!o||o!==n.sessionId)return;typeof r.i=="number"&&Number.isFinite(r.i)&&this.replayCursorBySession.set(o,Math.max(this.replayCursorBySession.get(o)??0,Math.trunc(r.i))),typeof r.d=="string"&&r.d.length>0&&n.onEvent({type:"data",data:r.d});return}case"bok":{if(this.boundSessionId=r.s??this.requestedSessionId,!n)return;n.retryCount=0,n.connected=!0,this.clearConnectionTimeout(n),n.onEvent({type:"connected",runtime:r.runtime,ptyBackend:r.ptyBackend});return}case"x":{if(!n){this.boundSessionId=null;return}if(r.s&&r.s!==n.sessionId)return;n.connected=!1,this.clearConnectionTimeout(n),this.boundSessionId=null,this.requestedSessionId=null,this.replayCursorBySession.delete(n.sessionId),n.onEvent({type:"exit",exitCode:r.exitCode,signal:r.signal??null});return}case"e":{const o=wl(r.c),s=r.f===!0||r.c==="SESSION_NOT_FOUND";(r.c==="NOT_BOUND"||r.c==="SESSION_NOT_FOUND")&&(this.boundSessionId=null),n&&(n.connected=!1,s&&this.clearConnectionTimeout(n),n.onError?.(o,s)),r.f===!0&&this.handleSocketFailure(o);return}default:return}}async asUint8Array(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(t instanceof Uint8Array)return t;if(typeof Blob<"u"&&t instanceof Blob){const r=await t.arrayBuffer();return new Uint8Array(r)}return null}async asText(t){if(typeof t=="string")return t;const r=await this.asUint8Array(t);return r?uo.decode(r):""}handleSocketFailure(t){this.boundSessionId=null,this.requestedSessionId=null,this.resetConnection(),this.scheduleReconnect(t)}resetConnection(){if(this.openPromise=null,this.stopKeepalive(),this.socket){const t=this.socket;this.socket=null,t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,(t.readyState===ce||t.readyState===Ft)&&t.close()}this.boundSessionId=null}}const ue=()=>{const e=globalThis;return e[_r]||(e[_r]={inputCapability:null,streamCapability:null,manager:null}),e[_r]},Sn=()=>{const e=ue();return e.manager||(e.manager=new bl),e.manager},Is=e=>{const t=ue();if(t.inputCapability=e?.input??null,t.streamCapability=e?.stream??null,!wt(t.inputCapability)&&!wt(t.streamCapability)){t.manager?.close(),t.manager=null;return}const r=wn(bn(t));if(!r)return;Sn().configure(r)},Sl=async(e,t)=>{const r=await u(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain"},body:t});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to send terminal input"}));throw new Error(n.error||"Failed to send terminal input")}};async function Tl(e){const t=await u("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.cwd,cols:e.cols??80,rows:e.rows??24})});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(n.error||"Failed to create terminal session")}const r=await t.json();return Is(r.capabilities),r}const fo=(e,t,r,n={})=>{const o=n.maxRetries??3,s=n.initialRetryDelay??1e3,i=n.maxRetryDelay??8e3,a=n.connectionTimeout??1e4;let c=null,l=0,d=null,f=null,w=!1,p=!1;const h=()=>{d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},b=()=>{w||(w=!0,h(),c&&(c.close(),c=null))},T=(R,E)=>{if(!(w||p)){if(l<o&&!E){l+=1;const C=Math.min(s*Math.pow(2,l-1),i);t({type:"reconnecting",attempt:l,maxAttempts:o}),d=setTimeout(()=>{!w&&!p&&S()},C);return}r?.(R,!0),b()}},S=()=>{if(w||p||c&&c.readyState!==EventSource.CLOSED)return;c=new EventSource(X().sse(`/api/terminal/${e}/stream`));let R=!1;f=setTimeout(()=>{!R&&c?.readyState!==EventSource.OPEN&&(c?.close(),T(new Error("Connection timeout"),!1))},a),c.onopen=()=>{R||(R=!0,l=0,h(),t({type:"connected"}))},c.onmessage=E=>{try{const C=JSON.parse(E.data);C.type==="exit"&&(ue().manager?.unbindSession(e),p=!0,b()),t(C)}catch(C){r?.(C,!1)}},c.onerror=()=>{h();const E=p||c?.readyState===EventSource.CLOSED;c?.close(),c=null,p||T(new Error("Terminal stream connection error"),E)}};return S(),b};function El(e,t,r,n={}){const o=ue();if(!wt(o.streamCapability))return fo(e,t,r,n);const s=Sn(),i=wn(bn(o));return i?(s.configure(i),s.subscribe(e,t,r,n)):fo(e,t,r,n)}async function kl(e,t){const r=ue();r.manager&&await r.manager.sendInput(e,t)||await Sl(e,t)}async function vl(e,t,r){const n=await u(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:t,rows:r})});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(o.error||"Failed to resize terminal")}}async function Al(e){ue().manager?.unbindSession(e);const t=await u(`/api/terminal/${e}`,{method:"DELETE"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(r.error||"Failed to close terminal")}}async function Pl(e,t){ue().manager?.unbindSession(e);const r=await u(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t.cwd,cols:t.cols??80,rows:t.rows??24})});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(o.error||"Failed to restart terminal")}const n=await r.json();return Is(n.capabilities),n}async function Dl(e){const t=await u("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}e.sessionId&&ue().manager?.unbindSession(e.sessionId)}function pf(){const e=ue();e.manager?.close(),e.manager=null,e.inputCapability=null,e.streamCapability=null}function mf(){const e=ue();if(e.inputCapability&&e.streamCapability&&!wt(e.inputCapability)&&!wt(e.streamCapability))return;const t=bn(e)||Os,r=wn(t);if(!r)return;const n=Sn();n.isConnectedOrConnecting(r)||(n.configure(r),n.prime())}const Ml=e=>{const t=e?.retry;return{maxRetries:t?.maxRetries??3,initialRetryDelay:t?.initialDelayMs??1e3,maxRetryDelay:t?.maxDelayMs??8e3,connectionTimeout:e?.connectionTimeoutMs??1e4}},Cl=()=>({async createSession(e){return Tl(e)},connect(e,t,r){const n=El(e,t.onEvent,t.onError,Ml(r));return{close:()=>n()}},async sendInput(e,t){await kl(e,t)},async resize(e){await vl(e.sessionId,e.cols,e.rows)},async close(e){await Al(e)},async restartSession(e,t){return Pl(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows})},async forceKill(e){await Dl(e)}}),m="/api/git",Rl=1200,Ol=5e3,Zt=new Map,We=new Map,_s=new Map,ho=new Map,xt=new Map,bt=e=>e.trim(),Il=(e,t)=>t==="light"?`${bt(e)}::light`:bt(e),Zr=e=>_s.get(bt(e))??0,ve=e=>{const t=bt(e);_s.set(t,Zr(e)+1);for(const r of Array.from(Zt.keys()))(r===t||r.startsWith(`${t}::`))&&Zt.delete(r);for(const r of Array.from(We.keys()))(r===t||r.startsWith(`${t}::`))&&We.delete(r)};function y(e,t,r){const n={...r};return t&&(n.directory=t),X().api(e,n)}async function _l(e){const t=bt(e),r=Date.now(),n=ho.get(t);if(n&&n.expiresAt>r)return n.value;const o=xt.get(t);if(o)return o;const s=(async()=>{const i=await u(y(`${m}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return ho.set(t,{value:c,expiresAt:Date.now()+Ol}),c})();xt.set(t,s);try{return await s}finally{xt.get(t)===s&&xt.delete(t)}}async function Fl(e,t){const r=t?.mode,n=Il(e,r),o=Date.now(),s=Zt.get(n);if(s&&s.expiresAt>o)return s.value;const i=We.get(n);if(i)return i;const a=(async()=>{const c=Zr(e),l=await u(y(`${m}/status`,e,r?{mode:r}:void 0));if(!l.ok)throw new Error(`Failed to get git status: ${l.statusText}`);const d=await l.json();return Zr(e)===c&&Zt.set(n,{value:d,expiresAt:Date.now()+Rl}),d})();We.set(n,a);try{return await a}finally{We.get(n)===a&&We.delete(n)}}async function yf(e){const t=await u(y(`${m}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const r=await t.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:e}}async function gf(e){const t=await u(y(`${m}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const r=await t.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:e}}async function wf(e,t){const r=await u(y(`${m}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!r.ok)throw new Error(`Failed to get git commit summaries: ${r.statusText}`);const n=await r.json().catch(()=>({}));return{commits:Array.isArray(n.commits)?n.commits.map(o=>({sha:typeof o.sha=="string"?o.sha:"",short:typeof o.short=="string"?o.short:"",subject:typeof o.subject=="string"?o.subject:""})).filter(o=>o.sha&&o.short):[]}}async function xl(e,t){const{path:r,staged:n,contextLines:o}=t;if(!r)throw new Error("path is required to fetch git diff");const s=await u(y(`${m}/diff`,e,{path:r,staged:n?"true":void 0,context:o}));if(!s.ok)throw new Error(`Failed to get git diff: ${s.statusText}`);return s.json()}async function Ll(e,t){const{path:r,staged:n}=t;if(!r)throw new Error("path is required to fetch git file diff");const o=await u(y(`${m}/file-diff`,e,{path:r,staged:n?"true":void 0}));if(!o.ok)throw new Error(`Failed to get git file diff: ${o.statusText}`);return o.json()}async function Ul(e,t,r){if(!t)throw new Error("path is required to revert git changes");const n=await u(y(`${m}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:r?.scope})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to revert git changes")}ve(e)}async function Nl(e,t){await Fs(e,[t])}async function Fs(e,t){const r=t.map(o=>o.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to stage git changes");const n=await u(y(`${m}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to stage git changes")}ve(e)}async function Bl(e,t){await xs(e,[t])}async function xs(e,t){const r=t.map(o=>o.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to unstage git changes");const n=await u(y(`${m}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to unstage git changes")}ve(e)}async function jl(e,t,r){await Tn(e,t,r,"stage")}async function Hl(e,t,r){await Tn(e,t,r,"unstage")}async function zl(e,t,r){await Tn(e,t,r,"discard")}async function Tn(e,t,r,n){if(!t)throw new Error("path is required to apply a git hunk");if(typeof r!="string"||!r.trim())throw new Error("patch is required to apply a git hunk");const o=await u(y(`${m}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:r,action:n})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to apply git hunk")}ve(e)}async function $l(e){if(!e)return!1;const t=await u(y(`${m}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function Gl(e){const t=await u(y(`${m}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function Wl(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const r=await u(y(`${m}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to delete branch")}return r.json()}async function ql(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const r=await u(y(`${m}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to delete remote branch")}return r.json()}async function Kl(e,t){const r=t?.remote?.trim();if(!r)throw new Error("remote is required to remove a remote");const n=await u(y(`${m}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to remove remote")}return n.json()}async function Vl(e,t,r){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const n={files:t};r?.zenModel&&(n.zenModel=r.zenModel),r?.providerId&&(n.providerId=r.providerId),r?.modelId&&(n.modelId=r.modelId);const o=await u(y(`${m}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));console.error("[git-generation][browser] http error",{status:o.status,statusText:o.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 s=await o.json();if(!s?.message||typeof s.message!="object")throw new Error("Malformed commit generation response");const i=typeof s.message.subject=="string"&&s.message.subject.trim().length>0?s.message.subject.trim():"",a=Array.isArray(s.message.highlights)?s.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:i,highlights:a}}}async function Jl(e,t){const{base:r,head:n,context:o,zenModel:s,providerId:i,modelId:a}=t;if(!r||!n)throw new Error("base and head are required");const c={base:r,head:n};o?.trim()&&(c.context=o.trim()),s&&(c.zenModel=s),i&&(c.providerId=i),a&&(c.modelId=a);const l=await u(y(`${m}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const p=await l.json().catch(()=>({error:l.statusText}));throw new Error(p.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),f=typeof d?.title=="string"?d.title:"",w=typeof d?.body=="string"?d.body:"";if(!f&&!w)throw new Error("Malformed PR description response");return{title:f,body:w}}async function po(e){const t=await u(y(`${m}/worktrees`,e));if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to list worktrees")}return t.json()}async function mo(e,t){const r=await u(y(`${m}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to validate worktree")}return r.json()}async function Yl(e){const t=await u(y(`${m}/worktrees/bootstrap-status`,e));if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to get worktree bootstrap status")}return t.json()}async function Ql(e,t){const r=await u(y(`${m}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to preview worktree")}return r.json()}async function yo(e,t){const r=await u(y(`${m}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to create worktree")}return r.json()}async function go(e,t){const r=await u(y(`${m}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to delete worktree")}return r.json()}async function Xl(e,t,r={}){const n=await u(y(`${m}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:r.addAll??!1,files:r.files,stageFiles:r.stageFiles})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to create commit")}const o=await n.json();return ve(e),o}async function Zl(e,t={}){const r=await u(y(`${m}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to push")}const n=await r.json();return ve(e),n}async function ed(e,t={}){const r=await u(y(`${m}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to pull")}const n=await r.json();return ve(e),n}async function td(e,t={}){const r=await u(y(`${m}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to fetch")}const n=await r.json();return ve(e),n}async function rd(e){const t=await u(y(`${m}/stashes`,e));if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to list stashes")}return t.json()}async function nd(e,t){const r=await u(y(`${m}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to count stash files")}return r.json()}async function Ls(e,t={}){const r=await u(y(`${m}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to stash changes")}return r.json()}const En=async(e,t,r)=>{const n=await u(y(`${m}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||`Failed to ${t}`)}return n.json()},od=(e,t)=>En(e,"stash/apply",t),Us=(e,t)=>En(e,"stash/pop",t),sd=(e,t)=>En(e,"stash/drop",t);async function id(e,t){const r=await u(y(`${m}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to checkout branch")}return r.json()}async function ad(e,t,r){const n=await u(y(`${m}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create branch")}return n.json()}async function cd(e,t,r){const n=await u(y(`${m}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to rename branch")}return n.json()}async function ld(e,t={}){const r=await u(y(`${m}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(`Failed to get git log: ${n.error||r.statusText}`)}return r.json()}async function dd(e,t){const r=await u(y(`${m}/commit-files`,e,{hash:t}));if(!r.ok)throw new Error(`Failed to get commit files: ${r.statusText}`);return r.json()}async function bf(e,t,r,n){const o=await u(y(`${m}/commit-file-diff`,e,{hash:t,path:r,binary:n?"true":void 0}));if(!o.ok)throw new Error(`Failed to get commit file diff: ${o.statusText}`);return o.json()}async function ud(){const e=await u(y(`${m}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function fd(e){const t=await u(y(`${m}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to create git identity")}return t.json()}async function hd(e,t){const r=await u(y(`${m}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to update git identity")}return r.json()}async function pd(e){const t=await u(y(`${m}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to delete git identity")}}async function md(e){if(!e)return null;const t=await u(y(`${m}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const r=await t.json();return r?{userName:r.userName??null,userEmail:r.userEmail??null,sshCommand:r.sshCommand??null}:null}async function yd(e){if(!e)return!1;const t=await u(y(`${m}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function Sf(){const e=await u(y(`${m}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function gd(e,t){const r=await u(y(`${m}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to set git identity")}return r.json()}async function Tf(){const e=await u(y(`${m}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function Ef(e,t){if(!e)return null;const r=await u(y(`${m}/remote-url`,e,{remote:t}));return r.ok?(await r.json()).url??null:null}async function wd(e){const t=await u(y(`${m}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function bd(e,t){const r=await u(y(`${m}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to rebase")}return r.json()}async function Sd(e){const t=await u(y(`${m}/rebase/abort`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to abort rebase")}return t.json()}async function Td(e,t){const r=await u(y(`${m}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to merge")}return r.json()}async function Ed(e,t){const r=await u(y(`${m}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to checkout commit")}return r.json()}async function kd(e,t){const r=await u(y(`${m}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to cherry-pick")}return r.json()}async function vd(e,t){const r=await u(y(`${m}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to revert commit")}return r.json()}async function Ad(e,t,r,n){const o=await u(y(`${m}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:r,force:n})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to reset")}return o.json()}async function Pd(e){const t=await u(y(`${m}/merge/abort`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to abort merge")}return t.json()}async function Dd(e){const t=await u(y(`${m}/rebase/continue`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to continue rebase")}return t.json()}async function Md(e){const t=await u(y(`${m}/merge/continue`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to continue merge")}return t.json()}async function Cd(e,t){return await Ls(e,{message:t?.message}),{success:!0}}async function Rd(e){return await Us(e,{ref:"stash@{0}"}),{success:!0}}async function Od(e){const t=await u(y(`${m}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function Id(e,t){const r=await u(`${m}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!r.ok)throw new Error(`Failed to validate worktree directory: ${r.statusText}`);return r.json()}async function _d(e){const t=await u(`${m}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const Fd=()=>({checkIsGitRepository:_l,getGitStatus:Fl,getGitDiff:xl,getGitFileDiff:Ll,revertGitFile:Ul,stageGitFile:Nl,stageGitFiles:Fs,unstageGitFile:Bl,unstageGitFiles:xs,stageGitHunk:jl,unstageGitHunk:Hl,revertGitHunk:zl,isLinkedWorktree:$l,getGitBranches:Gl,deleteGitBranch:Wl,deleteRemoteBranch:ql,removeRemote:Kl,generateCommitMessage:Vl,generatePullRequestDescription:Jl,listGitWorktrees:po,validateGitWorktree:mo,createGitWorktree:yo,deleteGitWorktree:go,validateWorktreeDirectory:Id,canonicalizeWorktreeState:_d,createGitCommit(e,t,r){return Xl(e,t,r)},gitPush:Zl,gitPull:ed,gitFetch:td,listGitStashes:rd,countGitStashFiles:nd,stashGitChanges:Ls,applyGitStash:od,popGitStash:Us,dropGitStash:sd,checkoutBranch:id,createBranch:ad,renameBranch:cd,getGitLog(e,t){return ld(e,t)},getCommitFiles:dd,getCurrentGitIdentity:md,hasLocalIdentity:yd,setGitIdentity:gd,getGitIdentities:ud,createGitIdentity:fd,updateGitIdentity:hd,deleteGitIdentity:pd,getRemotes:wd,rebase:bd,abortRebase:Sd,continueRebase:Dd,merge:Td,abortMerge:Pd,continueMerge:Md,checkoutCommit:Ed,cherryPick:kd,revertCommit:vd,resetToCommit:Ad,stash:Cd,stashPop:Rd,getConflictDetails:Od,worktree:{list:po,validate:mo,bootstrapStatus:Yl,preview:Ql,create:yo,remove:go}}),W=e=>e.replace(/\\/g,"/"),xd=(e,t)=>{const r=W(t?.directory||t?.path||e),n=Array.isArray(t?.entries)?t.entries:[];return{directory:r,entries:n.filter(o=>!!(o&&typeof o.name=="string"&&typeof o.path=="string")).map(o=>({name:o.name,path:W(o.path),isDirectory:!!o.isDirectory}))}},le=(e,t)=>{const r=t||e?.();return r?{"x-opencode-directory":r}:void 0},Ld=({getDirectory:e})=>({async listDirectory(t,r){const n=W(t),o=new URLSearchParams;n&&o.set("path",n),r?.respectGitignore&&o.set("respectGitignore","true");const s=await u("/api/fs/list",{query:o,headers:le(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to list directory")}const i=await s.json();return xd(n,i)},async search(t){const r=new URLSearchParams,n=W(t.directory);n&&r.set("directory",n),r.set("query",t.query),r.set("dirs","false"),r.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&r.set("limit",String(t.maxResults));const o=await u("/api/find/file",{query:r,headers:le(e)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to search files")}const s=await o.json();return(Array.isArray(s)?s:[]).map(a=>({path:W(`${n}/${a}`),preview:[W(a)]}))},async createDirectory(t){const r=W(t),n=await u("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...le(e)},body:JSON.stringify({path:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to create directory")}const o=await n.json();return{success:!!o?.success,path:typeof o?.path=="string"?W(o.path):r}},async statFile(t,r){const n=W(t),o=new URLSearchParams({path:n});r?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&o.set("outsideFileGrant",r.outsideFileGrant);const s=await u("/api/fs/stat",{query:o,headers:le(e,r?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to stat file")}const i=await s.json().catch(()=>({}));return{path:typeof i.path=="string"?W(i.path):n,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,r){const n=W(t),o=new URLSearchParams({path:n});r?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&o.set("outsideFileGrant",r.outsideFileGrant),r?.optional&&o.set("optional","true");const s=await u("/api/fs/read",{query:o,cache:r?.optional?"no-store":"default",headers:le(e,r?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await s.text(),path:n}},async writeFile(t,r){const n=W(t),o=await u("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...le(e)},body:JSON.stringify({path:n,content:r})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to write file")}const s=await o.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?W(s.path):n}},async delete(t){const r=W(t),n=await u("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...le(e)},body:JSON.stringify({path:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to delete file")}return{success:!!(await n.json().catch(()=>({}))).success}},async rename(t,r){const n=await u("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...le(e)},body:JSON.stringify({oldPath:t,newPath:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to rename file")}const o=await n.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?W(o.path):r}},async revealPath(t){const r=await u("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...le(e)},body:JSON.stringify({path:W(t)})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to reveal path")}return{success:!!(await r.json().catch(()=>({}))).success}},async downloadFile(t){const r=W(t),n=await u("/api/fs/raw",{query:{path:r,download:!0},headers:le(e)});if(!n.ok)throw new Error(`Download failed (${n.status})`);const o=await n.blob(),s=URL.createObjectURL(o),i=document.createElement("a");i.href=s,i.download=r.split("/").pop()||"file",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>URL.revokeObjectURL(s),100)}}),wo="/api/config/settings",Ud="/api/config/reload",bo=e=>!e||typeof e!="object"?{}:e,Nd=()=>({async load(){const e=await u(wo,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:bo(await e.json().catch(()=>({}))),source:"web"}},async save(e){const t=await u(wo,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to save settings")}return bo(await t.json().catch(()=>({})))},async restartOpenCode(){const e=await u(Ud,{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}}}),Bd=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),jd=1500,en=5e3,Hd="openchamber-notification-claim:",lt=new Map,zd=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),$d=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).join("|")},Gd=e=>{for(const[t,r]of lt)e-r>en&<.delete(t)},Wd=e=>{const t=$d(e);if(!t)return!0;const r=Date.now();Gd(r);const n=lt.get(t)??0;if(r-n<en)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${Hd}${t}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&r-s<en)return lt.set(t,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(r))}}catch{}return lt.set(t,r),!0},Ns=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(r=>{setTimeout(()=>r(null),jd)})])??e}catch{return e}},qd=async e=>{const t=await Ns();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(r){return console.warn("Failed to send notification via service worker",r),!1}},Kd=async()=>{const e=await Ns();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},Vd=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(!zd()&&await Kd()||!Wd(e))return!0;try{return await qd(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},Jd=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,requireHidden:e?.requireHidden}}),!0}catch(r){return console.warn("Failed to send native notification (desktop)",r),!1}},Yd=()=>({async notifyAgentCompletion(e){return await Jd(e)||await Vd(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),Qd=()=>({async getAvailableTools(){const e=await u("/api/experimental/tool/ids");if(!e.ok)throw new Error(`Tools API returned ${e.status} ${e.statusText}`);const t=await e.json();if(!Array.isArray(t))throw new Error("Tools API returned invalid data format");return t.filter(r=>typeof r=="string"&&r!=="invalid").sort()}}),ze=async(e,t)=>{try{const r=await u(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return r.ok?await r.json():null}catch{return null}},Xd=()=>({async getVapidPublicKey(){return ze("/api/push/vapid-public-key")},async subscribe(e){return ze("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return ze("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return ze("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return ze("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return ze("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),j=async e=>await e.json().catch(()=>null),Zd=({urls:e})=>({async authStatus(){const t=await u("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await j(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to load GitHub status");return r},async authStart(){const t=await u("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),r=await j(t);if(!t.ok||!r||!("deviceCode"in r))throw new Error(r?.error||t.statusText||"Failed to start GitHub auth");return r},async authComplete(t){const r=await u("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to complete GitHub auth");return n},async authDisconnect(){const t=await u("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),r=await j(t);if(!t.ok)throw new Error(r?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!r?.removed}},async authActivate(t){const r=await u("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to activate GitHub account");return n},async authSetGhCliDisabled(t){const r=await u("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to update gh CLI setting");return{disabled:!!n.disabled}},async me(){const t=await u("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),r=await j(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to fetch GitHub user");return r},async prStatus(t,r,n,o){const s=new URLSearchParams({directory:t,branch:r,...n?{remote:n}:{},...o?.force?{force:"true"}:{}}),i=await u(`/api/github/pr/status?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await j(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prCreate(t){const r=await u("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to create PR");return n},async prUpdate(t){const r=await u("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to update PR");return n},async prMerge(t){const r=await u("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to merge PR");return n},async prReady(t){const r=await u("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to mark PR ready");return n},async repoUpstream(t){const r=await u(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to detect upstream repo");return n},async repoBranches(t,r){const n=await u(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(r)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await j(n);if(!n.ok||!o)throw new Error(o?.error||n.statusText||"Failed to fetch repo branches");return o.branches??[]},async prsList(t,r){const n=r?.page??1,o=new URLSearchParams({directory:t,page:String(n)});r?.query&&o.set("query",r.query);const s=await u(`/api/github/pulls/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull requests");return i},async prContext(t,r,n){const o=new URLSearchParams({directory:t,number:String(r)});n?.includeDiff&&o.set("diff","1"),n?.includeCheckDetails&&o.set("checkDetails","1"),n?.sourceRepo?.owner&&n.sourceRepo.repo&&(o.set("owner",n.sourceRepo.owner),o.set("repo",n.sourceRepo.repo));const s=await u(e.api("/api/github/pulls/context",o),{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull request context");return i},async issuesList(t,r){const n=r?.page??1,o=new URLSearchParams({directory:t,page:String(n)});r?.query&&o.set("query",r.query);const s=await u(`/api/github/issues/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issues");return i},async issueGet(t,r,n){const o=new URLSearchParams({directory:t,number:String(r)});n?.sourceRepo?.owner&&n.sourceRepo.repo&&(o.set("owner",n.sourceRepo.owner),o.set("repo",n.sourceRepo.repo));const s=await u(e.api("/api/github/issues/get",o),{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue");return i},async issueComments(t,r,n){const o=new URLSearchParams({directory:t,number:String(r)});n?.sourceRepo?.owner&&n.sourceRepo.repo&&(o.set("owner",n.sourceRepo.owner),o.set("repo",n.sourceRepo.repo));const s=await u(e.api("/api/github/issues/comments",o),{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue comments");return i}}),Te=async e=>await e.json().catch(()=>null),eu=()=>({async listClients(){const e=await u("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Te(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 u("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),r=await Te(t);if(!t.ok||!r?.client||typeof r.token!="string")throw new Error(r?.error||t.statusText||"Failed to create remote client token");return r},async createPairingSession(e={}){const t=await u("/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}:{}})}),r=await Te(t);if(!t.ok||typeof r?.pairing?.secret!="string"||!r?.server)throw new Error(r?.error||t.statusText||"Failed to create pairing session");return r},async listPendingPairings(){const e=await u("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Te(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 u("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Te(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 u(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),r=await Te(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to cancel pairing");return{cancelled:r.cancelled===!0}},async revokeClient(e){const t=await u(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),r=await Te(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to revoke remote client");return r},async purgeRevokedClients(){const e=await u("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Te(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),tu=()=>({api:(...e)=>X().api(...e),authenticatedAsset:(...e)=>X().authenticatedAsset(...e),auth:(...e)=>X().auth(...e),health:(...e)=>X().health(...e),rawFile:(...e)=>X().rawFile(...e),sse:(...e)=>X().sse(...e),websocket:(...e)=>X().websocket(...e)}),ru=(e={})=>{const t=e.urls??sn();ra(t);const r=tu();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Cl(),git:Fd(),files:Ld({getDirectory:()=>Xr.getState().currentDirectory}),settings:Nd(),permissions:Bd(),notifications:Yd(),github:Zd({urls:r}),push:Xd(),clientAuth:eu(),tools:Qd()}},So=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}};let Bs=Promise.resolve();const kf=()=>Bs,vf=()=>{const e=typeof window.__OPENCHAMBER_API_BASE_URL__=="string"?window.__OPENCHAMBER_API_BASE_URL__.trim():"",t=typeof window.__OPENCHAMBER_CLIENT_TOKEN__=="string"?window.__OPENCHAMBER_CLIENT_TOKEN__.trim():"",r=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__.trim():"",n=Qo({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});pa({apiBaseUrl:e,runtimeKey:So(e,r)?"local":null}),jo(t||null),Ho(window.__OPENCHAMBER_RUNTIME_HEADERS__||null),nn(e||void 0).catch(()=>{}),r&&!So(e,r)&&Object.keys(ir()).length>0&&Ko(r).catch(()=>{}),ha();const o=window.__OPENCHAMBER_RELAY_HOST_ID__;return Bs=Promise.race([_a(typeof o=="string"&&o?o:void 0).catch(()=>{}),new Promise(s=>{window.setTimeout(s,1e4)})]),ru({urls:n})};export{cf as $,Al as A,El as B,Ze as C,cr as D,Ra as E,Lu as F,Ca as G,xu as H,H as I,zo as J,gu as K,Dl as L,ot as M,Su as N,cs as O,Ju as P,Yu as Q,wc as R,Zc as S,Ou as T,su as U,iu as V,wu as W,Cu as X,Mu as Y,lf as Z,df as _,Tt as a,yo as a$,se as a0,$u as a1,ba as a2,wa as a3,au as a4,af as a5,Vu as a6,cu as a7,lu as a8,Ea as a9,yu as aA,bu as aB,Eu as aC,ku as aD,pf as aE,ec as aF,el as aG,Gu as aH,Yl as aI,Ps as aJ,os as aK,sr as aL,fl as aM,Pd as aN,Sd as aO,od as aP,_d as aQ,_l as aR,id as aS,Ed as aT,kd as aU,Md as aV,Dd as aW,nd as aX,ad as aY,Xl as aZ,fd as a_,Pu as aa,vu as ab,Au as ac,fn as ad,Uu as ae,Fu as af,Bu as ag,Je as ah,_u as ai,Ia as aj,ju as ak,Du as al,Mc as am,vc as an,Ku as ao,ic as ap,dc as aq,ac as ar,uc as as,Pc as at,lr as au,uu as av,hu as aw,mu as ax,fu as ay,pu as az,X as b,nf as b$,Wl as b0,pd as b1,go as b2,ql as b3,Tf as b4,sd as b5,bf as b6,dd as b7,Od as b8,md as b9,gf as bA,vd as bB,Ul as bC,zl as bD,gd as bE,Nl as bF,Fs as bG,jl as bH,Cd as bI,Ls as bJ,Rd as bK,Bl as bL,xs as bM,Hl as bN,hd as bO,Id as bP,Y as bQ,qu as bR,sc as bS,zu as bT,Hu as bU,Nu as bV,ir as bW,Rt as bX,Dr as bY,Qu as bZ,Zu as b_,Gl as ba,wf as bb,xl as bc,Ll as bd,ud as be,ld as bf,Fl as bg,Sf as bh,Ef as bi,wd as bj,mo as bk,po as bl,td as bm,ed as bn,Zl as bo,yd as bp,$l as bq,rd as br,Td as bs,Us as bt,Ql as bu,bd as bv,Kl as bw,cd as bx,Ad as by,yf as bz,vf as c,ef as c0,Xu as c1,tf as c2,As as c3,rf as c4,uf as c5,ff as c6,Tu as c7,hf as c8,cc as c9,lc as ca,mf as cb,un as d,Xr as e,St as f,kf as g,u as h,ou as i,Fo as j,ar as k,du as l,ma as m,sf as n,ke as o,of as p,ge as q,nn as r,Nn as s,ns as t,de as u,Q as v,Iu as w,Ru as x,ka as y,Wu as z};
|