@openchamber/web 1.13.4 → 1.13.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli-output.js +2 -0
- package/bin/cli-output.test.js +36 -0
- package/bin/cli.test.js +12 -0
- package/bin/lib/cli-http.js +1 -0
- package/bin/lib/cli-network.js +1 -0
- package/bin/lib/cli-paths.js +2 -0
- package/bin/lib/commands-tunnel.js +6 -2
- package/dist/assets/{DiagramView-BAoYIAGR.js → DiagramView-C_f1Il8p.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-B0NE4mIY.js → MarkdownRendererImpl-BR0DXO9F.js} +3 -3
- package/dist/assets/{MultiRunWindow-BT4kt6aB.js → MultiRunWindow-WBqBXcts.js} +1 -1
- package/dist/assets/NewWorktreeDialog-D7l2VA7o.js +167 -0
- package/dist/assets/{OnboardingScreen-CbJOPUxm.js → OnboardingScreen-ChaxLu9k.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-BbUzUNEi.js → SessionSwitcherDropdown-xaYa-FIx.js} +1 -1
- package/dist/assets/{SettingsWindow-CSb8eo8p.js → SettingsWindow-D5aAKCEM.js} +1 -1
- package/dist/assets/{TerminalView-ME5MOz7S.js → TerminalView-D8GzsMZF.js} +1 -1
- package/dist/assets/{es-Bk-yR0w-.js → es-D0PPWgfL.js} +1 -1
- package/dist/assets/{fr-f1ibV7QU.js → fr-4AxG2GNC.js} +1 -1
- package/dist/assets/index-DJHN0H4h.js +3 -0
- package/dist/assets/{index-B82A6jBD.css → index-DxqTiFfR.css} +1 -1
- package/dist/assets/{ja-D9mS3zWP.js → ja-BPVJtPU2.js} +1 -1
- package/dist/assets/{ko-Cpl1IA3D.js → ko-BJHERh2a.js} +1 -1
- package/dist/assets/{main-D6eC2bnV.js → main-CLkcy9_q.js} +2 -2
- package/dist/assets/main-DUn82Iwq.js +214 -0
- package/dist/assets/miniChat-Ag1CYNF5.js +2 -0
- package/dist/assets/mobile-DtojUfiY.js +2 -0
- package/dist/assets/{pl-CYke_fxL.js → pl-CH00wT_K.js} +1 -1
- package/dist/assets/{pt-BR-Clb6Z8up.js → pt-BR-1tfKEfvN.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-3vxeddJO.js → renderElectronMiniChatApp-BTsP-lHc.js} +2 -2
- package/dist/assets/{renderMobileApp-BrvLHYCY.js → renderMobileApp-CSEgabkw.js} +3 -3
- package/dist/assets/{uk-CXn8cxXa.js → uk-BkeRI8D4.js} +1 -1
- package/dist/assets/{useAppFontEffects-b7bqtGFf.js → useAppFontEffects-BPhei6aO.js} +107 -107
- package/dist/assets/{zh-CN-BRwwlEdG.js → zh-CN-DtROWolc.js} +1 -1
- package/dist/assets/{zh-TW-D5pg5Z8l.js → zh-TW-CDqNEP6z.js} +1 -1
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/git/routes.test.js +4 -4
- package/server/lib/github/routes.js +1 -0
- package/server/lib/package-manager.js +1 -1
- package/server/lib/package-manager.test.js +8 -1
- package/server/lib/quota/providers/google/index.js +14 -6
- package/server/lib/quota/providers/index.js +3 -3
- package/server/lib/quota/providers/index.test.js +17 -0
- package/server/lib/tunnels/providers/ngrok.js +1 -1
- package/dist/assets/NewWorktreeDialog-Bx-zQyBp.js +0 -167
- package/dist/assets/index-BsXkdBYx.js +0 -3
- package/dist/assets/main-fsOGbLGZ.js +0 -214
- package/dist/assets/miniChat-DKGU29GZ.js +0 -2
- package/dist/assets/mobile-YHQHMYWC.js +0 -2
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-By2L9XvG.js","assets/vendor--Dwc_TRgJ.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as Ro,c as Fo,a as ze,d as $e,p as Dr,b as Mr,e as Pr,R as Fe}from"./vendor-.bun-By2L9XvG.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 Ar=()=>null,Cr="",J="",ue=0,W=null,Ce=0;const Or=1e4,Ge=t=>typeof t!="string"?"":t.trim(),_o=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_CLIENT_TOKEN__;return Ge(t)},xo=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},jo=(t,e)=>{const r=typeof t=="string"&&t.trim()?t.trim():xo();if(!r)return e;try{return new URL(e,`${r.replace(/\/+$/,"")}/`).toString()}catch{return e}},We=()=>{J="",ue=0},No=()=>{Ce+=1,W=null,We(),Rt()},Ir=t=>{const e=Ge(t);Cr=e,No(),Ar=()=>e?{type:"bearer",token:e}:null},Rr=()=>Cr||_o(),Lo=(t,e)=>{const r=Ge(t);if(!r||typeof e!="number"||!Number.isFinite(e)){We();return}const o=J;J=r,ue=e,o&&o!==r&&Ho()},Fr=()=>!J||ue<=Date.now()+Or?(We(),""):J,Uo=()=>{const t=Fr();return!t&&(Rr()||typeof window<"u")&&It().catch(()=>{}),t},_r=async()=>{const t=await Ar(),e=t?.type==="bearer"?Ge(t.token):Rr();return e?{type:"bearer",token:e}:null},xr=t=>{if(W)return W;const e=Ce,o=(async()=>{const n=await _r(),i=new Headers;n?.type==="bearer"&&i.set("Authorization",`Bearer ${n.token}`);const s=await fetch(jo(t,"/auth/url-token"),{method:"POST",headers:i,credentials:"include"});if(!s.ok)throw e===Ce&&We(),new Error(`Failed to mint runtime URL auth token (${s.status})`);const a=await s.json().catch(()=>null),c=typeof a?.token=="string"?a.token.trim():"",l=typeof a?.expiresAt=="number"?a.expiresAt:0;if(e!==Ce)throw new Error("Runtime URL auth token response is stale");if(Lo(c,l),!J)throw new Error("Runtime URL auth token response was invalid");return J})().finally(()=>{W===o&&(W=null)});return W=o,W},It=async t=>{const e=Fr();return e||xr(t)};let Z=0,ce=null,jr=null;const ft=new Set,Bo=5e3,Ho=()=>{for(const t of ft)try{t()}catch{}},Nr=()=>{ce!==null&&(clearTimeout(ce),ce=null)},Rt=()=>{if(Nr(),Z<=0||typeof window>"u")return;const t=ue-Or-Bo,e=ue>0?Math.max(0,t-Date.now()):0;ce=setTimeout(()=>{ce=null,!(Z<=0)&&xr(jr).catch(()=>{}).finally(()=>{Rt()})},e)},Na=t=>{typeof t=="string"&&t.trim()&&(jr=t.trim()),Z+=1,Rt();let e=!1;return()=>{e||(e=!0,Z=Math.max(0,Z-1),Z===0&&Nr())}},La=t=>(ft.add(t),()=>{ft.delete(t)}),zo=async t=>{const e=new Headers(t);if(e.has("Authorization"))return e;const r=await _r();return r?.type==="bearer"&&e.set("Authorization",`Bearer ${r.token}`),e},Ft=/^[a-z][a-z\d+.-]*:\/\//i,$o=t=>{const e=t.trim();return e?e.startsWith("/")?e:`/${e}`:"/"},pt=t=>typeof t!="string"?"":t.trim().replace(/\/+$/,""),Go=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return pt(t)},Wo=t=>{const e=t.currentHref?.();return e||(typeof window<"u"?window.location.href||window.location.origin:"")},ht=(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))},qo=(t,e)=>{if(!e)return t;const r=new URLSearchParams;ht({searchParams:r},e);const o=r.toString();return o?t.includes("?")?`${t}&${o}`:`${t}?${o}`:t},Gt=(t,e,r)=>{if(Ft.test(e)){const i=new URL(e);return ht(i,r),i.toString()}const o=$o(e);if(!t)return qo(o,r);const n=new URL(o,`${t}/`);return ht(n,r),n.toString()},Ye=t=>{const e=Uo();if(!e)return t;if(Ft.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)}`},Ko=(t,e)=>{const r=Ft.test(t)?new URL(t):new URL(t,Wo(e));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},_t=(t={})=>{const e=pt(t.apiBaseUrl),r=pt(t.realtimeBaseUrl),o=()=>e||Go(),n=()=>r||o(),i=(a,c)=>Gt(o(),a,c),s=(a,c)=>Gt(n(),a,c);return{api:i,authenticatedAsset:(a,c)=>Ye(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)=>Ye(s(a,c)),websocket:(a,c)=>Ko(Ye(s(a,c)),t)}};let _e=_t();const P=()=>_e,Vo=t=>{_e=t},Lr=t=>(_e=_t(t),_e),fe=t=>t.startsWith("/api/")||t==="/api"||t.startsWith("/auth/")||t==="/auth"||t==="/health",Jo=()=>typeof window>"u"?"":window.location.origin||"",Ur=t=>{if(typeof window>"u")return!1;const e=Jo();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}},Br=t=>/^[a-z][a-z\d+.-]*:\/\//i.test(t),Qo=(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))},Oe=t=>{try{const e=P().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;const r=new URL(e);return t.origin!==r.origin?!1:fe(t.pathname)}catch{return!1}},Xe=t=>{if(fe(t))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;try{const e=new URL(t);return Ur(e)&&fe(e.pathname)}catch{return!1}},Yo=(t,e)=>{try{const r=new URL(t);if(!Ur(r))return t;const o=V(`${r.pathname}${r.search}`,e);return!Br(o)&&(r.protocol==="http:"||r.protocol==="https:")?(Qo(r,e),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return t}},V=(t,e)=>t==="/health"?P().health(e):t.startsWith("/auth/")||t==="/auth"?P().auth(t,e):fe(t)?P().api(t,e):/^[a-z][a-z\d+.-]*:\/\//i.test(t)?Yo(t,e):t,Xo=t=>{const e=t instanceof Request?t.url:t.toString();if(!Br(e))return fe(e);try{return Oe(new URL(e))}catch{return!1}},Zo=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},en=(t,e)=>!Zo(e),Wt=t=>{if(!t)return;const e=t instanceof Headers?Array.from(t.entries()):Array.isArray(t)?t:Object.entries(t);if(e.length===0)return;const r=[];let o=!1,n=!1;for(const[i,s]of e)en(i,s)?(r.push([i,encodeURIComponent(s)]),o=!0,i.toLowerCase()==="x-opencode-directory"&&(n=!0)):r.push([i,s]);return n&&r.push(["x-opencode-directory-encoding","uri"]),o?r:void 0},q=async(t,e,r=!0)=>{const o=new Headers(Wt(t)??t);return e&&new Headers(Wt(e)??e).forEach((n,i)=>o.set(i,n)),r?zo(o):o},tn=(t,e)=>{if(typeof t=="string")return V(t,e);if(t instanceof URL)return V(t.toString(),e);const r=V(t.url,e);return r===t.url?t:new Request(r,t)},rn=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Se=new Map,on=(t,e,r)=>r||t!=="GET"||e.includes("/event")||!rn.test(e)?null:`GET ${e}`,u=async(t,e={})=>{const{query:r,...o}=e,n=tn(t,r),i=n instanceof Request?n.headers:void 0,s=await q(i,o.headers,Xo(n)),a=()=>n instanceof Request?fetch(new Request(n,{...o,headers:s})):fetch(n,{...o,headers:s}),c=n instanceof Request?n.url:n instanceof URL?n.toString():String(n),l=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase(),d=o.signal!=null||n instanceof Request,f=on(l,c,d);if(!f)return a();const g=Se.get(f);if(g)return g.then(p=>p.clone());const y=a();return Se.set(f,y),y.then(()=>Se.delete(f),()=>Se.delete(f)),y.then(p=>p.clone())};let qt=!1;const nn=()=>{if(qt||typeof window>"u")return;qt=!0;const t=window.fetch.bind(window);window.fetch=async(e,r)=>{if(typeof e=="string"){if(!Xe(e)){try{const n=new URL(e);if(Oe(n)){const i=await q(void 0,r?.headers);return t(e,{...r,headers:i})}}catch{}return t(e,r)}const o=await q(void 0,r?.headers);return t(V(e),{...r,headers:o})}if(e instanceof URL){const o=e.toString();if(!Xe(o)){if(Oe(e)){const i=await q(void 0,r?.headers);return t(e,{...r,headers:i})}return t(e,r)}const n=await q(void 0,r?.headers);return t(V(o),{...r,headers:n})}if(e instanceof Request){if(!Xe(e.url)){try{const s=new URL(e.url);if(Oe(s)){const a=await q(e.headers,r?.headers);return t(new Request(e,{...r,headers:a}))}}catch{}return t(e,r)}const o=await q(e.headers,r?.headers),n=V(e.url),i=n===e.url?e:new Request(n,e);return t(new Request(i,{...r,headers:o}))}return t(e,r)}},mt="openchamber:runtime-endpoint-changed";let xe="",pe="";const xt=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"}`}},Hr=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},zr=()=>{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}},jt=()=>xe||Hr(),qe=()=>{if(pe)return pe;const t=jt();return $r(t,zr())?"local":xt(t)},sn=(t={})=>{if(xe||pe)return;const e=t.apiBaseUrl?.trim()||Hr();e&&(xe=e,pe=t.runtimeKey?.trim()||($r(e,zr())?"local":xt(e)))},Ua=t=>{const e=t.apiBaseUrl.trim(),r=jt(),o=qe(),n=t.runtimeKey?.trim()||xt(e);if(xe=e,pe=n,typeof window<"u"){const i=window;i.__OPENCHAMBER_API_BASE_URL__=e,i.__OPENCHAMBER_CLIENT_TOKEN__=t.clientToken||void 0}Lr({apiBaseUrl:e,realtimeBaseUrl:e}),Ir(t.clientToken||null),It(e).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(mt,{detail:{apiBaseUrl:e,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o}}))},an=t=>{if(typeof window>"u")return()=>{};const e=r=>{t(r.detail)};return window.addEventListener(mt,e),()=>window.removeEventListener(mt,e)},cn=["local","remote",null],ln=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Gr(t){if(!t||typeof t!="object")return{valid:!1};const e=t,r=e.target,o=e.status;if(r!==null&&(typeof r!="string"||!cn.includes(r)))return{valid:!1};if(typeof o!="string"||!ln.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 Ba(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 Ha(t){return t.isDesktopShell?t.bootOutcomeKnown?t.bootViewIsMain===!1?!0:t.isInitialized:!1:t.isInitialized}function za(t){return t.isDesktopShell&&!t.isDesktopLocalOriginActive}function dn(){if(un()!=="valid")return null;const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,r=Gr(e);return r.valid?r.outcome:null}function un(){if(typeof window>"u")return"not-injected";const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return t==null?"not-injected":Gr(t).valid?"valid":"malformed"}let yt=null;const $a=t=>{yt=t},Ke=()=>yt||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),fn=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,oe=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,Wr=()=>fn()?.runtime==="electron",A=()=>typeof oe()?.invoke=="function",qr=()=>Wr()&&A(),O=async(t,e)=>{const r=oe();return typeof r?.invoke!="function"?null:r.invoke(t,e??{})},Ga=async()=>{if(!qr()||!I())return null;try{const t=await O("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}},Wa=async t=>{if(!qr()||!I())return null;try{const e=await O("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}},Kt=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}}},Ze=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}}},pn=t=>t.replace(/^\[|\]$/g,"").toLowerCase(),ne=t=>{const e=pn(t);return e==="localhost"||e==="127.0.0.1"||e==="::1"},I=()=>{if(typeof window>"u"||!Kr())return!1;if(qe()==="local")return!0;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=Ze(t),r=Ze(jt());if(!r&&e&&dn()?.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&&ne(e.hostname)&&ne(r.hostname)}const o=Ze(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&&ne(e.hostname)&&ne(o.hostname)}const n=Kt(t),i=Kt(window.location.origin)||window.location.origin;return n&&i&&n===i?!0:!!(o&&ne(o.hostname))},Kr=()=>typeof window>"u"?!1:Wr(),qa=async()=>{if(!Kr())return!1;try{return await O("desktop_start_window_drag"),!0}catch{return!1}},Ve=()=>Ke()?.runtime?.isVSCode===!0,Ka=()=>{const e=Ke()?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!Ve()},Vr=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Va=async t=>{if(A()&&I())try{const e=await oe()?.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}},Jr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Ja=async t=>{if(A()&&I())try{const e=await oe()?.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(!Jr(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"}},Qa=async t=>{const e=typeof t=="string"?t.trim():"";if(!e)return{success:!1,error:"Path is required"};if(!A()||!I())return{success:!1,error:"Native file access not available"};try{const r=await oe()?.grantFileAccess?.(e);if(!Jr(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)}}},Ya=async t=>({success:!0}),Xa=async t=>({success:!0}),Za=async()=>{if(!A())return null;try{return await O("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates",t),null}},ec=async t=>{if(!A())return!1;const e=oe();let r=null,o=0,n;try{return typeof t=="function"&&e?.listen&&(r=await e.listen("openchamber:update-progress",i=>{const s=i?.payload;if(!s||typeof s!="object")return;const a=s,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){o=0,n=typeof l?.contentLength=="number"?l.contentLength:void 0,t({downloaded:o,total:n});return}if(c==="Progress"){const d=l?.downloaded,f=l?.total;typeof d=="number"&&(o=d),typeof f=="number"&&(n=f),t({downloaded:o,total:n});return}c==="Finished"&&t({downloaded:o,total:n})})),await O("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{}}},tc=async()=>A()?hn():!1,hn=async()=>{if(!A())return!1;try{return await O("desktop_restart"),!0}catch(t){return console.warn("Failed to restart desktop app",t),!1}},rc=async()=>{if(!A()||!I())return null;try{const t=await O("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}},mn=async(t,e)=>{if(!A()||!I())return!1;const r=t?.trim();if(!r)return!1;try{return await O("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}},oc=async t=>{if(!A()||!I())return!1;const e=t?.trim();if(!e)return!1;try{return await O("desktop_reveal_path",{path:e}),!0}catch{return mn(e)}},nc=async(t,e)=>{if(!A()||!I())return null;const r=t?.trim();if(!r)return null;try{const o=await O("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}},ic=async(t,e,r)=>{if(!A()||!I())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await O("desktop_open_in_app",{projectPath:o,appId:n,appName:i}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},sc=async(t,e,r)=>{if(!A()||!I())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await O("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}},ac=async(t,e)=>{if(!A()||!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 O("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}}},Vt=500,Qr=()=>{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}},cc=()=>Qr(),R=(t,e)=>{if(!Qr())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>Vt&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Vt)},yn=()=>{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__=yn);const lc=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}},gn=3,wn=3e4,bn=1e3,Yr=32e3,Sn=3,Tn=3600*1e3,vn=600*1e3,Xr=new Set([429,502,503,504]),te=new Map;function kn(){const t=Date.now();for(const[e,r]of te)r.consecutiveErrors===0&&t-r.lastErrorAt>Tn&&te.delete(e)}typeof setInterval<"u"&&setInterval(kn,vn).unref?.();function En(t){let e=te.get(t);return e||(e={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:wn},te.set(t,e)),e}function Dn(t){if(!t)return;const e=te.get(t);e&&(e.consecutiveErrors=0,e.lastErrorAt=0)}function Jt(t,e){if(!t)return;const r=En(t);r.consecutiveErrors+=1,r.lastErrorAt=Date.now(),Mn(e)&&r.consecutiveErrors>=gn&&(r.circuitOpen=!0,r.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${t} after ${r.consecutiveErrors} consecutive errors`))}function Mn(t){return t!==void 0&&Xr.has(t)}function Zr(t){const e=te.get(t);return e?.circuitOpen?Date.now()-e.circuitOpenAt>=e.circuitCooldownMs?(e.circuitOpen=!1,e.consecutiveErrors=0,e.circuitCooldownMs=Math.min(e.circuitCooldownMs*2,Yr*4),!1):!0:!1}function Pn(t,e,r){return!(!Xr.has(e)||r>=Sn-1||Zr(t))}function An(t){if(!(!t||!Zr(t)))throw new Error(`Provider ${t} is temporarily unavailable after repeated errors. Please retry shortly.`)}function Qt(t){const e=bn*2**t;return Math.min(e,Yr)}const Yt="/api",Cn=1e4;function le(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 C(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${le(t.error)}`);throw r!==void 0&&(o.status=r),o}if(t.data===void 0||t.data===null)throw new Error(`${e} failed: empty response`);return t.data}function Y(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${le(t.error)}`);throw r!==void 0&&(o.status=r),o}return t.data}const On=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Xt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",In=14;let Zt=0,et=0;const Rn=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+=Xt[e[o]%Xt.length];return r},er=t=>{const e=Date.now();e!==Zt&&(Zt=e,et=0),et+=1;const r=BigInt(e)*BigInt(4096)+BigInt(et),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}${Rn(In)}`},Fn=t=>t instanceof DOMException&&t.name==="AbortError"||t instanceof TypeError,tr=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(On.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}},rr=()=>{try{return P().api("/api")}catch{return null}},tt=t=>Fo({...t,fetch:u}),X=t=>t.replace(/\\/g,"/"),or=400,nr=()=>{const t=Ke();return t&&t.runtime?.isDesktop&&t.files?t.files:null};class _n{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=Yt){const o=rr()||e;this.baseUrl=tr(o),this.client=tt({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const e=rr(),r=tr(e||Yt);r!==this.baseUrl&&(this.baseUrl=r,this.client=tt({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=tt({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 C(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 C(n,"session.get")}async deleteSession(e,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,n=await this.client.session.delete({sessionID:e,...o?{directory:o}:{}});return Y(n,"session.delete")===!0}async updateSession(e,r,o){const n=this.normalizeCandidatePath(o)??this.currentDirectory,i={...r.title!==void 0?{title:r.title}:{},...r.metadata!==void 0?{metadata:r.metadata}:{},...r.time?.archived!==void 0&&r.time.archived!==null?{time:{archived:r.time.archived}}:{}},s=await this.client.session.update({sessionID:e,...n?{directory:n}:{},...i});return C(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 C(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 Ro(async()=>{const{default:f}=await import("./vendor-.bun-By2L9XvG.js").then(g=>g.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}),l=await new Promise((f,g)=>{const y=new FileReader;y.onload=()=>f(y.result),y.onerror=g,y.readAsDataURL(c)});let d=e.filename;return d&&(d=d.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:d,url:l}}catch(r){return console.warn("Failed to convert HEIC to JPEG:",r),e}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let r=e.url;if(e.url.startsWith("data:")){const o=e.url.indexOf(",");if(o!==-1){const n=e.url.substring(5,o),i=e.url.substring(o);r=`data:${n.replace(/^[^;,]+/,"text/plain")}${i}`}}return{mime:"text/plain",filename:e.filename,url:r}}async toNormalizedFilePartInput(e){const r=await this.normalizeFilePart(e);return{...e.id?{id:e.id}:{},type:"file",mime:r.mime,filename:r.filename,url:r.url}}async sendMessage(e){const r=e.messageId??er("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}),An(e.providerID);let i;for(let s=0;s<3;s++){try{const d=await this.client.session.promptAsync({sessionID:e.id,...n?{directory:n}:{},model:{providerID:e.providerID,modelID:e.modelID},agent:e.agent,variant:e.variant,messageID:r,...e.format?{format:e.format}:{},parts:o});if(d.response instanceof Response)i=d.response;else if(d.error){const f=d.response?.status||500;i=new Response(JSON.stringify(d.error),{status:f})}else i=new Response(JSON.stringify(d.data??!0),{status:200})}catch(d){if(s<2&&Fn(d)){const f=Qt(s);console.warn(`[prompt] fetch failed for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${f}ms`,d?.message),await new Promise(g=>setTimeout(g,f));continue}throw Jt(e.providerID),d}if(i.ok)return Dn(e.providerID),r;if(Pn(e.providerID,i.status,s)){const d=Qt(s);console.warn(`[prompt] ${i.status} for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${d}ms`),await new Promise(f=>setTimeout(f,d));continue}let a="";try{a=await i.text()}catch{}const c=a&&a.trim().length>0?`: ${a.trim()}`:"",l=new Error(`Failed to send message (${i.status})${c}`);throw Jt(e.providerID,i.status),l}throw new Error("Failed to send message after retries")}async sendCommand(e){const r=e.messageId??er("msg"),o=[];if(e.files&&e.files.length>0)for(const s of e.files)o.push(await this.toNormalizedFilePartInput(s));const n=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,i=await this.client.session.command({sessionID:e.id,...n?{directory:n}:{},command:e.command,arguments:e.arguments??"",model:`${e.providerID}/${e.modelID}`,agent:e.agent,variant:e.variant,...o.length>0?{parts:o}:{},messageID:r});return Y(i,"session.command"),r}async abortSession(e){return!!(await this.client.session.abort({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(e){const r=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,o=await this.client.session.shell({sessionID:e.sessionId,...r?{directory:r}:{},messageID:e.messageId,agent:e.agent,model:e.model,command:e.command});return C(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 C(s,"session.revert")}async summarizeSession(e,r,o,n){const i=this.normalizeCandidatePath(n)??this.currentDirectory,s=await this.client.session.summarize({sessionID:e,...i?{directory:i}:{},providerID:r,modelID:o});return Y(s,"session.summarize")===!0}async unrevertSession(e){const r=await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return C(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 C(i,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e){try{const r=typeof e=="string"?e.trim():"",o=await this.client.session.status(r?{directory:r}:void 0);return o.error||!o.data||typeof o.data!="object"?null:o.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const e=await u("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const r=await e.json().catch(()=>null);return!r||typeof r!="object"?null:r}catch{return null}}async listToolIds(e){try{const r=typeof e?.directory=="string"?e.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(r?{directory:r}:void 0)).data||[]).filter(i=>typeof i=="string"&&i!=="invalid")}catch{return[]}}async replyToPermission(e,r,o){const n=this.normalizeCandidatePath(o?.directory??null)??this.currentDirectory,i=await this.client.permission.reply({requestID:e,...n?{directory:n}:{},reply:r,...o?.message?{message:o.message}:{}});return Y(i,"permission.reply")===!0}async listPendingPermissions(e){const r=[],o=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.permission.list(l?{directory:l}:void 0);if(d.error)throw new Error(`permission.list failed: ${le(d.error)}`);return d.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&n.add(l)}for(const c of n)r.push(o(c));const i=await Promise.all(r),s=[],a=new Set;for(const c of i)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),s.push(l))}return s}async replyToQuestion(e,r,o){const n=!Array.isArray(r)||r.length===0?[]:Array.isArray(r[0])?r:[r],i=this.normalizeCandidatePath(o)??this.currentDirectory,s=await this.client.question.reply({requestID:e,...i?{directory:i}:{},answers:n});return Y(s,"question.reply")===!0}async rejectQuestion(e){const r=await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Y(r,"question.reject")===!0}async listPendingQuestions(e){const r=[],o=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.question.list(l?{directory:l}:void 0);if(d.error)throw new Error(`question.list failed: ${le(d.error)}`);return d.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&n.add(l)}for(const c of n)r.push(o(c));const i=await Promise.all(r),s=[],a=new Set;for(const c of i)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),s.push(l))}return s}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(e){const r=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,o=r??"",n=this.configCache.get(o);if(n&&n.expiresAt>Date.now())return 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(),d=await(r?this.getScopedApiClient(r):this.client).config.get();if(!d.data)throw new Error("Failed to get config");const f=typeof performance<"u"?performance.now():Date.now();return R("opencodeClient.getConfig:end",{directory:r??null,durationMs:Math.round(f-c)}),s===this.configCacheGeneration&&this.configCache.set(o,{config:d.data,expiresAt:Date.now()+Cn}),d.data})();this.configInFlight.set(o,a);try{return await a}finally{this.configInFlight.get(o)===a&&this.configInFlight.delete(o)}}async updateConfig(e){const r=await this.client.config.update({config:e}),o=C(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 C(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})`:""}: ${le(a.error)}`):new Error(`agent.list failed (${c.status})`);const l=await c.json().catch(()=>null);if(!Array.isArray(l))throw new Error("agent.list failed: invalid response");return l})();this.listAgentsInFlight.set(o,i);try{return await i}finally{this.listAgentsInFlight.delete(o)}}async readFile(e){try{const r=await this.client.file.read({path:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(C(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=C(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(C(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(C(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=nr();if(o?.createDirectory)try{return await o.createDirectory(e)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}const n={path:e,...r?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},i=await u(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await i.json()}async cloneRepository(e){const r=await u(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(o.error||"Failed to clone repository")}return await r.json()}async listLocalDirectory(e,r){const n=`${typeof e=="string"?X(e.trim()):""}|${r?.respectGitignore?"1":"0"}`,i=Date.now(),s=this.listDirectoryCache.get(n);if(s&&s.expiresAt>i)return s.entries;const a=this.listDirectoryInFlight.get(n);if(a)return a;const l=(async()=>{const d=nr();if(d)try{const f=await d.listDirectory(e||"",r);if(!f||!Array.isArray(f.entries))return[];const g=f.entries.map(y=>({name:y.name,path:X(y.path),isDirectory:!!y.isDirectory,isFile:!y.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:g,expiresAt:Date.now()+or}),g}catch(f){throw console.error("Failed to list directory contents:",f),f}try{const f=new URLSearchParams;e&&e.trim().length>0&&f.set("path",e),r?.respectGitignore&&f.set("respectGitignore","true");const g=f.toString(),y=await u(`${this.baseUrl}/fs/list${g?`?${g}`:""}`);if(!y.ok){const b=await y.json().catch(()=>({})),T=typeof b.error=="string"?b.error:"Failed to list directory";throw new Error(T)}const p=await y.json();if(!p||!Array.isArray(p.entries))return[];const w=p.entries;return this.listDirectoryCache.set(n,{entries:w,expiresAt:Date.now()+or}),w}catch(f){throw console.error("Failed to list directory contents:",f),f}})().finally(()=>{this.listDirectoryInFlight.get(n)===l&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,l),l}async searchFiles(e,r){const o=typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():this.currentDirectory,n=o?X(o):null,i=o?this.getScopedApiClient(o):this.client;try{const s=await i.find.files({query:e,limit:typeof r?.limit=="number"&&Number.isFinite(r.limit)?r.limit:void 0,dirs:r?.dirs===!1||r?.type==="file"?"false":"true",type:r?.type});return(Array.isArray(s?.data)?s.data:[]).map(c=>{const l=X(c),d=l.split("/").filter(Boolean).pop()||l,f=X(n?`${n}/${l}`:l);return{name:d,path:f,relativePath:l,extension:d.includes(".")?d.split(".").pop()?.toLowerCase():void 0}})}catch(s){throw console.error("Failed to search files:",s),s}}async getFilesystemHome(){const e=qe();if(!e||e==="local"){const r=await Vr();if(r)return r}try{const r=await u(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){const n=await r.json().catch(()=>({})),i=typeof n.error=="string"&&n.error.length>0?n.error:"Failed to resolve home directory";throw new Error(i)}const o=await r.json();return o&&typeof o.home=="string"&&o.home.length>0?o.home:null}catch(r){return console.warn("Failed to resolve filesystem home directory:",r),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!="string"||!e.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",e),null;const r=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",r,"with path:",e);try{const o=await u(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})}),n=await o.json().catch(()=>null);if(!o.ok){const i=n??{},s=typeof i.error=="string"&&i.error.length>0?i.error:"Failed to update OpenCode working directory";throw new Error(s)}return n&&typeof n=="object"?n:{success:!0,restarted:!1,path:e}}catch(o){throw console.warn("Failed to update OpenCode working directory:",o),o}}}const H=new _n,xn=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 rt=null,ot=null;const eo=t=>{if(typeof window>"u")return null;try{return window[t]??null}catch{return null}},je=()=>{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}}},jn=()=>{const t=eo("localStorage");if(!t)return je();const e=je();let r=!0;const o=()=>{r=!1};return{getItem:l=>{if(r)try{const d=t.getItem(l);if(d!==null)return d}catch{o()}return e.getItem(l)},setItem:(l,d)=>{if(r)try{t.setItem(l,d),e.removeItem(l);return}catch{o();try{t.removeItem(l)}catch{}}e.setItem(l,d)},removeItem:l=>{try{t.removeItem(l)}catch{o()}e.removeItem(l)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:l=>{if(r)try{return t.key(l)}catch{o()}return e.key(l)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},Q=()=>(rt||(rt=jn()),rt),Nn=()=>{const t=eo("sessionStorage");if(!t)return je();const e=je();let r=!0;const o=()=>{r=!1};return{getItem:l=>{if(r)try{const d=t.getItem(l);if(d!==null)return d}catch{o()}return e.getItem(l)},setItem:(l,d)=>{if(r)try{t.setItem(l,d),e.removeItem(l);return}catch{o();try{t.removeItem(l)}catch{}}e.setItem(l,d)},removeItem:l=>{try{t.removeItem(l)}catch{o()}e.removeItem(l)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:l=>{if(r)try{return t.key(l)}catch{o()}return e.key(l)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},dc=()=>(ot||(ot=Nn()),ot),Ln={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},uc={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function ir(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Te={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)"}}},nt={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Te.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:nt.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Te.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:nt.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Te.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:nt.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Te.tool.inline})},Un=[{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'}],Bn=[{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'}],to=t=>Object.fromEntries(t.map(e=>[e.id,e])),Hn=to(Un),zn=to(Bn),$n="ibm-plex-sans",Gn="ibm-plex-mono",ro=t=>typeof t=="string"&&t in Hn,oo=t=>typeof t=="string"&&t in zn,gt="openchamber.mobileKeyboardMode",Wn='meta[name="viewport"]',sr="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",fc=()=>!0;function Je(t,e="resize-content"){return t==="native"||t==="resize-content"?t:e}const qn=t=>Je(t)==="resize-content"?`${sr}, interactive-widget=resizes-content`:sr,Kn=()=>{if(typeof window>"u")return"resize-content";try{return Je(localStorage.getItem(gt))}catch{return"resize-content"}},no=t=>{const e=Je(t);if(typeof window<"u")try{e==="resize-content"?localStorage.removeItem(gt):localStorage.setItem(gt,e)}catch{}return e},pc=t=>{const e=no(t);if(typeof document>"u")return e;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",e);const r=document.querySelector(Wn);if(r instanceof HTMLMetaElement){const o=qn(e);r.getAttribute("content")!==o&&r.setAttribute("content",o)}return e};function ar(t){return t==="vim"?"vim":"default"}const ve={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},B={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},ke=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,Vn=t=>{if(!t||typeof t!="object")return!1;const e=t;return ke(e.completion,ve.completion)&&ke(e.error,ve.error)&&ke(e.question,ve.question)&&ke(e.subtask,ve.subtask)},Nt=380,Jn=380,Qn=1400,io=12,cr=120,ie=280,se=360,Yn=860,it=new Map,st=t=>(t??qe()).trim()||"default",M=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},so=t=>Number.isFinite(t)?Math.min(Qn,Math.max(Jn,Math.round(t))):Nt,Ne=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.replace(/\\/g,"/"):null},ao=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.length>cr?e.slice(0,cr):e:null},Xn=(t,e)=>(t==="file"||t==="preview")&&e||t,co=(t,e,r)=>{if(t==="diff")return t;if(typeof r=="string"){const o=r.trim();if(o)return o}return Xn(t,e)},lo=(t,e)=>e===t?t:`${t}:${e}`,uo=t=>{const e=Ne(t.targetPath),r=co(t.mode,e,t.dedupeKey);return{id:lo(t.mode,r),mode:t.mode,targetPath:e,dedupeKey:r,label:ao(t.label),readOnly:t.readOnly===!0,stagedDiff:t.stagedDiff===!0,touchedAt:Date.now()}},fo=(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))},po=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=Ne(typeof n.targetPath=="string"?n.targetPath:null),s=co(n.mode,i,typeof n.dedupeKey=="string"?n.dedupeKey:null),a=lo(n.mode,s);!a||r.has(a)||(r.add(a),e.push({id:a,mode:n.mode,targetPath:i,dedupeKey:s,label:ao(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},he=(t,e)=>e&&t.some(r=>r.id===e)?e:t.length===0?null:t[t.length-1].id,$=t=>{if(t){const e=po(t.tabs),r=he(e,t.activeTabId);return{...t,tabs:e,activeTabId:r,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:Nt,touchedAt:Date.now()}},Zn=(t,e)=>{const r=uo(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=fo(n,io,i);return{...t,isOpen:!0,tabs:s,activeTabId:he(s,i),touchedAt:Date.now()}},ei=(t,e)=>{const r=t.tabs.filter(n=>n.id!==e),o=t.activeTabId===e?r[r.length-1]?.id??null:he(r,t.activeTabId);return{...t,tabs:r,activeTabId:o,isOpen:r.length>0?t.isOpen:!1,touchedAt:Date.now()}},ti=(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},ri=(t,e,r)=>({...t,tabs:t.tabs.map(o=>o.id===e?{...o,targetPath:r}:o)}),at=t=>{if(!t||typeof t!="object")return{};const e=t,r={};for(const[o,n]of Object.entries(e)){const i=M(o);if(!i||!n||typeof n!="object")continue;const s=n;let a=po(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=[uo({mode:s.mode,targetPath:typeof s.targetPath=="string"?s.targetPath:null,dedupeKey:typeof s.dedupeKey=="string"?s.dedupeKey:null,label:typeof s.label=="string"?s.label:null})],c=a[0]?.id??null);const l=he(a,c),d=fo(a,io,l);r[i]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:d,activeTabId:he(d,l),width:so(typeof s.width=="number"?s.width:Nt),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},G=(t,e)=>{const r=Object.entries(t);if(r.length<=e)return t;r.sort((n,i)=>(i[1]?.touchedAt??0)-(n[1]?.touchedAt??0));const o={};for(const[n,i]of r.slice(0,e))o[n]=i;return o},N=ze()($e(Dr((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:ie,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:se,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:$n,monoFont:Gn,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Kn(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...B.completion},error:{...B.error},question:{...B.question},subtask:{...B.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!0,inputSpellcheckEnabled:!1,wideChatLayoutEnabled:!1,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,expandedEditorToolbar:!1,showSplitAssistantMessageActions:!1,isMobileSessionStatusBarCollapsed:!1,mobileSessionPanelOpen:!1,mobileSessionFilterProjectId:null,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:r=>{t({theme:r}),e().applyTheme()},toggleSidebar:()=>{t(r=>{const o=!r.isSidebarOpen;return o&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:o,sidebarWidth:ie}:{isSidebarOpen:o}})},setSidebarOpen:r=>{t(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==ie?{isSidebarOpen:r,sidebarWidth:ie}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:ie}:{isSidebarOpen:r})},setSidebarWidth:r=>{t({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(r=>{const o=!r.isRightSidebarOpen;return o&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:o,rightSidebarWidth:se}:{isRightSidebarOpen:o}})},setRightSidebarOpen:r=>{t(o=>{if(o.isRightSidebarOpen===r)return o;const n=r&&!o.hasManuallyResizedRightSidebar&&o.rightSidebarWidth!==se;return{isRightSidebarOpen:r,rightSidebarWidth:n?se:o.rightSidebarWidth}})},setRightSidebarWidth:r=>{const o=Math.min(Yn,Math.max(se,r));t({rightSidebarWidth:o,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:r=>{t({rightSidebarTab:r})},openContextPanelTab:(r,o)=>{const n=M((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=$(s),c={...i.contextPanelByDirectory,[n]:Zn(a,o)};return{contextPanelByDirectory:G(c,20)}})},openContextDiff:(r,o,n=!1)=>{const i=M((r||"").trim()),s=(o||"").trim();!i||!s||e().openContextPanelTab(i,{mode:"diff",targetPath:s,stagedDiff:n})},openContextFile:(r,o)=>{const n=M((r||"").trim()),i=Ne(o);!n||!i||(e().openContextPanelTab(n,{mode:"file",targetPath:i}),e().setPendingFileFocusPath(i),e().setPendingFileNavigation(null))},openContextFileAtLine:(r,o,n,i)=>{const s=M((r||"").trim()),a=Ne(o),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,l=Number.isFinite(i)?Math.max(1,Math.trunc(i)):1;!s||!a||(e().openContextPanelTab(s,{mode:"file",targetPath:a}),e().setPendingFileFocusPath(null),e().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:r=>{const o=M((r||"").trim());o&&e().openContextPanelTab(o,{mode:"context"})},openContextPlan:r=>{const o=M((r||"").trim());o&&e().openContextPanelTab(o,{mode:"plan"})},openContextPreview:(r,o)=>{const n=M((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=M((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=M((r||"").trim()),s=(o||"").trim();!i||!s||t(a=>{const c=a.contextPanelByDirectory[i];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[i]:ri(c,s,n)}}:a})},setActiveContextPanelTab:(r,o)=>{const n=M((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=$(a);if(!c.tabs.some(d=>d.id===i)||c.activeTabId===i&&c.isOpen)return s;const l={...s.contextPanelByDirectory,[n]:{...c,isOpen:!0,activeTabId:i,touchedAt:Date.now(),tabs:c.tabs.map(d=>d.id===i?{...d,touchedAt:Date.now()}:d)}};return{contextPanelByDirectory:G(l,20)}})},reorderContextPanelTabs:(r,o,n)=>{const i=M((r||"").trim()),s=(o||"").trim(),a=(n||"").trim();!i||!s||!a||t(c=>{const l=c.contextPanelByDirectory[i],d=$(l);if(!d.tabs.some(y=>y.id===s)||!d.tabs.some(y=>y.id===a))return c;const f=ti(d,s,a);if(f.tabs===d.tabs)return c;const g={...c.contextPanelByDirectory,[i]:f};return{contextPanelByDirectory:G(g,20)}})},closeContextPanelTab:(r,o)=>{const n=M((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=$(a);if(!c.tabs.some(d=>d.id===i))return s;const l={...s.contextPanelByDirectory,[n]:ei(c,i)};return{contextPanelByDirectory:G(l,20)}})},closeContextPanel:r=>{const o=M((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o];if(!i||!i.isOpen)return n;const s={...n.contextPanelByDirectory,[o]:{...$(i),isOpen:!1}};return{contextPanelByDirectory:G(s,20)}})},toggleContextPanelExpanded:r=>{const o=M((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o],s=$(i),a={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:G(a,20)}})},setContextPanelWidth:(r,o)=>{const n=M((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=$(s),c={...i.contextPanelByDirectory,[n]:{...a,width:so(o)}};return{contextPanelByDirectory:G(c,20)}})},toggleBottomTerminal:()=>{t(r=>{const o=!r.isBottomTerminalOpen;if(o&&typeof window<"u"){const n=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:o,bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:o}})},setBottomTerminalOpen:r=>{t(o=>{if(o.isBottomTerminalOpen===r){if(!r)return o;if(!o.hasManuallyResizedBottomTerminal&&typeof window<"u"){const n=Math.floor(window.innerHeight*.32);return o.bottomTerminalHeight===n&&o.hasManuallyResizedBottomTerminal===!1?o:{isBottomTerminalOpen:r,bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!1}}return o}if(r&&typeof window<"u"){const n=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:r,bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:r}})},setBottomTerminalExpanded:r=>{t({isBottomTerminalExpanded:r})},setBottomTerminalHeight:r=>{t({bottomTerminalHeight:r,hasManuallyResizedBottomTerminal:!0})},setNotesPanelHeight:r=>{t({notesPanelHeight:r})},setTodoPanelHeight:r=>{t({todoPanelHeight:r})},setSessionSwitcherOpen:r=>{e().isSessionSwitcherOpen!==r&&t({isSessionSwitcherOpen:r})},setSessionDropdownOpen:r=>{e().isSessionDropdownOpen!==r&&t({isSessionDropdownOpen:r})},setMainTabGuard:r=>{e().mainTabGuard!==r&&t({mainTabGuard:r})},setActiveMainTab:r=>{const o=e().mainTabGuard;o&&!o(r)||(it.set(st(),r),t({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{it.set(st(r),e().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=it.get(st(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(Ln);if(n===1){for(const[s]of i)o.style.removeProperty(ir(s));return}for(const[s,a]of i){const c=parseFloat(a);Number.isFinite(c)&&o.style.setProperty(ir(s),`${c*n}rem`)}},applyPadding:()=>{const{padding:r}=e(),o=document.documentElement,n=r/100;if(n===1){o.style.removeProperty("--padding-scale"),o.style.removeProperty("--line-height-tight"),o.style.removeProperty("--line-height-normal"),o.style.removeProperty("--line-height-relaxed"),o.style.removeProperty("--line-height-loose");return}const i=Math.sqrt(n);o.style.setProperty("--padding-scale",i.toString());const s=1+(n-1)*.15;o.style.setProperty("--line-height-tight",(1.25*s).toFixed(3)),o.style.setProperty("--line-height-normal",(1.5*s).toFixed(3)),o.style.setProperty("--line-height-relaxed",(1.625*s).toFixed(3)),o.style.setProperty("--line-height-loose",(2*s).toFixed(3))},setDiffLayoutPreference:r=>{t({diffLayoutPreference:r})},setDiffFileLayout:(r,o)=>{t(n=>({diffFileLayout:{...n.diffFileLayout,[r]:o}}))},setDiffWrapLines:r=>{t({diffWrapLines:r})},setGitChangesViewMode:r=>{t({gitChangesViewMode:r})},setInputBarOffset:r=>{t({inputBarOffset:r})},setMobileKeyboardMode:r=>{t(o=>o.mobileKeyboardMode===r?o:{mobileKeyboardMode:r})},toggleFavoriteModel:(r,o)=>{t(n=>n.favoriteModels.some(s=>s.providerID===r&&s.modelID===o)?{favoriteModels:n.favoriteModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{favoriteModels:[{providerID:r,modelID:o},...n.favoriteModels]})},reorderFavoriteModel:(r,o,n,i)=>{t(s=>{const a=s.favoriteModels.findIndex(f=>f.providerID===r&&f.modelID===o),c=s.favoriteModels.findIndex(f=>f.providerID===n&&f.modelID===i);if(a===-1||c===-1||a===c)return s;const l=s.favoriteModels.slice(),[d]=l.splice(a,1);return d?(l.splice(c,0,d),{favoriteModels:l}):s})},setProviderOrder:r=>{t(o=>{const n=r.filter(s=>typeof s=="string"&&s.length>0),i=o.providerOrder;return i.length===n.length&&i.every((s,a)=>s===n[a])?o:{providerOrder:n}})},toggleHiddenModel:(r,o)=>{t(n=>n.hiddenModels.some(s=>s.providerID===r&&s.modelID===o)?{hiddenModels:n.hiddenModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{hiddenModels:[{providerID:r,modelID:o},...n.hiddenModels]})},isHiddenModel:(r,o)=>{const{hiddenModels:n}=e();return n.some(i=>i.providerID===r&&i.modelID===o)},hideAllModels:(r,o)=>{t(n=>{const i=n.hiddenModels.filter(a=>a.providerID!==r);return{hiddenModels:[...o.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:r,modelID:a})),...i]}})},showAllModels:r=>{t(o=>({hiddenModels:o.hiddenModels.filter(n=>n.providerID!==r)}))},toggleModelProviderCollapsed:r=>{const o=typeof r=="string"?r.trim():"";o&&t(n=>n.collapsedModelProviders.includes(o)?{collapsedModelProviders:n.collapsedModelProviders.filter(s=>s!==o)}:{collapsedModelProviders:[...n.collapsedModelProviders,o]})},setModelProvidersCollapsed:(r,o)=>{const n=Array.from(new Set(r.filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)));n.length!==0&&t(i=>{const s=new Set(n),a=i.collapsedModelProviders.filter(c=>!s.has(c));return{collapsedModelProviders:o?[...a,...n]:a}})},isFavoriteModel:(r,o)=>{const{favoriteModels:n}=e();return n.some(i=>i.providerID===r&&i.modelID===o)},addRecentModel:(r,o)=>{t(n=>{const i=n.recentModels.filter(s=>!(s.providerID===r&&s.modelID===o));return{recentModels:[{providerID:r,modelID:o},...i].slice(0,5)}})},addRecentAgent:r=>{const o=typeof r=="string"?r.trim():"";o&&t(n=>{if(n.recentAgents.includes(o))return n;const i=n.recentAgents;return{recentAgents:[o,...i].slice(0,5)}})},addRecentEffort:(r,o,n)=>{const i=typeof r=="string"?r.trim():"",s=typeof o=="string"?o.trim():"";if(!i||!s)return;const a=`${i}/${s}`,c=typeof n=="string"&&n.trim().length>0?n.trim():"default";t(l=>{const d=l.recentEfforts[a]??[];if(d.includes(c))return l;const f=d;return{recentEfforts:{...l.recentEfforts,[a]:[c,...f].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(r=>{const o={};if(r.isBottomTerminalOpen&&!r.hasManuallyResizedBottomTerminal){const n=Math.floor(window.innerHeight*.32);r.bottomTerminalHeight!==n&&(o.bottomTerminalHeight=n)}return Object.keys(o).length>0?o:r})},applyTheme:()=>{const{theme:r}=e(),o=document.documentElement;if(o.classList.remove("light","dark"),r==="system"){const n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(n)}else o.classList.add(r)},setMultiRunLauncherOpen:r=>{t(o=>({isMultiRunLauncherOpen:r,multiRunLauncherPrefillPrompt:r?o.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:r=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:r,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:r=>{t({isTimelineDialogOpen:r})},setImagePreviewOpen:r=>{t({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{t({nativeNotificationsEnabled:r})},setNotificationMode:r=>{t({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{t({showTerminalQuickKeysOnDesktop:r})},setNotifyOnSubtasks:r=>{t({notifyOnSubtasks:r})},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:ar(r)})},toggleExpandedInput:()=>{t(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{t({isExpandedInput:r})}}),{name:"ui-store",storage:Mr(()=>Q()),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&&Vn(r.notificationTemplates)&&(r.notificationTemplates={completion:{...B.completion},error:{...B.error},question:{...B.question},subtask:{...B.subtask}}),e<3){const o=new Set([90,120,180,220]),n=r.memoryLimitHistorical,i=r.memoryLimitActiveSession;typeof n=="number"&&!o.has(n)?r.messageLimit=n:typeof i=="number"&&!o.has(i)&&(r.messageLimit=i),delete r.memoryLimitHistorical,delete r.memoryLimitViewport,delete r.memoryLimitActiveSession}if((typeof r.rightSidebarTab!="string"||r.rightSidebarTab!=="git"&&r.rightSidebarTab!=="files"&&r.rightSidebarTab!=="context")&&(r.rightSidebarTab="git"),r.contextPanelByDirectory=at(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=at(r.contextPanelByDirectory)),e<7&&(r.contextPanelByDirectory=at(r.contextPanelByDirectory)),e<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=ar(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,providerOrder:t.providerOrder,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,gitChangesViewMode:t.gitChangesViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,showTerminalQuickKeysOnDesktop:t.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:t.notifyOnSubtasks,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"})),oi=ze()($e(Dr((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}}})},reorderQueue:(r,o,n)=>{o!==n&&t(i=>{const s=i.queuedMessages[r];if(!s)return i;const a=s.findIndex(f=>f.id===o),c=s.findIndex(f=>f.id===n);if(a===-1||c===-1)return i;const l=s.slice(),[d]=l.splice(a,1);return l.splice(c,0,d),{queuedMessages:{...i.queuedMessages,[r]:l}}})},popToInput:(r,o)=>{const s=(e().queuedMessages[r]??[]).find(a=>a.id===o);return s?(t(a=>{const l=(a.queuedMessages[r]??[]).filter(d=>d.id!==o);if(l.length===0){const{[r]:d,...f}=a.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...a.queuedMessages,[r]:l}}}),s):null},clearQueue:r=>{t(o=>{const{[r]:n,...i}=o.queuedMessages;return{queuedMessages:i}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:r=>{t({queueModeEnabled:r}),U({queueModeEnabled:r})},getQueueForSession:r=>e().queuedMessages[r]??[]}),{name:"message-queue-store",storage:Mr(()=>Q()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),ho="directoryTreeShowHidden",wt="directory-show-hidden-change",lr=()=>{if(typeof window>"u")return!0;try{const t=Q().getItem(ho);return t===null?!0:t==="true"}catch{return!0}},ni=()=>{typeof window>"u"||window.dispatchEvent(new Event(wt))},ii=(t,e={})=>{if(!(typeof window>"u")){try{Q().setItem(ho,t?"true":"false"),ni()}catch{}e.persist!==!1&&U({directoryShowHidden:t})}},hc=()=>{const t=Pr.c(2),[e,r]=Fe.useState(lr);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(lr())};return window.addEventListener("storage",i),window.addEventListener(wt,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(wt,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),Fe.useEffect(o,n),e},mo="filesViewShowGitignored",bt="files-view-show-gitignored-change",dr=()=>{if(typeof window>"u")return!1;try{return Q().getItem(mo)==="true"}catch{return!1}},si=()=>{typeof window>"u"||window.dispatchEvent(new Event(bt))},ai=(t,e={})=>{if(!(typeof window>"u")){try{Q().setItem(mo,t?"true":"false"),si()}catch{}e.persist!==!1&&U({filesViewShowGitignored:t})}},mc=()=>{const t=Pr.c(2),[e,r]=Fe.useState(dr);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(dr())};return window.addEventListener("storage",i),window.addEventListener(bt,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(bt,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),Fe.useEffect(o,n),e},ci=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},li=t=>{if(!t||typeof t!="object")return null;const e=t;return{showReasoningTraces:e.showReasoningTraces,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks}},di=t=>{const e=N.getState();typeof t.showReasoningTraces=="boolean"&&e.setShowReasoningTraces(t.showReasoningTraces),typeof t.collapsibleThinkingBlocks=="boolean"&&e.setCollapsibleThinkingBlocks(t.collapsibleThinkingBlocks)},ui=async()=>{if(typeof window>"u")return null;const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const e=JSON.parse(t),r=li(e);return ci(r)}catch(e){return console.warn("Failed to parse stored appearance preferences:",e),null}},yo=[{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"}],fi=new Map(yo.map(t=>[t.name,t])),yc=t=>fi.get(t),gc=yo.map(t=>({type:"command",name:t.name})),wc="terminal-box",bc="book-open",Sc=t=>`${t.type}:${t.name}`,Tc=(t,e)=>t.type===e.type&&t.name===e.name,vc=t=>{const e=t.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):t},go=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},pi=t=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=t}catch{}},St=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),pi(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"&&no(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))}},Tt=t=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))},hi=t=>{if(!Array.isArray(t))return;const e=[],r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const n=o,i=typeof n.id=="string"?n.id.trim():"",s=typeof n.label=="string"?n.label.trim():"",a=typeof n.source=="string"?n.source.trim():"",c=typeof n.subpath=="string"?n.subpath.trim():"",l=typeof n.gitIdentityId=="string"?n.gitIdentityId.trim():"";!i||!s||!a||r.has(i)||(r.add(i),e.push({id:i,label:s,source:a,...c?{subpath:c}:{},...l?{gitIdentityId:l}:{}}))}return e},mi=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},yi=(t,e)=>{const r=Object.entries(t),o=Object.entries(e);return r.length!==o.length?!1:r.every(([n,i])=>e[n]===i)},ct=(t,e)=>t.length===e.length&&t.every((r,o)=>r.providerID===e[o]?.providerID&&r.modelID===e[o]?.modelID),vt=(t,e)=>t.length===e.length&&t.every((r,o)=>r===e[o]),kt=t=>{if(Array.isArray(t))return Array.from(new Set(t.filter(e=>typeof e=="string"&&e.length>0)))},gi=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const e={};for(const[r,o]of Object.entries(t)){if(!r||!Array.isArray(o))continue;const n=kt(o);n&&n.length>0&&(e[r]=n.slice(0,5))}return Object.keys(e).length>0?e:void 0},wi=(t,e)=>{const r=Object.keys(t);return r.length!==Object.keys(e).length?!1:r.every(o=>Array.isArray(e[o])&&vt(t[o],e[o]))},bi=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Si=t=>{if(typeof t!="string")return null;const e=t.trim();return e&&bi.test(e)?e.toLowerCase():null},Ti=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=xn(a);if(!c||r.has(c)||o.has(a))continue;r.add(c),o.add(a);const l={id:c,path:a};if(typeof i.label=="string"&&i.label.trim().length>0&&(l.label=i.label.trim()),typeof i.icon=="string"&&i.icon.trim().length>0&&(l.icon=i.icon.trim()),i.iconImage===null)l.iconImage=null;else if(i.iconImage&&typeof i.iconImage=="object"){const d=i.iconImage,f=typeof d.mime=="string"?d.mime.trim():"",g=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,y=d.source==="custom"||d.source==="auto"?d.source:null;f&&g>0&&y&&(l.iconImage={mime:f,updatedAt:g,source:y})}if(typeof i.color=="string"&&i.color.trim().length>0&&(l.color=i.color.trim()),i.iconBackground===null)l.iconBackground=null;else{const d=Si(i.iconBackground);d&&(l.iconBackground=d)}typeof i.addedAt=="number"&&Number.isFinite(i.addedAt)&&i.addedAt>=0&&(l.addedAt=i.addedAt),typeof i.lastOpenedAt=="number"&&Number.isFinite(i.lastOpenedAt)&&i.lastOpenedAt>=0&&(l.lastOpenedAt=i.lastOpenedAt),typeof i.sidebarCollapsed=="boolean"&&(l.sidebarCollapsed=i.sidebarCollapsed),e.push(l)}return e.length>0?e:void 0},vi=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},ki=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},lt=(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},wo=()=>{const t=N.persist;if(t&&typeof t=="object")return t},bo=()=>Ke()?.settings??null,Et=t=>{const e=N.getState(),r=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,o=typeof window<"u"?window.__zustand_config_store__??null:null,n=oi.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=go(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),ro(t.uiFont)&&t.uiFont!==e.uiFont&&e.setUiFont(t.uiFont),oo(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&&!yi(t.shortcutOverrides,e.shortcutOverrides)&&N.setState({shortcutOverrides:t.shortcutOverrides}),typeof t.mobileKeyboardMode=="string"){const i=Je(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;ct(i,s)||N.setState({favoriteModels:s})}if(Array.isArray(t.hiddenModels)){const i=e.hiddenModels,s=t.hiddenModels;ct(i,s)||N.setState({hiddenModels:s})}if(Array.isArray(t.collapsedModelProviders)){const i=e.collapsedModelProviders,s=t.collapsedModelProviders;vt(i,s)||N.setState({collapsedModelProviders:s})}if(Array.isArray(t.recentModels)){const i=e.recentModels,s=t.recentModels;ct(i,s)||N.setState({recentModels:s})}if(Array.isArray(t.recentAgents)){const i=e.recentAgents,s=t.recentAgents;vt(i,s)||N.setState({recentAgents:s})}if(t.recentEfforts&&typeof t.recentEfforts=="object"){const i=e.recentEfforts,s=t.recentEfforts;wi(i,s)||N.setState({recentEfforts: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"&&ii(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&ai(t.filesViewShowGitignored,{persist:!1})},ur=t=>{if(!t||typeof t!="object")return null;const e=t,r={};if(typeof e.themeId=="string"&&e.themeId.length>0&&(r.themeId=e.themeId),(e.useSystemTheme===!0||e.useSystemTheme===!1)&&(r.useSystemTheme=e.useSystemTheme),typeof e.themeVariant=="string"&&(e.themeVariant==="light"||e.themeVariant==="dark")&&(r.themeVariant=e.themeVariant),typeof e.lightThemeId=="string"&&e.lightThemeId.length>0&&(r.lightThemeId=e.lightThemeId),typeof e.darkThemeId=="string"&&e.darkThemeId.length>0&&(r.darkThemeId=e.darkThemeId),typeof e.lastDirectory=="string"&&e.lastDirectory.length>0&&(r.lastDirectory=e.lastDirectory),typeof e.homeDirectory=="string"&&e.homeDirectory.length>0&&(r.homeDirectory=e.homeDirectory),typeof e.opencodeBinary=="string"){const p=e.opencodeBinary.trim();r.opencodeBinary=p.length>0?p:void 0}typeof e.desktopLanAccessEnabled=="boolean"&&(r.desktopLanAccessEnabled=e.desktopLanAccessEnabled);const o=Ti(e.projects);if(o&&(r.projects=o),typeof e.activeProjectId=="string"&&e.activeProjectId.length>0&&(r.activeProjectId=e.activeProjectId),Array.isArray(e.securityScopedBookmarks)&&(r.securityScopedBookmarks=e.securityScopedBookmarks.filter(p=>typeof p=="string"&&p.length>0)),Array.isArray(e.pinnedDirectories)&&(r.pinnedDirectories=Array.from(new Set(e.pinnedDirectories.filter(p=>typeof p=="string"&&p.length>0)))),Array.isArray(e.draftStarters)&&(r.draftStarters=go(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 p=e.tunnelProvider.trim().toLowerCase();p.length>0&&(r.tunnelProvider=p)}if(typeof e.tunnelMode=="string"){const p=e.tunnelMode.trim().toLowerCase();(p==="quick"||p==="managed-remote"||p==="managed-local")&&(r.tunnelMode=p)}if(e.tunnelBootstrapTtlMs===null?r.tunnelBootstrapTtlMs=null:typeof e.tunnelBootstrapTtlMs=="number"&&Number.isFinite(e.tunnelBootstrapTtlMs)&&(r.tunnelBootstrapTtlMs=e.tunnelBootstrapTtlMs),typeof e.tunnelSessionTtlMs=="number"&&Number.isFinite(e.tunnelSessionTtlMs)&&(r.tunnelSessionTtlMs=e.tunnelSessionTtlMs),e.managedLocalTunnelConfigPath===null)r.managedLocalTunnelConfigPath=null;else if(typeof e.managedLocalTunnelConfigPath=="string"){const p=e.managedLocalTunnelConfigPath.trim();r.managedLocalTunnelConfigPath=p.length>0?p:null}typeof e.managedRemoteTunnelHostname=="string"&&(r.managedRemoteTunnelHostname=e.managedRemoteTunnelHostname.trim()),e.managedRemoteTunnelToken===null?r.managedRemoteTunnelToken=null:typeof e.managedRemoteTunnelToken=="string"&&(r.managedRemoteTunnelToken=e.managedRemoteTunnelToken.trim());const n=vi(e.managedRemoteTunnelPresets);if(n&&(r.managedRemoteTunnelPresets=n),typeof e.managedRemoteTunnelSelectedPresetId=="string"){const p=e.managedRemoteTunnelSelectedPresetId.trim();r.managedRemoteTunnelSelectedPresetId=p.length>0?p:void 0}const i=ki(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 p=e.notificationTemplates,w=v=>{const Qe=p[v];if(!Qe||typeof Qe!="object")return;const be=Qe,Oo=typeof be.title=="string"?be.title:"",Io=typeof be.message=="string"?be.message:"";return{title:Oo,message:Io}},b=w("completion"),T=w("error"),E=w("question"),S=w("subtask");(b||T||E||S)&&(r.notificationTemplates={completion:b??{title:"Task Complete",message:"Your task has finished."},error:T??{title:"Error Occurred",message:"An error occurred while processing your task."},question:E??{title:"Input Needed",message:"Please provide input to continue."},subtask:S??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof e.summarizeLastMessage=="boolean"&&(r.summarizeLastMessage=e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&(r.summaryThreshold=Math.max(0,Math.round(e.summaryThreshold))),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&(r.summaryLength=Math.max(10,Math.round(e.summaryLength))),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&(r.maxLastMessageLength=Math.max(10,Math.round(e.maxLastMessageLength))),typeof e.usageAutoRefresh=="boolean"&&(r.usageAutoRefresh=e.usageAutoRefresh),typeof e.usageRefreshIntervalMs=="number"&&Number.isFinite(e.usageRefreshIntervalMs)&&(r.usageRefreshIntervalMs=e.usageRefreshIntervalMs),(e.usageDisplayMode==="usage"||e.usageDisplayMode==="remaining")&&(r.usageDisplayMode=e.usageDisplayMode),typeof e.usageShowPredValues=="boolean"&&(r.usageShowPredValues=e.usageShowPredValues),Array.isArray(e.usageDropdownProviders)&&(r.usageDropdownProviders=e.usageDropdownProviders.filter(p=>typeof p=="string"&&p.length>0)),e.usageSelectedModels&&typeof e.usageSelectedModels=="object"){const p={};for(const[w,b]of Object.entries(e.usageSelectedModels))Array.isArray(b)&&(p[w]=b.filter(T=>typeof T=="string"));Object.keys(p).length>0&&(r.usageSelectedModels=p)}if(e.usageCollapsedFamilies&&typeof e.usageCollapsedFamilies=="object"){const p={};for(const[w,b]of Object.entries(e.usageCollapsedFamilies))Array.isArray(b)&&(p[w]=b.filter(T=>typeof T=="string"));Object.keys(p).length>0&&(r.usageCollapsedFamilies=p)}if(e.usageExpandedFamilies&&typeof e.usageExpandedFamilies=="object"){const p={};for(const[w,b]of Object.entries(e.usageExpandedFamilies))Array.isArray(b)&&(p[w]=b.filter(T=>typeof T=="string"));Object.keys(p).length>0&&(r.usageExpandedFamilies=p)}if(e.usageModelGroups&&typeof e.usageModelGroups=="object"){const p={};for(const[w,b]of Object.entries(e.usageModelGroups))if(b&&typeof b=="object"){const T=b,E={};Array.isArray(T.customGroups)&&(E.customGroups=T.customGroups.filter(S=>S&&typeof S=="object").map(S=>({id:String(S.id??""),label:String(S.label??""),models:Array.isArray(S.models)?S.models.filter(v=>typeof v=="string"):[],order:typeof S.order=="number"?S.order:0}))),T.modelAssignments&&typeof T.modelAssignments=="object"&&(E.modelAssignments=Object.fromEntries(Object.entries(T.modelAssignments).filter(([,S])=>typeof S=="string").map(([S,v])=>[S,String(v)]))),T.renamedGroups&&typeof T.renamedGroups=="object"&&(E.renamedGroups=Object.fromEntries(Object.entries(T.renamedGroups).filter(([,S])=>typeof S=="string").map(([S,v])=>[S,String(v)]))),Object.keys(E).length>0&&(p[w]=E)}Object.keys(p).length>0&&(r.usageModelGroups=p)}typeof e.inputSpellcheckEnabled=="boolean"&&(r.inputSpellcheckEnabled=e.inputSpellcheckEnabled),typeof e.showOpenCodeUpdateNotifications=="boolean"&&(r.showOpenCodeUpdateNotifications=e.showOpenCodeUpdateNotifications),typeof e.openCodeUpdateToastDismissedVersion=="string"&&(r.openCodeUpdateToastDismissedVersion=e.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof e.showToolFileIcons=="boolean"&&(r.showToolFileIcons=e.showToolFileIcons),typeof e.showTurnChangedFiles=="boolean"&&(r.showTurnChangedFiles=e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&(r.showExpandedBashTools=e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&(r.showExpandedEditTools=e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&(r.timeFormatPreference=e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&(r.weekStartPreference=e.weekStartPreference),typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&(r.chatRenderMode=e.chatRenderMode),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&(r.messageStreamTransport=e.messageStreamTransport),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&(r.activityRenderMode=e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&(r.mermaidRenderingMode=e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&(r.userMessageRenderingMode=e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&(r.collapsibleUserMessages=e.collapsibleUserMessages),typeof e.stickyUserHeader=="boolean"&&(r.stickyUserHeader=e.stickyUserHeader),typeof e.wideChatLayoutEnabled=="boolean"&&(r.wideChatLayoutEnabled=e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&(r.showSplitAssistantMessageActions=e.showSplitAssistantMessageActions),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&(r.fontSize=e.fontSize),typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&(r.terminalFontSize=e.terminalFontSize),ro(e.uiFont)&&(r.uiFont=e.uiFont),oo(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=mi(e.shortcutOverrides);s&&(r.shortcutOverrides=s),typeof e.mobileKeyboardMode=="string"&&(e.mobileKeyboardMode==="native"||e.mobileKeyboardMode==="resize-content")&&(r.mobileKeyboardMode=e.mobileKeyboardMode);const a=lt(e.favoriteModels,64);a&&(r.favoriteModels=a);const c=lt(e.hiddenModels,1024);c&&(r.hiddenModels=c);const l=kt(e.collapsedModelProviders);l&&(r.collapsedModelProviders=l);const d=lt(e.recentModels,16);d&&(r.recentModels=d);const f=kt(e.recentAgents);f&&(r.recentAgents=f);const g=gi(e.recentEfforts);if(g&&(r.recentEfforts=g),typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&(r.diffLayoutPreference=e.diffLayoutPreference),typeof e.gitChangesViewMode=="string"&&(e.gitChangesViewMode==="flat"||e.gitChangesViewMode==="tree")&&(r.gitChangesViewMode=e.gitChangesViewMode),typeof e.directoryShowHidden=="boolean"&&(r.directoryShowHidden=e.directoryShowHidden),typeof e.filesViewShowGitignored=="boolean"&&(r.filesViewShowGitignored=e.filesViewShowGitignored),typeof e.openInAppId=="string"&&e.openInAppId.length>0&&(r.openInAppId=e.openInAppId),typeof e.pwaAppName=="string"){const p=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);r.pwaAppName=p.length>0?p:""}const y=hi(e.skillCatalogs);return y&&(r.skillCatalogs=y),typeof e.reportUsage=="boolean"&&(r.reportUsage=e.reportUsage),typeof e.globalBehaviorPrompt=="string"&&(r.globalBehaviorPrompt=e.globalBehaviorPrompt),typeof e.responseStyleEnabled=="boolean"&&(r.responseStyleEnabled=e.responseStyleEnabled),typeof e.responseStylePreset=="string"&&(e.responseStylePreset==="concise"||e.responseStylePreset==="detailed"||e.responseStylePreset==="mentor"||e.responseStylePreset==="pushback"||e.responseStylePreset==="noFiller"||e.responseStylePreset==="matchEnergy"||e.responseStylePreset==="warmPeer"||e.responseStylePreset==="custom")&&(r.responseStylePreset=e.responseStylePreset),typeof e.responseStyleCustomInstructions=="string"&&(r.responseStyleCustomInstructions=e.responseStyleCustomInstructions),(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 K=null,ae=null;const Ei=2e3,Di=async()=>K&&Date.now()-K.at<Ei?K.value:ae||(ae=(async()=>{const t=bo();if(t)try{const e=await t.load(),r=ur(e.settings);return K={value:r,at:Date.now()},r}catch(e){console.warn("Failed to load shared settings from runtime settings API:",e)}try{const e=await u("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const r=await e.json().catch(()=>null),o=ur(r);return K={value:o,at:Date.now()},o}catch(e){return console.warn("Failed to load shared settings from server:",e),null}})().finally(()=>{ae=null}),ae),kc=async()=>{if(typeof window>"u")return;const t=wo(),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{St(o)}catch(n){console.warn("persistToLocalStorage failed:",n)}await e();try{Et(o)}catch(n){console.warn("applyDesktopUiPreferences failed:",n)}Tt(o)};try{const o=await Di();o&&await r(o)}catch(o){console.warn("Failed to synchronise settings:",o)}};let Le=null,Ie=null,Dt=[];const Mi=200,Pi=async()=>{const t=Le,e=Dt;if(Le=null,Ie=null,Dt=[],!t||Object.keys(t).length===0){e.forEach(o=>o());return}const r=bo();if(r)try{const o=await r.save(t);o&&(St(o),Et(o),Tt(o),K=null),e.forEach(n=>n());return}catch(o){console.warn("Failed to update settings via runtime settings API:",o)}try{const o=await u("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!o.ok){console.warn("Failed to update shared settings via API:",o.status,o.statusText);return}const n=await o.json().catch(()=>null);n&&(St(n),Et(n),Tt(n),K=null)}catch(o){console.warn("Failed to update shared settings via API:",o)}finally{e.forEach(o=>o())}},U=async t=>{if(typeof window>"u")return;Le={...Le??{},...t},Ie&&clearTimeout(Ie);const e=new Promise(r=>{Dt.push(r)});return Ie=setTimeout(()=>{Pi()},Mi),e},Ec=async()=>{if(typeof window>"u")return;const t=wo();try{const e=await ui();if(!e)return;const r=()=>di(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)}},Ai=3e4,Ci=40,Oi=60,Ii=(t,e,r,o,n,i)=>{const s=t.trim(),a=e.trim().toLowerCase();return JSON.stringify([s,a,r,o,n,i])},fr=(t,e)=>{try{const r=JSON.parse(t);return Array.isArray(r)&&r[0]===e}catch{return!1}},Ri=ze()($e((t,e)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(r,o,n=Oi,i){if(!r||r.trim().length===0)return[];const s=r.trim(),a=typeof o=="string"?o.trim():"",c=!!i?.includeHidden,l=i?.respectGitignore??!0,d=i?.type==="directory"?"directory":"file",f=Ii(s,a,n,c,l,d),g=Date.now(),y=e().cache[f];if(y&&g-y.timestamp<Ai)return y.files;const p=e().inFlight[f];if(p)return p;const w=H.searchFiles(a,{directory:s,limit:n,includeHidden:c,respectGitignore:l,dirs:d!=="file",type:d}).then(b=>(t(T=>{if(T.inFlight[f]!==w)return T;const E={...T.cache,[f]:{files:b,timestamp:Date.now()}},S=T.cacheKeys.filter(v=>v!==f);for(S.push(f);S.length>Ci;){const v=S.shift();v&&delete E[v]}return{cache:E,cacheKeys:S}}),b)).finally(()=>{t(b=>{if(b.inFlight[f]!==w)return b;const T={...b.inFlight};return delete T[f],{inFlight:T}})});return t(b=>({inFlight:{...b.inFlight,[f]:w}})),w},invalidateDirectory(r){if(!r||r.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=r.trim();t(n=>{const i={...n.cache},s=n.cacheKeys.filter(l=>fr(l,o)?(delete i[l],!1):!0),a=Object.entries(n.inFlight).filter(([l])=>!fr(l,o)),c=Object.fromEntries(a);return{cache:i,cacheKeys:s,inFlight:c}})}}),{name:"file-search-store"})),Fi=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Mt="openchamber_stream_perf",we=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Mt)==="1"}catch{return!1}},pr=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),_i=()=>{if(!we()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const t=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:t,lastUpdatedAt:t}}return window.__openchamberStreamPerfState},So=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),Lt=(t,e)=>{const r=_i();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()},Dc=t=>{if(!(typeof window>"u"))try{if(t){window.localStorage.setItem(Mt,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Mt),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},Mc=()=>{typeof window>"u"||(we()&&(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()}))},Pc=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberStreamPerfState;return!we()||!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:So(t.counters)}},Ac=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberVsCodeStreamPerfState;if(!we()||!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:So(t.counters)}},Cc=(t,e=1)=>{Lt(t,e)},Oc=(t,e)=>{Lt(t,e)},Ic=(t,e)=>{if(!we())return e();const r=pr();try{return e()}finally{Lt(t,pr()-r)}};var xi={};let _=null,hr=0;const F=Q(),mr=F.getItem("lastDirectory"),ji=typeof mr=="string"&&mr.length>0,Ee=t=>{try{Ri.getState().invalidateDirectory(t)}catch(e){console.warn("Failed to invalidate file search cache:",e)}},re=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},Ni=(t,e)=>{const r=t.trim();return r.startsWith("~")?r==="~"?e||r:(r.startsWith("~/")||r.startsWith("~\\"))&&e?`${e}${r.slice(1)}`:r:r},Re=(t,e)=>{const r=Ni(t,e);return re(r)},Li=()=>{const t=F.getItem("homeDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=re(t);return e.length>0?e:null},Ui=()=>{const t=F.getItem("lastDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=re(t);return e.length>0?e:null},Bi=()=>{if(typeof process>"u")return null;const t=xi,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=re(e);return o.length>0?o:null}const r=process?.cwd?.();if(typeof r=="string"&&r.trim().length>0){const o=re(r);return o.length>0?o:null}return null},Ue=()=>{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=Li();if(r&&!Ve())return _=r,r}const t=Bi();return t||"/"},Hi=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},zi=t=>(_=t,typeof window<"u"&&F.setItem("homeDirectory",t),U({homeDirectory:t}),t),Pt=async()=>{const t=o=>{const n=Hi(o);return n?zi(n):null};try{const o=await H.getFilesystemHome(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain filesystem home directory:",o)}try{const o=await H.getSystemInfo(),n=t(o?.homeDirectory);if(n)return n}catch(o){console.warn("Failed to get home directory from system info:",o)}try{const o=await Vr(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain desktop-integrated home directory:",o)}const e=Ue(),r=t(e);return r||e},$i=()=>{if(!Ve())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const e=re(t);return e.length>0?e:null},me=$i()||Ue(),Be=(()=>{const t=Ui();return t&&!Ve()?Re(t,me):me})();Be&&H.setDirectory(Be);const Gi=!!(me&&me!=="/"),At=ze()($e((t,e)=>({currentDirectory:Be,directoryHistory:[Be],historyIndex:0,homeDirectory:me,hasPersistedDirectory:ji,isHomeReady:Gi,isSwitchingDirectory:!1,setDirectory:(r,o)=>{const n=_||e().homeDirectory||F.getItem("homeDirectory"),i=Re(r,n);Fi()&&console.log("[DirectoryStore] setDirectory called with path:",i),H.setDirectory(i),Ee(),t(s=>{const a=[...s.directoryHistory.slice(0,s.historyIndex+1),i];return F.setItem("lastDirectory",i),U({lastDirectory:i}),{currentDirectory:i,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const r=e();if(r.historyIndex>0){const o=r.historyIndex-1,n=r.directoryHistory[o];H.setDirectory(n),Ee(),F.setItem("lastDirectory",n),U({lastDirectory:n}),t({currentDirectory:n,historyIndex:o,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const r=e();if(r.historyIndex<r.directoryHistory.length-1){const o=r.historyIndex+1,n=r.directoryHistory[o];H.setDirectory(n),Ee(),F.setItem("lastDirectory",n),U({lastDirectory:n}),t({currentDirectory:n,historyIndex:o,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:r,setDirectory:o}=e(),n=_||e().homeDirectory||Ue();if(r===n||r==="/")return;const i=r.endsWith("/")?r.slice(0,-1):r,s=i.lastIndexOf("/");if(s===-1){const a=_||Ue();o(a)}else o(s===0?"/":i.substring(0,s))},goHome:async()=>{const r=_||e().homeDirectory||await Pt();e().setDirectory(r)},synchronizeHomeDirectory:r=>{const o=e(),n=r;_=n;const i=o.homeDirectory!==n,s=F.getItem("lastDirectory"),a=typeof s=="string"&&s.length>0,c=!a&&(o.currentDirectory==="/"||o.currentDirectory===o.homeDirectory||!o.currentDirectory);if(!i&&!c){o.isHomeReady||t({isHomeReady:!0});return}const l=typeof n=="string"&&n!==""&&n!=="/",d=o.currentDirectory?Re(o.currentDirectory,n):o.currentDirectory,f=o.directoryHistory.map(w=>Re(w,n)),g=f.some((w,b)=>w!==o.directoryHistory[b]),y=!!(d&&d!==o.currentDirectory),p={homeDirectory:n,hasPersistedDirectory:a,isHomeReady:l};if(c?(p.currentDirectory=n,p.directoryHistory=[n],p.historyIndex=0,p.isSwitchingDirectory=!1):(y||g)&&(p.currentDirectory=d,p.directoryHistory=f,p.historyIndex=Math.min(o.historyIndex,f.length-1),p.isSwitchingDirectory=!1),t(()=>p),(c||y)&&l){const w=c?n:d;H.setDirectory(w),Ee(),F.setItem("lastDirectory",w),U({lastDirectory:w})}U({homeDirectory:n})}}),{name:"directory-store"}));typeof window<"u"&&(Pt().then(t=>{At.getState().synchronizeHomeDirectory(t)}),an(()=>{_=null;const t=++hr;Pt().then(e=>{t===hr&&At.getState().synchronizeHomeDirectory(e)})}));const To=1,x=1,De=0,vo="/api/terminal/ws",Wi=1200,qi=250,Ki=2e4,Vi=5e3,dt="__openchamberTerminalTransportState",Ji=new TextEncoder,yr=new TextDecoder,Ut=t=>P().websocket(t),ut=t=>{const e=Ji.encode(JSON.stringify(t)),r=new Uint8Array(e.length+1);return r[0]=To,r.set(e,1),r},ye=t=>t?((t.transports??[]).includes("ws")||t.preferred==="ws")&&typeof t.ws?.path=="string"&&t.ws.path.length>0:!1,Bt=t=>t.streamCapability?.ws?.path??t.inputCapability?.ws?.path??vo,Qi=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 Yi{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(Wi);if(!o||o.readyState!==x)return!1;try{return this.boundSessionId!==e&&(this.requestedSessionId=e,o.send(ut({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===De)?!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===De)||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===De&&(i.close(),n(null))},Vi)}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(ut({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()*qi),l=a+c;this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},l)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}sendControl(e){if(!this.socket||this.socket.readyState!==x)return!1;try{return this.socket.send(ut(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})},Ki)}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]===To){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(yr.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=Qi(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?yr.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===De)&&e.close()}this.boundSessionId=null}}const L=()=>{const t=globalThis;return t[dt]||(t[dt]={inputCapability:null,streamCapability:null,manager:null}),t[dt]},Ht=()=>{const t=L();return t.manager||(t.manager=new Yi),t.manager},ko=t=>{const e=L();if(e.inputCapability=t?.input??null,e.streamCapability=t?.stream??null,!ye(e.inputCapability)&&!ye(e.streamCapability)){e.manager?.close(),e.manager=null;return}const r=Ut(Bt(e));if(!r)return;Ht().configure(r)},Xi=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 Zi(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 ko(r.capabilities),r}const gr=(t,e,r,o={})=>{const n=o.maxRetries??3,i=o.initialRetryDelay??1e3,s=o.maxRetryDelay??8e3,a=o.connectionTimeout??1e4;let c=null,l=0,d=null,f=null,g=!1,y=!1;const p=()=>{d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},w=()=>{g||(g=!0,p(),c&&(c.close(),c=null))},b=(E,S)=>{if(!(g||y)){if(l<n&&!S){l+=1;const v=Math.min(i*Math.pow(2,l-1),s);e({type:"reconnecting",attempt:l,maxAttempts:n}),d=setTimeout(()=>{!g&&!y&&T()},v);return}r?.(E,!0),w()}},T=()=>{if(g||y||c&&c.readyState!==EventSource.CLOSED)return;c=new EventSource(P().sse(`/api/terminal/${t}/stream`));let E=!1;f=setTimeout(()=>{!E&&c?.readyState!==EventSource.OPEN&&(c?.close(),b(new Error("Connection timeout"),!1))},a),c.onopen=()=>{E||(E=!0,l=0,p(),e({type:"connected"}))},c.onmessage=S=>{try{const v=JSON.parse(S.data);v.type==="exit"&&(L().manager?.unbindSession(t),y=!0,w()),e(v)}catch(v){r?.(v,!1)}},c.onerror=()=>{p();const S=y||c?.readyState===EventSource.CLOSED;c?.close(),c=null,y||b(new Error("Terminal stream connection error"),S)}};return T(),w};function es(t,e,r,o={}){const n=L();if(!ye(n.streamCapability))return gr(t,e,r,o);const i=Ht(),s=Ut(Bt(n));return s?(i.configure(s),i.subscribe(t,e,r,o)):gr(t,e,r,o)}async function ts(t,e){const r=L();r.manager&&await r.manager.sendInput(t,e)||await Xi(t,e)}async function rs(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 os(t){L().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 ns(t,e){L().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 ko(o.capabilities),o}async function is(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&&L().manager?.unbindSession(t.sessionId)}function Rc(){const t=L();t.manager?.close(),t.manager=null,t.inputCapability=null,t.streamCapability=null}function Fc(){const t=L();if(t.inputCapability&&t.streamCapability&&!ye(t.inputCapability)&&!ye(t.streamCapability))return;const e=Bt(t)||vo,r=Ut(e);if(!r)return;const o=Ht();o.isConnectedOrConnecting(r)||(o.configure(r),o.prime())}const ss=t=>{const e=t?.retry;return{maxRetries:e?.maxRetries??3,initialRetryDelay:e?.initialDelayMs??1e3,maxRetryDelay:e?.maxDelayMs??8e3,connectionTimeout:t?.connectionTimeoutMs??1e4}},as=()=>({async createSession(t){return Zi(t)},connect(t,e,r){const o=es(t,e.onEvent,e.onError,ss(r));return{close:()=>o()}},async sendInput(t,e){await ts(t,e)},async resize(t){await rs(t.sessionId,t.cols,t.rows)},async close(t){await os(t)},async restartSession(t,e){return ns(t,{cwd:e.cwd??"",cols:e.cols,rows:e.rows})},async forceKill(t){await is(t)}}),h="/api/git",cs=1200,ls=5e3,He=new Map,ee=new Map,Eo=new Map,wr=new Map,Me=new Map,ge=t=>t.trim(),ds=(t,e)=>e==="light"?`${ge(t)}::light`:ge(t),Ct=t=>Eo.get(ge(t))??0,z=t=>{const e=ge(t);Eo.set(e,Ct(t)+1);for(const r of Array.from(He.keys()))(r===e||r.startsWith(`${e}::`))&&He.delete(r);for(const r of Array.from(ee.keys()))(r===e||r.startsWith(`${e}::`))&&ee.delete(r)};function m(t,e,r){const o={...r};return e&&(o.directory=e),P().api(t,o)}async function us(t){const e=ge(t),r=Date.now(),o=wr.get(e);if(o&&o.expiresAt>r)return o.value;const n=Me.get(e);if(n)return n;const i=(async()=>{const s=await u(m(`${h}/check`,t));if(!s.ok)throw new Error(`Failed to check git repository: ${s.statusText}`);const c=!!(await s.json()).isGitRepository;return wr.set(e,{value:c,expiresAt:Date.now()+ls}),c})();Me.set(e,i);try{return await i}finally{Me.get(e)===i&&Me.delete(e)}}async function fs(t,e){const r=e?.mode,o=ds(t,r),n=Date.now(),i=He.get(o);if(i&&i.expiresAt>n)return i.value;const s=ee.get(o);if(s)return s;const a=(async()=>{const c=Ct(t),l=await u(m(`${h}/status`,t,r?{mode:r}:void 0));if(!l.ok)throw new Error(`Failed to get git status: ${l.statusText}`);const d=await l.json();return Ct(t)===c&&He.set(o,{value:d,expiresAt:Date.now()+cs}),d})();ee.set(o,a);try{return await a}finally{ee.get(o)===a&&ee.delete(o)}}async function _c(t){const e=await u(m(`${h}/primary-root`,t));if(!e.ok)throw new Error(`Failed to resolve git primary root: ${e.statusText}`);const r=await e.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:t}}async function xc(t){const e=await u(m(`${h}/toplevel`,t));if(!e.ok)throw new Error(`Failed to resolve git toplevel: ${e.statusText}`);const r=await e.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:t}}async function jc(t,e){const r=await u(m(`${h}/commit-summaries`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:e})});if(!r.ok)throw new Error(`Failed to get git commit summaries: ${r.statusText}`);const o=await r.json().catch(()=>({}));return{commits:Array.isArray(o.commits)?o.commits.map(n=>({sha:typeof n.sha=="string"?n.sha:"",short:typeof n.short=="string"?n.short:"",subject:typeof n.subject=="string"?n.subject:""})).filter(n=>n.sha&&n.short):[]}}async function ps(t,e){const{path:r,staged:o,contextLines:n}=e;if(!r)throw new Error("path is required to fetch git diff");const i=await u(m(`${h}/diff`,t,{path:r,staged:o?"true":void 0,context:n}));if(!i.ok)throw new Error(`Failed to get git diff: ${i.statusText}`);return i.json()}async function hs(t,e){const{path:r,staged:o}=e;if(!r)throw new Error("path is required to fetch git file diff");const n=await u(m(`${h}/file-diff`,t,{path:r,staged:o?"true":void 0}));if(!n.ok)throw new Error(`Failed to get git file diff: ${n.statusText}`);return n.json()}async function ms(t,e,r){if(!e)throw new Error("path is required to revert git changes");const o=await u(m(`${h}/revert`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,scope:r?.scope})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to revert git changes")}z(t)}async function ys(t,e){await Do(t,[e])}async function Do(t,e){const r=e.map(n=>n.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to stage git changes");const o=await u(m(`${h}/stage`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to stage git changes")}z(t)}async function gs(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 unstage git changes");const o=await u(m(`${h}/unstage`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to unstage git changes")}z(t)}async function ws(t,e,r){await zt(t,e,r,"stage")}async function bs(t,e,r){await zt(t,e,r,"unstage")}async function Ss(t,e,r){await zt(t,e,r,"discard")}async function zt(t,e,r,o){if(!e)throw new Error("path is required to apply a git hunk");if(typeof r!="string"||!r.trim())throw new Error("patch is required to apply a git hunk");const n=await u(m(`${h}/apply-hunk`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,patch:r,action:o})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to apply git hunk")}z(t)}async function Ts(t){if(!t)return!1;const e=await u(m(`${h}/worktree-type`,t));if(!e.ok)throw new Error(`Failed to detect worktree type: ${e.statusText}`);return!!(await e.json()).linked}async function vs(t){const e=await u(m(`${h}/branches`,t));if(!e.ok)throw new Error(`Failed to get branches: ${e.statusText}`);return e.json()}async function ks(t,e){if(!e?.branch)throw new Error("branch is required to delete a branch");const r=await u(m(`${h}/branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete branch")}return r.json()}async function Es(t,e){if(!e?.branch)throw new Error("branch is required to delete remote branch");const r=await u(m(`${h}/remote-branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete remote branch")}return r.json()}async function Ds(t,e){const r=e?.remote?.trim();if(!r)throw new Error("remote is required to remove a remote");const o=await u(m(`${h}/remotes`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to remove remote")}return o.json()}async function Ms(t,e,r){if(!Array.isArray(e)||e.length===0)throw new Error("No files provided to generate commit message");const o={files:e};r?.zenModel&&(o.zenModel=r.zenModel),r?.providerId&&(o.providerId=r.providerId),r?.modelId&&(o.modelId=r.modelId);const n=await u(m(`${h}/commit-message`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!n.ok){const c=await n.json().catch(()=>({error:n.statusText}));console.error("[git-generation][browser] http error",{status:n.status,statusText:n.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const i=await n.json();if(!i?.message||typeof i.message!="object")throw new Error("Malformed commit generation response");const s=typeof i.message.subject=="string"&&i.message.subject.trim().length>0?i.message.subject.trim():"",a=Array.isArray(i.message.highlights)?i.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:s,highlights:a}}}async function Ps(t,e){const{base:r,head:o,context:n,zenModel:i,providerId:s,modelId:a}=e;if(!r||!o)throw new Error("base and head are required");const c={base:r,head:o};n?.trim()&&(c.context=n.trim()),i&&(c.zenModel=i),s&&(c.providerId=s),a&&(c.modelId=a);const l=await u(m(`${h}/pr-description`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const y=await l.json().catch(()=>({error:l.statusText}));throw new Error(y.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),f=typeof d?.title=="string"?d.title:"",g=typeof d?.body=="string"?d.body:"";if(!f&&!g)throw new Error("Malformed PR description response");return{title:f,body:g}}async function br(t){const e=await u(m(`${h}/worktrees`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to list worktrees")}return e.json()}async function Sr(t,e){const r=await u(m(`${h}/worktrees/validate`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to validate worktree")}return r.json()}async function As(t){const e=await u(m(`${h}/worktrees/bootstrap-status`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to get worktree bootstrap status")}return e.json()}async function Cs(t,e){const r=await u(m(`${h}/worktrees/preview`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to preview worktree")}return r.json()}async function Tr(t,e){const r=await u(m(`${h}/worktrees`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create worktree")}return r.json()}async function vr(t,e){const r=await u(m(`${h}/worktrees`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete worktree")}return r.json()}async function Os(t,e,r={}){const o=await u(m(`${h}/commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e,addAll:r.addAll??!1,files:r.files,stageFiles:r.stageFiles})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to create commit")}const n=await o.json();return z(t),n}async function Is(t,e={}){const r=await u(m(`${h}/push`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to push")}const o=await r.json();return z(t),o}async function Rs(t,e={}){const r=await u(m(`${h}/pull`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to pull")}const o=await r.json();return z(t),o}async function Fs(t,e={}){const r=await u(m(`${h}/fetch`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to fetch")}const o=await r.json();return z(t),o}async function _s(t){const e=await u(m(`${h}/stashes`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to list stashes")}return e.json()}async function xs(t,e){const r=await u(m(`${h}/stashes/file-counts`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to count stash files")}return r.json()}async function Po(t,e={}){const r=await u(m(`${h}/stash`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to stash changes")}return r.json()}const $t=async(t,e,r)=>{const o=await u(m(`${h}/${e}`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||`Failed to ${e}`)}return o.json()},js=(t,e)=>$t(t,"stash/apply",e),Ao=(t,e)=>$t(t,"stash/pop",e),Ns=(t,e)=>$t(t,"stash/drop",e);async function Ls(t,e){const r=await u(m(`${h}/checkout`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to checkout branch")}return r.json()}async function Us(t,e,r){const o=await u(m(`${h}/branches`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,startPoint:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to create branch")}return o.json()}async function Bs(t,e,r){const o=await u(m(`${h}/branches/rename`,t),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:e,newName:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to rename branch")}return o.json()}async function Hs(t,e={}){const r=await u(m(`${h}/log`,t,{maxCount:e.maxCount,from:e.from,to:e.to,file:e.file,all:e.all?"true":void 0}));if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(`Failed to get git log: ${o.error||r.statusText}`)}return r.json()}async function zs(t,e){const r=await u(m(`${h}/commit-files`,t,{hash:e}));if(!r.ok)throw new Error(`Failed to get commit files: ${r.statusText}`);return r.json()}async function Nc(t,e,r,o){const n=await u(m(`${h}/commit-file-diff`,t,{hash:e,path:r,binary:o?"true":void 0}));if(!n.ok)throw new Error(`Failed to get commit file diff: ${n.statusText}`);return n.json()}async function $s(){const t=await u(m(`${h}/identities`,void 0));if(!t.ok)throw new Error(`Failed to get git identities: ${t.statusText}`);return t.json()}async function Gs(t){const e=await u(m(`${h}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to create git identity")}return e.json()}async function Ws(t,e){const r=await u(m(`${h}/identities/${t}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to update git identity")}return r.json()}async function qs(t){const e=await u(m(`${h}/identities/${t}`,void 0),{method:"DELETE"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to delete git identity")}}async function Ks(t){if(!t)return null;const e=await u(m(`${h}/current-identity`,t));if(!e.ok)throw new Error(`Failed to get current git identity: ${e.statusText}`);const r=await e.json();return r?{userName:r.userName??null,userEmail:r.userEmail??null,sshCommand:r.sshCommand??null}:null}async function Vs(t){if(!t)return!1;const e=await u(m(`${h}/has-local-identity`,t));if(!e.ok)throw new Error(`Failed to check local identity: ${e.statusText}`);return(await e.json().catch(()=>null))?.hasLocalIdentity===!0}async function Lc(){const t=await u(m(`${h}/global-identity`,void 0));if(!t.ok)throw new Error(`Failed to get global git identity: ${t.statusText}`);const e=await t.json();return!e||!e.userName&&!e.userEmail?null:{userName:e.userName??null,userEmail:e.userEmail??null,sshCommand:e.sshCommand??null}}async function Js(t,e){const r=await u(m(`${h}/set-identity`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to set git identity")}return r.json()}async function Uc(){const t=await u(m(`${h}/discover-credentials`,void 0));if(!t.ok)throw new Error(`Failed to discover git credentials: ${t.statusText}`);return t.json()}async function Bc(t,e){if(!t)return null;const r=await u(m(`${h}/remote-url`,t,{remote:e}));return r.ok?(await r.json()).url??null:null}async function Qs(t){const e=await u(m(`${h}/remotes`,t));if(!e.ok)throw new Error(`Failed to get remotes: ${e.statusText}`);return e.json()}async function Ys(t,e){const r=await u(m(`${h}/rebase`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rebase")}return r.json()}async function Xs(t){const e=await u(m(`${h}/rebase/abort`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to abort rebase")}return e.json()}async function Zs(t,e){const r=await u(m(`${h}/merge`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to merge")}return r.json()}async function ea(t,e){const r=await u(m(`${h}/checkout-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to checkout commit")}return r.json()}async function ta(t,e){const r=await u(m(`${h}/cherry-pick`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to cherry-pick")}return r.json()}async function ra(t,e){const r=await u(m(`${h}/revert-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to revert commit")}return r.json()}async function oa(t,e,r,o){const n=await u(m(`${h}/reset-to-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e,mode:r,force:o})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to reset")}return n.json()}async function na(t){const e=await u(m(`${h}/merge/abort`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to abort merge")}return e.json()}async function ia(t){const e=await u(m(`${h}/rebase/continue`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to continue rebase")}return e.json()}async function sa(t){const e=await u(m(`${h}/merge/continue`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to continue merge")}return e.json()}async function aa(t,e){return await Po(t,{message:e?.message}),{success:!0}}async function ca(t){return await Ao(t,{ref:"stash@{0}"}),{success:!0}}async function la(t){const e=await u(m(`${h}/conflict-details`,t));if(!e.ok)throw new Error(`Failed to get conflict details: ${e.statusText}`);return e.json()}async function da(t,e){const r=await u(`${h}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t,worktreeRoot:e})});if(!r.ok)throw new Error(`Failed to validate worktree directory: ${r.statusText}`);return r.json()}async function ua(t){const e=await u(`${h}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!e.ok)throw new Error(`Failed to canonicalize worktree state: ${e.statusText}`);return e.json()}const fa=()=>({checkIsGitRepository:us,getGitStatus:fs,getGitDiff:ps,getGitFileDiff:hs,revertGitFile:ms,stageGitFile:ys,stageGitFiles:Do,unstageGitFile:gs,unstageGitFiles:Mo,stageGitHunk:ws,unstageGitHunk:bs,revertGitHunk:Ss,isLinkedWorktree:Ts,getGitBranches:vs,deleteGitBranch:ks,deleteRemoteBranch:Es,removeRemote:Ds,generateCommitMessage:Ms,generatePullRequestDescription:Ps,listGitWorktrees:br,validateGitWorktree:Sr,createGitWorktree:Tr,deleteGitWorktree:vr,validateWorktreeDirectory:da,canonicalizeWorktreeState:ua,createGitCommit(t,e,r){return Os(t,e,r)},gitPush:Is,gitPull:Rs,gitFetch:Fs,listGitStashes:_s,countGitStashFiles:xs,stashGitChanges:Po,applyGitStash:js,popGitStash:Ao,dropGitStash:Ns,checkoutBranch:Ls,createBranch:Us,renameBranch:Bs,getGitLog(t,e){return Hs(t,e)},getCommitFiles:zs,getCurrentGitIdentity:Ks,hasLocalIdentity:Vs,setGitIdentity:Js,getGitIdentities:$s,createGitIdentity:Gs,updateGitIdentity:Ws,deleteGitIdentity:qs,getRemotes:Qs,rebase:Ys,abortRebase:Xs,continueRebase:ia,merge:Zs,abortMerge:na,continueMerge:sa,checkoutCommit:ea,cherryPick:ta,revertCommit:ra,resetToCommit:oa,stash:aa,stashPop:ca,getConflictDetails:la,worktree:{list:br,validate:Sr,bootstrapStatus:As,preview:Cs,create:Tr,remove:vr}}),D=t=>t.replace(/\\/g,"/"),pa=(t,e)=>{const r=D(e?.directory||e?.path||t),o=Array.isArray(e?.entries)?e.entries:[];return{directory:r,entries:o.filter(n=>!!(n&&typeof n.name=="string"&&typeof n.path=="string")).map(n=>({name:n.name,path:D(n.path),isDirectory:!!n.isDirectory}))}},j=(t,e)=>{const r=e||t?.();return r?{"x-opencode-directory":r}:void 0},ha=({getDirectory:t})=>({async listDirectory(e,r){const o=D(e),n=new URLSearchParams;o&&n.set("path",o),r?.respectGitignore&&n.set("respectGitignore","true");const i=await u("/api/fs/list",{query:n,headers:j(t)});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to list directory")}const s=await i.json();return pa(o,s)},async search(e){const r=new URLSearchParams,o=D(e.directory);o&&r.set("directory",o),r.set("query",e.query),r.set("dirs","false"),r.set("type","file"),typeof e.maxResults=="number"&&Number.isFinite(e.maxResults)&&r.set("limit",String(e.maxResults));const n=await u("/api/find/file",{query:r,headers:j(t)});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Failed to search files")}const i=await n.json();return(Array.isArray(i)?i:[]).map(a=>({path:D(`${o}/${a}`),preview:[D(a)]}))},async createDirectory(e){const r=D(e),o=await u("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:r})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to create directory")}const n=await o.json();return{success:!!n?.success,path:typeof n?.path=="string"?D(n.path):r}},async statFile(e,r){const o=D(e),n=new URLSearchParams({path:o});r?.allowOutsideWorkspace&&n.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&n.set("outsideFileGrant",r.outsideFileGrant);const i=await u("/api/fs/stat",{query:n,headers:j(t,r?.directory)});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to stat file")}const s=await i.json().catch(()=>({}));return{path:typeof s.path=="string"?D(s.path):o,isFile:!!s.isFile,size:typeof s.size=="number"?s.size:0,mtimeMs:typeof s.mtimeMs=="number"?s.mtimeMs:void 0}},async readFile(e,r){const o=D(e),n=new URLSearchParams({path:o});r?.allowOutsideWorkspace&&n.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&n.set("outsideFileGrant",r.outsideFileGrant),r?.optional&&n.set("optional","true");const i=await u("/api/fs/read",{query:n,cache:r?.optional?"no-store":"default",headers:j(t,r?.directory)});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await i.text(),path:o}},async writeFile(e,r){const o=D(e),n=await u("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:o,content:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to write file")}const i=await n.json().catch(()=>({}));return{success:!!i.success,path:typeof i.path=="string"?D(i.path):o}},async delete(e){const r=D(e),o=await u("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:r})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to delete file")}return{success:!!(await o.json().catch(()=>({}))).success}},async rename(e,r){const o=await u("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({oldPath:e,newPath:r})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to rename file")}const n=await o.json().catch(()=>({}));return{success:!!n.success,path:typeof n.path=="string"?D(n.path):r}},async revealPath(e){const r=await u("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...j(t)},body:JSON.stringify({path:D(e)})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to reveal path")}return{success:!!(await r.json().catch(()=>({}))).success}},async downloadFile(e){const r=D(e),o=await u("/api/fs/raw",{query:{path:r,download:!0},headers:j(t)});if(!o.ok)throw new Error(`Download failed (${o.status})`);const n=await o.blob(),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=r.split("/").pop()||"file",document.body.appendChild(s),s.click(),document.body.removeChild(s),setTimeout(()=>URL.revokeObjectURL(i),100)}}),kr="/api/config/settings",ma="/api/config/reload",Er=t=>!t||typeof t!="object"?{}:t,ya=()=>({async load(){const t=await u(kr,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load settings: ${t.statusText}`);return{settings:Er(await t.json().catch(()=>({}))),source:"web"}},async save(t){const e=await u(kr,{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 Er(await e.json().catch(()=>({})))},async restartOpenCode(){const t=await u(ma,{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}}}),ga=()=>({async requestDirectoryAccess(t){return{success:!0,path:t.path}},async startAccessingDirectory(t){return{success:!0}},async stopAccessingDirectory(t){return{success:!0}}}),wa=1500,Ot=5e3,ba="openchamber-notification-claim:",de=new Map,Sa=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Ta=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("|")},va=t=>{for(const[e,r]of de)t-r>Ot&&de.delete(e)},ka=t=>{const e=Ta(t);if(!e)return!0;const r=Date.now();va(r);const o=de.get(e)??0;if(r-o<Ot)return!1;try{if(typeof window<"u"&&window.localStorage){const n=`${ba}${e}`,i=Number(window.localStorage.getItem(n)??"0");if(Number.isFinite(i)&&r-i<Ot)return de.set(e,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(n),window.localStorage.setItem(n,String(r))}}catch{}return de.set(e,r),!0},Co=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),wa)})])??t}catch{return t}},Ea=async t=>{const e=await Co();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}},Da=async()=>{const t=await Co();if(!t||!("pushManager"in t)||!t.pushManager)return!1;try{return!!await t.pushManager.getSubscription()}catch{return!1}},Ma=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(!Sa()&&await Da()||!ka(t))return!0;try{return await Ea(t)||new Notification(t?.title??"OpenChamber",{body:t?.body,tag:t?.tag}),!0}catch(e){return console.warn("Failed to send notification",e),!1}},Pa=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}},Aa=()=>({async notifyAgentCompletion(t){return await Pa(t)||await Ma(t)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),Ca=()=>({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()}}),Pe=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}},Oa=()=>({async getVapidPublicKey(){return Pe("/api/push/vapid-public-key")},async subscribe(t){return Pe("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async unsubscribe(t){return Pe("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async setVisibility(t){return Pe("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})}}),k=async t=>await t.json().catch(()=>null),Ia=({urls:t})=>({async authStatus(){const e=await u("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(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 k(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issue comments");return s}}),Ae=async t=>await t.json().catch(()=>null),Ra=()=>({async listClients(){const t=await u("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),e=await Ae(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 Ae(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 Ae(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 Ae(t);if(!t.ok||!e)throw new Error(e?.error||t.statusText||"Failed to clear revoked clients");return e}}),Fa=()=>({api:(...t)=>P().api(...t),authenticatedAsset:(...t)=>P().authenticatedAsset(...t),auth:(...t)=>P().auth(...t),health:(...t)=>P().health(...t),rawFile:(...t)=>P().rawFile(...t),sse:(...t)=>P().sse(...t),websocket:(...t)=>P().websocket(...t)}),_a=(t={})=>{const e=t.urls??_t();Vo(e);const r=Fa();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:as(),git:fa(),files:ha({getDirectory:()=>At.getState().currentDirectory}),settings:ya(),permissions:ga(),notifications:Aa(),github:Ia({urls:r}),push:Oa(),clientAuth:Ra(),tools:Ca()}},xa=(t,e)=>{if(!t||!e)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}},Hc=()=>{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=Lr({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return sn({apiBaseUrl:t,runtimeKey:xa(t,r)?"local":null}),Ir(e||null),It(t||void 0).catch(()=>{}),nn(),_a({urls:o})};export{Ha as $,is as A,se as B,Ja as C,Q as D,hc as E,mc as F,Ri as G,sc as H,Na as I,La as J,Ka as K,an as L,nc as M,oc as N,Pc as O,Ac as P,Mc as Q,Yn as R,R as S,cc as T,un as U,dn as V,Ba as W,Dc as X,pc as Y,Rc as Z,qe as _,jt as a,Qs as a$,za as a0,hn as a1,tc as a2,Za as a3,ec as a4,Wr as a5,Ua as a6,ai as a7,oi as a8,fc as a9,ta as aA,sa as aB,ia as aC,xs as aD,Us as aE,Os as aF,Gs as aG,Tr as aH,ks as aI,qs as aJ,vr as aK,Es as aL,Uc as aM,Ns as aN,Nc as aO,zs as aP,la as aQ,Ks as aR,vs as aS,jc as aT,ps as aU,hs as aV,$s as aW,Hs as aX,fs as aY,Lc as aZ,Bc as a_,Un as aa,$n as ab,Bn as ac,Gn as ad,ii as ae,Je as af,Ga as ag,rc as ah,Wa as ai,Va as aj,Ya as ak,Xa as al,xn as am,Fi as an,lc as ao,As as ap,go as aq,Vr as ar,We as as,na as at,Xs as au,js as av,ua as aw,us as ax,Ls as ay,ea as az,N as b,Sr as b0,br as b1,Fs as b2,Rs as b3,Is as b4,Vs as b5,Ts as b6,_s as b7,Zs as b8,Ao as b9,nt as bA,yc as bB,wc as bC,vc as bD,bc as bE,gc as bF,Sc as bG,yo as bH,Tc as bI,Cc as bJ,Oc as bK,Qa as bL,Ic as bM,Hn as bN,zn as bO,Fc as bP,Cs as ba,Ys as bb,Ds as bc,Bs as bd,oa as be,_c as bf,xc as bg,ra as bh,ms as bi,Ss as bj,Js as bk,ys as bl,Do as bm,ws as bn,aa as bo,Po as bp,ca as bq,gs as br,Mo as bs,bs as bt,Ws as bu,da as bv,A as bw,uc as bx,Ln as by,Te as bz,Hc as c,$a as d,u as e,U as f,P as g,Kr as h,Ec as i,I as j,ac as k,ic as l,mn as m,dc as n,H as o,os as p,Ke as q,It as r,kc as s,es as t,At as u,qr as v,Ve as w,O as x,Rr as y,qa as z};
|