@openchamber/web 1.13.1 → 1.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramView-la2P5DUr.js → DiagramView-l49NCoWI.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-BspFAgXe.js +7 -0
- package/dist/assets/{MultiRunWindow-B9NPliTC.js → MultiRunWindow-BP1L8slG.js} +1 -1
- package/dist/assets/{NewWorktreeDialog-BnK_0_OO.js → NewWorktreeDialog-B2o615D_.js} +1 -1
- package/dist/assets/OnboardingScreen-DNQQWFmn.js +1 -0
- package/dist/assets/{SessionSwitcherDropdown-CuRsG7FM.js → SessionSwitcherDropdown-Bz03hrU9.js} +1 -1
- package/dist/assets/{SettingsWindow-Cs3xbqtf.js → SettingsWindow-L-jJDG3k.js} +1 -1
- package/dist/assets/{TerminalView-CLKpaKdm.js → TerminalView-CZYwjWYc.js} +1 -1
- package/dist/assets/index-Di3CDurc.css +1 -0
- package/dist/assets/index-DkRLSXEX.js +3 -0
- package/dist/assets/{main-B2rXVG8L.js → main-DmS7A2g8.js} +2 -2
- package/dist/assets/main-gqEqIL1b.js +214 -0
- package/dist/assets/miniChat-DZORfsku.js +2 -0
- package/dist/assets/mobile-DkitItmP.js +2 -0
- package/dist/assets/{renderElectronMiniChatApp-BLM-RCP0.js → renderElectronMiniChatApp-S7GCIhbH.js} +2 -2
- package/dist/assets/{renderMobileApp-BXScr4up.js → renderMobileApp-CxEnmaQL.js} +3 -3
- package/dist/assets/{useAppFontEffects-ByW8wOJM.js → useAppFontEffects-DkrfZHQv.js} +114 -114
- package/dist/assets/vendor--Dwc_TRgJ.css +1 -0
- package/dist/assets/{vendor-.bun-d5B0wgQr.js → vendor-.bun-CIlawBoH.js} +1 -1
- package/dist/index.html +5 -5
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +1 -1
- package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/dist/assets/MarkdownRendererImpl-CkGSBGo5.js +0 -8
- package/dist/assets/OnboardingScreen-laLzQZgy.js +0 -1
- package/dist/assets/index-68ujKCUc.js +0 -3
- package/dist/assets/index-C-aQ_xRH.css +0 -1
- package/dist/assets/main-CuEzPtRt.js +0 -214
- package/dist/assets/miniChat-DVXSR0vu.js +0 -2
- package/dist/assets/mobile-BgYrNCOf.js +0 -2
- package/dist/assets/vendor--V65Sl9C2.css +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CIlawBoH.js","assets/vendor--Dwc_TRgJ.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as So,c as To,a as Le,d as Ue,p as yr,b as gr,e as wr,R as Oe}from"./vendor-.bun-CIlawBoH.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 br=()=>null,Sr="",q="",le=0,$=null,Pe=0;const Tr=1e4,Be=t=>typeof t!="string"?"":t.trim(),vo=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_CLIENT_TOKEN__;return Be(t)},ko=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},Do=(t,e)=>{const r=typeof t=="string"&&t.trim()?t.trim():ko();if(!r)return e;try{return new URL(e,`${r.replace(/\/+$/,"")}/`).toString()}catch{return e}},He=()=>{q="",le=0},Eo=()=>{Pe+=1,$=null,He(),vt()},vr=t=>{const e=Be(t);Sr=e,Eo(),br=()=>e?{type:"bearer",token:e}:null},kr=()=>Sr||vo(),Po=(t,e)=>{const r=Be(t);if(!r||typeof e!="number"||!Number.isFinite(e)){He();return}const o=q;q=r,le=e,o&&o!==r&&Ao()},Dr=()=>!q||le<=Date.now()+Tr?(He(),""):q,Mo=()=>{const t=Dr();return!t&&(kr()||typeof window<"u")&&Tt().catch(()=>{}),t},Er=async()=>{const t=await br(),e=t?.type==="bearer"?Be(t.token):kr();return e?{type:"bearer",token:e}:null},Pr=t=>{if($)return $;const e=Pe,o=(async()=>{const n=await Er(),i=new Headers;n?.type==="bearer"&&i.set("Authorization",`Bearer ${n.token}`);const s=await fetch(Do(t,"/auth/url-token"),{method:"POST",headers:i,credentials:"include"});if(!s.ok)throw e===Pe&&He(),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():"",d=typeof a?.expiresAt=="number"?a.expiresAt:0;if(e!==Pe)throw new Error("Runtime URL auth token response is stale");if(Po(c,d),!q)throw new Error("Runtime URL auth token response was invalid");return q})().finally(()=>{$===o&&($=null)});return $=o,$},Tt=async t=>{const e=Dr();return e||Pr(t)};let Y=0,se=null,Mr=null;const it=new Set,Co=5e3,Ao=()=>{for(const t of it)try{t()}catch{}},Cr=()=>{se!==null&&(clearTimeout(se),se=null)},vt=()=>{if(Cr(),Y<=0||typeof window>"u")return;const t=le-Tr-Co,e=le>0?Math.max(0,t-Date.now()):0;se=setTimeout(()=>{se=null,!(Y<=0)&&Pr(Mr).catch(()=>{}).finally(()=>{vt()})},e)},Sa=t=>{typeof t=="string"&&t.trim()&&(Mr=t.trim()),Y+=1,vt();let e=!1;return()=>{e||(e=!0,Y=Math.max(0,Y-1),Y===0&&Cr())}},Ta=t=>(it.add(t),()=>{it.delete(t)}),Oo=async t=>{const e=new Headers(t);if(e.has("Authorization"))return e;const r=await Er();return r?.type==="bearer"&&e.set("Authorization",`Bearer ${r.token}`),e},kt=/^[a-z][a-z\d+.-]*:\/\//i,Io=t=>{const e=t.trim();return e?e.startsWith("/")?e:`/${e}`:"/"},st=t=>typeof t!="string"?"":t.trim().replace(/\/+$/,""),Ro=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return st(t)},Fo=t=>{const e=t.currentHref?.();return e||(typeof window<"u"?window.location.href||window.location.origin:"")},at=(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))},_o=(t,e)=>{if(!e)return t;const r=new URLSearchParams;at({searchParams:r},e);const o=r.toString();return o?t.includes("?")?`${t}&${o}`:`${t}?${o}`:t},_t=(t,e,r)=>{if(kt.test(e)){const i=new URL(e);return at(i,r),i.toString()}const o=Io(e);if(!t)return _o(o,r);const n=new URL(o,`${t}/`);return at(n,r),n.toString()},qe=t=>{const e=Mo();if(!e)return t;if(kt.test(t)){const o=new URL(t);return o.searchParams.set("oc_url_token",e),o.toString()}const r=t.includes("?")?"&":"?";return`${t}${r}oc_url_token=${encodeURIComponent(e)}`},xo=(t,e)=>{const r=kt.test(t)?new URL(t):new URL(t,Fo(e));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},Dt=(t={})=>{const e=st(t.apiBaseUrl),r=st(t.realtimeBaseUrl),o=()=>e||Ro(),n=()=>r||o(),i=(a,c)=>_t(o(),a,c),s=(a,c)=>_t(n(),a,c);return{api:i,authenticatedAsset:(a,c)=>qe(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)=>qe(s(a,c)),websocket:(a,c)=>xo(qe(s(a,c)),t)}};let Ie=Dt();const D=()=>Ie,jo=t=>{Ie=t},Ar=t=>(Ie=Dt(t),Ie),de=t=>t.startsWith("/api/")||t==="/api"||t.startsWith("/auth/")||t==="/auth"||t==="/health",No=()=>typeof window>"u"?"":window.location.origin||"",Or=t=>{if(typeof window>"u")return!1;const e=No();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}},Ir=t=>/^[a-z][a-z\d+.-]*:\/\//i.test(t),Lo=(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))},Me=t=>{try{const e=D().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;const r=new URL(e);return t.origin!==r.origin?!1:de(t.pathname)}catch{return!1}},Ke=t=>{if(de(t))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;try{const e=new URL(t);return Or(e)&&de(e.pathname)}catch{return!1}},Uo=(t,e)=>{try{const r=new URL(t);if(!Or(r))return t;const o=W(`${r.pathname}${r.search}`,e);return!Ir(o)&&(r.protocol==="http:"||r.protocol==="https:")?(Lo(r,e),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return t}},W=(t,e)=>t==="/health"?D().health(e):t.startsWith("/auth/")||t==="/auth"?D().auth(t,e):de(t)?D().api(t,e):/^[a-z][a-z\d+.-]*:\/\//i.test(t)?Uo(t,e):t,Bo=t=>{const e=t instanceof Request?t.url:t.toString();if(!Ir(e))return de(e);try{return Me(new URL(e))}catch{return!1}},G=async(t,e,r=!0)=>{const o=new Headers(t);return e&&new Headers(e).forEach((n,i)=>o.set(i,n)),r?Oo(o):o},Ho=(t,e)=>{if(typeof t=="string")return W(t,e);if(t instanceof URL)return W(t.toString(),e);const r=W(t.url,e);return r===t.url?t:new Request(r,t)},zo=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,ye=new Map,$o=(t,e,r)=>r||t!=="GET"||e.includes("/event")||!zo.test(e)?null:`GET ${e}`,u=async(t,e={})=>{const{query:r,...o}=e,n=Ho(t,r),i=n instanceof Request?n.headers:void 0,s=await G(i,o.headers,Bo(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),d=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase(),l=o.signal!=null||n instanceof Request,f=$o(d,c,l);if(!f)return a();const y=ye.get(f);if(y)return y.then(w=>w.clone());const m=a();return ye.set(f,m),m.then(()=>ye.delete(f),()=>ye.delete(f)),m.then(w=>w.clone())};let xt=!1;const Go=()=>{if(xt||typeof window>"u")return;xt=!0;const t=window.fetch.bind(window);window.fetch=async(e,r)=>{if(typeof e=="string"){if(!Ke(e)){try{const n=new URL(e);if(Me(n)){const i=await G(void 0,r?.headers);return t(e,{...r,headers:i})}}catch{}return t(e,r)}const o=await G(void 0,r?.headers);return t(W(e),{...r,headers:o})}if(e instanceof URL){const o=e.toString();if(!Ke(o)){if(Me(e)){const i=await G(void 0,r?.headers);return t(e,{...r,headers:i})}return t(e,r)}const n=await G(void 0,r?.headers);return t(W(o),{...r,headers:n})}if(e instanceof Request){if(!Ke(e.url)){try{const s=new URL(e.url);if(Me(s)){const a=await G(e.headers,r?.headers);return t(new Request(e,{...r,headers:a}))}}catch{}return t(e,r)}const o=await G(e.headers,r?.headers),n=W(e.url),i=n===e.url?e:new Request(n,e);return t(new Request(i,{...r,headers:o}))}return t(e,r)}},ct="openchamber:runtime-endpoint-changed";let Re="",ue="";const Et=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"}`}},Rr=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},Fr=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof t=="string"?t.trim():""},_r=(t,e)=>{if(!t||!e)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}},Pt=()=>Re||Rr(),ze=()=>{if(ue)return ue;const t=Pt();return _r(t,Fr())?"local":Et(t)},Wo=(t={})=>{if(Re||ue)return;const e=t.apiBaseUrl?.trim()||Rr();e&&(Re=e,ue=t.runtimeKey?.trim()||(_r(e,Fr())?"local":Et(e)))},va=t=>{const e=t.apiBaseUrl.trim(),r=Pt(),o=ze(),n=t.runtimeKey?.trim()||Et(e);if(Re=e,ue=n,typeof window<"u"){const i=window;i.__OPENCHAMBER_API_BASE_URL__=e,i.__OPENCHAMBER_CLIENT_TOKEN__=t.clientToken||void 0}Ar({apiBaseUrl:e,realtimeBaseUrl:e}),vr(t.clientToken||null),Tt(e).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ct,{detail:{apiBaseUrl:e,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o}}))},qo=t=>{if(typeof window>"u")return()=>{};const e=r=>{t(r.detail)};return window.addEventListener(ct,e),()=>window.removeEventListener(ct,e)},Ko=["local","remote",null],Vo=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function xr(t){if(!t||typeof t!="object")return{valid:!1};const e=t,r=e.target,o=e.status;if(r!==null&&(typeof r!="string"||!Ko.includes(r)))return{valid:!1};if(typeof o!="string"||!Vo.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 ka(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 Da(t){return t.isDesktopShell?t.bootOutcomeKnown?t.bootViewIsMain===!1?!0:t.isInitialized:!1:t.isInitialized}function Ea(t){return t.isDesktopShell&&!t.isDesktopLocalOriginActive}function Jo(){if(Qo()!=="valid")return null;const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,r=xr(e);return r.valid?r.outcome:null}function Qo(){if(typeof window>"u")return"not-injected";const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return t==null?"not-injected":xr(t).valid?"valid":"malformed"}let lt=null;const Pa=t=>{lt=t},$e=()=>lt||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Yo=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,te=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,jr=()=>Yo()?.runtime==="electron",E=()=>typeof te()?.invoke=="function",Nr=()=>jr()&&E(),A=async(t,e)=>{const r=te();return typeof r?.invoke!="function"?null:r.invoke(t,e??{})},Ma=async()=>{if(!Nr()||!I())return null;try{const t=await A("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}},Ca=async t=>{if(!Nr()||!I())return null;try{const e=await A("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}},jt=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}}},Ve=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}}},Xo=t=>t.replace(/^\[|\]$/g,"").toLowerCase(),re=t=>{const e=Xo(t);return e==="localhost"||e==="127.0.0.1"||e==="::1"},I=()=>{if(typeof window>"u"||!Lr())return!1;if(ze()==="local")return!0;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=Ve(t),r=Ve(Pt());if(!r&&e&&Jo()?.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&&re(e.hostname)&&re(r.hostname)}const o=Ve(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&&re(e.hostname)&&re(o.hostname)}const n=jt(t),i=jt(window.location.origin)||window.location.origin;return n&&i&&n===i?!0:!!(o&&re(o.hostname))},Lr=()=>typeof window>"u"?!1:jr(),Aa=async()=>{if(!Lr())return!1;try{return await A("desktop_start_window_drag"),!0}catch{return!1}},Ge=()=>$e()?.runtime?.isVSCode===!0,Oa=()=>{const e=$e()?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!Ge()},Ur=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Ia=async t=>{if(E()&&I())try{const e=await te()?.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}},Br=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Ra=async t=>{if(E()&&I())try{const e=await te()?.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(!Br(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"}},Fa=async t=>{const e=typeof t=="string"?t.trim():"";if(!e)return{success:!1,error:"Path is required"};if(!E()||!I())return{success:!1,error:"Native file access not available"};try{const r=await te()?.grantFileAccess?.(e);if(!Br(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)}}},_a=async t=>({success:!0}),xa=async t=>({success:!0}),ja=async()=>{if(!E())return null;try{return await A("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates",t),null}},Na=async t=>{if(!E())return!1;const e=te();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,d=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){o=0,n=typeof d?.contentLength=="number"?d.contentLength:void 0,t({downloaded:o,total:n});return}if(c==="Progress"){const l=d?.downloaded,f=d?.total;typeof l=="number"&&(o=l),typeof f=="number"&&(n=f),t({downloaded:o,total:n});return}c==="Finished"&&t({downloaded:o,total:n})})),await A("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{}}},La=async()=>E()?Zo():!1,Zo=async()=>{if(!E())return!1;try{return await A("desktop_restart"),!0}catch(t){return console.warn("Failed to restart desktop app",t),!1}},Ua=async()=>{if(!E()||!I())return null;try{const t=await A("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}},en=async(t,e)=>{if(!E()||!I())return!1;const r=t?.trim();if(!r)return!1;try{return await A("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}},Ba=async t=>{if(!E()||!I())return!1;const e=t?.trim();if(!e)return!1;try{return await A("desktop_reveal_path",{path:e}),!0}catch{return en(e)}},Ha=async(t,e)=>{if(!E()||!I())return null;const r=t?.trim();if(!r)return null;try{const o=await A("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}},za=async(t,e,r)=>{if(!E()||!I())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await A("desktop_open_in_app",{projectPath:o,appId:n,appName:i}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},$a=async(t,e,r)=>{if(!E()||!I())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await A("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}},Ga=async(t,e)=>{if(!E()||!I())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 A("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}}},Nt=500,Hr=()=>{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}},Wa=()=>Hr(),R=(t,e)=>{if(!Hr())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>Nt&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Nt)},tn=()=>{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__=tn);const qa=async(t,e,r)=>{const o=typeof performance<"u"?performance.now():Date.now();R(`${t}:start`,r);try{const n=await e(),i=typeof performance<"u"?performance.now():Date.now();return R(`${t}:end`,{durationMs:Math.round(i-o)}),n}catch(n){const i=typeof performance<"u"?performance.now():Date.now();throw R(`${t}:error`,{durationMs:Math.round(i-o),error:n instanceof Error?n.message:String(n)}),n}},rn=3,on=3e4,nn=1e3,zr=32e3,sn=3,an=3600*1e3,cn=600*1e3,$r=new Set([429,502,503,504]),Z=new Map;function ln(){const t=Date.now();for(const[e,r]of Z)r.consecutiveErrors===0&&t-r.lastErrorAt>an&&Z.delete(e)}typeof setInterval<"u"&&setInterval(ln,cn).unref?.();function dn(t){let e=Z.get(t);return e||(e={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:on},Z.set(t,e)),e}function un(t){if(!t)return;const e=Z.get(t);e&&(e.consecutiveErrors=0,e.lastErrorAt=0)}function Lt(t,e){if(!t)return;const r=dn(t);r.consecutiveErrors+=1,r.lastErrorAt=Date.now(),fn(e)&&r.consecutiveErrors>=rn&&(r.circuitOpen=!0,r.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${t} after ${r.consecutiveErrors} consecutive errors`))}function fn(t){return t!==void 0&&$r.has(t)}function Gr(t){const e=Z.get(t);return e?.circuitOpen?Date.now()-e.circuitOpenAt>=e.circuitCooldownMs?(e.circuitOpen=!1,e.consecutiveErrors=0,e.circuitCooldownMs=Math.min(e.circuitCooldownMs*2,zr*4),!1):!0:!1}function pn(t,e,r){return!(!$r.has(e)||r>=sn-1||Gr(t))}function hn(t){if(!(!t||!Gr(t)))throw new Error(`Provider ${t} is temporarily unavailable after repeated errors. Please retry shortly.`)}function Ut(t){const e=nn*2**t;return Math.min(e,zr)}const Bt="/api",mn=1e4;function ae(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 P(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${ae(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 V(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${ae(t.error)}`);throw r!==void 0&&(o.status=r),o}return t.data}const yn=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ht="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gn=14;let zt=0,Je=0;const wn=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+=Ht[e[o]%Ht.length];return r},$t=t=>{const e=Date.now();e!==zt&&(zt=e,Je=0),Je+=1;const r=BigInt(e)*BigInt(4096)+BigInt(Je),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}${wn(gn)}`},bn=t=>t instanceof DOMException&&t.name==="AbortError"||t instanceof TypeError,Gt=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(yn.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}},Wt=()=>{try{return D().api("/api")}catch{return null}},Qe=t=>To({...t,fetch:u}),J=t=>t.replace(/\\/g,"/"),qt=400,Kt=()=>{const t=$e();return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Sn{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=Bt){const o=Wt()||e;this.baseUrl=Gt(o),this.client=Qe({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const e=Wt(),r=Gt(e||Bt);r!==this.baseUrl&&(this.baseUrl=r,this.client=Qe({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=Qe({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&&R("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 P(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 P(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 V(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 P(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 P(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 So(async()=>{const{default:f}=await import("./vendor-.bun-CIlawBoH.js").then(y=>y.h);return{default:f}},__vite__mapDeps([0,1]))).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}),d=await new Promise((f,y)=>{const m=new FileReader;m.onload=()=>f(m.result),m.onerror=y,m.readAsDataURL(c)});let l=e.filename;return l&&(l=l.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:l,url:d}}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??$t("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}),hn(e.providerID);let i;for(let s=0;s<3;s++){try{const l=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.format?{format:e.format}:{},parts:o});if(l.response instanceof Response)i=l.response;else if(l.error){const f=l.response?.status||500;i=new Response(JSON.stringify(l.error),{status:f})}else i=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){if(s<2&&bn(l)){const f=Ut(s);console.warn(`[prompt] fetch failed for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${f}ms`,l?.message),await new Promise(y=>setTimeout(y,f));continue}throw Lt(e.providerID),l}if(i.ok)return un(e.providerID),r;if(pn(e.providerID,i.status,s)){const l=Ut(s);console.warn(`[prompt] ${i.status} for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${l}ms`),await new Promise(f=>setTimeout(f,l));continue}let a="";try{a=await i.text()}catch{}const c=a&&a.trim().length>0?`: ${a.trim()}`:"",d=new Error(`Failed to send message (${i.status})${c}`);throw Lt(e.providerID,i.status),d}throw new Error("Failed to send message after retries")}async sendCommand(e){const r=e.messageId??$t("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 V(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 P(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 P(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 V(s,"session.summarize")===!0}async unrevertSession(e){const r=await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return P(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 P(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 V(i,"permission.reply")===!0}async listPendingPermissions(e){const r=[],o=async c=>{const d=typeof c=="string"?c.trim():"",l=await this.client.permission.list(d?{directory:d}:void 0);if(l.error)throw new Error(`permission.list failed: ${ae(l.error)}`);return l.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&n.add(d)}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 d of c){if(!d||typeof d!="object")continue;const l=d.id;typeof l!="string"||l.length===0||a.has(l)||(a.add(l),s.push(d))}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 V(s,"question.reply")===!0}async rejectQuestion(e){const r=await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return V(r,"question.reject")===!0}async listPendingQuestions(e){const r=[],o=async c=>{const d=typeof c=="string"?c.trim():"",l=await this.client.question.list(d?{directory:d}:void 0);if(l.error)throw new Error(`question.list failed: ${ae(l.error)}`);return l.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&n.add(d)}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 d of c){if(!d||typeof d!="object")continue;const l=d.id;typeof l!="string"||l.length===0||a.has(l)||(a.add(l),s.push(d))}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 R("opencodeClient.getConfig:cacheHit",{directory:r??null}),n.config;const i=this.configInFlight.get(o);if(i)return R("opencodeClient.getConfig:deduped",{directory:r??null}),i;const s=this.configCacheGeneration,a=(async()=>{R("opencodeClient.getConfig:start",{directory:r??null});const c=typeof performance<"u"?performance.now():Date.now(),l=await(r?this.getScopedApiClient(r):this.client).config.get();if(!l.data)throw new Error("Failed to get config");const f=typeof performance<"u"?performance.now():Date.now();return R("opencodeClient.getConfig:end",{directory:r??null,durationMs:Math.round(f-c)}),s===this.configCacheGeneration&&this.configCache.set(o,{config:l.data,expiresAt:Date.now()+mn}),l.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=P(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 P(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})`:""}: ${ae(a.error)}`):new Error(`agent.list failed (${c.status})`);const d=await c.json().catch(()=>null);if(!Array.isArray(d))throw new Error("agent.list failed: invalid response");return d})();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(P(r,"file.read"))}catch{return`// Content of ${e}
|
|
3
|
+
// 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=P(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(P(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(P(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`;R("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:r});const o=await u(r);if(R("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const n=await o.json();return R("opencodeClient.checkHealth:result",{healthy:n?.healthy}),n?.healthy===!0}catch{return!1}}async createDirectory(e,r){const o=Kt();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"?J(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 d=(async()=>{const l=Kt();if(l)try{const f=await l.listDirectory(e||"",r);if(!f||!Array.isArray(f.entries))return[];const y=f.entries.map(m=>({name:m.name,path:J(m.path),isDirectory:!!m.isDirectory,isFile:!m.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:y,expiresAt:Date.now()+qt}),y}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 y=f.toString(),m=await u(`${this.baseUrl}/fs/list${y?`?${y}`:""}`);if(!m.ok){const b=await m.json().catch(()=>({})),v=typeof b.error=="string"?b.error:"Failed to list directory";throw new Error(v)}const w=await m.json();if(!w||!Array.isArray(w.entries))return[];const g=w.entries;return this.listDirectoryCache.set(n,{entries:g,expiresAt:Date.now()+qt}),g}catch(f){throw console.error("Failed to list directory contents:",f),f}})().finally(()=>{this.listDirectoryInFlight.get(n)===d&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,d),d}async searchFiles(e,r){const o=typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():this.currentDirectory,n=o?J(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 d=J(c),l=d.split("/").filter(Boolean).pop()||d,f=J(n?`${n}/${d}`:d);return{name:l,path:f,relativePath:d,extension:l.includes(".")?l.split(".").pop()?.toLowerCase():void 0}})}catch(s){throw console.error("Failed to search files:",s),s}}async getFilesystemHome(){const e=ze();if(!e||e==="local"){const r=await Ur();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 B=new Sn,Tn=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 Ye=null,Xe=null;const Wr=t=>{if(typeof window>"u")return null;try{return window[t]??null}catch{return null}},Fe=()=>{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}}},vn=()=>{const t=Wr("localStorage");if(!t)return Fe();const e=Fe();let r=!0;const o=()=>{r=!1};return{getItem:d=>{if(r)try{const l=t.getItem(d);if(l!==null)return l}catch{o()}return e.getItem(d)},setItem:(d,l)=>{if(r)try{t.setItem(d,l),e.removeItem(d);return}catch{o();try{t.removeItem(d)}catch{}}e.setItem(d,l)},removeItem:d=>{try{t.removeItem(d)}catch{o()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:d=>{if(r)try{return t.key(d)}catch{o()}return e.key(d)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},K=()=>(Ye||(Ye=vn()),Ye),kn=()=>{const t=Wr("sessionStorage");if(!t)return Fe();const e=Fe();let r=!0;const o=()=>{r=!1};return{getItem:d=>{if(r)try{const l=t.getItem(d);if(l!==null)return l}catch{o()}return e.getItem(d)},setItem:(d,l)=>{if(r)try{t.setItem(d,l),e.removeItem(d);return}catch{o();try{t.removeItem(d)}catch{}}e.setItem(d,l)},removeItem:d=>{try{t.removeItem(d)}catch{o()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:d=>{if(r)try{return t.key(d)}catch{o()}return e.key(d)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},Ka=()=>(Xe||(Xe=kn()),Xe),Dn={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Va={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Vt(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const ge={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)"}}},Ze={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...ge.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ze.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...ge.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ze.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...ge.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ze.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...ge.tool.inline})},En=[{id:"ibm-plex-sans",label:"IBM Plex Sans",description:"Humanist sans-serif for optimal readability in the interface.",stack:'"IBM Plex Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'},{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'}],Pn=[{id:"ibm-plex-mono",label:"IBM Plex Mono",description:"Balanced monospace for code blocks and technical content.",stack:'"IBM Plex Mono", "SFMono-Regular", "Menlo", monospace'},{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'}],qr=t=>Object.fromEntries(t.map(e=>[e.id,e])),Mn=qr(En),Cn=qr(Pn),An="ibm-plex-sans",On="ibm-plex-mono",Kr=t=>typeof t=="string"&&t in Mn,Vr=t=>typeof t=="string"&&t in Cn,dt="openchamber.mobileKeyboardMode",In='meta[name="viewport"]',Jt="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Ja=()=>!0;function We(t,e="resize-content"){return t==="native"||t==="resize-content"?t:e}const Rn=t=>We(t)==="resize-content"?`${Jt}, interactive-widget=resizes-content`:Jt,Fn=()=>{if(typeof window>"u")return"resize-content";try{return We(localStorage.getItem(dt))}catch{return"resize-content"}},Jr=t=>{const e=We(t);if(typeof window<"u")try{e==="resize-content"?localStorage.removeItem(dt):localStorage.setItem(dt,e)}catch{}return e},Qa=t=>{const e=Jr(t);if(typeof document>"u")return e;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",e);const r=document.querySelector(In);if(r instanceof HTMLMetaElement){const o=Rn(e);r.getAttribute("content")!==o&&r.setAttribute("content",o)}return e};function Qt(t){return t==="vim"?"vim":"default"}const we={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}"}},U={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},be=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,_n=t=>{if(!t||typeof t!="object")return!1;const e=t;return be(e.completion,we.completion)&&be(e.error,we.error)&&be(e.question,we.question)&&be(e.subtask,we.subtask)},Mt=380,xn=380,jn=1400,Qr=12,Yt=120,oe=280,ne=360,Nn=860,et=new Map,tt=t=>(t??ze()).trim()||"default",k=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},Yr=t=>Number.isFinite(t)?Math.min(jn,Math.max(xn,Math.round(t))):Mt,_e=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.replace(/\\/g,"/"):null},Xr=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.length>Yt?e.slice(0,Yt):e:null},Ln=(t,e)=>(t==="file"||t==="preview")&&e||t,Zr=(t,e,r)=>{if(t==="diff")return t;if(typeof r=="string"){const o=r.trim();if(o)return o}return Ln(t,e)},eo=(t,e)=>e===t?t:`${t}:${e}`,to=t=>{const e=_e(t.targetPath),r=Zr(t.mode,e,t.dedupeKey);return{id:eo(t.mode,r),mode:t.mode,targetPath:e,dedupeKey:r,label:Xr(t.label),readOnly:t.readOnly===!0,stagedDiff:t.stagedDiff===!0,touchedAt:Date.now()}},ro=(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))},oo=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=Zr(n.mode,i,typeof n.dedupeKey=="string"?n.dedupeKey:null),a=eo(n.mode,s);!a||r.has(a)||(r.add(a),e.push({id:a,mode:n.mode,targetPath:i,dedupeKey:s,label:Xr(typeof n.label=="string"?n.label:null),readOnly:n.readOnly===!0,stagedDiff:n.stagedDiff===!0,touchedAt:typeof n.touchedAt=="number"&&Number.isFinite(n.touchedAt)?n.touchedAt:Date.now()}))}return e},fe=(t,e)=>e&&t.some(r=>r.id===e)?e:t.length===0?null:t[t.length-1].id,H=t=>{if(t){const e=oo(t.tabs),r=fe(e,t.activeTabId);return{...t,tabs:e,activeTabId:r,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:Mt,touchedAt:Date.now()}},Un=(t,e)=>{const r=to(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,stagedDiff:r.stagedDiff,readOnly:r.readOnly,touchedAt:Date.now()}:a),i=r.id,s=ro(n,Qr,i);return{...t,isOpen:!0,tabs:s,activeTabId:fe(s,i),touchedAt:Date.now()}},Bn=(t,e)=>{const r=t.tabs.filter(n=>n.id!==e),o=t.activeTabId===e?r[r.length-1]?.id??null:fe(r,t.activeTabId);return{...t,tabs:r,activeTabId:o,isOpen:r.length>0?t.isOpen:!1,touchedAt:Date.now()}},Hn=(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},zn=(t,e,r)=>({...t,tabs:t.tabs.map(o=>o.id===e?{...o,targetPath:r}:o)}),rt=t=>{if(!t||typeof t!="object")return{};const e=t,r={};for(const[o,n]of Object.entries(e)){const i=k(o);if(!i||!n||typeof n!="object")continue;const s=n;let a=oo(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=[to({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 d=fe(a,c),l=ro(a,Qr,d);r[i]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:l,activeTabId:fe(l,d),width:Yr(typeof s.width=="number"?s.width:Mt),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},z=(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},X=Le()(Ue(yr((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:oe,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:ne,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,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:An,monoFont:On,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Fn(),favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...U.completion},error:{...U.error},question:{...U.question},subtask:{...U.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:oe}:{isSidebarOpen:o}})},setSidebarOpen:r=>{t(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==oe?{isSidebarOpen:r,sidebarWidth:oe}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:oe}:{isSidebarOpen:r})},setSidebarWidth:r=>{t({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(r=>{const o=!r.isRightSidebarOpen;return o&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:o,rightSidebarWidth:ne}:{isRightSidebarOpen:o}})},setRightSidebarOpen:r=>{t(o=>{if(o.isRightSidebarOpen===r)return o;const n=r&&!o.hasManuallyResizedRightSidebar&&o.rightSidebarWidth!==ne;return{isRightSidebarOpen:r,rightSidebarWidth:n?ne:o.rightSidebarWidth}})},setRightSidebarWidth:r=>{const o=Math.min(Nn,Math.max(ne,r));t({rightSidebarWidth:o,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:r=>{t({rightSidebarTab:r})},openContextPanelTab:(r,o)=>{const n=k((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=H(s),c={...i.contextPanelByDirectory,[n]:Un(a,o)};return{contextPanelByDirectory:z(c,20)}})},openContextDiff:(r,o,n=!1)=>{const i=k((r||"").trim()),s=(o||"").trim();!i||!s||e().openContextPanelTab(i,{mode:"diff",targetPath:s,stagedDiff:n})},openContextFile:(r,o)=>{const n=k((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=k((r||"").trim()),a=_e(o),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,d=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:d}))},openContextOverview:r=>{const o=k((r||"").trim());o&&e().openContextPanelTab(o,{mode:"context"})},openContextPlan:r=>{const o=k((r||"").trim());o&&e().openContextPanelTab(o,{mode:"plan"})},openContextPreview:(r,o)=>{const n=k((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=k((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=k((r||"").trim()),s=(o||"").trim();!i||!s||t(a=>{const c=a.contextPanelByDirectory[i];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[i]:zn(c,s,n)}}:a})},setActiveContextPanelTab:(r,o)=>{const n=k((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=H(a);if(!c.tabs.some(l=>l.id===i)||c.activeTabId===i&&c.isOpen)return s;const d={...s.contextPanelByDirectory,[n]:{...c,isOpen:!0,activeTabId:i,touchedAt:Date.now(),tabs:c.tabs.map(l=>l.id===i?{...l,touchedAt:Date.now()}:l)}};return{contextPanelByDirectory:z(d,20)}})},reorderContextPanelTabs:(r,o,n)=>{const i=k((r||"").trim()),s=(o||"").trim(),a=(n||"").trim();!i||!s||!a||t(c=>{const d=c.contextPanelByDirectory[i],l=H(d);if(!l.tabs.some(m=>m.id===s)||!l.tabs.some(m=>m.id===a))return c;const f=Hn(l,s,a);if(f.tabs===l.tabs)return c;const y={...c.contextPanelByDirectory,[i]:f};return{contextPanelByDirectory:z(y,20)}})},closeContextPanelTab:(r,o)=>{const n=k((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=H(a);if(!c.tabs.some(l=>l.id===i))return s;const d={...s.contextPanelByDirectory,[n]:Bn(c,i)};return{contextPanelByDirectory:z(d,20)}})},closeContextPanel:r=>{const o=k((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o];if(!i||!i.isOpen)return n;const s={...n.contextPanelByDirectory,[o]:{...H(i),isOpen:!1}};return{contextPanelByDirectory:z(s,20)}})},toggleContextPanelExpanded:r=>{const o=k((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o],s=H(i),a={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:z(a,20)}})},setContextPanelWidth:(r,o)=>{const n=k((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=H(s),c={...i.contextPanelByDirectory,[n]:{...a,width:Yr(o)}};return{contextPanelByDirectory:z(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)||(et.set(tt(),r),t({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{et.set(tt(r),e().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=et.get(tt(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})},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(Dn);if(n===1){for(const[s]of i)o.style.removeProperty(Vt(s));return}for(const[s,a]of i){const c=parseFloat(a);Number.isFinite(c)&&o.style.setProperty(Vt(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 d=s.favoriteModels.slice(),[l]=d.splice(a,1);return l?(d.splice(c,0,l),{favoriteModels:d}):s})},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(d=>{const l=d.recentEfforts[a]??[];if(l.includes(c))return d;const f=l;return{recentEfforts:{...d.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})},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:Qt(r)})},toggleExpandedInput:()=>{t(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{t({isExpandedInput:r})}}),{name:"ui-store",storage:gr(()=>K()),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&&_n(r.notificationTemplates)&&(r.notificationTemplates={completion:{...U.completion},error:{...U.error},question:{...U.question},subtask:{...U.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=rt(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=rt(r.contextPanelByDirectory)),e<7&&(r.contextPanelByDirectory=rt(r.contextPanelByDirectory)),e<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=Qt(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,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,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,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"})),$n=Le()(Ue(yr((t,e)=>({queuedMessages:{},queueModeEnabled:!0,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}}})},popToInput:(r,o)=>{const s=(e().queuedMessages[r]??[]).find(a=>a.id===o);return s?(t(a=>{const d=(a.queuedMessages[r]??[]).filter(l=>l.id!==o);if(d.length===0){const{[r]:l,...f}=a.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...a.queuedMessages,[r]:d}}}),s):null},clearQueue:r=>{t(o=>{const{[r]:n,...i}=o.queuedMessages;return{queuedMessages:i}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:r=>{t({queueModeEnabled:r}),L({queueModeEnabled:r})},getQueueForSession:r=>e().queuedMessages[r]??[]}),{name:"message-queue-store",storage:gr(()=>K()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),no="directoryTreeShowHidden",ut="directory-show-hidden-change",Xt=()=>{if(typeof window>"u")return!0;try{const t=K().getItem(no);return t===null?!0:t==="true"}catch{return!0}},Gn=()=>{typeof window>"u"||window.dispatchEvent(new Event(ut))},Wn=(t,e={})=>{if(!(typeof window>"u")){try{K().setItem(no,t?"true":"false"),Gn()}catch{}e.persist!==!1&&L({directoryShowHidden:t})}},Ya=()=>{const t=wr.c(2),[e,r]=Oe.useState(Xt);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(Xt())};return window.addEventListener("storage",i),window.addEventListener(ut,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(ut,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),Oe.useEffect(o,n),e},io="filesViewShowGitignored",ft="files-view-show-gitignored-change",Zt=()=>{if(typeof window>"u")return!1;try{return K().getItem(io)==="true"}catch{return!1}},qn=()=>{typeof window>"u"||window.dispatchEvent(new Event(ft))},Kn=(t,e={})=>{if(!(typeof window>"u")){try{K().setItem(io,t?"true":"false"),qn()}catch{}e.persist!==!1&&L({filesViewShowGitignored:t})}},Xa=()=>{const t=wr.c(2),[e,r]=Oe.useState(Zt);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(Zt())};return window.addEventListener("storage",i),window.addEventListener(ft,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(ft,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),Oe.useEffect(o,n),e},Vn=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},Jn=t=>{if(!t||typeof t!="object")return null;const e=t;return{showReasoningTraces:e.showReasoningTraces,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks}},Qn=t=>{const e=X.getState();typeof t.showReasoningTraces=="boolean"&&e.setShowReasoningTraces(t.showReasoningTraces),typeof t.collapsibleThinkingBlocks=="boolean"&&e.setCollapsibleThinkingBlocks(t.collapsibleThinkingBlocks)},Yn=async()=>{if(typeof window>"u")return null;const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const e=JSON.parse(t),r=Jn(e);return Vn(r)}catch(e){return console.warn("Failed to parse stored appearance preferences:",e),null}},so=[{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"}],Xn=new Map(so.map(t=>[t.name,t])),Za=t=>Xn.get(t),ec=so.map(t=>({type:"command",name:t.name})),tc="terminal-box",rc="book-open",oc=t=>`${t.type}:${t.name}`,nc=(t,e)=>t.type===e.type&&t.name===e.name,ic=t=>{const e=t.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):t},ao=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},Zn=t=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=t}catch{}},pt=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),Zn(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"&&Jr(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")}(t.sttProvider==="browser"||t.sttProvider==="server")&&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.sttLanguage=="string"&&localStorage.setItem("sttLanguage",t.sttLanguage),typeof t.sttSilenceThresholdDb=="number"&&Number.isFinite(t.sttSilenceThresholdDb)&&localStorage.setItem("sttSilenceThresholdDb",String(t.sttSilenceThresholdDb)),typeof t.sttSilenceHoldMs=="number"&&Number.isFinite(t.sttSilenceHoldMs)&&localStorage.setItem("sttSilenceHoldMs",String(t.sttSilenceHoldMs)),typeof t.sttTranscribeOnStop=="boolean"&&localStorage.setItem("sttTranscribeOnStop",String(t.sttTranscribeOnStop))}},ht=t=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))},ei=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():"",d=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}:{},...d?{gitIdentityId:d}:{}}))}return e},ti=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},ri=(t,e)=>{const r=Object.entries(t),o=Object.entries(e);return r.length!==o.length?!1:r.every(([n,i])=>e[n]===i)},oi=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,ni=t=>{if(typeof t!="string")return null;const e=t.trim();return e&&oi.test(e)?e.toLowerCase():null},ii=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=Tn(a);if(!c||r.has(c)||o.has(a))continue;r.add(c),o.add(a);const d={id:c,path:a};if(typeof i.label=="string"&&i.label.trim().length>0&&(d.label=i.label.trim()),typeof i.icon=="string"&&i.icon.trim().length>0&&(d.icon=i.icon.trim()),i.iconImage===null)d.iconImage=null;else if(i.iconImage&&typeof i.iconImage=="object"){const l=i.iconImage,f=typeof l.mime=="string"?l.mime.trim():"",y=typeof l.updatedAt=="number"&&Number.isFinite(l.updatedAt)?Math.max(0,Math.round(l.updatedAt)):0,m=l.source==="custom"||l.source==="auto"?l.source:null;f&&y>0&&m&&(d.iconImage={mime:f,updatedAt:y,source:m})}if(typeof i.color=="string"&&i.color.trim().length>0&&(d.color=i.color.trim()),i.iconBackground===null)d.iconBackground=null;else{const l=ni(i.iconBackground);l&&(d.iconBackground=l)}typeof i.addedAt=="number"&&Number.isFinite(i.addedAt)&&i.addedAt>=0&&(d.addedAt=i.addedAt),typeof i.lastOpenedAt=="number"&&Number.isFinite(i.lastOpenedAt)&&i.lastOpenedAt>=0&&(d.lastOpenedAt=i.lastOpenedAt),typeof i.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=i.sidebarCollapsed),e.push(d)}return e.length>0?e:void 0},si=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},ai=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},er=(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},co=()=>{const t=X.persist;if(t&&typeof t=="object")return t},lo=()=>$e()?.settings??null,mt=t=>{const e=X.getState(),r=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,o=typeof window<"u"?window.__zustand_config_store__??null:null,n=$n.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==e.showReasoningTraces&&e.setShowReasoningTraces(t.showReasoningTraces),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 i=Math.max(1,Math.min(365,t.autoDeleteAfterDays));i!==e.autoDeleteAfterDays&&e.setAutoDeleteAfterDays(i)}if((t.sessionRetentionAction==="archive"||t.sessionRetentionAction==="delete")&&t.sessionRetentionAction!==e.sessionRetentionAction&&e.setSessionRetentionAction(t.sessionRetentionAction),typeof t.queueModeEnabled=="boolean"&&t.queueModeEnabled!==n.queueModeEnabled&&n.setQueueMode(t.queueModeEnabled),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 i=ao(t.draftStarters);JSON.stringify(e.globalDraftStarters)!==JSON.stringify(i)&&e.setGlobalDraftStarters(i)}if(typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&t.terminalFontSize!==e.terminalFontSize&&e.setTerminalFontSize(t.terminalFontSize),Kr(t.uiFont)&&t.uiFont!==e.uiFont&&e.setUiFont(t.uiFont),Vr(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&&!ri(t.shortcutOverrides,e.shortcutOverrides)&&X.setState({shortcutOverrides:t.shortcutOverrides}),typeof t.mobileKeyboardMode=="string"){const i=We(t.mobileKeyboardMode,e.mobileKeyboardMode);i!==e.mobileKeyboardMode&&e.setMobileKeyboardMode(i)}if(o&&r){const i={};(t.sttProvider==="browser"||t.sttProvider==="server")&&t.sttProvider!==r.sttProvider&&(i.sttProvider=t.sttProvider),typeof t.sttServerUrl=="string"&&t.sttServerUrl!==r.sttServerUrl&&(i.sttServerUrl=t.sttServerUrl),typeof t.sttModel=="string"&&t.sttModel!==r.sttModel&&(i.sttModel=t.sttModel),typeof t.sttLanguage=="string"&&t.sttLanguage!==r.sttLanguage&&(i.sttLanguage=t.sttLanguage),typeof t.sttSilenceThresholdDb=="number"&&Number.isFinite(t.sttSilenceThresholdDb)&&t.sttSilenceThresholdDb!==r.sttSilenceThresholdDb&&(i.sttSilenceThresholdDb=t.sttSilenceThresholdDb),typeof t.sttSilenceHoldMs=="number"&&Number.isFinite(t.sttSilenceHoldMs)&&t.sttSilenceHoldMs!==r.sttSilenceHoldMs&&(i.sttSilenceHoldMs=t.sttSilenceHoldMs),typeof t.sttTranscribeOnStop=="boolean"&&t.sttTranscribeOnStop!==r.sttTranscribeOnStop&&(i.sttTranscribeOnStop=t.sttTranscribeOnStop),Object.keys(i).length>0&&o.setState(i)}if(Array.isArray(t.favoriteModels)){const i=e.favoriteModels,s=t.favoriteModels;i.length===s.length&&i.every((c,d)=>c.providerID===s[d]?.providerID&&c.modelID===s[d]?.modelID)||X.setState({favoriteModels:s})}if(Array.isArray(t.recentModels)){const i=e.recentModels,s=t.recentModels;i.length===s.length&&i.every((c,d)=>c.providerID===s[d]?.providerID&&c.modelID===s[d]?.modelID)||X.setState({recentModels:s})}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"&&Wn(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&Kn(t.filesViewShowGitignored,{persist:!1})},tr=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 l=e.opencodeBinary.trim();r.opencodeBinary=l.length>0?l:void 0}typeof e.desktopLanAccessEnabled=="boolean"&&(r.desktopLanAccessEnabled=e.desktopLanAccessEnabled);const o=ii(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(l=>typeof l=="string"&&l.length>0)),Array.isArray(e.pinnedDirectories)&&(r.pinnedDirectories=Array.from(new Set(e.pinnedDirectories.filter(l=>typeof l=="string"&&l.length>0)))),Array.isArray(e.draftStarters)&&(r.draftStarters=ao(e.draftStarters)),typeof e.showReasoningTraces=="boolean"&&(r.showReasoningTraces=e.showReasoningTraces),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 l=e.tunnelProvider.trim().toLowerCase();l.length>0&&(r.tunnelProvider=l)}if(typeof e.tunnelMode=="string"){const l=e.tunnelMode.trim().toLowerCase();(l==="quick"||l==="managed-remote"||l==="managed-local")&&(r.tunnelMode=l)}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 l=e.managedLocalTunnelConfigPath.trim();r.managedLocalTunnelConfigPath=l.length>0?l: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=si(e.managedRemoteTunnelPresets);if(n&&(r.managedRemoteTunnelPresets=n),typeof e.managedRemoteTunnelSelectedPresetId=="string"){const l=e.managedRemoteTunnelSelectedPresetId.trim();r.managedRemoteTunnelSelectedPresetId=l.length>0?l:void 0}const i=ai(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.autoCreateWorktree=="boolean"&&(r.autoCreateWorktree=e.autoCreateWorktree),typeof e.gitmojiEnabled=="boolean"&&(r.gitmojiEnabled=e.gitmojiEnabled),typeof e.queueModeEnabled=="boolean"&&(r.queueModeEnabled=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 l=e.notificationTemplates,f=b=>{const v=l[b];if(!v||typeof v!="object")return;const M=v,O=typeof M.title=="string"?M.title:"",C=typeof M.message=="string"?M.message:"";return{title:O,message:C}},y=f("completion"),m=f("error"),w=f("question"),g=f("subtask");(y||m||w||g)&&(r.notificationTemplates={completion:y??{title:"Task Complete",message:"Your task has finished."},error:m??{title:"Error Occurred",message:"An error occurred while processing your task."},question:w??{title:"Input Needed",message:"Please provide input to continue."},subtask:g??{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(l=>typeof l=="string"&&l.length>0)),e.usageSelectedModels&&typeof e.usageSelectedModels=="object"){const l={};for(const[f,y]of Object.entries(e.usageSelectedModels))Array.isArray(y)&&(l[f]=y.filter(m=>typeof m=="string"));Object.keys(l).length>0&&(r.usageSelectedModels=l)}if(e.usageCollapsedFamilies&&typeof e.usageCollapsedFamilies=="object"){const l={};for(const[f,y]of Object.entries(e.usageCollapsedFamilies))Array.isArray(y)&&(l[f]=y.filter(m=>typeof m=="string"));Object.keys(l).length>0&&(r.usageCollapsedFamilies=l)}if(e.usageExpandedFamilies&&typeof e.usageExpandedFamilies=="object"){const l={};for(const[f,y]of Object.entries(e.usageExpandedFamilies))Array.isArray(y)&&(l[f]=y.filter(m=>typeof m=="string"));Object.keys(l).length>0&&(r.usageExpandedFamilies=l)}if(e.usageModelGroups&&typeof e.usageModelGroups=="object"){const l={};for(const[f,y]of Object.entries(e.usageModelGroups))if(y&&typeof y=="object"){const m=y,w={};Array.isArray(m.customGroups)&&(w.customGroups=m.customGroups.filter(g=>g&&typeof g=="object").map(g=>({id:String(g.id??""),label:String(g.label??""),models:Array.isArray(g.models)?g.models.filter(b=>typeof b=="string"):[],order:typeof g.order=="number"?g.order:0}))),m.modelAssignments&&typeof m.modelAssignments=="object"&&(w.modelAssignments=Object.fromEntries(Object.entries(m.modelAssignments).filter(([,g])=>typeof g=="string").map(([g,b])=>[g,String(b)]))),m.renamedGroups&&typeof m.renamedGroups=="object"&&(w.renamedGroups=Object.fromEntries(Object.entries(m.renamedGroups).filter(([,g])=>typeof g=="string").map(([g,b])=>[g,String(b)]))),Object.keys(w).length>0&&(l[f]=w)}Object.keys(l).length>0&&(r.usageModelGroups=l)}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),Kr(e.uiFont)&&(r.uiFont=e.uiFont),Vr(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=ti(e.shortcutOverrides);s&&(r.shortcutOverrides=s),typeof e.mobileKeyboardMode=="string"&&(e.mobileKeyboardMode==="native"||e.mobileKeyboardMode==="resize-content")&&(r.mobileKeyboardMode=e.mobileKeyboardMode);const a=er(e.favoriteModels,64);a&&(r.favoriteModels=a);const c=er(e.recentModels,16);if(c&&(r.recentModels=c),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 l=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);r.pwaAppName=l.length>0?l:""}const d=ei(e.skillCatalogs);return d&&(r.skillCatalogs=d),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),(e.sttProvider==="browser"||e.sttProvider==="server")&&(r.sttProvider=e.sttProvider),typeof e.sttServerUrl=="string"&&(r.sttServerUrl=e.sttServerUrl.trim()),typeof e.sttModel=="string"&&(r.sttModel=e.sttModel.trim()),typeof e.sttLanguage=="string"&&(r.sttLanguage=e.sttLanguage.trim()),typeof e.sttSilenceThresholdDb=="number"&&Number.isFinite(e.sttSilenceThresholdDb)&&(r.sttSilenceThresholdDb=e.sttSilenceThresholdDb),typeof e.sttSilenceHoldMs=="number"&&Number.isFinite(e.sttSilenceHoldMs)&&(r.sttSilenceHoldMs=e.sttSilenceHoldMs),typeof e.sttTranscribeOnStop=="boolean"&&(r.sttTranscribeOnStop=e.sttTranscribeOnStop),r};let Q=null,ie=null;const ci=2e3,li=async()=>Q&&Date.now()-Q.at<ci?Q.value:ie||(ie=(async()=>{const t=lo();if(t)try{const e=await t.load(),r=tr(e.settings);return Q={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=tr(r);return Q={value:o,at:Date.now()},o}catch(e){return console.warn("Failed to load shared settings from server:",e),null}})().finally(()=>{ie=null}),ie),sc=async()=>{if(typeof window>"u")return;const t=co(),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{pt(o)}catch(n){console.warn("persistToLocalStorage failed:",n)}await e();try{mt(o)}catch(n){console.warn("applyDesktopUiPreferences failed:",n)}ht(o)};try{const o=await li();o&&await r(o)}catch(o){console.warn("Failed to synchronise settings:",o)}};let xe=null,Ce=null;const di=200,ui=async()=>{const t=xe;if(xe=null,Ce=null,!t||Object.keys(t).length===0)return;const e=lo();if(e)try{const r=await e.save(t);r&&(pt(r),mt(r),ht(r));return}catch(r){console.warn("Failed to update settings via runtime settings API:",r)}try{const r=await u("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!r.ok){console.warn("Failed to update shared settings via API:",r.status,r.statusText);return}const o=await r.json().catch(()=>null);o&&(pt(o),mt(o),ht(o),Q=null)}catch(r){console.warn("Failed to update shared settings via API:",r)}},L=async t=>{typeof window>"u"||(xe={...xe??{},...t},Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{ui()},di))},ac=async()=>{if(typeof window>"u")return;const t=co();try{const e=await Yn();if(!e)return;const r=()=>Qn(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)}},fi=3e4,pi=40,hi=60,mi=(t,e,r,o,n,i)=>{const s=t.trim(),a=e.trim().toLowerCase();return JSON.stringify([s,a,r,o,n,i])},rr=(t,e)=>{try{const r=JSON.parse(t);return Array.isArray(r)&&r[0]===e}catch{return!1}},yi=Le()(Ue((t,e)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(r,o,n=hi,i){if(!r||r.trim().length===0)return[];const s=r.trim(),a=typeof o=="string"?o.trim():"",c=!!i?.includeHidden,d=i?.respectGitignore??!0,l=i?.type==="directory"?"directory":"file",f=mi(s,a,n,c,d,l),y=Date.now(),m=e().cache[f];if(m&&y-m.timestamp<fi)return m.files;const w=e().inFlight[f];if(w)return w;const g=B.searchFiles(a,{directory:s,limit:n,includeHidden:c,respectGitignore:d,dirs:l!=="file",type:l}).then(b=>(t(v=>{if(v.inFlight[f]!==g)return v;const M={...v.cache,[f]:{files:b,timestamp:Date.now()}},O=v.cacheKeys.filter(C=>C!==f);for(O.push(f);O.length>pi;){const C=O.shift();C&&delete M[C]}return{cache:M,cacheKeys:O}}),b)).finally(()=>{t(b=>{if(b.inFlight[f]!==g)return b;const v={...b.inFlight};return delete v[f],{inFlight:v}})});return t(b=>({inFlight:{...b.inFlight,[f]:g}})),g},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(d=>rr(d,o)?(delete i[d],!1):!0),a=Object.entries(n.inFlight).filter(([d])=>!rr(d,o)),c=Object.fromEntries(a);return{cache:i,cacheKeys:s,inFlight:c}})}}),{name:"file-search-store"})),gi=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},yt="openchamber_stream_perf",me=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(yt)==="1"}catch{return!1}},or=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),wi=()=>{if(!me()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const t=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:t,lastUpdatedAt:t}}return window.__openchamberStreamPerfState},uo=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),Ct=(t,e)=>{const r=wi();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()},cc=t=>{if(!(typeof window>"u"))try{if(t){window.localStorage.setItem(yt,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(yt),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},lc=()=>{typeof window>"u"||(me()&&(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()}))},dc=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberStreamPerfState;return!me()||!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:uo(t.counters)}},uc=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberVsCodeStreamPerfState;if(!me()||!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:uo(t.counters)}},fc=(t,e=1)=>{Ct(t,e)},pc=(t,e)=>{Ct(t,e)},hc=(t,e)=>{if(!me())return e();const r=or();try{return e()}finally{Ct(t,or()-r)}};var bi={};let _=null,nr=0;const F=K(),ir=F.getItem("lastDirectory"),Si=typeof ir=="string"&&ir.length>0,Se=t=>{try{yi.getState().invalidateDirectory(t)}catch(e){console.warn("Failed to invalidate file search cache:",e)}},ee=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},Ti=(t,e)=>{const r=t.trim();return r.startsWith("~")?r==="~"?e||r:(r.startsWith("~/")||r.startsWith("~\\"))&&e?`${e}${r.slice(1)}`:r:r},Ae=(t,e)=>{const r=Ti(t,e);return ee(r)},vi=()=>{const t=F.getItem("homeDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=ee(t);return e.length>0?e:null},ki=()=>{const t=F.getItem("lastDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=ee(t);return e.length>0?e:null},Di=()=>{if(typeof process>"u")return null;const t=bi,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=ee(e);return o.length>0?o:null}const r=process?.cwd?.();if(typeof r=="string"&&r.trim().length>0){const o=ee(r);return o.length>0?o:null}return null},je=()=>{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=vi();if(r&&!Ge())return _=r,r}const t=Di();return t||"/"},Ei=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},Pi=t=>(_=t,typeof window<"u"&&F.setItem("homeDirectory",t),L({homeDirectory:t}),t),gt=async()=>{const t=o=>{const n=Ei(o);return n?Pi(n):null};try{const o=await B.getFilesystemHome(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain filesystem home directory:",o)}try{const o=await B.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 Ur(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain desktop-integrated home directory:",o)}const e=je(),r=t(e);return r||e},Mi=()=>{if(!Ge())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const e=ee(t);return e.length>0?e:null},pe=Mi()||je(),Ne=(()=>{const t=ki();return t&&!Ge()?Ae(t,pe):pe})();Ne&&B.setDirectory(Ne);const Ci=!!(pe&&pe!=="/"),wt=Le()(Ue((t,e)=>({currentDirectory:Ne,directoryHistory:[Ne],historyIndex:0,homeDirectory:pe,hasPersistedDirectory:Si,isHomeReady:Ci,isSwitchingDirectory:!1,setDirectory:(r,o)=>{const n=_||e().homeDirectory||F.getItem("homeDirectory"),i=Ae(r,n);gi()&&console.log("[DirectoryStore] setDirectory called with path:",i),B.setDirectory(i),Se(),t(s=>{const a=[...s.directoryHistory.slice(0,s.historyIndex+1),i];return F.setItem("lastDirectory",i),L({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];B.setDirectory(n),Se(),F.setItem("lastDirectory",n),L({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];B.setDirectory(n),Se(),F.setItem("lastDirectory",n),L({lastDirectory:n}),t({currentDirectory:n,historyIndex:o,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:r,setDirectory:o}=e(),n=_||e().homeDirectory||je();if(r===n||r==="/")return;const i=r.endsWith("/")?r.slice(0,-1):r,s=i.lastIndexOf("/");if(s===-1){const a=_||je();o(a)}else o(s===0?"/":i.substring(0,s))},goHome:async()=>{const r=_||e().homeDirectory||await gt();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 d=typeof n=="string"&&n!==""&&n!=="/",l=o.currentDirectory?Ae(o.currentDirectory,n):o.currentDirectory,f=o.directoryHistory.map(g=>Ae(g,n)),y=f.some((g,b)=>g!==o.directoryHistory[b]),m=!!(l&&l!==o.currentDirectory),w={homeDirectory:n,hasPersistedDirectory:a,isHomeReady:d};if(c?(w.currentDirectory=n,w.directoryHistory=[n],w.historyIndex=0,w.isSwitchingDirectory=!1):(m||y)&&(w.currentDirectory=l,w.directoryHistory=f,w.historyIndex=Math.min(o.historyIndex,f.length-1),w.isSwitchingDirectory=!1),t(()=>w),(c||m)&&d){const g=c?n:l;B.setDirectory(g),Se(),F.setItem("lastDirectory",g),L({lastDirectory:g})}L({homeDirectory:n})}}),{name:"directory-store"}));typeof window<"u"&&(gt().then(t=>{wt.getState().synchronizeHomeDirectory(t)}),qo(()=>{_=null;const t=++nr;gt().then(e=>{t===nr&&wt.getState().synchronizeHomeDirectory(e)})}));const fo=1,x=1,Te=0,po="/api/terminal/ws",Ai=1200,Oi=250,Ii=2e4,Ri=5e3,ot="__openchamberTerminalTransportState",Fi=new TextEncoder,sr=new TextDecoder,At=t=>D().websocket(t),nt=t=>{const e=Fi.encode(JSON.stringify(t)),r=new Uint8Array(e.length+1);return r[0]=fo,r.set(e,1),r},he=t=>t?((t.transports??[]).includes("ws")||t.preferred==="ws")&&typeof t.ws?.path=="string"&&t.ws.path.length>0:!1,Ot=t=>t.streamCapability?.ws?.path??t.inputCapability?.ws?.path??po,_i=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 xi{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(Ai);if(!o||o.readyState!==x)return!1;try{return this.boundSessionId!==e&&(this.requestedSessionId=e,o.send(nt({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===Te)?!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===Te)||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===Te&&(i.close(),n(null))},Ri)}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(nt({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()*Oi),d=a+c;this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},d)}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(nt(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})},Ii)}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]===fo){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(sr.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=_i(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?sr.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===Te)&&e.close()}this.boundSessionId=null}}const N=()=>{const t=globalThis;return t[ot]||(t[ot]={inputCapability:null,streamCapability:null,manager:null}),t[ot]},It=()=>{const t=N();return t.manager||(t.manager=new xi),t.manager},ho=t=>{const e=N();if(e.inputCapability=t?.input??null,e.streamCapability=t?.stream??null,!he(e.inputCapability)&&!he(e.streamCapability)){e.manager?.close(),e.manager=null;return}const r=At(Ot(e));if(!r)return;It().configure(r)},ji=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 Ni(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 ho(r.capabilities),r}const ar=(t,e,r,o={})=>{const n=o.maxRetries??3,i=o.initialRetryDelay??1e3,s=o.maxRetryDelay??8e3,a=o.connectionTimeout??1e4;let c=null,d=0,l=null,f=null,y=!1,m=!1;const w=()=>{l&&(clearTimeout(l),l=null),f&&(clearTimeout(f),f=null)},g=()=>{y||(y=!0,w(),c&&(c.close(),c=null))},b=(M,O)=>{if(!(y||m)){if(d<n&&!O){d+=1;const C=Math.min(i*Math.pow(2,d-1),s);e({type:"reconnecting",attempt:d,maxAttempts:n}),l=setTimeout(()=>{!y&&!m&&v()},C);return}r?.(M,!0),g()}},v=()=>{if(y||m||c&&c.readyState!==EventSource.CLOSED)return;c=new EventSource(D().sse(`/api/terminal/${t}/stream`));let M=!1;f=setTimeout(()=>{!M&&c?.readyState!==EventSource.OPEN&&(c?.close(),b(new Error("Connection timeout"),!1))},a),c.onopen=()=>{M||(M=!0,d=0,w(),e({type:"connected"}))},c.onmessage=O=>{try{const C=JSON.parse(O.data);C.type==="exit"&&(N().manager?.unbindSession(t),m=!0,g()),e(C)}catch(C){r?.(C,!1)}},c.onerror=()=>{w();const O=m||c?.readyState===EventSource.CLOSED;c?.close(),c=null,m||b(new Error("Terminal stream connection error"),O)}};return v(),g};function Li(t,e,r,o={}){const n=N();if(!he(n.streamCapability))return ar(t,e,r,o);const i=It(),s=At(Ot(n));return s?(i.configure(s),i.subscribe(t,e,r,o)):ar(t,e,r,o)}async function Ui(t,e){const r=N();r.manager&&await r.manager.sendInput(t,e)||await ji(t,e)}async function Bi(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 Hi(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 zi(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 ho(o.capabilities),o}async function $i(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 mc(){const t=N();t.manager?.close(),t.manager=null,t.inputCapability=null,t.streamCapability=null}function yc(){const t=N();if(t.inputCapability&&t.streamCapability&&!he(t.inputCapability)&&!he(t.streamCapability))return;const e=Ot(t)||po,r=At(e);if(!r)return;const o=It();o.isConnectedOrConnecting(r)||(o.configure(r),o.prime())}const Gi=t=>{const e=t?.retry;return{maxRetries:e?.maxRetries??3,initialRetryDelay:e?.initialDelayMs??1e3,maxRetryDelay:e?.maxDelayMs??8e3,connectionTimeout:t?.connectionTimeoutMs??1e4}},Wi=()=>({async createSession(t){return Ni(t)},connect(t,e,r){const o=Li(t,e.onEvent,e.onError,Gi(r));return{close:()=>o()}},async sendInput(t,e){await Ui(t,e)},async resize(t){await Bi(t.sessionId,t.cols,t.rows)},async close(t){await Hi(t)},async restartSession(t,e){return zi(t,{cwd:e.cwd??"",cols:e.cols,rows:e.rows})},async forceKill(t){await $i(t)}}),p="/api/git",qi=1200,Ki=5e3,cr=new Map,ve=new Map,lr=new Map,ke=new Map,bt=t=>t.trim();function h(t,e,r){const o={...r};return e&&(o.directory=e),D().api(t,o)}async function Vi(t){const e=bt(t),r=Date.now(),o=lr.get(e);if(o&&o.expiresAt>r)return o.value;const n=ke.get(e);if(n)return n;const i=(async()=>{const s=await u(h(`${p}/check`,t));if(!s.ok)throw new Error(`Failed to check git repository: ${s.statusText}`);const c=!!(await s.json()).isGitRepository;return lr.set(e,{value:c,expiresAt:Date.now()+Ki}),c})();ke.set(e,i);try{return await i}finally{ke.get(e)===i&&ke.delete(e)}}async function Ji(t,e){const r=e?.mode,o=r==="light"?`${bt(t)}::light`:bt(t),n=Date.now(),i=cr.get(o);if(i&&i.expiresAt>n)return i.value;const s=ve.get(o);if(s)return s;const a=(async()=>{const c=await u(h(`${p}/status`,t,r?{mode:r}:void 0));if(!c.ok)throw new Error(`Failed to get git status: ${c.statusText}`);const d=await c.json();return cr.set(o,{value:d,expiresAt:Date.now()+qi}),d})();ve.set(o,a);try{return await a}finally{ve.get(o)===a&&ve.delete(o)}}async function gc(t){const e=await u(h(`${p}/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 wc(t){const e=await u(h(`${p}/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 bc(t,e){const r=await u(h(`${p}/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 Qi(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(h(`${p}/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 Yi(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(h(`${p}/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 Xi(t,e,r){if(!e)throw new Error("path is required to revert git changes");const o=await u(h(`${p}/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")}}async function Zi(t,e){await mo(t,[e])}async function mo(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(h(`${p}/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")}}async function es(t,e){await yo(t,[e])}async function yo(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(h(`${p}/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")}}async function ts(t,e,r){await Rt(t,e,r,"stage")}async function rs(t,e,r){await Rt(t,e,r,"unstage")}async function os(t,e,r){await Rt(t,e,r,"discard")}async function Rt(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(h(`${p}/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")}}async function ns(t){if(!t)return!1;const e=await u(h(`${p}/worktree-type`,t));if(!e.ok)throw new Error(`Failed to detect worktree type: ${e.statusText}`);return!!(await e.json()).linked}async function is(t){const e=await u(h(`${p}/branches`,t));if(!e.ok)throw new Error(`Failed to get branches: ${e.statusText}`);return e.json()}async function ss(t,e){if(!e?.branch)throw new Error("branch is required to delete a branch");const r=await u(h(`${p}/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 as(t,e){if(!e?.branch)throw new Error("branch is required to delete remote branch");const r=await u(h(`${p}/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 cs(t,e){const r=e?.remote?.trim();if(!r)throw new Error("remote is required to remove a remote");const o=await u(h(`${p}/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 ls(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(h(`${p}/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 d=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${d}`)}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 ds(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 d=await u(h(`${p}/pr-description`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){const m=await d.json().catch(()=>({error:d.statusText}));throw new Error(m.error||"Failed to generate PR description")}const l=await d.json().catch(()=>null),f=typeof l?.title=="string"?l.title:"",y=typeof l?.body=="string"?l.body:"";if(!f&&!y)throw new Error("Malformed PR description response");return{title:f,body:y}}async function dr(t){const e=await u(h(`${p}/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 ur(t,e){const r=await u(h(`${p}/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 us(t){const e=await u(h(`${p}/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 fs(t,e){const r=await u(h(`${p}/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 fr(t,e){const r=await u(h(`${p}/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 pr(t,e){const r=await u(h(`${p}/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 ps(t,e,r={}){const o=await u(h(`${p}/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 n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to create commit")}return o.json()}async function hs(t,e={}){const r=await u(h(`${p}/push`,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 push")}return r.json()}async function ms(t,e={}){const r=await u(h(`${p}/pull`,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 pull")}return r.json()}async function ys(t,e={}){const r=await u(h(`${p}/fetch`,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 fetch")}return r.json()}async function gs(t){const e=await u(h(`${p}/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 ws(t,e){const r=await u(h(`${p}/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 go(t,e={}){const r=await u(h(`${p}/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 Ft=async(t,e,r)=>{const o=await u(h(`${p}/${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()},bs=(t,e)=>Ft(t,"stash/apply",e),wo=(t,e)=>Ft(t,"stash/pop",e),Ss=(t,e)=>Ft(t,"stash/drop",e);async function Ts(t,e){const r=await u(h(`${p}/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 vs(t,e,r){const o=await u(h(`${p}/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 ks(t,e,r){const o=await u(h(`${p}/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 Ds(t,e={}){const r=await u(h(`${p}/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 Es(t,e){const r=await u(h(`${p}/commit-files`,t,{hash:e}));if(!r.ok)throw new Error(`Failed to get commit files: ${r.statusText}`);return r.json()}async function Sc(t,e,r,o){const n=await u(h(`${p}/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 Ps(){const t=await u(h(`${p}/identities`,void 0));if(!t.ok)throw new Error(`Failed to get git identities: ${t.statusText}`);return t.json()}async function Ms(t){const e=await u(h(`${p}/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 Cs(t,e){const r=await u(h(`${p}/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 As(t){const e=await u(h(`${p}/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 Os(t){if(!t)return null;const e=await u(h(`${p}/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 Is(t){if(!t)return!1;const e=await u(h(`${p}/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 Tc(){const t=await u(h(`${p}/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 Rs(t,e){const r=await u(h(`${p}/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 vc(){const t=await u(h(`${p}/discover-credentials`,void 0));if(!t.ok)throw new Error(`Failed to discover git credentials: ${t.statusText}`);return t.json()}async function kc(t,e){if(!t)return null;const r=await u(h(`${p}/remote-url`,t,{remote:e}));return r.ok?(await r.json()).url??null:null}async function Fs(t){const e=await u(h(`${p}/remotes`,t));if(!e.ok)throw new Error(`Failed to get remotes: ${e.statusText}`);return e.json()}async function _s(t,e){const r=await u(h(`${p}/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 xs(t){const e=await u(h(`${p}/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 js(t,e){const r=await u(h(`${p}/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 Ns(t,e){const r=await u(h(`${p}/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 Ls(t,e){const r=await u(h(`${p}/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 Us(t,e){const r=await u(h(`${p}/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 Bs(t,e,r,o){const n=await u(h(`${p}/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 Hs(t){const e=await u(h(`${p}/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 zs(t){const e=await u(h(`${p}/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 $s(t){const e=await u(h(`${p}/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 Gs(t,e){return await go(t,{message:e?.message}),{success:!0}}async function Ws(t){return await wo(t,{ref:"stash@{0}"}),{success:!0}}async function qs(t){const e=await u(h(`${p}/conflict-details`,t));if(!e.ok)throw new Error(`Failed to get conflict details: ${e.statusText}`);return e.json()}async function Ks(t,e){const r=await u(`${p}/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 Vs(t){const e=await u(`${p}/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 Js=()=>({checkIsGitRepository:Vi,getGitStatus:Ji,getGitDiff:Qi,getGitFileDiff:Yi,revertGitFile:Xi,stageGitFile:Zi,stageGitFiles:mo,unstageGitFile:es,unstageGitFiles:yo,stageGitHunk:ts,unstageGitHunk:rs,revertGitHunk:os,isLinkedWorktree:ns,getGitBranches:is,deleteGitBranch:ss,deleteRemoteBranch:as,removeRemote:cs,generateCommitMessage:ls,generatePullRequestDescription:ds,listGitWorktrees:dr,validateGitWorktree:ur,createGitWorktree:fr,deleteGitWorktree:pr,validateWorktreeDirectory:Ks,canonicalizeWorktreeState:Vs,createGitCommit(t,e,r){return ps(t,e,r)},gitPush:hs,gitPull:ms,gitFetch:ys,listGitStashes:gs,countGitStashFiles:ws,stashGitChanges:go,applyGitStash:bs,popGitStash:wo,dropGitStash:Ss,checkoutBranch:Ts,createBranch:vs,renameBranch:ks,getGitLog(t,e){return Ds(t,e)},getCommitFiles:Es,getCurrentGitIdentity:Os,hasLocalIdentity:Is,setGitIdentity:Rs,getGitIdentities:Ps,createGitIdentity:Ms,updateGitIdentity:Cs,deleteGitIdentity:As,getRemotes:Fs,rebase:_s,abortRebase:xs,continueRebase:zs,merge:js,abortMerge:Hs,continueMerge:$s,checkoutCommit:Ns,cherryPick:Ls,revertCommit:Us,resetToCommit:Bs,stash:Gs,stashPop:Ws,getConflictDetails:qs,worktree:{list:dr,validate:ur,bootstrapStatus:us,preview:fs,create:fr,remove:pr}}),T=t=>t.replace(/\\/g,"/"),Qs=(t,e)=>{const r=T(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:T(n.path),isDirectory:!!n.isDirectory}))}},j=(t,e)=>{const r=e||t?.();return r?{"x-opencode-directory":r}:void 0},Ys=({urls:t,getDirectory:e})=>({async listDirectory(r,o){const n=T(r),i=new URLSearchParams;n&&i.set("path",n),o?.respectGitignore&&i.set("respectGitignore","true");const s=await u(t.api("/api/fs/list",i),{headers:j(e)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));throw new Error(c.error||"Failed to list directory")}const a=await s.json();return Qs(n,a)},async search(r){const o=new URLSearchParams,n=T(r.directory);n&&o.set("directory",n),o.set("query",r.query),o.set("dirs","false"),o.set("type","file"),typeof r.maxResults=="number"&&Number.isFinite(r.maxResults)&&o.set("limit",String(r.maxResults));const i=await u(t.api("/api/find/file",o),{headers:j(e)});if(!i.ok){const c=await i.json().catch(()=>({error:i.statusText}));throw new Error(c.error||"Failed to search files")}const s=await i.json();return(Array.isArray(s)?s:[]).map(c=>({path:T(`${n}/${c}`),preview:[T(c)]}))},async createDirectory(r){const o=T(r),n=await u(t.api("/api/fs/mkdir"),{method:"POST",headers:{"Content-Type":"application/json",...j(e)},body:JSON.stringify({path:o})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to create directory")}const i=await n.json();return{success:!!i?.success,path:typeof i?.path=="string"?T(i.path):o}},async statFile(r,o){const n=T(r),i=new URLSearchParams({path:n});o?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),o?.outsideFileGrant&&i.set("outsideFileGrant",o.outsideFileGrant);const s=await u(t.api("/api/fs/stat",i),{headers:j(e,o?.directory)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));throw new Error(c.error||"Failed to stat file")}const a=await s.json().catch(()=>({}));return{path:typeof a.path=="string"?T(a.path):n,isFile:!!a.isFile,size:typeof a.size=="number"?a.size:0,mtimeMs:typeof a.mtimeMs=="number"?a.mtimeMs:void 0}},async readFile(r,o){const n=T(r),i=new URLSearchParams({path:n});o?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),o?.outsideFileGrant&&i.set("outsideFileGrant",o.outsideFileGrant),o?.optional&&i.set("optional","true");const s=await u(t.api("/api/fs/read",i),{cache:o?.optional?"no-store":"default",headers:j(e,o?.directory)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));throw new Error(c.error||"Failed to read file")}return{content:await s.text(),path:n}},async writeFile(r,o){const n=T(r),i=await u(t.api("/api/fs/write"),{method:"POST",headers:{"Content-Type":"application/json",...j(e)},body:JSON.stringify({path:n,content:o})});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to write file")}const s=await i.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?T(s.path):n}},async delete(r){const o=T(r),n=await u(t.api("/api/fs/delete"),{method:"POST",headers:{"Content-Type":"application/json",...j(e)},body:JSON.stringify({path:o})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to delete file")}return{success:!!(await n.json().catch(()=>({}))).success}},async rename(r,o){const n=await u(t.api("/api/fs/rename"),{method:"POST",headers:{"Content-Type":"application/json",...j(e)},body:JSON.stringify({oldPath:r,newPath:o})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to rename file")}const i=await n.json().catch(()=>({}));return{success:!!i.success,path:typeof i.path=="string"?T(i.path):o}},async revealPath(r){const o=await u(t.api("/api/fs/reveal"),{method:"POST",headers:{"Content-Type":"application/json",...j(e)},body:JSON.stringify({path:T(r)})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to reveal path")}return{success:!!(await o.json().catch(()=>({}))).success}},async downloadFile(r){const o=T(r),n=await u("/api/fs/raw",{query:{path:o,download:!0},headers:j(e)});if(!n.ok)throw new Error(`Download failed (${n.status})`);const i=await n.blob(),s=URL.createObjectURL(i),a=document.createElement("a");a.href=s,a.download=o.split("/").pop()||"file",document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(s),100)}}),hr="/api/config/settings",Xs="/api/config/reload",mr=t=>!t||typeof t!="object"?{}:t,Zs=()=>({async load(){const t=await u(hr,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load settings: ${t.statusText}`);return{settings:mr(await t.json().catch(()=>({}))),source:"web"}},async save(t){const e=await u(hr,{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 mr(await e.json().catch(()=>({})))},async restartOpenCode(){const t=await u(Xs,{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}}}),ea=()=>({async requestDirectoryAccess(t){return{success:!0,path:t.path}},async startAccessingDirectory(t){return{success:!0}},async stopAccessingDirectory(t){return{success:!0}}}),ta=1500,St=5e3,ra="openchamber-notification-claim:",ce=new Map,oa=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),na=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("|")},ia=t=>{for(const[e,r]of ce)t-r>St&&ce.delete(e)},sa=t=>{const e=na(t);if(!e)return!0;const r=Date.now();ia(r);const o=ce.get(e)??0;if(r-o<St)return!1;try{if(typeof window<"u"&&window.localStorage){const n=`${ra}${e}`,i=Number(window.localStorage.getItem(n)??"0");if(Number.isFinite(i)&&r-i<St)return ce.set(e,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(n),window.localStorage.setItem(n,String(r))}}catch{}return ce.set(e,r),!0},bo=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),ta)})])??t}catch{return t}},aa=async t=>{const e=await bo();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}},ca=async()=>{const t=await bo();if(!t||!("pushManager"in t)||!t.pushManager)return!1;try{return!!await t.pushManager.getSubscription()}catch{return!1}},la=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(!oa()&&await ca()||!sa(t))return!0;try{return await aa(t)||new Notification(t?.title??"OpenChamber",{body:t?.body,tag:t?.tag}),!0}catch(e){return console.warn("Failed to send notification",e),!1}},da=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}},ua=()=>({async notifyAgentCompletion(t){return await da(t)||await la(t)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),fa=()=>({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()}}),De=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}},pa=()=>({async getVapidPublicKey(){return De("/api/push/vapid-public-key")},async subscribe(t){return De("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async unsubscribe(t){return De("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async setVisibility(t){return De("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})}}),S=async t=>await t.json().catch(()=>null),ha=({urls:t})=>({async authStatus(){const e=await u("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(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 S(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issue comments");return s}}),Ee=async t=>await t.json().catch(()=>null),ma=()=>({async listClients(){const t=await u("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),e=await Ee(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 Ee(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 Ee(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 Ee(t);if(!t.ok||!e)throw new Error(e?.error||t.statusText||"Failed to clear revoked clients");return e}}),ya=()=>({api:(...t)=>D().api(...t),authenticatedAsset:(...t)=>D().authenticatedAsset(...t),auth:(...t)=>D().auth(...t),health:(...t)=>D().health(...t),rawFile:(...t)=>D().rawFile(...t),sse:(...t)=>D().sse(...t),websocket:(...t)=>D().websocket(...t)}),ga=(t={})=>{const e=t.urls??Dt();jo(e);const r=ya();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Wi(),git:Js(),files:Ys({urls:r,getDirectory:()=>wt.getState().currentDirectory}),settings:Zs(),permissions:ea(),notifications:ua(),github:ha({urls:r}),push:pa(),clientAuth:ma(),tools:fa()}},wa=(t,e)=>{if(!t||!e)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}},Dc=()=>{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=Ar({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return Wo({apiBaseUrl:t,runtimeKey:wa(t,r)?"local":null}),vr(e||null),Tt(t||void 0).catch(()=>{}),Go(),ga({urls:o})};export{Ea as $,$i as A,ne as B,Ra as C,K as D,Ya as E,Xa as F,yi as G,$a as H,Sa as I,Ta as J,Oa as K,qo as L,Ha as M,Ba as N,dc as O,uc as P,lc as Q,Nn as R,R as S,Wa as T,Qo as U,Jo as V,ka as W,cc as X,Qa as Y,mc as Z,Da as _,Pt as a,dr as a$,Zo as a0,La as a1,ja as a2,Na as a3,jr as a4,va as a5,Kn as a6,$n as a7,Ja as a8,En as a9,ws as aA,vs as aB,ps as aC,Ms as aD,fr as aE,ss as aF,As as aG,pr as aH,as as aI,vc as aJ,Ss as aK,Sc as aL,Es as aM,qs as aN,Os as aO,is as aP,bc as aQ,Qi as aR,Yi as aS,Ps as aT,Ds as aU,Ji as aV,us as aW,Tc as aX,kc as aY,Fs as aZ,ur as a_,An as aa,Pn as ab,On as ac,Wn as ad,We as ae,Ma as af,Ua as ag,Ca as ah,Ia as ai,_a as aj,xa as ak,Tn as al,gi as am,qa as an,He as ao,ze as ap,Hs as aq,xs as ar,bs as as,Vs as at,Vi as au,Ts as av,Ns as aw,Ls as ax,$s as ay,zs as az,X as b,ys as b0,ms as b1,hs as b2,Is as b3,ns as b4,gs as b5,js as b6,wo as b7,fs as b8,_s as b9,Ur as bA,Za as bB,tc as bC,ic as bD,rc as bE,ec as bF,oc as bG,so as bH,nc as bI,fc as bJ,pc as bK,Fa as bL,hc as bM,Mn as bN,Cn as bO,yc as bP,cs as ba,ks as bb,Bs as bc,gc as bd,wc as be,Us as bf,Xi as bg,os as bh,Rs as bi,Zi as bj,mo as bk,ts as bl,Gs as bm,go as bn,Ws as bo,es as bp,yo as bq,rs as br,Cs as bs,Ks as bt,E as bu,Va as bv,Dn as bw,ge as bx,Ze as by,ao as bz,Dc as c,Pa as d,u as e,L as f,D as g,Lr as h,ac as i,I as j,Ga as k,za as l,en as m,Ka as n,B as o,Hi as p,$e as q,Tt as r,sc as s,Li as t,wt as u,Nr as v,Ge as w,A as x,kr as y,Aa as z};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-
|
|
2
|
-
import{c as w}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CIlawBoH.js","assets/vendor--Dwc_TRgJ.css","assets/renderMobileApp-CxEnmaQL.js","assets/index-DkRLSXEX.js","assets/index-Di3CDurc.css","assets/useAppFontEffects-DkrfZHQv.js","assets/NewWorktreeDialog-B2o615D_.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/main-gqEqIL1b.js","assets/SessionSwitcherDropdown-Bz03hrU9.js","assets/main-BV3KOtdA.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as w}from"./index-DkRLSXEX.js";import{_ as a}from"./vendor-.bun-CIlawBoH.js";import{g as p}from"./mobileLayoutPreference-Dio-WWkI.js";function h(t={}){const{immediate:r=!1,onNeedRefresh:n,onOfflineReady:o,onRegistered:s,onRegisteredSW:c,onRegisterError:d}=t;let i,u;const f=async(e=!0)=>{await u};async function m(){if("serviceWorker"in navigator){if(i=await a(async()=>{const{Workbox:e}=await import("./vendor-.bun-CIlawBoH.js").then(_=>_.cm);return{Workbox:e}},__vite__mapDeps([0,1])).then(({Workbox:e})=>new e("/sw.js",{scope:"/",type:"classic"})).catch(e=>{d?.(e)}),!i)return;i.addEventListener("activated",e=>{(e.isUpdate||e.isExternal)&&window.location.reload()}),i.addEventListener("installed",e=>{e.isUpdate||o?.()}),i.register({immediate:r}).then(e=>{c?c("/sw.js",e):s?.(e)}).catch(e=>{d?.(e)})}}return u=m(),f}window.__OPENCHAMBER_RUNTIME_APIS__=w();const v=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(pointer: coarse)").matches,g=()=>{const r=new URLSearchParams(window.location.search).get("surface");if(r==="mobile")return"mobile";if(r==="desktop")return"desktop";const n=Math.min(window.innerWidth||0,window.screen?.width||window.innerWidth||0),o=navigator.maxTouchPoints||0;return n>0&&n<=760&&(o>0||v())&&p()==="new"?"mobile":"desktop"},l=g();window.__OPENCHAMBER_SURFACE__=l;const S=()=>!(!("serviceWorker"in navigator)||!window.isSecureContext||window.location.protocol!=="http:"&&window.location.protocol!=="https:"||document.prerendering||String(document.visibilityState)==="prerender"),E=t=>{let r=!1;const n=()=>{r||S()&&(r=!0,t())},o=()=>{setTimeout(n,0)};document.readyState==="complete"?o():window.addEventListener("load",o,{once:!0}),(document.prerendering||String(document.visibilityState)==="prerender")&&document.addEventListener("visibilitychange",n,{once:!0})},P=()=>{E(()=>{try{h({onRegisterError(t){console.warn("[PWA] service worker registration skipped:",t)}})}catch(t){console.warn("[PWA] service worker registration skipped:",t)}})};l==="mobile"?a(async()=>{const{renderMobileApp:t}=await import("./renderMobileApp-CxEnmaQL.js");return{renderMobileApp:t}},__vite__mapDeps([2,0,1,3,4,5,6,7])).then(({renderMobileApp:t})=>{t(window.__OPENCHAMBER_RUNTIME_APIS__??w())}):a(()=>import("./main-gqEqIL1b.js").then(t=>t.m),__vite__mapDeps([8,0,1,3,4,5,6,7,9,10]));P();
|