@openchamber/web 1.14.1 → 1.15.0
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/bin/cli.test.js +8 -0
- package/bin/lib/DOCUMENTATION.md +3 -0
- package/bin/lib/cli-args.js +10 -0
- package/bin/lib/commands-connect-url.js +169 -22
- package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-HR2xZxJ8.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
- package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-DlFUaNQK.js} +1 -1
- package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
- package/dist/assets/{SessionSwitcherDropdown-4FWg9xMC.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
- package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
- package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-D_9BAjtv.js} +3 -3
- package/dist/assets/es-cjUissX4.js +15 -0
- package/dist/assets/fr-DqbXnTdK.js +13 -0
- package/dist/assets/index-Dg0nmvQU.css +1 -0
- package/dist/assets/index-ltrmNGAf.js +2 -0
- package/dist/assets/ja-Cetyq6Eg.js +15 -0
- package/dist/assets/ko-DtunWisP.js +15 -0
- package/dist/assets/main-BC0m8s1v.js +236 -0
- package/dist/assets/main-DzNa8r0N.js +2 -0
- package/dist/assets/miniChat-BRYDE-Se.js +2 -0
- package/dist/assets/mobile-C3QJVA97.js +2 -0
- package/dist/assets/pl-DctGLgve.js +15 -0
- package/dist/assets/pt-BR-CXPhf78S.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
- package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
- package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
- package/dist/assets/uk-Bdrc-kqF.js +15 -0
- package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DzBg8hrC.js} +123 -119
- package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
- package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
- package/dist/assets/zh-TW-CoqiQING.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -2
- package/server/index.js +130 -1
- package/server/lib/client-auth/pairing.js +308 -0
- package/server/lib/client-auth/pairing.test.js +142 -0
- package/server/lib/client-auth/remote-clients.js +65 -3
- package/server/lib/notifications/apns-runtime.js +9 -16
- package/server/lib/opencode/bootstrap-runtime.js +10 -0
- package/server/lib/opencode/core-routes.js +246 -6
- package/server/lib/opencode/core-routes.test.js +248 -9
- package/server/lib/opencode/network-runtime.js +14 -1
- package/server/lib/opencode/network-runtime.test.js +29 -9
- package/server/lib/opencode/proxy.js +47 -6
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-helpers.test.js +11 -0
- package/server/lib/opencode/settings-normalization-runtime.js +2 -0
- package/server/lib/package-manager.js +18 -5
- package/server/lib/relay/DOCUMENTATION.md +78 -0
- package/server/lib/relay/cross-compat.test.js +135 -0
- package/server/lib/relay/e2ee.js +341 -0
- package/server/lib/relay/e2ee.test.js +124 -0
- package/server/lib/relay/host-client.js +389 -0
- package/server/lib/relay/host-client.test.js +280 -0
- package/server/lib/relay/identity.js +73 -0
- package/server/lib/relay/identity.test.js +78 -0
- package/server/lib/relay/service.js +247 -0
- package/server/lib/relay/signing-key.js +50 -0
- package/server/lib/relay/tunnel-codec.js +373 -0
- package/server/lib/relay/tunnel-codec.test.js +58 -0
- package/server/lib/relay/tunnel-host.js +462 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
- package/server/lib/ui-auth/ui-auth.js +10 -0
- package/server/opencode-proxy.test.js +38 -0
- package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
- package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
- package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
- package/dist/assets/es-bWcuDy_2.js +0 -15
- package/dist/assets/fr-DzRs3OzV.js +0 -13
- package/dist/assets/index-KnWk9fmM.css +0 -1
- package/dist/assets/index-ZJTzZ0_U.js +0 -2
- package/dist/assets/ja-BqUX_UD3.js +0 -15
- package/dist/assets/ko-BQo10SNx.js +0 -15
- package/dist/assets/main-BDoqLlQB.js +0 -236
- package/dist/assets/main-DUGyTrDt.js +0 -2
- package/dist/assets/miniChat-DNDiX8GA.js +0 -2
- package/dist/assets/mobile-DnghtOCb.js +0 -2
- package/dist/assets/pl-Bgx_ATJT.js +0 -15
- package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
- package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
- package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
- package/dist/assets/uk-C9k8SP8q.js +0 -15
- package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
- package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{_ as tn,c as rn,a as Je,d as Qe,p as Hr,b as zr,R as je}from"./vendor-.bun-C6iL44L9.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))o(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&o(s)}).observe(document,{childList:!0,subtree:!0});function r(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(n){if(n.ep)return;n.ep=!0;const i=r(n);fetch(n.href,i)}})();let $r=()=>null,Gr="",Le={},J="",pe=0,W=null,re="",he=0,Q=null,Ie=0;const Ht=1e4,on=t=>t.toLowerCase()==="authorization",Wr=t=>{const e={};for(const[r,o]of Object.entries(t||{})){const n=r.trim(),i=o.trim();n&&i&&!on(n)&&(e[n]=i)}return e},nn=(t,e)=>{const r=Object.entries(t);return r.length!==Object.keys(e).length?!1:r.every(([o,n])=>e[o]===n)},Ye=t=>typeof t!="string"?"":t.trim(),sn=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_CLIENT_TOKEN__;return Ye(t)},an=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},qr=(t,e)=>{const r=typeof t=="string"&&t.trim()?t.trim():an();if(!r)return e;try{return new URL(e,`${r.replace(/\/+$/,"")}/`).toString()}catch{return e}},Xe=()=>{J="",pe=0,re="",he=0},Kr=()=>{Ie+=1,W=null,Xe(),$t()},Vr=t=>{const e=Ye(t);Gr=e,Kr(),$r=()=>e?{type:"bearer",token:e}:null},Jr=t=>{const e=Wr(t);nn(Le,e)||(Le=e,Kr())},Ze=()=>{if(Object.keys(Le).length>0)return Le;if(typeof window>"u")return{};const t=window.__OPENCHAMBER_RUNTIME_HEADERS__;return t&&typeof t=="object"?Wr(t):{}},Qr=()=>Gr||sn(),cn=(t,e)=>{const r=Ye(t);if(!r||typeof e!="number"||!Number.isFinite(e)){Xe();return}const o=J;J=r,pe=e,o&&o!==r&&pn()},Yr=()=>!J||pe<=Date.now()+Ht?(Xe(),""):J,Xr=()=>!re||he<=Date.now()+Ht?(re="",he=0,""):re,ln=()=>{const t=Yr();return!t&&(Qr()||typeof window<"u")&&zt().catch(()=>{}),t},dn=t=>{const e=Xr();return!e&&t&&typeof window<"u"&&to(t).catch(()=>{}),e},Zr=async()=>{const t=await $r(),e=t?.type==="bearer"?Ye(t.token):Qr();return e?{type:"bearer",token:e}:null},eo=t=>{if(W)return W;const e=Ie,o=(async()=>{const n=await Zr(),i=new Headers;for(const[d,f]of Object.entries(Ze()))i.set(d,f);n?.type==="bearer"&&i.set("Authorization",`Bearer ${n.token}`);const s=await fetch(qr(t,"/auth/url-token"),{method:"POST",headers:i,credentials:"include"});if(!s.ok)throw e===Ie&&Xe(),new Error(`Failed to mint runtime URL auth token (${s.status})`);const a=await s.json().catch(()=>null),c=typeof a?.token=="string"?a.token.trim():"",l=typeof a?.expiresAt=="number"?a.expiresAt:0;if(e!==Ie)throw new Error("Runtime URL auth token response is stale");if(cn(c,l),!J)throw new Error("Runtime URL auth token response was invalid");return J})().finally(()=>{W===o&&(W=null)});return W=o,W},un=t=>{if(Q)return Q;const r=(async()=>{const o=await fetch(qr(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw re="",he=0,new Error(`Failed to mint local runtime URL auth token (${o.status})`);const n=await o.json().catch(()=>null),i=typeof n?.token=="string"?n.token.trim():"",s=typeof n?.expiresAt=="number"?n.expiresAt:0;if(!i||!Number.isFinite(s))throw new Error("Local runtime URL auth token response was invalid");return re=i,he=s,i})().finally(()=>{Q===r&&(Q=null)});return Q=r,Q},zt=async t=>{const e=Yr();return e||eo(t)},to=async t=>{const e=Xr();return e||un(t)};let ee=0,de=null,ro=null;const Et=new Set,fn=5e3,pn=()=>{for(const t of Et)try{t()}catch{}},oo=()=>{de!==null&&(clearTimeout(de),de=null)},$t=()=>{if(oo(),ee<=0||typeof window>"u")return;const t=pe-Ht-fn,e=pe>0?Math.max(0,t-Date.now()):0;de=setTimeout(()=>{de=null,!(ee<=0)&&eo(ro).catch(()=>{}).finally(()=>{$t()})},e)},fc=t=>{typeof t=="string"&&t.trim()&&(ro=t.trim()),ee+=1,$t();let e=!1;return()=>{e||(e=!0,ee=Math.max(0,ee-1),ee===0&&oo())}},pc=t=>(Et.add(t),()=>{Et.delete(t)}),hn=async t=>{const e=new Headers(t);for(const[o,n]of Object.entries(Ze()))e.has(o)||e.set(o,n);if(e.has("Authorization"))return e;const r=await Zr();return r?.type==="bearer"&&e.set("Authorization",`Bearer ${r.token}`),e},Ne=/^[a-z][a-z\d+.-]*:\/\//i,mn=t=>{const e=t.trim();return e?e.startsWith("/")?e:`/${e}`:"/"},Ue=t=>typeof t!="string"?"":t.trim().replace(/\/+$/,""),yn=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return Ue(t)},gn=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Ue(t)},wn=()=>Object.keys(Ze()).length>0,bn=t=>{const e=t.currentHref?.();return e||(typeof window<"u"?window.location.href||window.location.origin:"")},kt=(t,e)=>{if(!e)return;const r=e instanceof URLSearchParams?Array.from(e.entries()):Object.entries(e);for(const[o,n]of r)n!=null&&t.searchParams.set(o,String(n))},Sn=(t,e)=>{if(!e)return t;const r=new URLSearchParams;kt({searchParams:r},e);const o=r.toString();return o?t.includes("?")?`${t}&${o}`:`${t}?${o}`:t},rr=(t,e,r)=>{if(Ne.test(e)){const i=new URL(e);return kt(i,r),i.toString()}const o=mn(e);if(!t)return Sn(o,r);const n=new URL(o,`${t}/`);return kt(n,r),n.toString()},st=t=>{const e=ln();if(!e)return t;const r=Ne.test(t)?new URL(t):new URL(t,"http://openchamber.local");return r.searchParams.set("oc_url_token",e),Ne.test(t)?r.toString():`${r.pathname}${r.search}${r.hash}`},no=(t,e)=>{const r=Ne.test(t)?new URL(t):new URL(t,bn(e));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},or=(t,e,r)=>{if(!wn())return null;const o=gn();if(!o)return null;try{const n=new URL(`/api/openchamber/realtime-proxy/${t==="sse"?"sse":"ws"}`,`${o}/`);n.searchParams.set("url",e);const i=dn(o);return i&&n.searchParams.set("oc_url_token",i),t==="ws"?(n.protocol=n.protocol==="https:"?"wss:":"ws:",no(n.toString(),r)):n.toString()}catch{return null}},Gt=(t={})=>{const e=Ue(t.apiBaseUrl),r=Ue(t.realtimeBaseUrl),o=()=>e||yn(),n=()=>r||o(),i=(a,c)=>rr(o(),a,c),s=(a,c)=>rr(n(),a,c);return{api:i,authenticatedAsset:(a,c)=>st(i(a,c)),auth:i,health:a=>i("/health",a),rawFile:(a,c)=>i("/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=st(s(a,c));return or("sse",l,t)||l},websocket:(a,c)=>{const l=no(st(s(a,c)),t);return or("ws",l,t)||l}}};let Be=Gt();const P=()=>Be,Tn=t=>{Be=t},io=t=>(Be=Gt(t),Be),me=t=>t.startsWith("/api/")||t==="/api"||t.startsWith("/auth/")||t==="/auth"||t==="/health",vn=()=>typeof window>"u"?"":window.location.origin||"",so=t=>{if(typeof window>"u")return!1;const e=vn();if(e&&t.origin===e)return!0;try{const r=new URL(window.location.href||e);return t.protocol===r.protocol&&t.host===r.host}catch{return!1}},ao=t=>/^[a-z][a-z\d+.-]*:\/\//i.test(t),En=(t,e)=>{if(!e)return;const r=e instanceof URLSearchParams?Array.from(e.entries()):Object.entries(e);for(const[o,n]of r)n!=null&&t.searchParams.set(o,String(n))},Fe=t=>{try{const e=P().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;const r=new URL(e);return t.origin!==r.origin?!1:me(t.pathname)}catch{return!1}},at=t=>{if(me(t))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;try{const e=new URL(t);return so(e)&&me(e.pathname)}catch{return!1}},kn=(t,e)=>{try{const r=new URL(t);if(!so(r))return t;const o=V(`${r.pathname}${r.search}`,e);return!ao(o)&&(r.protocol==="http:"||r.protocol==="https:")?(En(r,e),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return t}},V=(t,e)=>t==="/health"?P().health(e):t.startsWith("/auth/")||t==="/auth"?P().auth(t,e):me(t)?P().api(t,e):/^[a-z][a-z\d+.-]*:\/\//i.test(t)?kn(t,e):t,Dn=t=>{const e=t instanceof Request?t.url:t.toString();if(!ao(e))return me(e);try{return Fe(new URL(e))}catch{return!1}},An=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},Pn=(t,e)=>!An(e),nr=t=>{if(!t)return;const e=t instanceof Headers?Array.from(t.entries()):Array.isArray(t)?t:Object.entries(t);if(e.length===0)return;const r=[];let o=!1,n=!1;for(const[i,s]of e)Pn(i,s)?(r.push([i,encodeURIComponent(s)]),o=!0,i.toLowerCase()==="x-opencode-directory"&&(n=!0)):r.push([i,s]);return n&&r.push(["x-opencode-directory-encoding","uri"]),o?r:void 0},q=async(t,e,r=!0)=>{const o=new Headers(nr(t)??t);return e&&new Headers(nr(e)??e).forEach((n,i)=>o.set(i,n)),r?hn(o):o},Mn=(t,e)=>{if(typeof t=="string")return V(t,e);if(t instanceof URL)return V(t.toString(),e);const r=V(t.url,e);return r===t.url?t:new Request(r,t)},Cn=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,ke=new Map,On=(t,e,r)=>r||t!=="GET"||e.includes("/event")||!Cn.test(e)?null:`GET ${e}`,u=async(t,e={})=>{const{query:r,...o}=e,n=Mn(t,r),i=n instanceof Request?n.headers:void 0,s=await q(i,o.headers,Dn(n)),a=()=>n instanceof Request?fetch(new Request(n,{...o,headers:s})):fetch(n,{...o,headers:s}),c=n instanceof Request?n.url:n instanceof URL?n.toString():String(n),l=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase(),d=o.signal!=null||n instanceof Request,f=On(l,c,d);if(!f)return a();const g=ke.get(f);if(g)return g.then(p=>p.clone());const y=a();return ke.set(f,y),y.then(()=>ke.delete(f),()=>ke.delete(f)),y.then(p=>p.clone())};let ir=!1;const Rn=()=>{if(ir||typeof window>"u")return;ir=!0;const t=window.fetch.bind(window);window.fetch=async(e,r)=>{if(typeof e=="string"){if(!at(e)){try{const n=new URL(e);if(Fe(n)){const i=await q(void 0,r?.headers);return t(e,{...r,headers:i})}}catch{}return t(e,r)}const o=await q(void 0,r?.headers);return t(V(e),{...r,headers:o})}if(e instanceof URL){const o=e.toString();if(!at(o)){if(Fe(e)){const i=await q(void 0,r?.headers);return t(e,{...r,headers:i})}return t(e,r)}const n=await q(void 0,r?.headers);return t(V(o),{...r,headers:n})}if(e instanceof Request){if(!at(e.url)){try{const s=new URL(e.url);if(Fe(s)){const a=await q(e.headers,r?.headers);return t(new Request(e,{...r,headers:a}))}}catch{}return t(e,r)}const o=await q(e.headers,r?.headers),n=V(e.url),i=n===e.url?e:new Request(n,e);return t(new Request(i,{...r,headers:o}))}return t(e,r)}},Dt="openchamber:runtime-endpoint-changed";let He="",ye="";const ct=(t,e,r)=>{try{t[e]=r}catch{}},Wt=t=>{try{const e=new URL(t);return e.hash="",e.search="",e.pathname=e.pathname.replace(/\/+$/,"")||"/",`url:${e.toString().replace(/\/+$/,"")}`}catch{return`url:${t.trim().replace(/\/+$/,"")||"default"}`}},co=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},lo=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof t=="string"?t.trim():""},uo=(t,e)=>{if(!t||!e)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}},qt=()=>He||co(),et=()=>{if(ye)return ye;const t=qt();return uo(t,lo())?"local":Wt(t)},In=(t={})=>{if(He||ye)return;const e=t.apiBaseUrl?.trim()||co();e&&(He=e,ye=t.runtimeKey?.trim()||(uo(e,lo())?"local":Wt(e)))},hc=t=>{const e=t.apiBaseUrl.trim(),r=qt(),o=et(),n=t.runtimeKey?.trim()||Wt(e);if(He=e,ye=n,typeof window<"u"){const i=window;ct(i,"__OPENCHAMBER_API_BASE_URL__",e),ct(i,"__OPENCHAMBER_CLIENT_TOKEN__",t.clientToken||void 0),ct(i,"__OPENCHAMBER_RUNTIME_HEADERS__",t.requestHeaders||void 0)}io({apiBaseUrl:e,realtimeBaseUrl:e}),Jr(t.requestHeaders||null),Vr(t.clientToken||null),zt(e).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Dt,{detail:{apiBaseUrl:e,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o}}))},Fn=t=>{if(typeof window>"u")return()=>{};const e=r=>{t(r.detail)};return window.addEventListener(Dt,e),()=>window.removeEventListener(Dt,e)},_n=["local","remote",null],xn=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function fo(t){if(!t||typeof t!="object")return{valid:!1};const e=t,r=e.target,o=e.status;if(r!==null&&(typeof r!="string"||!_n.includes(r)))return{valid:!1};if(typeof o!="string"||!xn.includes(o))return{valid:!1};if(r==="remote"||r==="local"){if(o==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok"}};if(o==="ok"&&r==="remote")return typeof e.hostId!="string"||typeof e.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:e.hostId,url:e.url}};if(o==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable"}}:typeof e.hostId!="string"||typeof e.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:e.hostId,url:e.url}};if(o==="incompatible"||o==="wrong-service")return r!=="remote"?{valid:!1}:typeof e.hostId!="string"||typeof e.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:o,hostId:e.hostId,url:e.url}};if(o==="missing")return r!=="remote"?{valid:!1}:typeof e.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:e.hostId}}}if(r===null){if(o==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured"}};if(o==="missing")return{valid:!1}}return{valid:!1}}function mc(t){if(!t.isDesktopShell)return null;const e=t.bootOutcome;if(!e)return null;if(e.status==="ok"){if(e.target==="local")return{screen:"main"};if(e.target==="remote")return{screen:"main",hostId:e.hostId,url:e.url}}if(e.target===null&&e.status==="not-configured")return{screen:"chooser"};if(e.target==="local"&&e.status==="unreachable")return{screen:"recovery",variant:"local-unavailable"};if(e.target==="remote"){if(e.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:e.hostId,url:e.url};if(e.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:e.hostId,url:e.url};if(e.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:e.hostId,url:e.url};if(e.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:e.hostId}}return null}function yc(t){return t.isDesktopShell?t.bootOutcomeKnown?t.bootViewIsMain===!1?!0:t.isInitialized:!1:t.isInitialized}function gc(t){return t.isDesktopShell&&!t.isDesktopLocalOriginActive}function jn(){if(Ln()!=="valid")return null;const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,r=fo(e);return r.valid?r.outcome:null}function Ln(){if(typeof window>"u")return"not-injected";const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return t==null?"not-injected":fo(t).valid?"valid":"malformed"}let At=null;const wc=t=>{At=t},tt=()=>At||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Nn=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,ie=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,po=()=>Nn()?.runtime==="electron",M=()=>typeof ie()?.invoke=="function",rt=()=>po()&&M(),C=async(t,e)=>{const r=ie();return typeof r?.invoke!="function"?null:r.invoke(t,e??{})},bc=async()=>{if(!rt()||!R())return null;try{const t=await C("desktop_get_launch_at_login");return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to get launch at login status",t),null}},Sc=async t=>{if(!rt()||!R())return null;try{const e=await C("desktop_set_launch_at_login",{enabled:t});return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to set launch at login status",e),null}},Tc=async()=>{if(!rt()||!R())return null;try{const t=await C("desktop_get_keep_awake");return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to get keep awake status",t),null}},vc=async t=>{if(!rt()||!R())return null;try{const e=await C("desktop_set_keep_awake",{enabled:t});return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to set keep awake status",e),null}},sr=t=>{const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{try{return new URL(e.endsWith("/")?e:`${e}/`).origin}catch{return null}}},lt=t=>{const e=t.trim();if(!e)return null;try{return new URL(e)}catch{try{return new URL(e.endsWith("/")?e:`${e}/`)}catch{return null}}},Un=t=>t.replace(/^\[|\]$/g,"").toLowerCase(),se=t=>{const e=Un(t);return e==="localhost"||e==="127.0.0.1"||e==="::1"},R=()=>{if(typeof window>"u"||!ho())return!1;if(et()==="local")return!0;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=lt(t),r=lt(qt());if(!r&&e&&jn()?.target==="local")return!0;if(e&&r){if(e.origin===r.origin)return!0;const s=e.port||(e.protocol==="https:"?"443":"80"),a=r.port||(r.protocol==="https:"?"443":"80");return e.protocol===r.protocol&&s===a&&se(e.hostname)&&se(r.hostname)}const o=lt(window.location.origin);if(e&&o){if(e.origin===o.origin)return!0;const s=e.port||(e.protocol==="https:"?"443":"80"),a=o.port||(o.protocol==="https:"?"443":"80");return e.protocol===o.protocol&&s===a&&se(e.hostname)&&se(o.hostname)}const n=sr(t),i=sr(window.location.origin)||window.location.origin;return n&&i&&n===i?!0:!!(o&&se(o.hostname))},ho=()=>typeof window>"u"?!1:po(),Ec=async()=>{if(!ho())return!1;try{return await C("desktop_start_window_drag"),!0}catch{return!1}},ot=()=>tt()?.runtime?.isVSCode===!0,kc=()=>{const e=tt()?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!ot()},mo=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Dc=async t=>{if(M()&&R())try{const e=await ie()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory"});return!e||typeof e!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:e}}catch(e){return console.warn("Failed to request directory access",e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!0,path:t}},yo=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Ac=async t=>{if(M()&&R())try{const e=await ie()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...t?.filters?{filters:t.filters}:{},...t?.defaultPath?{defaultPath:t.defaultPath}:{}});if(!e)return{success:!1,error:"File selection cancelled"};if(typeof e=="string")return{success:!0,path:e};if(!yo(e))return{success:!1,error:"File selection cancelled"};const r=typeof e.path=="string"?e.path:"";return r?{success:!0,path:r,outsideFileGrant:typeof e.outsideFileGrant=="string"?e.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(e){return console.warn("Failed to request file access",e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!1,error:"Native file picker not available"}},Pc=async t=>{const e=typeof t=="string"?t.trim():"";if(!e)return{success:!1,error:"Path is required"};if(!M()||!R())return{success:!1,error:"Native file access not available"};try{const r=await ie()?.grantFileAccess?.(e);if(!yo(r))return{success:!1,error:"File access was not granted"};const o=typeof r.path=="string"?r.path:"",n=typeof r.outsideFileGrant=="string"?r.outsideFileGrant:"";return!o||!n?{success:!1,error:"File access was not granted"}:{success:!0,path:o,outsideFileGrant:n}}catch(r){return console.warn("Failed to request existing file access",r),{success:!1,error:r instanceof Error?r.message:String(r)}}},Mc=async t=>({success:!0}),Cc=async t=>({success:!0}),Oc=async()=>{if(!M())return null;try{return await C("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates",t),null}},Rc=async t=>{if(!M())return!1;const e=ie();let r=null,o=0,n;try{return typeof t=="function"&&e?.listen&&(r=await e.listen("openchamber:update-progress",i=>{const s=i?.payload;if(!s||typeof s!="object")return;const a=s,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){o=0,n=typeof l?.contentLength=="number"?l.contentLength:void 0,t({downloaded:o,total:n});return}if(c==="Progress"){const d=l?.downloaded,f=l?.total;typeof d=="number"&&(o=d),typeof f=="number"&&(n=f),t({downloaded:o,total:n});return}c==="Finished"&&t({downloaded:o,total:n})})),await C("desktop_download_and_install_update"),!0}catch(i){return console.warn("Failed to download update",i),!1}finally{if(r)try{const i=r();i instanceof Promise&&await i}catch{}}},Ic=async()=>M()?Bn():!1,Bn=async()=>{if(!M())return!1;try{return await C("desktop_restart"),!0}catch(t){return console.warn("Failed to restart desktop app",t),!1}},Fc=async()=>{if(!M()||!R())return null;try{const t=await C("desktop_get_lan_address");return typeof t=="string"&&t.trim().length>0?t.trim():null}catch(t){return console.warn("Failed to get desktop LAN address",t),null}},Hn=async(t,e)=>{if(!M()||!R())return!1;const r=t?.trim();if(!r)return!1;try{return await C("desktop_open_path",{path:r,app:typeof e=="string"&&e.trim().length>0?e.trim():void 0}),!0}catch(o){return console.warn("Failed to open path",o),!1}},_c=async t=>{if(!M()||!R())return!1;const e=t?.trim();if(!e)return!1;try{return await C("desktop_reveal_path",{path:e}),!0}catch{return Hn(e)}},xc=async(t,e)=>{if(!M()||!R())return null;const r=t?.trim();if(!r)return null;try{const o=await C("desktop_save_markdown_file",{defaultFileName:r,content:e});return typeof o=="string"&&o.trim().length>0?o:null}catch(o){return console.warn("Failed to save markdown file",o),null}},jc=async(t,e,r)=>{if(!M()||!R())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await C("desktop_open_in_app",{projectPath:o,appId:n,appName:i}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},Lc=async(t,e,r)=>{if(!M()||!R())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await C("desktop_open_file_in_app",{filePath:o,appId:n,appName:i}),!0}catch(s){return console.warn("Failed to open file in app",s),!1}},Nc=async(t,e)=>{if(!M()||!R())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const r=Array.isArray(t)?t.filter(o=>typeof o=="string"):[];if(r.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await C("desktop_get_installed_apps",{apps:r,force:e===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=o;return Array.isArray(n.apps)?{apps:n.apps.filter(s=>s&&typeof s=="object").map(s=>{const a=s;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(s=>s.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(o){return console.warn("Failed to fetch installed apps",o),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},ar=500,go=()=>{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}},Uc=()=>go(),I=(t,e)=>{if(!go())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:t,...e?{data:e}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>ar&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-ar)},zn=()=>{const t=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],e=t.findIndex(o=>o.name==="ModelControls:ready"),r=e>=0?Math.min(t.length,e+8):t.length;return t.slice(0,r).filter(o=>o.name.includes("checkConnection")||o.name.includes("checkHealth")||o.name.includes("initializeApp")||o.name.includes("initApp")||o.name.includes("loadProviders")||o.name.includes("loadAgents")||o.name.includes("config.defaults")||o.name.includes("modelsMetadata")||o.name.includes("ModelControls")||o.name.includes("activateDirectory")||o.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=zn);const Bc=async(t,e,r)=>{const o=typeof performance<"u"?performance.now():Date.now();I(`${t}:start`,r);try{const n=await e(),i=typeof performance<"u"?performance.now():Date.now();return I(`${t}:end`,{durationMs:Math.round(i-o)}),n}catch(n){const i=typeof performance<"u"?performance.now():Date.now();throw I(`${t}:error`,{durationMs:Math.round(i-o),error:n instanceof Error?n.message:String(n)}),n}},$n=3,Gn=3e4,Wn=1e3,wo=32e3,qn=3,Kn=3600*1e3,Vn=600*1e3,bo=new Set([429,502,503,504]),oe=new Map;function Jn(){const t=Date.now();for(const[e,r]of oe)r.consecutiveErrors===0&&t-r.lastErrorAt>Kn&&oe.delete(e)}typeof setInterval<"u"&&setInterval(Jn,Vn).unref?.();function Qn(t){let e=oe.get(t);return e||(e={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Gn},oe.set(t,e)),e}function Yn(t){if(!t)return;const e=oe.get(t);e&&(e.consecutiveErrors=0,e.lastErrorAt=0)}function cr(t,e){if(!t)return;const r=Qn(t);r.consecutiveErrors+=1,r.lastErrorAt=Date.now(),Xn(e)&&r.consecutiveErrors>=$n&&(r.circuitOpen=!0,r.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${t} after ${r.consecutiveErrors} consecutive errors`))}function Xn(t){return t!==void 0&&bo.has(t)}function So(t){const e=oe.get(t);return e?.circuitOpen?Date.now()-e.circuitOpenAt>=e.circuitCooldownMs?(e.circuitOpen=!1,e.consecutiveErrors=0,e.circuitCooldownMs=Math.min(e.circuitCooldownMs*2,wo*4),!1):!0:!1}function Zn(t,e,r){return!(!bo.has(e)||r>=qn-1||So(t))}function ei(t){if(!(!t||!So(t)))throw new Error(`Provider ${t} is temporarily unavailable after repeated errors. Please retry shortly.`)}function lr(t){const e=Wn*2**t;return Math.min(e,wo)}const dr="/api",ti=1e4,ri=4e3;function ue(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function O(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${ue(t.error)}`);throw r!==void 0&&(o.status=r),o}if(t.data===void 0||t.data===null)throw new Error(`${e} failed: empty response`);return t.data}function Y(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${ue(t.error)}`);throw r!==void 0&&(o.status=r),o}return t.data}const oi=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ur="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ni=14;let fr=0,dt=0;const ii=t=>{const e=new Uint8Array(t);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let o=0;o<t;o+=1)e[o]=Math.floor(Math.random()*256);let r="";for(let o=0;o<t;o+=1)r+=ur[e[o]%ur.length];return r},pr=t=>{const e=Date.now();e!==fr&&(fr=e,dt=0),dt+=1;const r=BigInt(e)*BigInt(4096)+BigInt(dt),o=new Uint8Array(6);for(let i=0;i<6;i+=1)o[i]=Number(r>>BigInt(40-8*i)&BigInt(255));const n=Array.from(o,i=>i.toString(16).padStart(2,"0")).join("");return`${t}_${n}${ii(ni)}`},si=t=>t instanceof DOMException&&t.name==="AbortError"||t instanceof TypeError,hr=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(oi.test(e)||typeof window>"u")return e;const r=window.location?.href||window.location?.origin;if(!r)return e;try{return new URL(e,r).toString()}catch(o){return console.warn("Failed to normalize OpenCode base URL:",o),e}},mr=()=>{try{return P().api("/api")}catch{return null}},ai=t=>{const e=typeof AbortSignal<"u"?AbortSignal:void 0;if(typeof e?.timeout=="function")return{signal:e.timeout(t),cleanup:()=>{}};const r=new AbortController,o=setTimeout(()=>r.abort(),t);return{signal:r.signal,cleanup:()=>clearTimeout(o)}},ut=t=>rn({...t,fetch:u}),X=t=>t.replace(/\\/g,"/"),yr=400,gr=()=>{const t=tt();return t&&t.runtime?.isDesktop&&t.files?t.files:null};class ci{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(e=dr){const o=mr()||e;this.baseUrl=hr(o),this.client=ut({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const e=mr(),r=hr(e||dr);r!==this.baseUrl&&(this.baseUrl=r,this.client=ut({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(e){return this.getScopedApiClient(e)}getScopedApiClient(e){const r=this.normalizeCandidatePath(e)??e,o=r||"",n=this.scopedClients.get(o);if(n)return n;const i=ut({baseUrl:this.baseUrl,directory:r});return this.scopedClients.set(o,i),i}normalizeCandidatePath(e){if(typeof e!="string")return null;const r=e.trim();if(!r)return null;const o=r.replace(/\\/g,"/").replace(/^([a-z]):/,(i,s)=>s.toUpperCase()+":");return(o.length>1?o.replace(/\/+$/,""):o)||null}deriveHomeDirectory(e){const r=e.match(/^([A-Za-z]:)(?:\/|$)/);if(r){const i=r[1],a=e.slice(i.length+(e.charAt(i.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${i}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${i}/${a[0]}`,username:a[0]}:{homeDirectory:i,username:void 0}}const o=e.startsWith("/"),n=e.split("/").filter(Boolean);return n.length>=2&&(n[0]==="Users"||n[0]==="home")?{homeDirectory:`${o?"/":""}${n[0]}/${n[1]}`,username:n[1]}:o?n.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${n.join("/")}`,username:n[n.length-1]}:n.length>0?{homeDirectory:`/${n.join("/")}`,username:n[n.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(e){const r=this.normalizeCandidatePath(e)??e;this.currentDirectory!==r&&I("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:r??null}),this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(e,r){const o=async()=>{if(e==null)return r();const i=this.currentDirectory,s=this.normalizeCandidatePath(e)??e;this.currentDirectory=s;try{return await r()}finally{this.currentDirectory===s&&(this.currentDirectory=i)}},n=this.directoryContextQueue.then(o,o);return this.directoryContextQueue=n.then(()=>{},()=>{}),n}getApiClient(){return this.client}async getSystemInfo(){const e=new Set,r=n=>{const i=this.normalizeCandidatePath(n);i&&e.add(i)};try{const i=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;i&&(r(i.directory),r(i.worktree),r(i.state))}catch(n){console.debug("Failed to load path info:",n)}if(!e.size)try{const n=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);r(n.data?.worktree)}catch(n){console.debug("Failed to load project info:",n)}if(!e.size)try{(await this.listSessions()).forEach(i=>r(i.directory))}catch(n){console.debug("Failed to inspect sessions for system info:",n)}if(r(this.currentDirectory),typeof window<"u")try{r(window.localStorage.getItem("lastDirectory")),r(window.localStorage.getItem("homeDirectory"))}catch{}if(!e.size&&typeof process<"u"&&typeof process.cwd=="function"&&r(process.cwd()),!e.size)return{homeDirectory:"/",username:void 0};const[o]=Array.from(e);return this.deriveHomeDirectory(o)}async probeDirectory(e){const r=this.normalizeCandidatePath(e);if(!r)return!1;try{const n=(await this.client.path.get({directory:r})).data,i=typeof n?.directory=="string"?n.directory:null;return!!(i&&i.trim().length>0)}catch{return!1}}async listSessions(){const e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data:[]}async createSession(e,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,n=await this.client.session.create({...o?{directory:o}:{},parentID:e?.parentID,title:e?.title,metadata:e?.metadata});return O(n,"session.create")}async getSession(e,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,n=await this.client.session.get({sessionID:e,...o?{directory:o}:{}});return O(n,"session.get")}async deleteSession(e,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,n=await this.client.session.delete({sessionID:e,...o?{directory:o}:{}});return Y(n,"session.delete")===!0}async updateSession(e,r,o){const n=this.normalizeCandidatePath(o)??this.currentDirectory,i={...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}}:{}},s=await this.client.session.update({sessionID:e,...n?{directory:n}:{},...i});return O(s,"session.update")}async getSessionMessages(e,r){const o=await this.client.session.messages({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof r=="number"?{limit:r}:{}});return O(o,"session.messages")}async getSessionTodos(e){try{const r=await this.client.session.todo({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(r.error)return[];const o=r.data;return!o||!Array.isArray(o)?[]:o}catch{return[]}}shouldNormalizeToTextPlain(e){if(!e)return!1;const r=e.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(e){if(!e)return!1;const r=e.toLowerCase();return r==="image/heic"||r==="image/heif"}async convertHeicToJpeg(e){try{const r=(await tn(async()=>{const{default:f}=await import("./vendor-.bun-C6iL44L9.js").then(g=>g.h);return{default:f}},[])).default,o=e.url.indexOf(",");if(o===-1)return e;const n=e.url.substring(o+1),i=atob(n),s=new Uint8Array(i.length);for(let f=0;f<i.length;f++)s[f]=i.charCodeAt(f);const a=new Blob([s],{type:e.mime}),c=await r({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((f,g)=>{const y=new FileReader;y.onload=()=>f(y.result),y.onerror=g,y.readAsDataURL(c)});let d=e.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),e}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let r=e.url;if(e.url.startsWith("data:")){const o=e.url.indexOf(",");if(o!==-1){const n=e.url.substring(5,o),i=e.url.substring(o);r=`data:${n.replace(/^[^;,]+/,"text/plain")}${i}`}}return{mime:"text/plain",filename:e.filename,url:r}}async toNormalizedFilePartInput(e){const r=await this.normalizeFilePart(e);return{...e.id?{id:e.id}:{},type:"file",mime:r.mime,filename:r.filename,url:r.url}}async sendMessage(e){const r=e.messageId??pr("msg"),o=[];if(e.prefaceText&&e.prefaceText.trim()&&o.push({type:"text",text:e.prefaceText,synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()){const s={type:"text",text:e.text};o.push(s)}if(e.files&&e.files.length>0)for(const s of e.files){const a=await this.toNormalizedFilePartInput(s);o.push(a)}if(e.additionalParts&&e.additionalParts.length>0){for(const s of e.additionalParts)if(s.text&&s.text.trim()&&o.push({type:"text",text:s.text,...s.synthetic?{synthetic:!0}:{}}),s.files&&s.files.length>0)for(const a of s.files){const c=await this.toNormalizedFilePartInput(a);o.push(c)}}if(e.agentMentions&&e.agentMentions.length>0)for(const s of e.agentMentions)s?.name&&o.push({type:"agent",name:s.name,...s.source?{source:s.source}:{}});if(o.length===0)throw new Error("Message must have at least one part (text or file)");const n=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory;e.format&&console.info("[git-generation][browser] send structured message",{sessionId:e.id,providerID:e.providerID,modelID:e.modelID,agent:e.agent,variant:e.variant,directory:n,baseUrl:this.baseUrl,formatType:e.format.type}),ei(e.providerID);let i;for(let s=0;s<3;s++){try{const d=await this.client.session.promptAsync({sessionID:e.id,...n?{directory:n}:{},model:{providerID:e.providerID,modelID:e.modelID},agent:e.agent,variant:e.variant,messageID:r,...e.delivery?{delivery:e.delivery}:{},...e.format?{format:e.format}:{},parts:o});if(d.response instanceof Response)i=d.response;else if(d.error){const f=d.response?.status||500;i=new Response(JSON.stringify(d.error),{status:f})}else i=new Response(JSON.stringify(d.data??!0),{status:200})}catch(d){if(s<2&&si(d)){const f=lr(s);console.warn(`[prompt] fetch failed for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${f}ms`,d?.message),await new Promise(g=>setTimeout(g,f));continue}throw cr(e.providerID),d}if(i.ok)return Yn(e.providerID),r;if(Zn(e.providerID,i.status,s)){const d=lr(s);console.warn(`[prompt] ${i.status} for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${d}ms`),await new Promise(f=>setTimeout(f,d));continue}let a="";try{a=await i.text()}catch{}const c=a&&a.trim().length>0?`: ${a.trim()}`:"",l=new Error(`Failed to send message (${i.status})${c}`);throw cr(e.providerID,i.status),l}throw new Error("Failed to send message after retries")}async sendCommand(e){const r=e.messageId??pr("msg"),o=[];if(e.files&&e.files.length>0)for(const s of e.files)o.push(await this.toNormalizedFilePartInput(s));const n=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,i=await this.client.session.command({sessionID:e.id,...n?{directory:n}:{},command:e.command,arguments:e.arguments??"",model:`${e.providerID}/${e.modelID}`,agent:e.agent,variant:e.variant,...o.length>0?{parts:o}:{},messageID:r});return Y(i,"session.command"),r}async abortSession(e){return!!(await this.client.session.abort({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(e){const r=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,o=await this.client.session.shell({sessionID:e.sessionId,...r?{directory:r}:{},messageID:e.messageId,agent:e.agent,model:e.model,command:e.command});return O(o,"session.shell")}async revertSession(e,r,o,n){const i=this.normalizeCandidatePath(n)??this.currentDirectory,s=await this.client.session.revert({sessionID:e,...i?{directory:i}:{},messageID:r,partID:o});return O(s,"session.revert")}async summarizeSession(e,r,o,n){const i=this.normalizeCandidatePath(n)??this.currentDirectory,s=await this.client.session.summarize({sessionID:e,...i?{directory:i}:{},providerID:r,modelID:o});return Y(s,"session.summarize")===!0}async unrevertSession(e){const r=await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return O(r,"session.unrevert")}async forkSession(e,r,o){const n=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.fork({sessionID:e,...n?{directory:n}:{},messageID:r});return O(i,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e){try{const r=typeof e=="string"?e.trim():"",o=await this.client.session.status(r?{directory:r}:void 0);return o.error||!o.data||typeof o.data!="object"?null:o.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const e=await u("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const r=await e.json().catch(()=>null);return!r||typeof r!="object"?null:r}catch{return null}}async listToolIds(e){try{const r=typeof e?.directory=="string"?e.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(r?{directory:r}:void 0)).data||[]).filter(i=>typeof i=="string"&&i!=="invalid")}catch{return[]}}async replyToPermission(e,r,o){const n=this.normalizeCandidatePath(o?.directory??null)??this.currentDirectory,i=await this.client.permission.reply({requestID:e,...n?{directory:n}:{},reply:r,...o?.message?{message:o.message}:{}});return Y(i,"permission.reply")===!0}async listPendingPermissions(e){const r=[],o=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: ${ue(d.error)}`);return d.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&n.add(l)}for(const c of n)r.push(o(c));const i=await Promise.all(r),s=[],a=new Set;for(const c of i)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),s.push(l))}return s}async replyToQuestion(e,r,o){const n=!Array.isArray(r)||r.length===0?[]:Array.isArray(r[0])?r:[r],i=this.normalizeCandidatePath(o)??this.currentDirectory,s=await this.client.question.reply({requestID:e,...i?{directory:i}:{},answers:n});return Y(s,"question.reply")===!0}async rejectQuestion(e){const r=await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Y(r,"question.reject")===!0}async listPendingQuestions(e){const r=[],o=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: ${ue(d.error)}`);return d.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&n.add(l)}for(const c of n)r.push(o(c));const i=await Promise.all(r),s=[],a=new Set;for(const c of i)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),s.push(l))}return s}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(e){const r=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,o=r??"",n=this.configCache.get(o);if(n&&n.expiresAt>Date.now())return I("opencodeClient.getConfig:cacheHit",{directory:r??null}),n.config;const i=this.configInFlight.get(o);if(i)return I("opencodeClient.getConfig:deduped",{directory:r??null}),i;const s=this.configCacheGeneration,a=(async()=>{I("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 I("opencodeClient.getConfig:end",{directory:r??null,durationMs:Math.round(f-c)}),s===this.configCacheGeneration&&this.configCache.set(o,{config:d.data,expiresAt:Date.now()+ti}),d.data})();this.configInFlight.set(o,a);try{return await a}finally{this.configInFlight.get(o)===a&&this.configInFlight.delete(o)}}async updateConfig(e){const r=await this.client.config.update({config:e}),o=O(r,"global.config.update");return this.clearConfigCache(),o}async updateConfigPartial(e){const r=await this.getConfig(),o=e(r);return await this.updateConfig(o)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(e){const r=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,o=r??"",n=this.configProvidersInFlight.get(o);if(n)return n;const i=(async()=>{const s=await this.client.config.providers(r?{directory:r}:void 0);return O(s,"config.providers")})();this.configProvidersInFlight.set(o,i);try{return await i}finally{this.configProvidersInFlight.delete(o)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(e){const r=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,o=r??"",n=this.listAgentsInFlight.get(o);if(n)return n;const i=(async()=>{const s=r?{directory:r}:void 0,a=await this.client.app.agents(s);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})`:""}: ${ue(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(o,i);try{return await i}finally{this.listAgentsInFlight.delete(o)}}async readFile(e){try{const r=await this.client.file.read({path:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(O(r,"file.read"))}catch{return`// Content of ${e}
|
|
2
|
-
// This would be loaded from the server`}}async listFiles(e){try{const r=e||this.currentDirectory||"/",o=await this.client.file.list({path:r,...this.currentDirectory?{directory:this.currentDirectory}:{}}),n=O(o,"file.list");return Array.isArray(n)?n:[]}catch{return[]}}async listCommands(){const e=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(O(e,"command.list")||[]).map(o=>({name:o.name,description:o.description,agent:o.agent,model:o.model,source:o.source}))}async listCommandsWithDetails(){const e=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(O(e,"command.list")||[]).map(o=>({name:o.name,description:o.description,agent:o.agent,model:o.model,source:o.source,template:o.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 o=[];for(const n of r){const i=typeof n.name=="string"?n.name.trim():"",s=typeof n.location=="string"?n.location:"";if(!i||!s)continue;const a={name:i,location:s};typeof n.description=="string"&&(a.description=n.description),typeof n.content=="string"&&(a.content=n.content),o.push(a)}return o}catch{return[]}}async getCommandDetails(e){try{const r=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(r.data){const o=r.data.find(n=>n.name===e);if(o)return{name:o.name,template:o.template,description:o.description,agent:o.agent,model:o.model}}return null}catch{return null}}async checkHealth(){try{const e=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,r=e==="/api"||e.endsWith("/api")?"/api/opencode/health":`${e}/opencode/health`;I("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:r});const o=ai(ri),n=await u(r,{signal:o.signal}).finally(o.cleanup);if(I("opencodeClient.checkHealth:response",{status:n.status}),!n.ok)return!1;const i=await n.json();return I("opencodeClient.checkHealth:result",{healthy:i?.healthy}),i?.healthy===!0}catch{return!1}}async createDirectory(e,r){const o=gr();if(o?.createDirectory)try{return await o.createDirectory(e)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}const n={path:e,...r?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},i=await u(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await i.json()}async cloneRepository(e){const r=await u(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(o.error||"Failed to clone repository")}return await r.json()}async listLocalDirectory(e,r){const n=`${typeof e=="string"?X(e.trim()):""}|${r?.respectGitignore?"1":"0"}`,i=Date.now(),s=this.listDirectoryCache.get(n);if(s&&s.expiresAt>i)return s.entries;const a=this.listDirectoryInFlight.get(n);if(a)return a;const l=(async()=>{const d=gr();if(d)try{const f=await d.listDirectory(e||"",r);if(!f||!Array.isArray(f.entries))return[];const g=f.entries.map(y=>({name:y.name,path:X(y.path),isDirectory:!!y.isDirectory,isFile:!y.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:g,expiresAt:Date.now()+yr}),g}catch(f){throw console.error("Failed to list directory contents:",f),f}try{const f=new URLSearchParams;e&&e.trim().length>0&&f.set("path",e),r?.respectGitignore&&f.set("respectGitignore","true");const g=f.toString(),y=await u(`${this.baseUrl}/fs/list${g?`?${g}`:""}`);if(!y.ok){const b=await y.json().catch(()=>({})),T=typeof b.error=="string"?b.error:"Failed to list directory";throw new Error(T)}const p=await y.json();if(!p||!Array.isArray(p.entries))return[];const w=p.entries;return this.listDirectoryCache.set(n,{entries:w,expiresAt:Date.now()+yr}),w}catch(f){throw console.error("Failed to list directory contents:",f),f}})().finally(()=>{this.listDirectoryInFlight.get(n)===l&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,l),l}async searchFiles(e,r){const o=typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():this.currentDirectory,n=o?X(o):null,i=o?this.getScopedApiClient(o):this.client;try{const s=await i.find.files({query:e,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(s?.data)?s.data:[]).map(c=>{const l=X(c),d=l.split("/").filter(Boolean).pop()||l,f=X(n?`${n}/${l}`:l);return{name:d,path:f,relativePath:l,extension:d.includes(".")?d.split(".").pop()?.toLowerCase():void 0}})}catch(s){throw console.error("Failed to search files:",s),s}}async getFilesystemHome(){const e=et();if(!e||e==="local"){const r=await mo();if(r)return r}try{const r=await u(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){const n=await r.json().catch(()=>({})),i=typeof n.error=="string"&&n.error.length>0?n.error:"Failed to resolve home directory";throw new Error(i)}const o=await r.json();return o&&typeof o.home=="string"&&o.home.length>0?o.home:null}catch(r){return console.warn("Failed to resolve filesystem home directory:",r),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!="string"||!e.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",e),null;const r=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",r,"with path:",e);try{const o=await u(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})}),n=await o.json().catch(()=>null);if(!o.ok){const i=n??{},s=typeof i.error=="string"&&i.error.length>0?i.error:"Failed to update OpenCode working directory";throw new Error(s)}return n&&typeof n=="object"?n:{success:!0,restarted:!1,path:e}}catch(o){throw console.warn("Failed to update OpenCode working directory:",o),o}}}const H=new ci,li=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!e)return"";const r=new TextEncoder().encode(e);let o="";for(const i of r)o+=String.fromCharCode(i);return`path_${typeof btoa=="function"?btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):e.replace(/[^A-Za-z0-9._-]+/g,"_")}`};let ft=null,pt=null,ht=null;const wr=new Set;let br=!1;const To=t=>{if(wr.add(t),br||typeof window>"u")return;br=!0;const e=()=>{for(const r of wr)r()};try{window.addEventListener("pagehide",e,{capture:!0}),window.addEventListener("beforeunload",e,{capture:!0}),window.addEventListener("visibilitychange",()=>{typeof document<"u"&&document.visibilityState==="hidden"&&e()}),window.addEventListener("freeze",e)}catch{}},di=(t,e)=>{let r;try{r=t()}catch{return}const o=new Map,n=new Set;let i;const s=()=>{if(i=void 0,o.size===0&&n.size===0)return;const c=Array.from(o.entries()),l=Array.from(n);o.clear(),n.clear();for(const[d,f]of c)try{r.setItem(d,JSON.stringify(f,e?.replacer))}catch(g){console.error("Failed to persist deferred storage value",g)}for(const d of l)try{r.removeItem(d)}catch(f){console.error("Failed to remove deferred storage value",f)}},a=()=>{i===void 0&&(i=setTimeout(s,0))};return To(s),{getItem:c=>{if(o.has(c))return o.get(c)??null;if(n.has(c))return null;const l=f=>f===null?null:JSON.parse(f,e?.reviver),d=r.getItem(c);return d instanceof Promise?d.then(l):l(d)},setItem:(c,l)=>{o.set(c,l),n.delete(c),a()},removeItem:c=>{o.delete(c),n.add(c),a()}}},vo=t=>di(()=>ko(),t),ui=t=>{const e=new Map,r=new Set;let o;const n=()=>{if(o=void 0,e.size===0&&r.size===0)return;const s=Array.from(e.entries()),a=Array.from(r);e.clear(),r.clear();for(const[c,l]of s)try{t.setItem(c,l)}catch(d){console.error("Failed to persist deferred storage value",d)}for(const c of a)try{t.removeItem(c)}catch(l){console.error("Failed to remove deferred storage value",l)}},i=()=>{o===void 0&&(o=setTimeout(n,0))};return To(n),{getItem:s=>e.has(s)?e.get(s)??null:r.has(s)?null:t.getItem(s),setItem:(s,a)=>{e.set(s,a),r.delete(s),i()},removeItem:s=>{e.delete(s),r.add(s),i()},clear:()=>{e.clear(),r.clear(),o!==void 0&&(clearTimeout(o),o=void 0),t.clear()},key:s=>t.key(s),get length(){return t.length}}},Eo=t=>{if(typeof window>"u")return null;try{return window[t]??null}catch{return null}},ze=()=>{const t=new Map;return{getItem:e=>t.get(e)??null,setItem:(e,r)=>{t.set(e,r)},removeItem:e=>{t.delete(e)},clear:()=>{t.clear()},key:e=>Array.from(t.keys())[e]??null,get length(){return t.size}}},fi=()=>{const t=Eo("localStorage");if(!t)return ze();const e=ze();let r=!0;const o=()=>{r=!1};return{getItem:l=>{if(r)try{const d=t.getItem(l);if(d!==null)return d}catch{o()}return e.getItem(l)},setItem:(l,d)=>{if(r)try{t.setItem(l,d),e.removeItem(l);return}catch{o();try{t.removeItem(l)}catch{}}e.setItem(l,d)},removeItem:l=>{try{t.removeItem(l)}catch{o()}e.removeItem(l)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:l=>{if(r)try{return t.key(l)}catch{o()}return e.key(l)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},ko=()=>(ft||(ft=fi()),ft),Te=()=>(ht||(ht=ui(ko())),ht),pi=()=>{const t=Eo("sessionStorage");if(!t)return ze();const e=ze();let r=!0;const o=()=>{r=!1};return{getItem:l=>{if(r)try{const d=t.getItem(l);if(d!==null)return d}catch{o()}return e.getItem(l)},setItem:(l,d)=>{if(r)try{t.setItem(l,d),e.removeItem(l);return}catch{o();try{t.removeItem(l)}catch{}}e.setItem(l,d)},removeItem:l=>{try{t.removeItem(l)}catch{o()}e.removeItem(l)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:l=>{if(r)try{return t.key(l)}catch{o()}return e.key(l)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},Hc=()=>(pt||(pt=pi()),pt),hi={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},zc={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Sr(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const De={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)"}}},mt={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...De.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:mt.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...De.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:mt.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...De.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:mt.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...De.tool.inline})},mi=[{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'}],yi=[{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'}],Do=t=>Object.fromEntries(t.map(e=>[e.id,e])),gi=Do(mi),wi=Do(yi),bi="system",Si="system-mono",Ao=t=>typeof t=="string"&&t in gi,Po=t=>typeof t=="string"&&t in wi,Pt="openchamber.mobileKeyboardMode",Ti='meta[name="viewport"]',Tr="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",$c=()=>!0;function nt(t,e="resize-content"){return t==="native"||t==="resize-content"?t:e}const vi=t=>nt(t)==="resize-content"?`${Tr}, interactive-widget=resizes-content`:Tr,Ei=()=>{if(typeof window>"u")return"resize-content";try{return nt(localStorage.getItem(Pt))}catch{return"resize-content"}},Mo=t=>{const e=nt(t);if(typeof window<"u")try{e==="resize-content"?localStorage.removeItem(Pt):localStorage.setItem(Pt,e)}catch{}return e},Gc=t=>{const e=Mo(t);if(typeof document>"u")return e;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",e);const r=document.querySelector(Ti);if(r instanceof HTMLMetaElement){const o=vi(e);r.getAttribute("content")!==o&&r.setAttribute("content",o)}return e};function vr(t){return t==="vim"?"vim":"default"}const Ae={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}"}},B={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Pe=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,ki=t=>{if(!t||typeof t!="object")return!1;const e=t;return Pe(e.completion,Ae.completion)&&Pe(e.error,Ae.error)&&Pe(e.question,Ae.question)&&Pe(e.subtask,Ae.subtask)},Kt=380,Di=380,Ai=1400,Co=12,Er=120,ae=280,ce=360,Pi=860,yt=new Map,gt=t=>(t??et()).trim()||"default",A=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),r=e.startsWith("//");let o=e.replace(/\/+$/g,"");return o=o.replace(/\/+/g,"/"),r&&!o.startsWith("//")&&(o=`/${o}`),o===""?e.startsWith("/")?"/":"":o},Oo=t=>Number.isFinite(t)?Math.min(Ai,Math.max(Di,Math.round(t))):Kt,$e=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.replace(/\\/g,"/"):null},Ge=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.length>Er?e.slice(0,Er):e:null},Mi=(t,e)=>(t==="file"||t==="preview")&&e||t,Ro=(t,e,r)=>{if(t==="diff")return t;if(typeof r=="string"){const o=r.trim();if(o)return o}return Mi(t,e)},Io=(t,e)=>e===t?t:`${t}:${e}`,Fo=t=>{const e=$e(t.targetPath),r=Ro(t.mode,e,t.dedupeKey);return{id:Io(t.mode,r),mode:t.mode,targetPath:e,dedupeKey:r,label:Ge(t.label),sessionTitleFallback:Ge(t.sessionTitleFallback),readOnly:t.readOnly===!0,stagedDiff:t.stagedDiff===!0,touchedAt:Date.now()}},_o=(t,e,r)=>{if(t.length<=e)return t;const n=[...t].sort((a,c)=>a.touchedAt-c.touchedAt).filter(a=>a.id!==r),i=t.length-e;if(i<=0||n.length===0)return t.slice(-e);const s=new Set(n.slice(0,i).map(a=>a.id));return t.filter(a=>!s.has(a.id))},xo=t=>{if(!Array.isArray(t))return[];const e=[],r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const n=o;if(n.mode!=="diff"&&n.mode!=="file"&&n.mode!=="context"&&n.mode!=="plan"&&n.mode!=="chat"&&n.mode!=="preview"&&n.mode!=="browser")continue;const i=$e(typeof n.targetPath=="string"?n.targetPath:null),s=Ro(n.mode,i,typeof n.dedupeKey=="string"?n.dedupeKey:null),a=Io(n.mode,s);!a||r.has(a)||(r.add(a),e.push({id:a,mode:n.mode,targetPath:i,dedupeKey:s,label:Ge(typeof n.label=="string"?n.label:null),sessionTitleFallback:Ge(typeof n.sessionTitleFallback=="string"?n.sessionTitleFallback:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()}))}return e},ge=(t,e)=>e&&t.some(r=>r.id===e)?e:t.length===0?null:t[t.length-1].id,$=t=>{if(t){const e=xo(t.tabs),r=ge(e,t.activeTabId);return{...t,tabs:e,activeTabId:r,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:Kt,touchedAt:Date.now()}},Ci=(t,e)=>{const r=Fo(e),o=t.tabs.findIndex(a=>a.id===r.id),n=o===-1?[...t.tabs,r]:t.tabs.map((a,c)=>c===o?{...a,mode:r.mode,targetPath:r.targetPath||a.targetPath,dedupeKey:r.dedupeKey,label:r.label,sessionTitleFallback:r.sessionTitleFallback||a.sessionTitleFallback,stagedDiff:r.stagedDiff,readOnly:r.readOnly,touchedAt:Date.now()}:a),i=r.id,s=_o(n,Co,i);return{...t,isOpen:!0,tabs:s,activeTabId:ge(s,i),touchedAt:Date.now()}},Oi=(t,e)=>{const r=t.tabs.filter(n=>n.id!==e),o=t.activeTabId===e?r[r.length-1]?.id??null:ge(r,t.activeTabId);return{...t,tabs:r,activeTabId:o,isOpen:r.length>0?t.isOpen:!1,touchedAt:Date.now()}},Ri=(t,e,r)=>{if(e===r)return t;const o=t.tabs.findIndex(a=>a.id===e),n=t.tabs.findIndex(a=>a.id===r);if(o===-1||n===-1)return t;const i=[...t.tabs],[s]=i.splice(o,1);return s?(i.splice(n,0,s),{...t,tabs:i,touchedAt:Date.now()}):t},Ii=(t,e,r)=>({...t,tabs:t.tabs.map(o=>o.id===e?{...o,targetPath:r}:o)}),wt=t=>{if(!t||typeof t!="object")return{};const e=t,r={};for(const[o,n]of Object.entries(e)){const i=A(o);if(!i||!n||typeof n!="object")continue;const s=n;let a=xo(s.tabs),c=typeof s.activeTabId=="string"?s.activeTabId:null;a.length===0&&(s.mode==="diff"||s.mode==="file"||s.mode==="context"||s.mode==="plan"||s.mode==="chat")&&(a=[Fo({mode:s.mode,targetPath:typeof s.targetPath=="string"?s.targetPath:null,dedupeKey:typeof s.dedupeKey=="string"?s.dedupeKey:null,label:typeof s.label=="string"?s.label:null})],c=a[0]?.id??null);const l=ge(a,c),d=_o(a,Co,l);r[i]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:d,activeTabId:ge(d,l),width:Oo(typeof s.width=="number"?s.width:Kt),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},G=(t,e)=>{const r=Object.entries(t);if(r.length<=e)return t;r.sort((n,i)=>(i[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const o={};for(const[n,i]of r.slice(0,e))o[n]=i;return o},L=Je()(Qe(Hr((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:ae,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:ce,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,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,groupReasoningBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:13,uiFont:bi,monoFont:Si,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Ei(),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:{...B.completion},error:{...B.error},question:{...B.question},subtask:{...B.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!0,inputSpellcheckEnabled:!1,wideChatLayoutEnabled:!1,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=>{t({theme:r}),e().applyTheme()},toggleSidebar:()=>{t(r=>{const o=!r.isSidebarOpen;return o&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:o,sidebarWidth:ae}:{isSidebarOpen:o}})},setSidebarOpen:r=>{t(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==ae?{isSidebarOpen:r,sidebarWidth:ae}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:ae}:{isSidebarOpen:r})},setSidebarWidth:r=>{t({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(r=>{const o=!r.isRightSidebarOpen;return o&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:o,rightSidebarWidth:ce}:{isRightSidebarOpen:o}})},setRightSidebarOpen:r=>{t(o=>{if(o.isRightSidebarOpen===r)return o;const n=r&&!o.hasManuallyResizedRightSidebar&&o.rightSidebarWidth!==ce;return{isRightSidebarOpen:r,rightSidebarWidth:n?ce:o.rightSidebarWidth}})},setRightSidebarWidth:r=>{const o=Math.min(Pi,Math.max(ce,r));t({rightSidebarWidth:o,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:r=>{t({rightSidebarTab:r})},openContextPanelTab:(r,o)=>{const n=A((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=$(s),c={...i.contextPanelByDirectory,[n]:Ci(a,o)};return{contextPanelByDirectory:G(c,20)}})},openContextDiff:(r,o,n=!1)=>{const i=A((r||"").trim()),s=(o||"").trim();!i||!s||e().openContextPanelTab(i,{mode:"diff",targetPath:s,stagedDiff:n})},openContextFile:(r,o)=>{const n=A((r||"").trim()),i=$e(o);!n||!i||(e().openContextPanelTab(n,{mode:"file",targetPath:i}),e().setPendingFileFocusPath(i),e().setPendingFileNavigation(null))},openContextFileAtLine:(r,o,n,i)=>{const s=A((r||"").trim()),a=$e(o),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,l=Number.isFinite(i)?Math.max(1,Math.trunc(i)):1;!s||!a||(e().openContextPanelTab(s,{mode:"file",targetPath:a}),e().setPendingFileFocusPath(null),e().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:r=>{const o=A((r||"").trim());o&&e().openContextPanelTab(o,{mode:"context"})},openContextPlan:r=>{const o=A((r||"").trim());o&&e().openContextPanelTab(o,{mode:"plan"})},openContextPreview:(r,o)=>{const n=A((r||"").trim()),i=(o||"").trim();if(!n||!i)return;let s=null;try{const a=new URL(i);(a.protocol==="http:"||a.protocol==="https:")&&(s=a.host||a.hostname||"Preview")}catch{}e().openContextPanelTab(n,{mode:"preview",targetPath:i,dedupeKey:i,label:s})},openContextBrowser:(r,o="")=>{const n=A((r||"").trim());if(!n)return;const i=typeof o=="string"&&o.trim().length>0?o.trim():"";e().openContextPanelTab(n,{mode:"browser",targetPath:i,dedupeKey:"desktop-browser",label:"Browser"})},setContextPanelTabTargetPath:(r,o,n)=>{const i=A((r||"").trim()),s=(o||"").trim();!i||!s||t(a=>{const c=a.contextPanelByDirectory[i];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[i]:Ii(c,s,n)}}:a})},setActiveContextPanelTab:(r,o)=>{const n=A((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=$(a);if(!c.tabs.some(d=>d.id===i)||c.activeTabId===i&&c.isOpen)return s;const l={...s.contextPanelByDirectory,[n]:{...c,isOpen:!0,activeTabId:i,touchedAt:Date.now(),tabs:c.tabs.map(d=>d.id===i?{...d,touchedAt:Date.now()}:d)}};return{contextPanelByDirectory:G(l,20)}})},reorderContextPanelTabs:(r,o,n)=>{const i=A((r||"").trim()),s=(o||"").trim(),a=(n||"").trim();!i||!s||!a||t(c=>{const l=c.contextPanelByDirectory[i],d=$(l);if(!d.tabs.some(y=>y.id===s)||!d.tabs.some(y=>y.id===a))return c;const f=Ri(d,s,a);if(f.tabs===d.tabs)return c;const g={...c.contextPanelByDirectory,[i]:f};return{contextPanelByDirectory:G(g,20)}})},closeContextPanelTab:(r,o)=>{const n=A((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=$(a);if(!c.tabs.some(d=>d.id===i))return s;const l={...s.contextPanelByDirectory,[n]:Oi(c,i)};return{contextPanelByDirectory:G(l,20)}})},closeContextPanel:r=>{const o=A((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o];if(!i||!i.isOpen)return n;const s={...n.contextPanelByDirectory,[o]:{...$(i),isOpen:!1}};return{contextPanelByDirectory:G(s,20)}})},toggleContextPanelExpanded:r=>{const o=A((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o],s=$(i),a={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:G(a,20)}})},setContextPanelWidth:(r,o)=>{const n=A((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=$(s),c={...i.contextPanelByDirectory,[n]:{...a,width:Oo(o)}};return{contextPanelByDirectory:G(c,20)}})},toggleBottomTerminal:()=>{t(r=>{const o=!r.isBottomTerminalOpen;if(o&&typeof window<"u"){const n=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:o,bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:o}})},setBottomTerminalOpen:r=>{t(o=>{if(o.isBottomTerminalOpen===r){if(!r)return o;if(!o.hasManuallyResizedBottomTerminal&&typeof window<"u"){const n=Math.floor(window.innerHeight*.32);return o.bottomTerminalHeight===n&&o.hasManuallyResizedBottomTerminal===!1?o:{isBottomTerminalOpen:r,bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!1}}return o}if(r&&typeof window<"u"){const n=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:r,bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:r}})},setBottomTerminalExpanded:r=>{t({isBottomTerminalExpanded:r})},setBottomTerminalHeight:r=>{t({bottomTerminalHeight:r,hasManuallyResizedBottomTerminal:!0})},setNotesPanelHeight:r=>{t({notesPanelHeight:r})},setTodoPanelHeight:r=>{t({todoPanelHeight:r})},setSessionSwitcherOpen:r=>{e().isSessionSwitcherOpen!==r&&t({isSessionSwitcherOpen:r})},setSessionDropdownOpen:r=>{e().isSessionDropdownOpen!==r&&t({isSessionDropdownOpen:r})},setMainTabGuard:r=>{e().mainTabGuard!==r&&t({mainTabGuard:r})},setActiveMainTab:r=>{const o=e().mainTabGuard;o&&!o(r)||(yt.set(gt(),r),t({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{yt.set(gt(r),e().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=yt.get(gt(r))??"chat";t({activeMainTab:o})},setPendingDiffFile:(r,o=!1)=>{t({pendingDiffFile:r,pendingDiffStaged:r?o:!1})},setPendingDiagramFile:r=>{t({pendingDiagramFile:r})},setPendingFileNavigation:r=>{t({pendingFileNavigation:r})},setPendingFileFocusPath:r=>{t({pendingFileFocusPath:r})},navigateToDiff:(r,o=!1)=>{const n=e().mainTabGuard;n&&!n("diff")||t({pendingDiffFile:r,pendingDiffStaged:o,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:r}=e();return r&&t({pendingDiffFile:null,pendingDiffStaged:!1}),r},navigateToDiagram:r=>{const o=e().mainTabGuard;o&&!o("diagram")||t({pendingDiagramFile:r,activeMainTab:"diagram"})},consumePendingDiagramFile:()=>{const{pendingDiagramFile:r}=e();return r&&t({pendingDiagramFile:null}),r},setIsMobile:r=>{t({isMobile:r})},toggleCommandPalette:()=>{t(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen}))},setCommandPaletteOpen:r=>{t({isCommandPaletteOpen:r})},toggleHelpDialog:()=>{t(r=>({isHelpDialogOpen:!r.isHelpDialogOpen}))},setHelpDialogOpen:r=>{t({isHelpDialogOpen:r})},setAboutDialogOpen:r=>{t({isAboutDialogOpen:r})},setOpenCodeStatusDialogOpen:r=>{t({isOpenCodeStatusDialogOpen:r})},setOpenCodeStatusText:r=>{t({openCodeStatusText:r})},setSessionCreateDialogOpen:r=>{t({isSessionCreateDialogOpen:r})},setScheduledTasksDialogOpen:r=>{t({isScheduledTasksDialogOpen:r})},setSettingsDialogOpen:r=>{t(o=>r?o.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:r=>{t({isNewWorktreeDialogOpen:r})},setModelSelectorOpen:r=>{t({isModelSelectorOpen:r})},setSidebarSection:r=>{t({sidebarSection:r})},setSettingsPage:r=>{t({settingsPage:r})},setSettingsProjectsSelectedId:r=>{t({settingsProjectsSelectedId:r})},setSettingsRemoteInstancesSelectedId:r=>{t({settingsRemoteInstancesSelectedId:r})},setEventStreamStatus:(r,o)=>{t({eventStreamStatus:r,eventStreamHint:o??null})},setShowReasoningTraces:r=>{t({showReasoningTraces:r})},setSessionRecapEnabled:r=>{t({sessionRecapEnabled:r})},setSessionSuggestionEnabled:r=>{t({sessionSuggestionEnabled:r})},setCollapsibleThinkingBlocks:r=>{t({collapsibleThinkingBlocks:r})},setChatRenderMode:r=>{t({chatRenderMode:r})},setActivityRenderMode:r=>{t({activityRenderMode:r})},setShowDeletionDialog:r=>{t({showDeletionDialog:r})},setAutoDeleteEnabled:r=>{t({autoDeleteEnabled:r})},setAutoDeleteAfterDays:r=>{const o=Math.max(1,Math.min(365,r));t({autoDeleteAfterDays:o})},setSessionRetentionAction:r=>{t({sessionRetentionAction:r})},setAutoDeleteLastRunAt:r=>{t({autoDeleteLastRunAt:r})},setMessageLimit:r=>{const o=Math.max(10,Math.min(500,Math.round(r)));t({messageLimit:o})},setFontSize:r=>{const o=Math.max(50,Math.min(200,r));t({fontSize:o}),e().applyTypography()},setGlobalDraftStarters:r=>{t({globalDraftStarters:r})},setTerminalFontSize:r=>{const o=Math.round(r),n=Math.max(9,Math.min(52,o));t({terminalFontSize:n})},setUiFont:r=>{t({uiFont:r})},setMonoFont:r=>{t({monoFont:r})},setPadding:r=>{const o=Math.max(50,Math.min(200,r));t({padding:o}),e().applyPadding()},setCornerRadius:r=>{t({cornerRadius:r})},applyTypography:()=>{const{fontSize:r}=e(),o=document.documentElement,n=r/100,i=Object.entries(hi);if(n===1){for(const[s]of i)o.style.removeProperty(Sr(s));return}for(const[s,a]of i){const c=parseFloat(a);Number.isFinite(c)&&o.style.setProperty(Sr(s),`${c*n}rem`)}},applyPadding:()=>{const{padding:r}=e(),o=document.documentElement,n=r/100;if(n===1){o.style.removeProperty("--padding-scale"),o.style.removeProperty("--line-height-tight"),o.style.removeProperty("--line-height-normal"),o.style.removeProperty("--line-height-relaxed"),o.style.removeProperty("--line-height-loose");return}const i=Math.sqrt(n);o.style.setProperty("--padding-scale",i.toString());const s=1+(n-1)*.15;o.style.setProperty("--line-height-tight",(1.25*s).toFixed(3)),o.style.setProperty("--line-height-normal",(1.5*s).toFixed(3)),o.style.setProperty("--line-height-relaxed",(1.625*s).toFixed(3)),o.style.setProperty("--line-height-loose",(2*s).toFixed(3))},setDiffLayoutPreference:r=>{t({diffLayoutPreference:r})},setDiffFileLayout:(r,o)=>{t(n=>({diffFileLayout:{...n.diffFileLayout,[r]:o}}))},setDiffWrapLines:r=>{t({diffWrapLines:r})},setGitChangesViewMode:r=>{t({gitChangesViewMode:r})},setInputBarOffset:r=>{t({inputBarOffset:r})},setMobileKeyboardMode:r=>{t(o=>o.mobileKeyboardMode===r?o:{mobileKeyboardMode:r})},toggleFavoriteModel:(r,o)=>{t(n=>n.favoriteModels.some(s=>s.providerID===r&&s.modelID===o)?{favoriteModels:n.favoriteModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{favoriteModels:[{providerID:r,modelID:o},...n.favoriteModels]})},reorderFavoriteModel:(r,o,n,i)=>{t(s=>{const a=s.favoriteModels.findIndex(f=>f.providerID===r&&f.modelID===o),c=s.favoriteModels.findIndex(f=>f.providerID===n&&f.modelID===i);if(a===-1||c===-1||a===c)return s;const l=s.favoriteModels.slice(),[d]=l.splice(a,1);return d?(l.splice(c,0,d),{favoriteModels:l}):s})},setProviderOrder:r=>{t(o=>{const n=r.filter(s=>typeof s=="string"&&s.length>0),i=o.providerOrder;return i.length===n.length&&i.every((s,a)=>s===n[a])?o:{providerOrder:n}})},toggleHiddenModel:(r,o)=>{t(n=>n.hiddenModels.some(s=>s.providerID===r&&s.modelID===o)?{hiddenModels:n.hiddenModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{hiddenModels:[{providerID:r,modelID:o},...n.hiddenModels]})},isHiddenModel:(r,o)=>{const{hiddenModels:n}=e();return n.some(i=>i.providerID===r&&i.modelID===o)},hideAllModels:(r,o)=>{t(n=>{const i=n.hiddenModels.filter(a=>a.providerID!==r);return{hiddenModels:[...o.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:r,modelID:a})),...i]}})},showAllModels:r=>{t(o=>({hiddenModels:o.hiddenModels.filter(n=>n.providerID!==r)}))},toggleModelProviderCollapsed:r=>{const o=typeof r=="string"?r.trim():"";o&&t(n=>n.collapsedModelProviders.includes(o)?{collapsedModelProviders:n.collapsedModelProviders.filter(s=>s!==o)}:{collapsedModelProviders:[...n.collapsedModelProviders,o]})},setModelProvidersCollapsed:(r,o)=>{const n=Array.from(new Set(r.filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)));n.length!==0&&t(i=>{const s=new Set(n),a=i.collapsedModelProviders.filter(c=>!s.has(c));return{collapsedModelProviders:o?[...a,...n]:a}})},isFavoriteModel:(r,o)=>{const{favoriteModels:n}=e();return n.some(i=>i.providerID===r&&i.modelID===o)},addRecentModel:(r,o)=>{t(n=>{const i=n.recentModels.filter(s=>!(s.providerID===r&&s.modelID===o));return{recentModels:[{providerID:r,modelID:o},...i].slice(0,5)}})},addRecentAgent:r=>{const o=typeof r=="string"?r.trim():"";o&&t(n=>{if(n.recentAgents.includes(o))return n;const i=n.recentAgents;return{recentAgents:[o,...i].slice(0,5)}})},addRecentEffort:(r,o,n)=>{const i=typeof r=="string"?r.trim():"",s=typeof o=="string"?o.trim():"";if(!i||!s)return;const a=`${i}/${s}`,c=typeof n=="string"&&n.trim().length>0?n.trim():"default";t(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"||t(r=>{const o={};if(r.isBottomTerminalOpen&&!r.hasManuallyResizedBottomTerminal){const n=Math.floor(window.innerHeight*.32);r.bottomTerminalHeight!==n&&(o.bottomTerminalHeight=n)}return Object.keys(o).length>0?o:r})},applyTheme:()=>{const{theme:r}=e(),o=document.documentElement;if(o.classList.remove("light","dark"),r==="system"){const n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(n)}else o.classList.add(r)},setMultiRunLauncherOpen:r=>{t(o=>({isMultiRunLauncherOpen:r,multiRunLauncherPrefillPrompt:r?o.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:r=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:r,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:r=>{t({isTimelineDialogOpen:r})},setImagePreviewOpen:r=>{t({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{t({nativeNotificationsEnabled:r})},setNotificationMode:r=>{t({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{t({showTerminalQuickKeysOnDesktop:r})},setNotifyOnSubtasks:r=>{t({notifyOnSubtasks:r})},setDockBadgeEnabled:r=>{t({dockBadgeEnabled:r})},setNotifyOnCompletion:r=>{t({notifyOnCompletion:r})},setNotifyOnError:r=>{t({notifyOnError:r})},setNotifyOnQuestion:r=>{t({notifyOnQuestion:r})},setNotificationTemplates:r=>{t({notificationTemplates:r})},setSummarizeLastMessage:r=>{t({summarizeLastMessage:r})},setSummaryThreshold:r=>{t({summaryThreshold:r})},setSummaryLength:r=>{t({summaryLength:r})},setMaxLastMessageLength:r=>{t({maxLastMessageLength:r})},setPersistChatDraft:r=>{t({persistChatDraft:r})},setShowOpenCodeUpdateNotifications:r=>{t({showOpenCodeUpdateNotifications:r})},setInputSpellcheckEnabled:r=>{t({inputSpellcheckEnabled:r})},setWideChatLayoutEnabled:r=>{t({wideChatLayoutEnabled:r})},setShowToolFileIcons:r=>{t({showToolFileIcons:r})},setShowTurnChangedFiles:r=>{t({showTurnChangedFiles:r})},setShowExpandedBashTools:r=>{t({showExpandedBashTools:r})},setShowExpandedEditTools:r=>{t({showExpandedEditTools:r})},setTimeFormatPreference:r=>{t({timeFormatPreference:r})},setWeekStartPreference:r=>{t({weekStartPreference:r})},setMermaidRenderingMode:r=>{t({mermaidRenderingMode:r})},setUserMessageRenderingMode:r=>{t({userMessageRenderingMode:r})},setCollapsibleUserMessages:r=>{t({collapsibleUserMessages:r})},setStickyUserHeader:r=>{t({stickyUserHeader:r})},setExpandedEditorToolbar:r=>{t({expandedEditorToolbar:r})},setShowSplitAssistantMessageActions:r=>{t({showSplitAssistantMessageActions:r})},setIsMobileSessionStatusBarCollapsed:r=>{t({isMobileSessionStatusBarCollapsed:r})},setMobileSessionPanelOpen:r=>{t({mobileSessionPanelOpen:r})},setMobileSessionFilterProjectId:r=>{t({mobileSessionFilterProjectId:r})},setReportUsage:r=>{t({reportUsage:r})},viewPagerPage:"center",setViewPagerPage:r=>{t({viewPagerPage:r}),t(r==="left"?{isSessionSwitcherOpen:!0,isRightSidebarOpen:!1}:r==="right"?{isRightSidebarOpen:!0,isSessionSwitcherOpen:!1}:{isSessionSwitcherOpen:!1,isRightSidebarOpen:!1})},setShortcutOverride:(r,o)=>{t(n=>({shortcutOverrides:{...n.shortcutOverrides,[r]:o}}))},clearShortcutOverride:r=>{t(o=>{const n={...o.shortcutOverrides};return delete n[r],{shortcutOverrides:n}})},resetAllShortcutOverrides:()=>{t({shortcutOverrides:{}})},setFileEditorKeymap:r=>{t({fileEditorKeymap:vr(r)})},toggleExpandedInput:()=>{t(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{t({isExpandedInput:r})}}),{name:"ui-store",storage:vo(),version:10,migrate:(t,e)=>{if(!t||typeof t!="object")return t;const r=t;if(e<10&&delete r.diffViewMode,e<9&&((typeof r.notesPanelHeight!="number"||!Number.isFinite(r.notesPanelHeight))&&(r.notesPanelHeight=112),(typeof r.todoPanelHeight!="number"||!Number.isFinite(r.todoPanelHeight))&&(r.todoPanelHeight=259)),e<1&&ki(r.notificationTemplates)&&(r.notificationTemplates={completion:{...B.completion},error:{...B.error},question:{...B.question},subtask:{...B.subtask}}),e<3){const o=new Set([90,120,180,220]),n=r.memoryLimitHistorical,i=r.memoryLimitActiveSession;typeof n=="number"&&!o.has(n)?r.messageLimit=n:typeof i=="number"&&!o.has(i)&&(r.messageLimit=i),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=wt(r.contextPanelByDirectory),e<5)if(!r.shortcutOverrides||typeof r.shortcutOverrides!="object")r.shortcutOverrides={};else{const o=r.shortcutOverrides,n={};for(const[i,s]of Object.entries(o))typeof i=="string"&&typeof s=="string"&&(n[i]=s);r.shortcutOverrides=n}return e<6&&(r.contextPanelByDirectory=wt(r.contextPanelByDirectory)),e<7&&(r.contextPanelByDirectory=wt(r.contextPanelByDirectory)),e<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=vr(r.fileEditorKeymap),r},partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isRightSidebarOpen:t.isRightSidebarOpen,rightSidebarWidth:t.rightSidebarWidth,rightSidebarTab:t.rightSidebarTab,contextPanelByDirectory:t.contextPanelByDirectory,isBottomTerminalOpen:t.isBottomTerminalOpen,isBottomTerminalExpanded:t.isBottomTerminalExpanded,bottomTerminalHeight:t.bottomTerminalHeight,notesPanelHeight:t.notesPanelHeight,todoPanelHeight:t.todoPanelHeight,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,settingsPage:t.settingsPage,settingsHasOpenedOnce:t.settingsHasOpenedOnce,settingsProjectsSelectedId:t.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:t.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,showReasoningTraces:t.showReasoningTraces,sessionRecapEnabled:t.sessionRecapEnabled,sessionSuggestionEnabled:t.sessionSuggestionEnabled,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,showDeletionDialog:t.showDeletionDialog,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,sessionRetentionAction:t.sessionRetentionAction,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,fontSize:t.fontSize,globalDraftStarters:t.globalDraftStarters,terminalFontSize:t.terminalFontSize,uiFont:t.uiFont,monoFont:t.monoFont,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,providerOrder:t.providerOrder,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,gitChangesViewMode:t.gitChangesViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,showTerminalQuickKeysOnDesktop:t.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:t.notifyOnSubtasks,dockBadgeEnabled:t.dockBadgeEnabled,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,persistChatDraft:t.persistChatDraft,showOpenCodeUpdateNotifications:t.showOpenCodeUpdateNotifications,inputSpellcheckEnabled:t.inputSpellcheckEnabled,wideChatLayoutEnabled:t.wideChatLayoutEnabled,showToolFileIcons:t.showToolFileIcons,showTurnChangedFiles:t.showTurnChangedFiles,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,timeFormatPreference:t.timeFormatPreference,weekStartPreference:t.weekStartPreference,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,collapsibleUserMessages:t.collapsibleUserMessages,stickyUserHeader:t.stickyUserHeader,expandedEditorToolbar:t.expandedEditorToolbar,showSplitAssistantMessageActions:t.showSplitAssistantMessageActions,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed,mobileSessionFilterProjectId:t.mobileSessionFilterProjectId,shortcutOverrides:t.shortcutOverrides,fileEditorKeymap:t.fileEditorKeymap})}),{name:"ui-store"})),jo="queue",Vt=t=>t==="steer"||t==="queue",Jt=(t,e)=>t==="immediate"?"steer":Vt(t)?t:e===!1?"steer":e===!0?"queue":jo,Fi=Je()(Qe(Hr((t,e)=>({queuedMessages:{},followUpBehavior:jo,addToQueue:(r,o)=>{const i={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:o.content,attachments:o.attachments,createdAt:Date.now(),sendConfig:o.sendConfig};t(s=>{const a=s.queuedMessages[r]??[];return{queuedMessages:{...s.queuedMessages,[r]:[...a,i]}}})},removeFromQueue:(r,o)=>{t(n=>{const s=(n.queuedMessages[r]??[]).filter(a=>a.id!==o);if(s.length===0){const{[r]:a,...c}=n.queuedMessages;return{queuedMessages:c}}return{queuedMessages:{...n.queuedMessages,[r]:s}}})},reorderQueue:(r,o,n)=>{o!==n&&t(i=>{const s=i.queuedMessages[r];if(!s)return i;const a=s.findIndex(f=>f.id===o),c=s.findIndex(f=>f.id===n);if(a===-1||c===-1)return i;const l=s.slice(),[d]=l.splice(a,1);return l.splice(c,0,d),{queuedMessages:{...i.queuedMessages,[r]:l}}})},popToInput:(r,o)=>{const s=(e().queuedMessages[r]??[]).find(a=>a.id===o);return s?(t(a=>{const l=(a.queuedMessages[r]??[]).filter(d=>d.id!==o);if(l.length===0){const{[r]:d,...f}=a.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...a.queuedMessages,[r]:l}}}),s):null},clearQueue:r=>{t(o=>{const{[r]:n,...i}=o.queuedMessages;return{queuedMessages:i}})},clearAllQueues:()=>{t({queuedMessages:{}})},setFollowUpBehavior:r=>{t({followUpBehavior:r}),U({followUpBehavior:r})},getQueueForSession:r=>e().queuedMessages[r]??[]}),{name:"message-queue-store",version:1,storage:vo(),partialize:t=>({queuedMessages:t.queuedMessages,followUpBehavior:t.followUpBehavior}),migrate:t=>{const e=t??{};return{queuedMessages:e.queuedMessages??{},followUpBehavior:Jt(e.followUpBehavior,e.queueModeEnabled??null)}}}),{name:"message-queue-store"})),Lo="directoryTreeShowHidden",Mt="directory-show-hidden-change",kr=()=>{if(typeof window>"u")return!0;try{const t=Te().getItem(Lo);return t===null?!0:t==="true"}catch{return!0}},_i=()=>{typeof window>"u"||window.dispatchEvent(new Event(Mt))},xi=(t,e={})=>{if(!(typeof window>"u")){try{Te().setItem(Lo,t?"true":"false"),_i()}catch{}e.persist!==!1&&U({directoryShowHidden:t})}},Wc=()=>{const t=zr.c(2),[e,r]=je.useState(kr);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(kr())};return window.addEventListener("storage",i),window.addEventListener(Mt,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(Mt,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),je.useEffect(o,n),e},No="filesViewShowGitignored",Ct="files-view-show-gitignored-change",Dr=()=>{if(typeof window>"u")return!1;try{return Te().getItem(No)==="true"}catch{return!1}},ji=()=>{typeof window>"u"||window.dispatchEvent(new Event(Ct))},Li=(t,e={})=>{if(!(typeof window>"u")){try{Te().setItem(No,t?"true":"false"),ji()}catch{}e.persist!==!1&&U({filesViewShowGitignored:t})}},qc=()=>{const t=zr.c(2),[e,r]=je.useState(Dr);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(Dr())};return window.addEventListener("storage",i),window.addEventListener(Ct,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(Ct,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),je.useEffect(o,n),e},Ni=t=>{if(!t||typeof t!="object")return null;const e={};return typeof t.showReasoningTraces=="boolean"&&(e.showReasoningTraces=t.showReasoningTraces),typeof t.collapsibleThinkingBlocks=="boolean"&&(e.collapsibleThinkingBlocks=t.collapsibleThinkingBlocks),Object.keys(e).length>0?e:null},Ui=t=>{if(!t||typeof t!="object")return null;const e=t;return{showReasoningTraces:e.showReasoningTraces,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks}},Bi=t=>{const e=L.getState();typeof t.showReasoningTraces=="boolean"&&e.setShowReasoningTraces(t.showReasoningTraces),typeof t.collapsibleThinkingBlocks=="boolean"&&e.setCollapsibleThinkingBlocks(t.collapsibleThinkingBlocks)},Hi=async()=>{if(typeof window>"u")return null;const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const e=JSON.parse(t),r=Ui(e);return Ni(r)}catch(e){return console.warn("Failed to parse stored appearance preferences:",e),null}},Uo=[{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"}],zi=new Map(Uo.map(t=>[t.name,t])),Kc=t=>zi.get(t),Vc=Uo.map(t=>({type:"command",name:t.name})),Jc="terminal-box",Qc="book-open",Yc=t=>`${t.type}:${t.name}`,Xc=(t,e)=>t.type===e.type&&t.name===e.name,Zc=t=>{const e=t.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):t},Bo=t=>{if(!Array.isArray(t))return[];const e=[],r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const n=o,i=n.type==="command"||n.type==="skill"?n.type:null,s=typeof n.name=="string"?n.name.trim():"";if(!i||!s)continue;const a=`${i}:${s}`;r.has(a)||(r.add(a),e.push({type:i,name:s}))}return e},$i=t=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=t}catch{}},Ot=t=>{if(!(typeof window>"u")){if(t.themeId&&localStorage.setItem("selectedThemeId",t.themeId),t.themeVariant&&localStorage.setItem("selectedThemeVariant",t.themeVariant),t.lightThemeId&&localStorage.setItem("lightThemeId",t.lightThemeId),t.darkThemeId&&localStorage.setItem("darkThemeId",t.darkThemeId),typeof t.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(t.useSystemTheme)),t.lastDirectory&&localStorage.setItem("lastDirectory",t.lastDirectory),t.homeDirectory&&(localStorage.setItem("homeDirectory",t.homeDirectory),$i(t.homeDirectory)),Array.isArray(t.projects)&&t.projects.length>0?localStorage.setItem("projects",JSON.stringify(t.projects)):localStorage.removeItem("projects"),t.activeProjectId?localStorage.setItem("activeProjectId",t.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(t.pinnedDirectories)&&t.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(t.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(t.projects)&&t.projects.length>0){const e=t.projects.filter(r=>r.sidebarCollapsed===!0).map(r=>r.id).filter(r=>typeof r=="string"&&r.length>0);e.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(e)):localStorage.removeItem("oc.sessions.projectCollapse")}if(typeof t.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(t.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof t.directoryShowHidden=="boolean"&&localStorage.setItem("directoryTreeShowHidden",t.directoryShowHidden?"true":"false"),typeof t.filesViewShowGitignored=="boolean"&&localStorage.setItem("filesViewShowGitignored",t.filesViewShowGitignored?"true":"false"),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&localStorage.setItem("openInAppId",t.openInAppId),typeof t.pwaAppName=="string"){const e=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);e.length>0?localStorage.setItem("openchamber.pwaName",e):localStorage.removeItem("openchamber.pwaName")}if(typeof t.mobileKeyboardMode=="string"&&Mo(t.mobileKeyboardMode),typeof t.openCodeUpdateToastDismissedVersion=="string"){const e=t.openCodeUpdateToastDismissedVersion.trim();e?localStorage.setItem("opencode-update-toast-dismissed-version",e):localStorage.removeItem("opencode-update-toast-dismissed-version")}typeof t.dictationEnabled=="boolean"&&localStorage.setItem("dictationEnabled",String(t.dictationEnabled)),(t.sttProvider==="local"||t.sttProvider==="openai-compatible")&&localStorage.setItem("sttProvider",t.sttProvider),typeof t.sttServerUrl=="string"&&localStorage.setItem("sttServerUrl",t.sttServerUrl),typeof t.sttModel=="string"&&localStorage.setItem("sttModel",t.sttModel),typeof t.sttLocalModel=="string"&&localStorage.setItem("sttLocalModel",t.sttLocalModel),typeof t.sttLanguage=="string"&&localStorage.setItem("sttLanguage",t.sttLanguage)}},Rt=t=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))},Gi=t=>{if(!Array.isArray(t))return;const e=[],r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const n=o,i=typeof n.id=="string"?n.id.trim():"",s=typeof n.label=="string"?n.label.trim():"",a=typeof n.source=="string"?n.source.trim():"",c=typeof n.subpath=="string"?n.subpath.trim():"",l=typeof n.gitIdentityId=="string"?n.gitIdentityId.trim():"";!i||!s||!a||r.has(i)||(r.add(i),e.push({id:i,label:s,source:a,...c?{subpath:c}:{},...l?{gitIdentityId:l}:{}}))}return e},Wi=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const e={};for(const[r,o]of Object.entries(t)){const n=typeof r=="string"?r.trim():"",i=typeof o=="string"?o.trim():"";!n||!i||(e[n]=i)}return e},qi=(t,e)=>{const r=Object.entries(t),o=Object.entries(e);return r.length!==o.length?!1:r.every(([n,i])=>e[n]===i)},bt=(t,e)=>t.length===e.length&&t.every((r,o)=>r.providerID===e[o]?.providerID&&r.modelID===e[o]?.modelID),It=(t,e)=>t.length===e.length&&t.every((r,o)=>r===e[o]),Ft=t=>{if(Array.isArray(t))return Array.from(new Set(t.filter(e=>typeof e=="string"&&e.length>0)))},Ki=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const e={};for(const[r,o]of Object.entries(t)){if(!r||!Array.isArray(o))continue;const n=Ft(o);n&&n.length>0&&(e[r]=n.slice(0,5))}return Object.keys(e).length>0?e:void 0},Vi=(t,e)=>{const r=Object.keys(t);return r.length!==Object.keys(e).length?!1:r.every(o=>Array.isArray(e[o])&&It(t[o],e[o]))},Ji=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Qi=t=>{if(typeof t!="string")return null;const e=t.trim();return e&&Ji.test(e)?e.toLowerCase():null},Yi=t=>{if(!Array.isArray(t))return;const e=[],r=new Set,o=new Set;for(const n of t){if(!n||typeof n!="object")continue;const i=n,s=typeof i.path=="string"?i.path.trim():"";if(!s)continue;const a=s==="/"?s:s.replace(/\\/g,"/").replace(/\/+$/,"");if(!a)continue;const c=li(a);if(!c||r.has(c)||o.has(a))continue;r.add(c),o.add(a);const l={id:c,path:a};if(typeof i.label=="string"&&i.label.trim().length>0&&(l.label=i.label.trim()),typeof i.icon=="string"&&i.icon.trim().length>0&&(l.icon=i.icon.trim()),i.iconImage===null)l.iconImage=null;else if(i.iconImage&&typeof i.iconImage=="object"){const d=i.iconImage,f=typeof d.mime=="string"?d.mime.trim():"",g=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,y=d.source==="custom"||d.source==="auto"?d.source:null;f&&g>0&&y&&(l.iconImage={mime:f,updatedAt:g,source:y})}if(typeof i.color=="string"&&i.color.trim().length>0&&(l.color=i.color.trim()),i.iconBackground===null)l.iconBackground=null;else{const d=Qi(i.iconBackground);d&&(l.iconBackground=d)}typeof i.addedAt=="number"&&Number.isFinite(i.addedAt)&&i.addedAt>=0&&(l.addedAt=i.addedAt),typeof i.lastOpenedAt=="number"&&Number.isFinite(i.lastOpenedAt)&&i.lastOpenedAt>=0&&(l.lastOpenedAt=i.lastOpenedAt),typeof i.sidebarCollapsed=="boolean"&&(l.sidebarCollapsed=i.sidebarCollapsed),e.push(l)}return e.length>0?e:void 0},Xi=t=>{if(!Array.isArray(t))return;const e=[],r=new Set,o=new Set;for(const n of t){if(!n||typeof n!="object")continue;const i=n,s=typeof i.id=="string"?i.id.trim():"",a=typeof i.name=="string"?i.name.trim():"",c=typeof i.hostname=="string"?i.hostname.trim().toLowerCase():"";!s||!a||!c||r.has(s)||o.has(c)||(r.add(s),o.add(c),e.push({id:s,name:a,hostname:c}))}return e},Zi=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const e=t,r={};for(const[o,n]of Object.entries(e)){const i=o.trim(),s=typeof n=="string"?n.trim():"";!i||!s||(r[i]=s)}return Object.keys(r).length>0?r:void 0},St=(t,e)=>{if(!Array.isArray(t))return;const r=[],o=new Set;for(const n of t){if(!n||typeof n!="object")continue;const i=n,s=typeof i.providerID=="string"?i.providerID.trim():"",a=typeof i.modelID=="string"?i.modelID.trim():"";if(!s||!a)continue;const c=`${s}/${a}`;if(!o.has(c)&&(o.add(c),r.push({providerID:s,modelID:a}),r.length>=e))break}return r},Ho=()=>{const t=L.persist;if(t&&typeof t=="object")return t},zo=()=>tt()?.settings??null,_t=t=>{const e=L.getState(),r=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,o=typeof window<"u"?window.__zustand_config_store__??null:null,n=Fi.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==e.showReasoningTraces&&e.setShowReasoningTraces(t.showReasoningTraces),typeof t.sessionRecapEnabled=="boolean"&&t.sessionRecapEnabled!==e.sessionRecapEnabled&&e.setSessionRecapEnabled(t.sessionRecapEnabled),typeof t.sessionSuggestionEnabled=="boolean"&&t.sessionSuggestionEnabled!==e.sessionSuggestionEnabled&&e.setSessionSuggestionEnabled(t.sessionSuggestionEnabled),typeof t.collapsibleThinkingBlocks=="boolean"&&t.collapsibleThinkingBlocks!==e.collapsibleThinkingBlocks&&e.setCollapsibleThinkingBlocks(t.collapsibleThinkingBlocks),typeof t.autoDeleteEnabled=="boolean"&&t.autoDeleteEnabled!==e.autoDeleteEnabled&&e.setAutoDeleteEnabled(t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)){const s=Math.max(1,Math.min(365,t.autoDeleteAfterDays));s!==e.autoDeleteAfterDays&&e.setAutoDeleteAfterDays(s)}(t.sessionRetentionAction==="archive"||t.sessionRetentionAction==="delete")&&t.sessionRetentionAction!==e.sessionRetentionAction&&e.setSessionRetentionAction(t.sessionRetentionAction);let i=null;if(Vt(t.followUpBehavior)?i=t.followUpBehavior:typeof t.queueModeEnabled=="boolean"&&(i=Jt(void 0,t.queueModeEnabled)),i&&i!==n.followUpBehavior&&n.setFollowUpBehavior(i),typeof t.showDeletionDialog=="boolean"&&t.showDeletionDialog!==e.showDeletionDialog&&e.setShowDeletionDialog(t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&t.nativeNotificationsEnabled!==e.nativeNotificationsEnabled&&e.setNativeNotificationsEnabled(t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&t.notificationMode!==e.notificationMode&&e.setNotificationMode(t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&t.notifyOnSubtasks!==e.notifyOnSubtasks&&e.setNotifyOnSubtasks(t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&t.notifyOnCompletion!==e.notifyOnCompletion&&e.setNotifyOnCompletion(t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&t.notifyOnError!==e.notifyOnError&&e.setNotifyOnError(t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&t.notifyOnQuestion!==e.notifyOnQuestion&&e.setNotifyOnQuestion(t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"&&e.setNotificationTemplates(t.notificationTemplates),typeof t.summarizeLastMessage=="boolean"&&t.summarizeLastMessage!==e.summarizeLastMessage&&e.setSummarizeLastMessage(t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&e.setSummaryThreshold(t.summaryThreshold),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&e.setSummaryLength(t.summaryLength),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&e.setMaxLastMessageLength(t.maxLastMessageLength),typeof t.inputSpellcheckEnabled=="boolean"&&t.inputSpellcheckEnabled!==e.inputSpellcheckEnabled&&e.setInputSpellcheckEnabled(t.inputSpellcheckEnabled),typeof t.showOpenCodeUpdateNotifications=="boolean"&&t.showOpenCodeUpdateNotifications!==e.showOpenCodeUpdateNotifications&&e.setShowOpenCodeUpdateNotifications(t.showOpenCodeUpdateNotifications),typeof t.showToolFileIcons=="boolean"&&t.showToolFileIcons!==e.showToolFileIcons&&e.setShowToolFileIcons(t.showToolFileIcons),typeof t.showTurnChangedFiles=="boolean"&&t.showTurnChangedFiles!==e.showTurnChangedFiles&&e.setShowTurnChangedFiles(t.showTurnChangedFiles),typeof t.showExpandedBashTools=="boolean"&&t.showExpandedBashTools!==e.showExpandedBashTools&&e.setShowExpandedBashTools(t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&t.showExpandedEditTools!==e.showExpandedEditTools&&e.setShowExpandedEditTools(t.showExpandedEditTools),typeof t.timeFormatPreference=="string"&&(t.timeFormatPreference==="auto"||t.timeFormatPreference==="12h"||t.timeFormatPreference==="24h")&&t.timeFormatPreference!==e.timeFormatPreference&&e.setTimeFormatPreference(t.timeFormatPreference),typeof t.weekStartPreference=="string"&&(t.weekStartPreference==="auto"||t.weekStartPreference==="sunday"||t.weekStartPreference==="monday")&&t.weekStartPreference!==e.weekStartPreference&&e.setWeekStartPreference(t.weekStartPreference),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&t.chatRenderMode!==e.chatRenderMode&&e.setChatRenderMode(t.chatRenderMode),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&t.activityRenderMode!==e.activityRenderMode&&e.setActivityRenderMode(t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&t.mermaidRenderingMode!==e.mermaidRenderingMode&&e.setMermaidRenderingMode(t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&t.userMessageRenderingMode!==e.userMessageRenderingMode&&e.setUserMessageRenderingMode(t.userMessageRenderingMode),typeof t.collapsibleUserMessages=="boolean"&&t.collapsibleUserMessages!==e.collapsibleUserMessages&&e.setCollapsibleUserMessages(t.collapsibleUserMessages),typeof t.messageStreamTransport=="string"&&(t.messageStreamTransport==="auto"||t.messageStreamTransport==="ws"||t.messageStreamTransport==="sse")&&r&&t.messageStreamTransport!==r.settingsMessageStreamTransport&&r.setSettingsMessageStreamTransport(t.messageStreamTransport),typeof t.stickyUserHeader=="boolean"&&t.stickyUserHeader!==e.stickyUserHeader&&e.setStickyUserHeader(t.stickyUserHeader),typeof t.expandedEditorToolbar=="boolean"&&t.expandedEditorToolbar!==e.expandedEditorToolbar&&e.setExpandedEditorToolbar(t.expandedEditorToolbar),typeof t.wideChatLayoutEnabled=="boolean"&&t.wideChatLayoutEnabled!==e.wideChatLayoutEnabled&&e.setWideChatLayoutEnabled(t.wideChatLayoutEnabled),typeof t.showSplitAssistantMessageActions=="boolean"&&t.showSplitAssistantMessageActions!==e.showSplitAssistantMessageActions&&e.setShowSplitAssistantMessageActions(t.showSplitAssistantMessageActions),typeof t.reportUsage=="boolean"&&t.reportUsage!==e.reportUsage&&e.setReportUsage(t.reportUsage),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&t.fontSize!==e.fontSize&&e.setFontSize(t.fontSize),Array.isArray(t.draftStarters)){const s=Bo(t.draftStarters);JSON.stringify(e.globalDraftStarters)!==JSON.stringify(s)&&e.setGlobalDraftStarters(s)}if(typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&t.terminalFontSize!==e.terminalFontSize&&e.setTerminalFontSize(t.terminalFontSize),Ao(t.uiFont)&&t.uiFont!==e.uiFont&&e.setUiFont(t.uiFont),Po(t.monoFont)&&t.monoFont!==e.monoFont&&e.setMonoFont(t.monoFont),typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding!==e.padding&&e.setPadding(t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&t.cornerRadius!==e.cornerRadius&&e.setCornerRadius(t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&t.inputBarOffset!==e.inputBarOffset&&e.setInputBarOffset(t.inputBarOffset),t.shortcutOverrides&&!qi(t.shortcutOverrides,e.shortcutOverrides)&&L.setState({shortcutOverrides:t.shortcutOverrides}),typeof t.mobileKeyboardMode=="string"){const s=nt(t.mobileKeyboardMode,e.mobileKeyboardMode);s!==e.mobileKeyboardMode&&e.setMobileKeyboardMode(s)}if(o&&r){const s={};typeof t.dictationEnabled=="boolean"&&t.dictationEnabled!==r.dictationEnabled&&(s.dictationEnabled=t.dictationEnabled),(t.sttProvider==="local"||t.sttProvider==="openai-compatible")&&t.sttProvider!==r.sttProvider&&(s.sttProvider=t.sttProvider),typeof t.sttServerUrl=="string"&&t.sttServerUrl!==r.sttServerUrl&&(s.sttServerUrl=t.sttServerUrl),typeof t.sttModel=="string"&&t.sttModel!==r.sttModel&&(s.sttModel=t.sttModel),typeof t.sttLocalModel=="string"&&t.sttLocalModel!==r.sttLocalModel&&(s.sttLocalModel=t.sttLocalModel),typeof t.sttLanguage=="string"&&t.sttLanguage!==r.sttLanguage&&(s.sttLanguage=t.sttLanguage),Object.keys(s).length>0&&o.setState(s)}if(Array.isArray(t.favoriteModels)){const s=e.favoriteModels,a=t.favoriteModels;bt(s,a)||L.setState({favoriteModels:a})}if(Array.isArray(t.hiddenModels)){const s=e.hiddenModels,a=t.hiddenModels;bt(s,a)||L.setState({hiddenModels:a})}if(Array.isArray(t.collapsedModelProviders)){const s=e.collapsedModelProviders,a=t.collapsedModelProviders;It(s,a)||L.setState({collapsedModelProviders:a})}if(Array.isArray(t.recentModels)){const s=e.recentModels,a=t.recentModels;bt(s,a)||L.setState({recentModels:a})}if(Array.isArray(t.recentAgents)){const s=e.recentAgents,a=t.recentAgents;It(s,a)||L.setState({recentAgents:a})}if(t.recentEfforts&&typeof t.recentEfforts=="object"){const s=e.recentEfforts,a=t.recentEfforts;Vi(s,a)||L.setState({recentEfforts:a})}typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&t.diffLayoutPreference!==e.diffLayoutPreference&&e.setDiffLayoutPreference(t.diffLayoutPreference),typeof t.gitChangesViewMode=="string"&&(t.gitChangesViewMode==="flat"||t.gitChangesViewMode==="tree")&&t.gitChangesViewMode!==e.gitChangesViewMode&&e.setGitChangesViewMode(t.gitChangesViewMode),typeof t.directoryShowHidden=="boolean"&&xi(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&Li(t.filesViewShowGitignored,{persist:!1})},Ar=t=>{if(!t||typeof t!="object")return null;const e=t,r={};if(typeof e.themeId=="string"&&e.themeId.length>0&&(r.themeId=e.themeId),(e.useSystemTheme===!0||e.useSystemTheme===!1)&&(r.useSystemTheme=e.useSystemTheme),typeof e.themeVariant=="string"&&(e.themeVariant==="light"||e.themeVariant==="dark")&&(r.themeVariant=e.themeVariant),typeof e.lightThemeId=="string"&&e.lightThemeId.length>0&&(r.lightThemeId=e.lightThemeId),typeof e.darkThemeId=="string"&&e.darkThemeId.length>0&&(r.darkThemeId=e.darkThemeId),typeof e.lastDirectory=="string"&&e.lastDirectory.length>0&&(r.lastDirectory=e.lastDirectory),typeof e.homeDirectory=="string"&&e.homeDirectory.length>0&&(r.homeDirectory=e.homeDirectory),typeof e.opencodeBinary=="string"){const p=e.opencodeBinary.trim();r.opencodeBinary=p.length>0?p:void 0}typeof e.desktopLanAccessEnabled=="boolean"&&(r.desktopLanAccessEnabled=e.desktopLanAccessEnabled);const o=Yi(e.projects);if(o&&(r.projects=o),typeof e.activeProjectId=="string"&&e.activeProjectId.length>0&&(r.activeProjectId=e.activeProjectId),Array.isArray(e.securityScopedBookmarks)&&(r.securityScopedBookmarks=e.securityScopedBookmarks.filter(p=>typeof p=="string"&&p.length>0)),Array.isArray(e.pinnedDirectories)&&(r.pinnedDirectories=Array.from(new Set(e.pinnedDirectories.filter(p=>typeof p=="string"&&p.length>0)))),Array.isArray(e.draftStarters)&&(r.draftStarters=Bo(e.draftStarters)),typeof e.showReasoningTraces=="boolean"&&(r.showReasoningTraces=e.showReasoningTraces),typeof e.sessionRecapEnabled=="boolean"&&(r.sessionRecapEnabled=e.sessionRecapEnabled),typeof e.sessionSuggestionEnabled=="boolean"&&(r.sessionSuggestionEnabled=e.sessionSuggestionEnabled),typeof e.collapsibleThinkingBlocks=="boolean"&&(r.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled=="boolean"&&(r.autoDeleteEnabled=e.autoDeleteEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)&&(r.autoDeleteAfterDays=e.autoDeleteAfterDays),(e.sessionRetentionAction==="archive"||e.sessionRetentionAction==="delete")&&(r.sessionRetentionAction=e.sessionRetentionAction),typeof e.tunnelProvider=="string"){const p=e.tunnelProvider.trim().toLowerCase();p.length>0&&(r.tunnelProvider=p)}if(typeof e.tunnelMode=="string"){const p=e.tunnelMode.trim().toLowerCase();(p==="quick"||p==="managed-remote"||p==="managed-local")&&(r.tunnelMode=p)}if(e.tunnelBootstrapTtlMs===null?r.tunnelBootstrapTtlMs=null:typeof e.tunnelBootstrapTtlMs=="number"&&Number.isFinite(e.tunnelBootstrapTtlMs)&&(r.tunnelBootstrapTtlMs=e.tunnelBootstrapTtlMs),typeof e.tunnelSessionTtlMs=="number"&&Number.isFinite(e.tunnelSessionTtlMs)&&(r.tunnelSessionTtlMs=e.tunnelSessionTtlMs),e.managedLocalTunnelConfigPath===null)r.managedLocalTunnelConfigPath=null;else if(typeof e.managedLocalTunnelConfigPath=="string"){const p=e.managedLocalTunnelConfigPath.trim();r.managedLocalTunnelConfigPath=p.length>0?p:null}typeof e.managedRemoteTunnelHostname=="string"&&(r.managedRemoteTunnelHostname=e.managedRemoteTunnelHostname.trim()),e.managedRemoteTunnelToken===null?r.managedRemoteTunnelToken=null:typeof e.managedRemoteTunnelToken=="string"&&(r.managedRemoteTunnelToken=e.managedRemoteTunnelToken.trim());const n=Xi(e.managedRemoteTunnelPresets);if(n&&(r.managedRemoteTunnelPresets=n),typeof e.managedRemoteTunnelSelectedPresetId=="string"){const p=e.managedRemoteTunnelSelectedPresetId.trim();r.managedRemoteTunnelSelectedPresetId=p.length>0?p:void 0}const i=Zi(e.managedRemoteTunnelPresetTokens);if(i&&(r.managedRemoteTunnelPresetTokens=i),typeof e.defaultModel=="string"&&e.defaultModel.length>0&&(r.defaultModel=e.defaultModel),typeof e.defaultVariant=="string"&&e.defaultVariant.length>0&&(r.defaultVariant=e.defaultVariant),typeof e.defaultAgent=="string"&&e.defaultAgent.length>0&&(r.defaultAgent=e.defaultAgent),typeof e.smallModelUseDefault=="boolean"&&(r.smallModelUseDefault=e.smallModelUseDefault),typeof e.smallModelOverride=="string"&&e.smallModelOverride.length>0&&(r.smallModelOverride=e.smallModelOverride),typeof e.autoCreateWorktree=="boolean"&&(r.autoCreateWorktree=e.autoCreateWorktree),typeof e.gitmojiEnabled=="boolean"&&(r.gitmojiEnabled=e.gitmojiEnabled),Vt(e.followUpBehavior)?r.followUpBehavior=e.followUpBehavior:typeof e.queueModeEnabled=="boolean"&&(r.followUpBehavior=Jt(void 0,e.queueModeEnabled)),typeof e.showDeletionDialog=="boolean"&&(r.showDeletionDialog=e.showDeletionDialog),typeof e.nativeNotificationsEnabled=="boolean"&&(r.nativeNotificationsEnabled=e.nativeNotificationsEnabled),typeof e.notificationMode=="string"&&(e.notificationMode==="always"||e.notificationMode==="hidden-only")&&(r.notificationMode=e.notificationMode),typeof e.notifyOnSubtasks=="boolean"&&(r.notifyOnSubtasks=e.notifyOnSubtasks),typeof e.notifyOnCompletion=="boolean"&&(r.notifyOnCompletion=e.notifyOnCompletion),typeof e.notifyOnError=="boolean"&&(r.notifyOnError=e.notifyOnError),typeof e.notifyOnQuestion=="boolean"&&(r.notifyOnQuestion=e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates=="object"){const p=e.notificationTemplates,w=v=>{const it=p[v];if(!it||typeof it!="object")return;const Ee=it,Zo=typeof Ee.title=="string"?Ee.title:"",en=typeof Ee.message=="string"?Ee.message:"";return{title:Zo,message:en}},b=w("completion"),T=w("error"),k=w("question"),S=w("subtask");(b||T||k||S)&&(r.notificationTemplates={completion:b??{title:"Task Complete",message:"Your task has finished."},error:T??{title:"Error Occurred",message:"An error occurred while processing your task."},question:k??{title:"Input Needed",message:"Please provide input to continue."},subtask:S??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof e.summarizeLastMessage=="boolean"&&(r.summarizeLastMessage=e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&(r.summaryThreshold=Math.max(0,Math.round(e.summaryThreshold))),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&(r.summaryLength=Math.max(10,Math.round(e.summaryLength))),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&(r.maxLastMessageLength=Math.max(10,Math.round(e.maxLastMessageLength))),typeof e.usageAutoRefresh=="boolean"&&(r.usageAutoRefresh=e.usageAutoRefresh),typeof e.usageRefreshIntervalMs=="number"&&Number.isFinite(e.usageRefreshIntervalMs)&&(r.usageRefreshIntervalMs=e.usageRefreshIntervalMs),(e.usageDisplayMode==="usage"||e.usageDisplayMode==="remaining")&&(r.usageDisplayMode=e.usageDisplayMode),typeof e.usageShowPredValues=="boolean"&&(r.usageShowPredValues=e.usageShowPredValues),Array.isArray(e.usageDropdownProviders)&&(r.usageDropdownProviders=e.usageDropdownProviders.filter(p=>typeof p=="string"&&p.length>0)),e.usageSelectedModels&&typeof e.usageSelectedModels=="object"){const p={};for(const[w,b]of Object.entries(e.usageSelectedModels))Array.isArray(b)&&(p[w]=b.filter(T=>typeof T=="string"));Object.keys(p).length>0&&(r.usageSelectedModels=p)}if(e.usageCollapsedFamilies&&typeof e.usageCollapsedFamilies=="object"){const p={};for(const[w,b]of Object.entries(e.usageCollapsedFamilies))Array.isArray(b)&&(p[w]=b.filter(T=>typeof T=="string"));Object.keys(p).length>0&&(r.usageCollapsedFamilies=p)}if(e.usageExpandedFamilies&&typeof e.usageExpandedFamilies=="object"){const p={};for(const[w,b]of Object.entries(e.usageExpandedFamilies))Array.isArray(b)&&(p[w]=b.filter(T=>typeof T=="string"));Object.keys(p).length>0&&(r.usageExpandedFamilies=p)}if(e.usageModelGroups&&typeof e.usageModelGroups=="object"){const p={};for(const[w,b]of Object.entries(e.usageModelGroups))if(b&&typeof b=="object"){const T=b,k={};Array.isArray(T.customGroups)&&(k.customGroups=T.customGroups.filter(S=>S&&typeof S=="object").map(S=>({id:String(S.id??""),label:String(S.label??""),models:Array.isArray(S.models)?S.models.filter(v=>typeof v=="string"):[],order:typeof S.order=="number"?S.order:0}))),T.modelAssignments&&typeof T.modelAssignments=="object"&&(k.modelAssignments=Object.fromEntries(Object.entries(T.modelAssignments).filter(([,S])=>typeof S=="string").map(([S,v])=>[S,String(v)]))),T.renamedGroups&&typeof T.renamedGroups=="object"&&(k.renamedGroups=Object.fromEntries(Object.entries(T.renamedGroups).filter(([,S])=>typeof S=="string").map(([S,v])=>[S,String(v)]))),Object.keys(k).length>0&&(p[w]=k)}Object.keys(p).length>0&&(r.usageModelGroups=p)}typeof e.inputSpellcheckEnabled=="boolean"&&(r.inputSpellcheckEnabled=e.inputSpellcheckEnabled),typeof e.showOpenCodeUpdateNotifications=="boolean"&&(r.showOpenCodeUpdateNotifications=e.showOpenCodeUpdateNotifications),typeof e.openCodeUpdateToastDismissedVersion=="string"&&(r.openCodeUpdateToastDismissedVersion=e.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof e.showToolFileIcons=="boolean"&&(r.showToolFileIcons=e.showToolFileIcons),typeof e.showTurnChangedFiles=="boolean"&&(r.showTurnChangedFiles=e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&(r.showExpandedBashTools=e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&(r.showExpandedEditTools=e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&(r.timeFormatPreference=e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&(r.weekStartPreference=e.weekStartPreference),typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&(r.chatRenderMode=e.chatRenderMode),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&(r.messageStreamTransport=e.messageStreamTransport),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&(r.activityRenderMode=e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&(r.mermaidRenderingMode=e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&(r.userMessageRenderingMode=e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&(r.collapsibleUserMessages=e.collapsibleUserMessages),typeof e.stickyUserHeader=="boolean"&&(r.stickyUserHeader=e.stickyUserHeader),typeof e.wideChatLayoutEnabled=="boolean"&&(r.wideChatLayoutEnabled=e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&(r.showSplitAssistantMessageActions=e.showSplitAssistantMessageActions),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&(r.fontSize=e.fontSize),typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&(r.terminalFontSize=e.terminalFontSize),Ao(e.uiFont)&&(r.uiFont=e.uiFont),Po(e.monoFont)&&(r.monoFont=e.monoFont),typeof e.padding=="number"&&Number.isFinite(e.padding)&&(r.padding=e.padding),typeof e.cornerRadius=="number"&&Number.isFinite(e.cornerRadius)&&(r.cornerRadius=e.cornerRadius),typeof e.inputBarOffset=="number"&&Number.isFinite(e.inputBarOffset)&&(r.inputBarOffset=e.inputBarOffset);const s=Wi(e.shortcutOverrides);s&&(r.shortcutOverrides=s),typeof e.mobileKeyboardMode=="string"&&(e.mobileKeyboardMode==="native"||e.mobileKeyboardMode==="resize-content")&&(r.mobileKeyboardMode=e.mobileKeyboardMode);const a=St(e.favoriteModels,64);a&&(r.favoriteModels=a);const c=St(e.hiddenModels,1024);c&&(r.hiddenModels=c);const l=Ft(e.collapsedModelProviders);l&&(r.collapsedModelProviders=l);const d=St(e.recentModels,16);d&&(r.recentModels=d);const f=Ft(e.recentAgents);f&&(r.recentAgents=f);const g=Ki(e.recentEfforts);if(g&&(r.recentEfforts=g),typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&(r.diffLayoutPreference=e.diffLayoutPreference),typeof e.gitChangesViewMode=="string"&&(e.gitChangesViewMode==="flat"||e.gitChangesViewMode==="tree")&&(r.gitChangesViewMode=e.gitChangesViewMode),typeof e.directoryShowHidden=="boolean"&&(r.directoryShowHidden=e.directoryShowHidden),typeof e.filesViewShowGitignored=="boolean"&&(r.filesViewShowGitignored=e.filesViewShowGitignored),typeof e.openInAppId=="string"&&e.openInAppId.length>0&&(r.openInAppId=e.openInAppId),typeof e.pwaAppName=="string"){const p=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);r.pwaAppName=p.length>0?p:""}const y=Gi(e.skillCatalogs);return y&&(r.skillCatalogs=y),typeof e.reportUsage=="boolean"&&(r.reportUsage=e.reportUsage),typeof e.globalBehaviorPrompt=="string"&&(r.globalBehaviorPrompt=e.globalBehaviorPrompt),typeof e.responseStyleEnabled=="boolean"&&(r.responseStyleEnabled=e.responseStyleEnabled),typeof e.responseStylePreset=="string"&&(e.responseStylePreset==="concise"||e.responseStylePreset==="detailed"||e.responseStylePreset==="mentor"||e.responseStylePreset==="pushback"||e.responseStylePreset==="noFiller"||e.responseStylePreset==="matchEnergy"||e.responseStylePreset==="warmPeer"||e.responseStylePreset==="custom")&&(r.responseStylePreset=e.responseStylePreset),typeof e.responseStyleCustomInstructions=="string"&&(r.responseStyleCustomInstructions=e.responseStyleCustomInstructions),typeof e.dictationEnabled=="boolean"&&(r.dictationEnabled=e.dictationEnabled),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?r.sttProvider=e.sttProvider:e.sttProvider==="server"?r.sttProvider="openai-compatible":(e.sttProvider==="browser"||e.sttProvider==="wasm")&&(r.sttProvider="local"),typeof e.sttServerUrl=="string"&&(r.sttServerUrl=e.sttServerUrl.trim()),typeof e.sttModel=="string"&&(r.sttModel=e.sttModel.trim()),typeof e.sttLocalModel=="string"&&(r.sttLocalModel=e.sttLocalModel.trim()),typeof e.sttLanguage=="string"&&(r.sttLanguage=e.sttLanguage.trim()),r};let K=null,le=null;const es=2e3,ts=async()=>K&&Date.now()-K.at<es?K.value:le||(le=(async()=>{const t=zo();if(t)try{const e=await t.load(),r=Ar(e.settings);return K={value:r,at:Date.now()},r}catch(e){console.warn("Failed to load shared settings from runtime settings API:",e)}try{const e=await u("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const r=await e.json().catch(()=>null),o=Ar(r);return K={value:o,at:Date.now()},o}catch(e){return console.warn("Failed to load shared settings from server:",e),null}})().finally(()=>{le=null}),le),el=async()=>{if(typeof window>"u")return;const t=Ho(),e=()=>!t?.hasHydrated||t.hasHydrated()||!t.onFinishHydration?Promise.resolve():new Promise(o=>{let n=!1;const i=()=>{n||(n=!0,o())},s=t.onFinishHydration(()=>{s?.(),i()});t.hasHydrated?.()&&i()}),r=async o=>{try{Ot(o)}catch(n){console.warn("persistToLocalStorage failed:",n)}await e();try{_t(o)}catch(n){console.warn("applyDesktopUiPreferences failed:",n)}Rt(o)};try{const o=await ts();o&&await r(o)}catch(o){console.warn("Failed to synchronise settings:",o)}};let We=null,_e=null,xt=[];const rs=200,os=async()=>{const t=We,e=xt;if(We=null,_e=null,xt=[],!t||Object.keys(t).length===0){e.forEach(o=>o());return}const r=zo();if(r)try{const o=await r.save(t);o&&(Ot(o),_t(o),Rt(o),K=null),e.forEach(n=>n());return}catch(o){console.warn("Failed to update settings via runtime settings API:",o)}try{const o=await u("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!o.ok){console.warn("Failed to update shared settings via API:",o.status,o.statusText);return}const n=await o.json().catch(()=>null);n&&(Ot(n),_t(n),Rt(n),K=null)}catch(o){console.warn("Failed to update shared settings via API:",o)}finally{e.forEach(o=>o())}},U=async t=>{if(typeof window>"u")return;We={...We??{},...t},_e&&clearTimeout(_e);const e=new Promise(r=>{xt.push(r)});return _e=setTimeout(()=>{os()},rs),e},tl=async()=>{if(typeof window>"u")return;const t=Ho();try{const e=await Hi();if(!e)return;const r=()=>Bi(e);if(t?.hasHydrated?.()){r();return}if(r(),t?.onFinishHydration){const o=t.onFinishHydration(()=>{o?.(),r()})}}catch(e){console.warn("Failed to load appearance preferences:",e)}},ns=3e4,is=40,ss=60,as=(t,e,r,o,n,i)=>{const s=t.trim(),a=e.trim().toLowerCase();return JSON.stringify([s,a,r,o,n,i])},Pr=(t,e)=>{try{const r=JSON.parse(t);return Array.isArray(r)&&r[0]===e}catch{return!1}},cs=Je()(Qe((t,e)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(r,o,n=ss,i){if(!r||r.trim().length===0)return[];const s=r.trim(),a=typeof o=="string"?o.trim():"",c=!!i?.includeHidden,l=i?.respectGitignore??!0,d=i?.type==="directory"?"directory":"file",f=as(s,a,n,c,l,d),g=Date.now(),y=e().cache[f];if(y&&g-y.timestamp<ns)return y.files;const p=e().inFlight[f];if(p)return p;const w=H.searchFiles(a,{directory:s,limit:n,includeHidden:c,respectGitignore:l,dirs:d!=="file",type:d}).then(b=>(t(T=>{if(T.inFlight[f]!==w)return T;const k={...T.cache,[f]:{files:b,timestamp:Date.now()}},S=T.cacheKeys.filter(v=>v!==f);for(S.push(f);S.length>is;){const v=S.shift();v&&delete k[v]}return{cache:k,cacheKeys:S}}),b)).finally(()=>{t(b=>{if(b.inFlight[f]!==w)return b;const T={...b.inFlight};return delete T[f],{inFlight:T}})});return t(b=>({inFlight:{...b.inFlight,[f]:w}})),w},invalidateDirectory(r){if(!r||r.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=r.trim();t(n=>{const i={...n.cache},s=n.cacheKeys.filter(l=>Pr(l,o)?(delete i[l],!1):!0),a=Object.entries(n.inFlight).filter(([l])=>!Pr(l,o)),c=Object.fromEntries(a);return{cache:i,cacheKeys:s,inFlight:c}})}}),{name:"file-search-store"})),ls=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},jt="openchamber_stream_perf",ve=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(jt)==="1"}catch{return!1}},Mr=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),ds=()=>{if(!ve()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const t=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:t,lastUpdatedAt:t}}return window.__openchamberStreamPerfState},$o=t=>Array.from(t.entries()).map(([e,r])=>({metric:e,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((e,r)=>r.total-e.total||r.count-e.count),Qt=(t,e)=>{const r=ds();if(!r)return;const o=r.counters.get(t)??{count:0,total:0,max:0,last:0};o.count+=1,o.total+=e,o.max=Math.max(o.max,e),o.last=e,r.counters.set(t,o),r.lastUpdatedAt=Date.now()},rl=t=>{if(!(typeof window>"u"))try{if(t){window.localStorage.setItem(jt,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(jt),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},ol=()=>{typeof window>"u"||(ve()&&(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()}))},nl=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberStreamPerfState;return!ve()||!t?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:t.startedAt,lastUpdatedAt:t.lastUpdatedAt,durationMs:Math.max(0,Date.now()-t.startedAt),entries:$o(t.counters)}},il=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberVsCodeStreamPerfState;if(!ve()||!t)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=typeof t.startedAt=="number"?t.startedAt:null,r=typeof t.lastUpdatedAt=="number"?t.lastUpdatedAt:null;return{enabled:!0,startedAt:e,lastUpdatedAt:r,durationMs:e?Math.max(0,Date.now()-e):0,entries:$o(t.counters)}},sl=(t,e=1)=>{Qt(t,e)},al=(t,e)=>{Qt(t,e)},cl=(t,e)=>{if(!ve())return e();const r=Mr();try{return e()}finally{Qt(t,Mr()-r)}};var us={};let _=null,Cr=0;const F=Te(),Or=F.getItem("lastDirectory"),fs=typeof Or=="string"&&Or.length>0,Me=t=>{try{cs.getState().invalidateDirectory(t)}catch(e){console.warn("Failed to invalidate file search cache:",e)}},ne=t=>{const e=t.trim();if(!e)return e;const r=e.replace(/\\/g,"/").replace(/^([a-z]):/,(o,n)=>n.toUpperCase()+":");return r.length>1?r.replace(/\/+$/,""):r},ps=(t,e)=>{const r=t.trim();return r.startsWith("~")?r==="~"?e||r:(r.startsWith("~/")||r.startsWith("~\\"))&&e?`${e}${r.slice(1)}`:r:r},xe=(t,e)=>{const r=ps(t,e);return ne(r)},hs=()=>{const t=F.getItem("homeDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=ne(t);return e.length>0?e:null},ms=()=>{const t=F.getItem("lastDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=ne(t);return e.length>0?e:null},ys=()=>{if(typeof process>"u")return null;const t=us,e=t?.HOME||t?.USERPROFILE||(t?.HOMEDRIVE&&t?.HOMEPATH?`${t.HOMEDRIVE}${t.HOMEPATH}`:void 0);if(typeof e=="string"&&e.trim().length>0){const o=ne(e);return o.length>0?o:null}const r=process?.cwd?.();if(typeof r=="string"&&r.trim().length>0){const o=ne(r);return o.length>0?o:null}return null},qe=()=>{if(typeof window<"u"){if(_)return _;const e=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(e&&e.length>0)return _=e,F.setItem("homeDirectory",e),e;const r=hs();if(r&&!ot())return _=r,r}const t=ys();return t||"/"},gs=t=>{if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const r=e.replace(/\\/g,"/");if(r.length>1){const o=r.replace(/\/+$/,"");if(o&&o.length>0)return o==="/"?null:o}return r==="/"||r.length===0?null:r},ws=t=>(_=t,typeof window<"u"&&F.setItem("homeDirectory",t),U({homeDirectory:t}),t),Lt=async()=>{const t=o=>{const n=gs(o);return n?ws(n):null};try{const o=await H.getFilesystemHome(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain filesystem home directory:",o)}try{const o=await H.getSystemInfo(),n=t(o?.homeDirectory);if(n)return n}catch(o){console.warn("Failed to get home directory from system info:",o)}try{const o=await mo(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain desktop-integrated home directory:",o)}const e=qe(),r=t(e);return r||e},bs=()=>{if(!ot())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const e=ne(t);return e.length>0?e:null},we=bs()||qe(),Ke=(()=>{const t=ms();return t&&!ot()?xe(t,we):we})();Ke&&H.setDirectory(Ke);const Ss=!!(we&&we!=="/"),Nt=Je()(Qe((t,e)=>({currentDirectory:Ke,directoryHistory:[Ke],historyIndex:0,homeDirectory:we,hasPersistedDirectory:fs,isHomeReady:Ss,isSwitchingDirectory:!1,setDirectory:(r,o)=>{const n=_||e().homeDirectory||F.getItem("homeDirectory"),i=xe(r,n);ls()&&console.log("[DirectoryStore] setDirectory called with path:",i),H.setDirectory(i),Me(),t(s=>{const a=[...s.directoryHistory.slice(0,s.historyIndex+1),i];return F.setItem("lastDirectory",i),U({lastDirectory:i}),{currentDirectory:i,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const r=e();if(r.historyIndex>0){const o=r.historyIndex-1,n=r.directoryHistory[o];H.setDirectory(n),Me(),F.setItem("lastDirectory",n),U({lastDirectory:n}),t({currentDirectory:n,historyIndex:o,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const r=e();if(r.historyIndex<r.directoryHistory.length-1){const o=r.historyIndex+1,n=r.directoryHistory[o];H.setDirectory(n),Me(),F.setItem("lastDirectory",n),U({lastDirectory:n}),t({currentDirectory:n,historyIndex:o,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:r,setDirectory:o}=e(),n=_||e().homeDirectory||qe();if(r===n||r==="/")return;const i=r.endsWith("/")?r.slice(0,-1):r,s=i.lastIndexOf("/");if(s===-1){const a=_||qe();o(a)}else o(s===0?"/":i.substring(0,s))},goHome:async()=>{const r=_||e().homeDirectory||await Lt();e().setDirectory(r)},synchronizeHomeDirectory:r=>{const o=e(),n=r;_=n;const i=o.homeDirectory!==n,s=F.getItem("lastDirectory"),a=typeof s=="string"&&s.length>0,c=!a&&(o.currentDirectory==="/"||o.currentDirectory===o.homeDirectory||!o.currentDirectory);if(!i&&!c){o.isHomeReady||t({isHomeReady:!0});return}const l=typeof n=="string"&&n!==""&&n!=="/",d=o.currentDirectory?xe(o.currentDirectory,n):o.currentDirectory,f=o.directoryHistory.map(w=>xe(w,n)),g=f.some((w,b)=>w!==o.directoryHistory[b]),y=!!(d&&d!==o.currentDirectory),p={homeDirectory:n,hasPersistedDirectory:a,isHomeReady:l};if(c?(p.currentDirectory=n,p.directoryHistory=[n],p.historyIndex=0,p.isSwitchingDirectory=!1):(y||g)&&(p.currentDirectory=d,p.directoryHistory=f,p.historyIndex=Math.min(o.historyIndex,f.length-1),p.isSwitchingDirectory=!1),t(()=>p),(c||y)&&l){const w=c?n:d;H.setDirectory(w),Me(),F.setItem("lastDirectory",w),U({lastDirectory:w})}U({homeDirectory:n})}}),{name:"directory-store"}));typeof window<"u"&&(Lt().then(t=>{Nt.getState().synchronizeHomeDirectory(t)}),Fn(()=>{_=null;const t=++Cr;Lt().then(e=>{t===Cr&&Nt.getState().synchronizeHomeDirectory(e)})}));const Go=1,x=1,Ce=0,Wo="/api/terminal/ws",Ts=1200,vs=250,Es=2e4,ks=5e3,Tt="__openchamberTerminalTransportState",Ds=new TextEncoder,Rr=new TextDecoder,Yt=t=>P().websocket(t),vt=t=>{const e=Ds.encode(JSON.stringify(t)),r=new Uint8Array(e.length+1);return r[0]=Go,r.set(e,1),r},be=t=>t?((t.transports??[]).includes("ws")||t.preferred==="ws")&&typeof t.ws?.path=="string"&&t.ws.path.length>0:!1,Xt=t=>t.streamCapability?.ws?.path??t.inputCapability?.ws?.path??Wo,As=t=>{switch(t){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 Ps{socket=null;socketUrl="";boundSessionId=null;requestedSessionId=null;openPromise=null;reconnectTimeout=null;keepaliveInterval=null;closed=!1;subscriptions=new Map;activeSubscriptionToken=null;replayCursorBySession=new Map;configure(e){if(e){if(this.socketUrl===e){this.closed=!1,this.isConnectedOrConnecting()||this.ensureConnected();return}this.socketUrl=e,this.closed=!1,this.resetConnection(),this.ensureConnected()}}subscribe(e,r,o,n){const i=Symbol(e),s={token:i,sessionId:e,onEvent:r,onError:o,maxRetries:n?.maxRetries??3,initialRetryDelay:n?.initialRetryDelay??1e3,maxRetryDelay:n?.maxRetryDelay??8e3,connectionTimeout:n?.connectionTimeout??1e4,retryCount:0,connected:!1,connectionTimeoutId:null};return this.subscriptions.set(i,s),this.activeSubscriptionToken=i,this.boundSessionId=null,this.requestedSessionId=e,this.ensureConnected(),this.startConnectionTimeout(s),this.bindActiveSession(),()=>{this.clearConnectionTimeout(s),this.subscriptions.delete(i),this.activeSubscriptionToken===i&&(this.activeSubscriptionToken=null),this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null),this.subscriptions.size===0&&(this.clearReconnectTimeout(),this.resetConnection())}}async sendInput(e,r){if(!e||!r||this.closed||!this.socketUrl)return!1;const o=await this.getOpenSocket(Ts);if(!o||o.readyState!==x)return!1;try{return this.boundSessionId!==e&&(this.requestedSessionId=e,o.send(vt({t:"b",s:e,r:this.replayCursorBySession.get(e)??0,v:2}))),o.send(r),!0}catch{return this.handleSocketFailure(new Error("Terminal websocket send failed")),!1}}unbindSession(e){e&&(this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null))}close(){this.closed=!0,this.clearReconnectTimeout();for(const e of this.subscriptions.values())this.clearConnectionTimeout(e);this.resetConnection(),this.socketUrl="",this.subscriptions.clear(),this.activeSubscriptionToken=null,this.replayCursorBySession.clear()}prime(){this.closed||!this.socketUrl||this.isConnectedOrConnecting()||this.ensureConnected()}isConnectedOrConnecting(e){return this.closed||e&&this.socketUrl!==e?!1:this.socket&&(this.socket.readyState===x||this.socket.readyState===Ce)?!0:this.openPromise!==null}getActiveSubscription(){return this.activeSubscriptionToken?this.subscriptions.get(this.activeSubscriptionToken)??null:null}startConnectionTimeout(e){this.clearConnectionTimeout(e),e.connectionTimeoutId=setTimeout(()=>{this.getActiveSubscription()?.token!==e.token||e.connected||this.handleSocketFailure(new Error("Connection timeout"))},e.connectionTimeout)}clearConnectionTimeout(e){e.connectionTimeoutId&&(clearTimeout(e.connectionTimeoutId),e.connectionTimeoutId=null)}async getOpenSocket(e){if(this.socket&&this.socket.readyState===x)return this.socket;if(this.ensureConnected(),this.socket&&this.socket.readyState===x)return this.socket;const r=await Promise.race([this.openPromise??Promise.resolve(null),new Promise(o=>{setTimeout(()=>o(null),e)})]);return r&&r.readyState===x?r:this.socket&&this.socket.readyState===x?this.socket:null}ensureConnected(){this.closed||!this.socketUrl||this.socket&&(this.socket.readyState===x||this.socket.readyState===Ce)||this.openPromise||(this.clearReconnectTimeout(),this.openPromise=new Promise(e=>{let r=!1,o=null;const n=i=>{r||(r=!0,o&&(clearTimeout(o),o=null),this.openPromise=null,e(i))};try{const i=new WebSocket(this.socketUrl);i.binaryType="arraybuffer",i.onopen=()=>{this.socket=i,this.startKeepalive(),n(i)},i.onmessage=s=>{this.handleSocketMessage(s.data)},i.onerror=()=>{!this.closed&&!this.getActiveSubscription()&&this.scheduleReconnect(new Error("Terminal websocket error"))},i.onclose=()=>{this.socket===i&&(this.socket=null,this.boundSessionId=null,this.stopKeepalive(),this.closed||this.scheduleReconnect(new Error("Terminal stream connection error"))),n(null)},this.socket=i,o=setTimeout(()=>{i.readyState===Ce&&(i.close(),n(null))},ks)}catch{n(null),this.closed||this.scheduleReconnect(new Error("Terminal websocket open failed"))}}))}bindActiveSession(){const e=this.getActiveSubscription();if(!(!e||!this.socket||this.socket.readyState!==x)){this.requestedSessionId=e.sessionId;try{this.socket.send(vt({t:"b",s:e.sessionId,r:this.replayCursorBySession.get(e.sessionId)??0,v:2}))}catch{this.handleSocketFailure(new Error("Terminal websocket bind failed"))}}}scheduleReconnect(e){if(this.closed||!this.socketUrl||this.reconnectTimeout)return;const r=this.getActiveSubscription();if(!r)return;const o=r.retryCount+1,n=r.initialRetryDelay,i=r.maxRetryDelay,s=r.maxRetries;if(o>s){this.clearConnectionTimeout(r),r.onError?.(e,!0);return}r.retryCount=o,r.connected=!1,r.onEvent({type:"reconnecting",attempt:o,maxAttempts:s}),this.startConnectionTimeout(r);const a=Math.min(n*Math.pow(2,Math.max(o-1,0)),i),c=Math.floor(Math.random()*vs),l=a+c;this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},l)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}sendControl(e){if(!this.socket||this.socket.readyState!==x)return!1;try{return this.socket.send(vt(e)),!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})},Es)}stopKeepalive(){this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null)}async handleSocketMessage(e){const r=await this.asUint8Array(e);if(r&&r.length>0&&r[0]===Go){this.handleControlMessage(r);return}const o=await this.asText(e);if(!o)return;const n=this.getActiveSubscription();n&&n.onEvent({type:"data",data:o})}handleControlMessage(e){if(e.length<2)return;let r;try{r=JSON.parse(Rr.decode(e.subarray(1)))}catch{this.handleSocketFailure(new Error("Terminal websocket control parse failed"));return}const o=this.getActiveSubscription();switch(r.t){case"ok":this.bindActiveSession();return;case"po":return;case"d":{const n=r.s??this.boundSessionId??this.requestedSessionId;if(!o||!n||n!==o.sessionId)return;typeof r.i=="number"&&Number.isFinite(r.i)&&this.replayCursorBySession.set(n,Math.max(this.replayCursorBySession.get(n)??0,Math.trunc(r.i))),typeof r.d=="string"&&r.d.length>0&&o.onEvent({type:"data",data:r.d});return}case"bok":{if(this.boundSessionId=r.s??this.requestedSessionId,!o)return;o.retryCount=0,o.connected=!0,this.clearConnectionTimeout(o),o.onEvent({type:"connected",runtime:r.runtime,ptyBackend:r.ptyBackend});return}case"x":{if(!o){this.boundSessionId=null;return}if(r.s&&r.s!==o.sessionId)return;o.connected=!1,this.clearConnectionTimeout(o),this.boundSessionId=null,this.requestedSessionId=null,this.replayCursorBySession.delete(o.sessionId),o.onEvent({type:"exit",exitCode:r.exitCode,signal:r.signal??null});return}case"e":{const n=As(r.c),i=r.f===!0||r.c==="SESSION_NOT_FOUND";(r.c==="NOT_BOUND"||r.c==="SESSION_NOT_FOUND")&&(this.boundSessionId=null),o&&(o.connected=!1,i&&this.clearConnectionTimeout(o),o.onError?.(n,i)),r.f===!0&&this.handleSocketFailure(n);return}default:return}}async asUint8Array(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return e;if(typeof Blob<"u"&&e instanceof Blob){const r=await e.arrayBuffer();return new Uint8Array(r)}return null}async asText(e){if(typeof e=="string")return e;const r=await this.asUint8Array(e);return r?Rr.decode(r):""}handleSocketFailure(e){this.boundSessionId=null,this.requestedSessionId=null,this.resetConnection(),this.scheduleReconnect(e)}resetConnection(){if(this.openPromise=null,this.stopKeepalive(),this.socket){const e=this.socket;this.socket=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,(e.readyState===x||e.readyState===Ce)&&e.close()}this.boundSessionId=null}}const N=()=>{const t=globalThis;return t[Tt]||(t[Tt]={inputCapability:null,streamCapability:null,manager:null}),t[Tt]},Zt=()=>{const t=N();return t.manager||(t.manager=new Ps),t.manager},qo=t=>{const e=N();if(e.inputCapability=t?.input??null,e.streamCapability=t?.stream??null,!be(e.inputCapability)&&!be(e.streamCapability)){e.manager?.close(),e.manager=null;return}const r=Yt(Xt(e));if(!r)return;Zt().configure(r)},Ms=async(t,e)=>{const r=await u(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to send terminal input"}));throw new Error(o.error||"Failed to send terminal input")}};async function Cs(t){const e=await u("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t.cwd,cols:t.cols??80,rows:t.rows??24})});if(!e.ok){const o=await e.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(o.error||"Failed to create terminal session")}const r=await e.json();return qo(r.capabilities),r}const Ir=(t,e,r,o={})=>{const n=o.maxRetries??3,i=o.initialRetryDelay??1e3,s=o.maxRetryDelay??8e3,a=o.connectionTimeout??1e4;let c=null,l=0,d=null,f=null,g=!1,y=!1;const p=()=>{d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},w=()=>{g||(g=!0,p(),c&&(c.close(),c=null))},b=(k,S)=>{if(!(g||y)){if(l<n&&!S){l+=1;const v=Math.min(i*Math.pow(2,l-1),s);e({type:"reconnecting",attempt:l,maxAttempts:n}),d=setTimeout(()=>{!g&&!y&&T()},v);return}r?.(k,!0),w()}},T=()=>{if(g||y||c&&c.readyState!==EventSource.CLOSED)return;c=new EventSource(P().sse(`/api/terminal/${t}/stream`));let k=!1;f=setTimeout(()=>{!k&&c?.readyState!==EventSource.OPEN&&(c?.close(),b(new Error("Connection timeout"),!1))},a),c.onopen=()=>{k||(k=!0,l=0,p(),e({type:"connected"}))},c.onmessage=S=>{try{const v=JSON.parse(S.data);v.type==="exit"&&(N().manager?.unbindSession(t),y=!0,w()),e(v)}catch(v){r?.(v,!1)}},c.onerror=()=>{p();const S=y||c?.readyState===EventSource.CLOSED;c?.close(),c=null,y||b(new Error("Terminal stream connection error"),S)}};return T(),w};function Os(t,e,r,o={}){const n=N();if(!be(n.streamCapability))return Ir(t,e,r,o);const i=Zt(),s=Yt(Xt(n));return s?(i.configure(s),i.subscribe(t,e,r,o)):Ir(t,e,r,o)}async function Rs(t,e){const r=N();r.manager&&await r.manager.sendInput(t,e)||await Ms(t,e)}async function Is(t,e,r){const o=await u(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:e,rows:r})});if(!o.ok){const n=await o.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(n.error||"Failed to resize terminal")}}async function Fs(t){N().manager?.unbindSession(t);const e=await u(`/api/terminal/${t}`,{method:"DELETE"});if(!e.ok){const r=await e.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(r.error||"Failed to close terminal")}}async function _s(t,e){N().manager?.unbindSession(t);const r=await u(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.cwd,cols:e.cols??80,rows:e.rows??24})});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(n.error||"Failed to restart terminal")}const o=await r.json();return qo(o.capabilities),o}async function xs(t){const e=await u("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok){const r=await e.json().catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}t.sessionId&&N().manager?.unbindSession(t.sessionId)}function ll(){const t=N();t.manager?.close(),t.manager=null,t.inputCapability=null,t.streamCapability=null}function dl(){const t=N();if(t.inputCapability&&t.streamCapability&&!be(t.inputCapability)&&!be(t.streamCapability))return;const e=Xt(t)||Wo,r=Yt(e);if(!r)return;const o=Zt();o.isConnectedOrConnecting(r)||(o.configure(r),o.prime())}const js=t=>{const e=t?.retry;return{maxRetries:e?.maxRetries??3,initialRetryDelay:e?.initialDelayMs??1e3,maxRetryDelay:e?.maxDelayMs??8e3,connectionTimeout:t?.connectionTimeoutMs??1e4}},Ls=()=>({async createSession(t){return Cs(t)},connect(t,e,r){const o=Os(t,e.onEvent,e.onError,js(r));return{close:()=>o()}},async sendInput(t,e){await Rs(t,e)},async resize(t){await Is(t.sessionId,t.cols,t.rows)},async close(t){await Fs(t)},async restartSession(t,e){return _s(t,{cwd:e.cwd??"",cols:e.cols,rows:e.rows})},async forceKill(t){await xs(t)}}),h="/api/git",Ns=1200,Us=5e3,Ve=new Map,te=new Map,Ko=new Map,Fr=new Map,Oe=new Map,Se=t=>t.trim(),Bs=(t,e)=>e==="light"?`${Se(t)}::light`:Se(t),Ut=t=>Ko.get(Se(t))??0,z=t=>{const e=Se(t);Ko.set(e,Ut(t)+1);for(const r of Array.from(Ve.keys()))(r===e||r.startsWith(`${e}::`))&&Ve.delete(r);for(const r of Array.from(te.keys()))(r===e||r.startsWith(`${e}::`))&&te.delete(r)};function m(t,e,r){const o={...r};return e&&(o.directory=e),P().api(t,o)}async function Hs(t){const e=Se(t),r=Date.now(),o=Fr.get(e);if(o&&o.expiresAt>r)return o.value;const n=Oe.get(e);if(n)return n;const i=(async()=>{const s=await u(m(`${h}/check`,t));if(!s.ok)throw new Error(`Failed to check git repository: ${s.statusText}`);const c=!!(await s.json()).isGitRepository;return Fr.set(e,{value:c,expiresAt:Date.now()+Us}),c})();Oe.set(e,i);try{return await i}finally{Oe.get(e)===i&&Oe.delete(e)}}async function zs(t,e){const r=e?.mode,o=Bs(t,r),n=Date.now(),i=Ve.get(o);if(i&&i.expiresAt>n)return i.value;const s=te.get(o);if(s)return s;const a=(async()=>{const c=Ut(t),l=await u(m(`${h}/status`,t,r?{mode:r}:void 0));if(!l.ok)throw new Error(`Failed to get git status: ${l.statusText}`);const d=await l.json();return Ut(t)===c&&Ve.set(o,{value:d,expiresAt:Date.now()+Ns}),d})();te.set(o,a);try{return await a}finally{te.get(o)===a&&te.delete(o)}}async function ul(t){const e=await u(m(`${h}/primary-root`,t));if(!e.ok)throw new Error(`Failed to resolve git primary root: ${e.statusText}`);const r=await e.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:t}}async function fl(t){const e=await u(m(`${h}/toplevel`,t));if(!e.ok)throw new Error(`Failed to resolve git toplevel: ${e.statusText}`);const r=await e.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:t}}async function pl(t,e){const r=await u(m(`${h}/commit-summaries`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:e})});if(!r.ok)throw new Error(`Failed to get git commit summaries: ${r.statusText}`);const o=await r.json().catch(()=>({}));return{commits:Array.isArray(o.commits)?o.commits.map(n=>({sha:typeof n.sha=="string"?n.sha:"",short:typeof n.short=="string"?n.short:"",subject:typeof n.subject=="string"?n.subject:""})).filter(n=>n.sha&&n.short):[]}}async function $s(t,e){const{path:r,staged:o,contextLines:n}=e;if(!r)throw new Error("path is required to fetch git diff");const i=await u(m(`${h}/diff`,t,{path:r,staged:o?"true":void 0,context:n}));if(!i.ok)throw new Error(`Failed to get git diff: ${i.statusText}`);return i.json()}async function Gs(t,e){const{path:r,staged:o}=e;if(!r)throw new Error("path is required to fetch git file diff");const n=await u(m(`${h}/file-diff`,t,{path:r,staged:o?"true":void 0}));if(!n.ok)throw new Error(`Failed to get git file diff: ${n.statusText}`);return n.json()}async function Ws(t,e,r){if(!e)throw new Error("path is required to revert git changes");const o=await u(m(`${h}/revert`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,scope:r?.scope})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to revert git changes")}z(t)}async function qs(t,e){await Vo(t,[e])}async function Vo(t,e){const r=e.map(n=>n.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to stage git changes");const o=await u(m(`${h}/stage`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to stage git changes")}z(t)}async function Ks(t,e){await Jo(t,[e])}async function Jo(t,e){const r=e.map(n=>n.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to unstage git changes");const o=await u(m(`${h}/unstage`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to unstage git changes")}z(t)}async function Vs(t,e,r){await er(t,e,r,"stage")}async function Js(t,e,r){await er(t,e,r,"unstage")}async function Qs(t,e,r){await er(t,e,r,"discard")}async function er(t,e,r,o){if(!e)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 n=await u(m(`${h}/apply-hunk`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,patch:r,action:o})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to apply git hunk")}z(t)}async function Ys(t){if(!t)return!1;const e=await u(m(`${h}/worktree-type`,t));if(!e.ok)throw new Error(`Failed to detect worktree type: ${e.statusText}`);return!!(await e.json()).linked}async function Xs(t){const e=await u(m(`${h}/branches`,t));if(!e.ok)throw new Error(`Failed to get branches: ${e.statusText}`);return e.json()}async function Zs(t,e){if(!e?.branch)throw new Error("branch is required to delete a branch");const r=await u(m(`${h}/branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete branch")}return r.json()}async function ea(t,e){if(!e?.branch)throw new Error("branch is required to delete remote branch");const r=await u(m(`${h}/remote-branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete remote branch")}return r.json()}async function ta(t,e){const r=e?.remote?.trim();if(!r)throw new Error("remote is required to remove a remote");const o=await u(m(`${h}/remotes`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to remove remote")}return o.json()}async function ra(t,e,r){if(!Array.isArray(e)||e.length===0)throw new Error("No files provided to generate commit message");const o={files:e};r?.zenModel&&(o.zenModel=r.zenModel),r?.providerId&&(o.providerId=r.providerId),r?.modelId&&(o.modelId=r.modelId);const n=await u(m(`${h}/commit-message`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!n.ok){const c=await n.json().catch(()=>({error:n.statusText}));console.error("[git-generation][browser] http error",{status:n.status,statusText:n.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const i=await n.json();if(!i?.message||typeof i.message!="object")throw new Error("Malformed commit generation response");const s=typeof i.message.subject=="string"&&i.message.subject.trim().length>0?i.message.subject.trim():"",a=Array.isArray(i.message.highlights)?i.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:s,highlights:a}}}async function oa(t,e){const{base:r,head:o,context:n,zenModel:i,providerId:s,modelId:a}=e;if(!r||!o)throw new Error("base and head are required");const c={base:r,head:o};n?.trim()&&(c.context=n.trim()),i&&(c.zenModel=i),s&&(c.providerId=s),a&&(c.modelId=a);const l=await u(m(`${h}/pr-description`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const y=await l.json().catch(()=>({error:l.statusText}));throw new Error(y.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),f=typeof d?.title=="string"?d.title:"",g=typeof d?.body=="string"?d.body:"";if(!f&&!g)throw new Error("Malformed PR description response");return{title:f,body:g}}async function _r(t){const e=await u(m(`${h}/worktrees`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to list worktrees")}return e.json()}async function xr(t,e){const r=await u(m(`${h}/worktrees/validate`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to validate worktree")}return r.json()}async function na(t){const e=await u(m(`${h}/worktrees/bootstrap-status`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to get worktree bootstrap status")}return e.json()}async function ia(t,e){const r=await u(m(`${h}/worktrees/preview`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to preview worktree")}return r.json()}async function jr(t,e){const r=await u(m(`${h}/worktrees`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create worktree")}return r.json()}async function Lr(t,e){const r=await u(m(`${h}/worktrees`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete worktree")}return r.json()}async function sa(t,e,r={}){const o=await u(m(`${h}/commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e,addAll:r.addAll??!1,files:r.files,stageFiles:r.stageFiles})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to create commit")}const n=await o.json();return z(t),n}async function aa(t,e={}){const r=await u(m(`${h}/push`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to push")}const o=await r.json();return z(t),o}async function ca(t,e={}){const r=await u(m(`${h}/pull`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to pull")}const o=await r.json();return z(t),o}async function la(t,e={}){const r=await u(m(`${h}/fetch`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to fetch")}const o=await r.json();return z(t),o}async function da(t){const e=await u(m(`${h}/stashes`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to list stashes")}return e.json()}async function ua(t,e){const r=await u(m(`${h}/stashes/file-counts`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to count stash files")}return r.json()}async function Qo(t,e={}){const r=await u(m(`${h}/stash`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to stash changes")}return r.json()}const tr=async(t,e,r)=>{const o=await u(m(`${h}/${e}`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||`Failed to ${e}`)}return o.json()},fa=(t,e)=>tr(t,"stash/apply",e),Yo=(t,e)=>tr(t,"stash/pop",e),pa=(t,e)=>tr(t,"stash/drop",e);async function ha(t,e){const r=await u(m(`${h}/checkout`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to checkout branch")}return r.json()}async function ma(t,e,r){const o=await u(m(`${h}/branches`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,startPoint:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to create branch")}return o.json()}async function ya(t,e,r){const o=await u(m(`${h}/branches/rename`,t),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:e,newName:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to rename branch")}return o.json()}async function ga(t,e={}){const r=await u(m(`${h}/log`,t,{maxCount:e.maxCount,from:e.from,to:e.to,file:e.file,all:e.all?"true":void 0}));if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(`Failed to get git log: ${o.error||r.statusText}`)}return r.json()}async function wa(t,e){const r=await u(m(`${h}/commit-files`,t,{hash:e}));if(!r.ok)throw new Error(`Failed to get commit files: ${r.statusText}`);return r.json()}async function hl(t,e,r,o){const n=await u(m(`${h}/commit-file-diff`,t,{hash:e,path:r,binary:o?"true":void 0}));if(!n.ok)throw new Error(`Failed to get commit file diff: ${n.statusText}`);return n.json()}async function ba(){const t=await u(m(`${h}/identities`,void 0));if(!t.ok)throw new Error(`Failed to get git identities: ${t.statusText}`);return t.json()}async function Sa(t){const e=await u(m(`${h}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to create git identity")}return e.json()}async function Ta(t,e){const r=await u(m(`${h}/identities/${t}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to update git identity")}return r.json()}async function va(t){const e=await u(m(`${h}/identities/${t}`,void 0),{method:"DELETE"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to delete git identity")}}async function Ea(t){if(!t)return null;const e=await u(m(`${h}/current-identity`,t));if(!e.ok)throw new Error(`Failed to get current git identity: ${e.statusText}`);const r=await e.json();return r?{userName:r.userName??null,userEmail:r.userEmail??null,sshCommand:r.sshCommand??null}:null}async function ka(t){if(!t)return!1;const e=await u(m(`${h}/has-local-identity`,t));if(!e.ok)throw new Error(`Failed to check local identity: ${e.statusText}`);return(await e.json().catch(()=>null))?.hasLocalIdentity===!0}async function ml(){const t=await u(m(`${h}/global-identity`,void 0));if(!t.ok)throw new Error(`Failed to get global git identity: ${t.statusText}`);const e=await t.json();return!e||!e.userName&&!e.userEmail?null:{userName:e.userName??null,userEmail:e.userEmail??null,sshCommand:e.sshCommand??null}}async function Da(t,e){const r=await u(m(`${h}/set-identity`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to set git identity")}return r.json()}async function yl(){const t=await u(m(`${h}/discover-credentials`,void 0));if(!t.ok)throw new Error(`Failed to discover git credentials: ${t.statusText}`);return t.json()}async function gl(t,e){if(!t)return null;const r=await u(m(`${h}/remote-url`,t,{remote:e}));return r.ok?(await r.json()).url??null:null}async function Aa(t){const e=await u(m(`${h}/remotes`,t));if(!e.ok)throw new Error(`Failed to get remotes: ${e.statusText}`);return e.json()}async function Pa(t,e){const r=await u(m(`${h}/rebase`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rebase")}return r.json()}async function Ma(t){const e=await u(m(`${h}/rebase/abort`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to abort rebase")}return e.json()}async function Ca(t,e){const r=await u(m(`${h}/merge`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to merge")}return r.json()}async function Oa(t,e){const r=await u(m(`${h}/checkout-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to checkout commit")}return r.json()}async function Ra(t,e){const r=await u(m(`${h}/cherry-pick`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to cherry-pick")}return r.json()}async function Ia(t,e){const r=await u(m(`${h}/revert-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to revert commit")}return r.json()}async function Fa(t,e,r,o){const n=await u(m(`${h}/reset-to-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e,mode:r,force:o})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to reset")}return n.json()}async function _a(t){const e=await u(m(`${h}/merge/abort`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to abort merge")}return e.json()}async function xa(t){const e=await u(m(`${h}/rebase/continue`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to continue rebase")}return e.json()}async function ja(t){const e=await u(m(`${h}/merge/continue`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to continue merge")}return e.json()}async function La(t,e){return await Qo(t,{message:e?.message}),{success:!0}}async function Na(t){return await Yo(t,{ref:"stash@{0}"}),{success:!0}}async function Ua(t){const e=await u(m(`${h}/conflict-details`,t));if(!e.ok)throw new Error(`Failed to get conflict details: ${e.statusText}`);return e.json()}async function Ba(t,e){const r=await u(`${h}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t,worktreeRoot:e})});if(!r.ok)throw new Error(`Failed to validate worktree directory: ${r.statusText}`);return r.json()}async function Ha(t){const e=await u(`${h}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!e.ok)throw new Error(`Failed to canonicalize worktree state: ${e.statusText}`);return e.json()}const za=()=>({checkIsGitRepository:Hs,getGitStatus:zs,getGitDiff:$s,getGitFileDiff:Gs,revertGitFile:Ws,stageGitFile:qs,stageGitFiles:Vo,unstageGitFile:Ks,unstageGitFiles:Jo,stageGitHunk:Vs,unstageGitHunk:Js,revertGitHunk:Qs,isLinkedWorktree:Ys,getGitBranches:Xs,deleteGitBranch:Zs,deleteRemoteBranch:ea,removeRemote:ta,generateCommitMessage:ra,generatePullRequestDescription:oa,listGitWorktrees:_r,validateGitWorktree:xr,createGitWorktree:jr,deleteGitWorktree:Lr,validateWorktreeDirectory:Ba,canonicalizeWorktreeState:Ha,createGitCommit(t,e,r){return sa(t,e,r)},gitPush:aa,gitPull:ca,gitFetch:la,listGitStashes:da,countGitStashFiles:ua,stashGitChanges:Qo,applyGitStash:fa,popGitStash:Yo,dropGitStash:pa,checkoutBranch:ha,createBranch:ma,renameBranch:ya,getGitLog(t,e){return ga(t,e)},getCommitFiles:wa,getCurrentGitIdentity:Ea,hasLocalIdentity:ka,setGitIdentity:Da,getGitIdentities:ba,createGitIdentity:Sa,updateGitIdentity:Ta,deleteGitIdentity:va,getRemotes:Aa,rebase:Pa,abortRebase:Ma,continueRebase:xa,merge:Ca,abortMerge:_a,continueMerge:ja,checkoutCommit:Oa,cherryPick:Ra,revertCommit:Ia,resetToCommit:Fa,stash:La,stashPop:Na,getConflictDetails:Ua,worktree:{list:_r,validate:xr,bootstrapStatus:na,preview:ia,create:jr,remove:Lr}}),D=t=>t.replace(/\\/g,"/"),$a=(t,e)=>{const r=D(e?.directory||e?.path||t),o=Array.isArray(e?.entries)?e.entries:[];return{directory:r,entries:o.filter(n=>!!(n&&typeof n.name=="string"&&typeof n.path=="string")).map(n=>({name:n.name,path:D(n.path),isDirectory:!!n.isDirectory}))}},j=(t,e)=>{const r=e||t?.();return r?{"x-opencode-directory":r}:void 0},Ga=({getDirectory:t})=>({async listDirectory(e,r){const o=D(e),n=new URLSearchParams;o&&n.set("path",o),r?.respectGitignore&&n.set("respectGitignore","true");const i=await u("/api/fs/list",{query:n,headers:j(t)});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to list directory")}const s=await i.json();return $a(o,s)},async search(e){const r=new URLSearchParams,o=D(e.directory);o&&r.set("directory",o),r.set("query",e.query),r.set("dirs","false"),r.set("type","file"),typeof e.maxResults=="number"&&Number.isFinite(e.maxResults)&&r.set("limit",String(e.maxResults));const n=await u("/api/find/file",{query:r,headers:j(t)});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to search files")}const i=await n.json();return(Array.isArray(i)?i:[]).map(a=>({path:D(`${o}/${a}`),preview:[D(a)]}))},async createDirectory(e){const r=D(e),o=await u("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:r})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to create directory")}const n=await o.json();return{success:!!n?.success,path:typeof n?.path=="string"?D(n.path):r}},async statFile(e,r){const o=D(e),n=new URLSearchParams({path:o});r?.allowOutsideWorkspace&&n.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&n.set("outsideFileGrant",r.outsideFileGrant);const i=await u("/api/fs/stat",{query:n,headers:j(t,r?.directory)});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to stat file")}const s=await i.json().catch(()=>({}));return{path:typeof s.path=="string"?D(s.path):o,isFile:!!s.isFile,size:typeof s.size=="number"?s.size:0,mtimeMs:typeof s.mtimeMs=="number"?s.mtimeMs:void 0}},async readFile(e,r){const o=D(e),n=new URLSearchParams({path:o});r?.allowOutsideWorkspace&&n.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&n.set("outsideFileGrant",r.outsideFileGrant),r?.optional&&n.set("optional","true");const i=await u("/api/fs/read",{query:n,cache:r?.optional?"no-store":"default",headers:j(t,r?.directory)});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await i.text(),path:o}},async writeFile(e,r){const o=D(e),n=await u("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:o,content:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to write file")}const i=await n.json().catch(()=>({}));return{success:!!i.success,path:typeof i.path=="string"?D(i.path):o}},async delete(e){const r=D(e),o=await u("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:r})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to delete file")}return{success:!!(await o.json().catch(()=>({}))).success}},async rename(e,r){const o=await u("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({oldPath:e,newPath:r})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to rename file")}const n=await o.json().catch(()=>({}));return{success:!!n.success,path:typeof n.path=="string"?D(n.path):r}},async revealPath(e){const r=await u("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:D(e)})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to reveal path")}return{success:!!(await r.json().catch(()=>({}))).success}},async downloadFile(e){const r=D(e),o=await u("/api/fs/raw",{query:{path:r,download:!0},headers:j(t)});if(!o.ok)throw new Error(`Download failed (${o.status})`);const n=await o.blob(),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=r.split("/").pop()||"file",document.body.appendChild(s),s.click(),document.body.removeChild(s),setTimeout(()=>URL.revokeObjectURL(i),100)}}),Nr="/api/config/settings",Wa="/api/config/reload",Ur=t=>!t||typeof t!="object"?{}:t,qa=()=>({async load(){const t=await u(Nr,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load settings: ${t.statusText}`);return{settings:Ur(await t.json().catch(()=>({}))),source:"web"}},async save(t){const e=await u(Nr,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!e.ok){const o=await e.json().catch(()=>({error:e.statusText}));throw new Error(o.error||"Failed to save settings")}return Ur(await e.json().catch(()=>({})))},async restartOpenCode(){const t=await u(Wa,{method:"POST"});if(!t.ok){const e=await t.json().catch(()=>({error:t.statusText}));throw new Error(e.error||"Failed to restart OpenCode")}return{restarted:!0}}}),Ka=()=>({async requestDirectoryAccess(t){return{success:!0,path:t.path}},async startAccessingDirectory(t){return{success:!0}},async stopAccessingDirectory(t){return{success:!0}}}),Va=1500,Bt=5e3,Ja="openchamber-notification-claim:",fe=new Map,Qa=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Ya=t=>{const e=typeof t?.tag=="string"?t.tag.trim():"";return e||[t?.sessionId,t?.kind,t?.title,t?.body].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).join("|")},Xa=t=>{for(const[e,r]of fe)t-r>Bt&&fe.delete(e)},Za=t=>{const e=Ya(t);if(!e)return!0;const r=Date.now();Xa(r);const o=fe.get(e)??0;if(r-o<Bt)return!1;try{if(typeof window<"u"&&window.localStorage){const n=`${Ja}${e}`,i=Number(window.localStorage.getItem(n)??"0");if(Number.isFinite(i)&&r-i<Bt)return fe.set(e,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(n),window.localStorage.setItem(n,String(r))}}catch{}return fe.set(e,r),!0},Xo=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let t=null;try{t=await navigator.serviceWorker.getRegistration()??null}catch{t=null}if(t?.active)return t;if(!t)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(r=>{setTimeout(()=>r(null),Va)})])??t}catch{return t}},ec=async t=>{const e=await Xo();if(!e||typeof e.showNotification!="function")return!1;try{return await e.showNotification(t?.title??"OpenChamber",{body:t?.body,tag:t?.tag}),!0}catch(r){return console.warn("Failed to send notification via service worker",r),!1}},tc=async()=>{const t=await Xo();if(!t||!("pushManager"in t)||!t.pushManager)return!1;try{return!!await t.pushManager.getSubscription()}catch{return!1}},rc=async t=>{if(t?.requireHidden&&typeof document<"u"&&document.hasFocus())return!0;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",t),!1;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),!1;if(!Qa()&&await tc()||!Za(t))return!0;try{return await ec(t)||new Notification(t?.title??"OpenChamber",{body:t?.body,tag:t?.tag}),!0}catch(e){return console.warn("Failed to send notification",e),!1}},oc=async t=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_DESKTOP__;if(!e?.invoke)return!1;try{return await e.invoke("desktop_notify",{payload:{title:t?.title,body:t?.body,tag:t?.tag,kind:t?.kind,sessionId:t?.sessionId,directory:t?.directory,requireHidden:t?.requireHidden}}),!0}catch(r){return console.warn("Failed to send native notification (desktop)",r),!1}},nc=()=>({async notifyAgentCompletion(t){return await oc(t)||await rc(t)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),ic=()=>({async getAvailableTools(){const t=await u("/api/experimental/tool/ids");if(!t.ok)throw new Error(`Tools API returned ${t.status} ${t.statusText}`);const e=await t.json();if(!Array.isArray(e))throw new Error("Tools API returned invalid data format");return e.filter(r=>typeof r=="string"&&r!=="invalid").sort()}}),Z=async(t,e)=>{try{const r=await u(t,{...e,credentials:"include",headers:{Accept:"application/json",...e?.headers??{}}});return r.ok?await r.json():null}catch{return null}},sc=()=>({async getVapidPublicKey(){return Z("/api/push/vapid-public-key")},async subscribe(t){return Z("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async unsubscribe(t){return Z("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async setVisibility(t){return Z("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})},async registerApnsToken(t){return Z("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async unregisterApnsToken(t){return Z("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}}),E=async t=>await t.json().catch(()=>null),ac=({urls:t})=>({async authStatus(){const e=await u("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await E(e);if(!e.ok||!r)throw new Error(r?.error||e.statusText||"Failed to load GitHub status");return r},async authStart(){const e=await u("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),r=await E(e);if(!e.ok||!r||!("deviceCode"in r))throw new Error(r?.error||e.statusText||"Failed to start GitHub auth");return r},async authComplete(e){const r=await u("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:e})}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to complete GitHub auth");return o},async authDisconnect(){const e=await u("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),r=await E(e);if(!e.ok)throw new Error(r?.error||e.statusText||"Failed to disconnect GitHub");return{removed:!!r?.removed}},async authActivate(e){const r=await u("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:e})}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to activate GitHub account");return o},async authSetGhCliDisabled(e){const r=await u("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:e})}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to update gh CLI setting");return{disabled:!!o.disabled}},async me(){const e=await u("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),r=await E(e);if(!e.ok||!r)throw new Error(r?.error||e.statusText||"Failed to fetch GitHub user");return r},async prStatus(e,r,o,n){const i=new URLSearchParams({directory:e,branch:r,...o?{remote:o}:{},...n?.force?{force:"true"}:{}}),s=await u(`/api/github/pr/status?${i.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await E(s);if(!s.ok||!a)throw new Error(a?.error||s.statusText||"Failed to load PR status");return a},async prCreate(e){const r=await u("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to create PR");return o},async prUpdate(e){const r=await u("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to update PR");return o},async prMerge(e){const r=await u("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to merge PR");return o},async prReady(e){const r=await u("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to mark PR ready");return o},async repoUpstream(e){const r=await u(`/api/github/repo/upstream?directory=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await E(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to detect upstream repo");return o},async repoBranches(e,r){const o=await u(`/api/github/repo/branches?owner=${encodeURIComponent(e)}&repo=${encodeURIComponent(r)}`,{method:"GET",headers:{Accept:"application/json"}}),n=await E(o);if(!o.ok||!n)throw new Error(n?.error||o.statusText||"Failed to fetch repo branches");return n.branches??[]},async prsList(e,r){const o=r?.page??1,n=new URLSearchParams({directory:e,page:String(o)});r?.query&&n.set("query",r.query);const i=await u(`/api/github/pulls/list?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),s=await E(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load pull requests");return s},async prContext(e,r,o){const n=new URLSearchParams({directory:e,number:String(r)});o?.includeDiff&&n.set("diff","1"),o?.includeCheckDetails&&n.set("checkDetails","1"),o?.sourceRepo?.owner&&o.sourceRepo.repo&&(n.set("owner",o.sourceRepo.owner),n.set("repo",o.sourceRepo.repo));const i=await u(t.api("/api/github/pulls/context",n),{method:"GET",headers:{Accept:"application/json"}}),s=await E(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load pull request context");return s},async issuesList(e,r){const o=r?.page??1,n=new URLSearchParams({directory:e,page:String(o)});r?.query&&n.set("query",r.query);const i=await u(`/api/github/issues/list?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),s=await E(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issues");return s},async issueGet(e,r,o){const n=new URLSearchParams({directory:e,number:String(r)});o?.sourceRepo?.owner&&o.sourceRepo.repo&&(n.set("owner",o.sourceRepo.owner),n.set("repo",o.sourceRepo.repo));const i=await u(t.api("/api/github/issues/get",n),{method:"GET",headers:{Accept:"application/json"}}),s=await E(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issue");return s},async issueComments(e,r,o){const n=new URLSearchParams({directory:e,number:String(r)});o?.sourceRepo?.owner&&o.sourceRepo.repo&&(n.set("owner",o.sourceRepo.owner),n.set("repo",o.sourceRepo.repo));const i=await u(t.api("/api/github/issues/comments",n),{method:"GET",headers:{Accept:"application/json"}}),s=await E(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issue comments");return s}}),Re=async t=>await t.json().catch(()=>null),cc=()=>({async listClients(){const t=await u("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),e=await Re(t);if(!t.ok||!e)throw new Error(e?.error||t.statusText||"Failed to load remote clients");return Array.isArray(e.clients)?e.clients:[]},async createClient(t={}){const e=await u("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:t.label??""})}),r=await Re(e);if(!e.ok||!r?.client||typeof r.token!="string")throw new Error(r?.error||e.statusText||"Failed to create remote client token");return r},async revokeClient(t){const e=await u(`/api/client-auth/clients/${encodeURIComponent(t)}`,{method:"DELETE",headers:{Accept:"application/json"}}),r=await Re(e);if(!e.ok||!r)throw new Error(r?.error||e.statusText||"Failed to revoke remote client");return r},async purgeRevokedClients(){const t=await u("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),e=await Re(t);if(!t.ok||!e)throw new Error(e?.error||t.statusText||"Failed to clear revoked clients");return e}}),lc=()=>({api:(...t)=>P().api(...t),authenticatedAsset:(...t)=>P().authenticatedAsset(...t),auth:(...t)=>P().auth(...t),health:(...t)=>P().health(...t),rawFile:(...t)=>P().rawFile(...t),sse:(...t)=>P().sse(...t),websocket:(...t)=>P().websocket(...t)}),dc=(t={})=>{const e=t.urls??Gt();Tn(e);const r=lc();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Ls(),git:za(),files:Ga({getDirectory:()=>Nt.getState().currentDirectory}),settings:qa(),permissions:Ka(),notifications:nc(),github:ac({urls:r}),push:sc(),clientAuth:cc(),tools:ic()}},Br=(t,e)=>{if(!t||!e)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}},wl=()=>{const t=typeof window.__OPENCHAMBER_API_BASE_URL__=="string"?window.__OPENCHAMBER_API_BASE_URL__.trim():"",e=typeof window.__OPENCHAMBER_CLIENT_TOKEN__=="string"?window.__OPENCHAMBER_CLIENT_TOKEN__.trim():"",r=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__.trim():"",o=io({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return In({apiBaseUrl:t,runtimeKey:Br(t,r)?"local":null}),Vr(e||null),Jr(window.__OPENCHAMBER_RUNTIME_HEADERS__||null),zt(t||void 0).catch(()=>{}),r&&!Br(t,r)&&Object.keys(Ze()).length>0&&to(r).catch(()=>{}),Rn(),dc({urls:o})};export{et as $,Qr as A,Ec as B,xs as C,ce as D,Ac as E,vo as F,Wc as G,qc as H,cs as I,Lc as J,fc as K,pc as L,kc as M,xc as N,_c as O,Te as P,nl as Q,Pi as R,il as S,ol as T,I as U,Uc as V,Ln as W,jn as X,mc as Y,rl as Z,Gc as _,qt as a,zs as a$,yc as a0,gc as a1,Bn as a2,Ic as a3,Oc as a4,Rc as a5,po as a6,Fc as a7,Li as a8,Fi as a9,Hs as aA,ha as aB,Oa as aC,Ra as aD,ja as aE,xa as aF,ua as aG,ma as aH,sa as aI,Sa as aJ,jr as aK,Zs as aL,va as aM,Lr as aN,ea as aO,yl as aP,pa as aQ,hl as aR,wa as aS,Ua as aT,Ea as aU,Xs as aV,pl as aW,$s as aX,Gs as aY,ba as aZ,ga as a_,$c as aa,mi as ab,bi as ac,yi as ad,Si as ae,xi as af,nt as ag,bc as ah,Tc as ai,Sc as aj,vc as ak,Dc as al,Mc as am,Cc as an,ll as ao,li as ap,ls as aq,Bc as ar,na as as,Bo as at,mo as au,Xe as av,_a as aw,Ma as ax,fa as ay,Ha as az,Nt as b,ml as b0,gl as b1,Aa as b2,xr as b3,_r as b4,la as b5,ca as b6,aa as b7,ka as b8,Ys as b9,zc as bA,hi as bB,Ze as bC,De as bD,mt as bE,Kc as bF,Jc as bG,Zc as bH,Qc as bI,Vc as bJ,Yc as bK,Uo as bL,Xc as bM,sl as bN,al as bO,Pc as bP,cl as bQ,gi as bR,wi as bS,dl as bT,da as ba,Ca as bb,Yo as bc,ia as bd,Pa as be,ta as bf,ya as bg,Fa as bh,ul as bi,fl as bj,Ia as bk,Ws as bl,Qs as bm,Da as bn,qs as bo,Vo as bp,Vs as bq,La as br,Qo as bs,Na as bt,Ks as bu,Jo as bv,Js as bw,Ta as bx,Ba as by,M as bz,wl as c,tt as d,wc as e,Fn as f,P as g,u as h,tl as i,el as j,U as k,ho as l,R as m,Nc as n,H as o,jc as p,Hn as q,zt as r,hc as s,Hc as t,L as u,Fs as v,Os as w,rt as x,ot as y,C as z};
|