@openchamber/web 1.13.1 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/assets/{DiagramView-la2P5DUr.js → DiagramView-l49NCoWI.js} +1 -1
  2. package/dist/assets/MarkdownRendererImpl-BspFAgXe.js +7 -0
  3. package/dist/assets/{MultiRunWindow-B9NPliTC.js → MultiRunWindow-BP1L8slG.js} +1 -1
  4. package/dist/assets/{NewWorktreeDialog-BnK_0_OO.js → NewWorktreeDialog-B2o615D_.js} +1 -1
  5. package/dist/assets/OnboardingScreen-DNQQWFmn.js +1 -0
  6. package/dist/assets/{SessionSwitcherDropdown-CuRsG7FM.js → SessionSwitcherDropdown-Bz03hrU9.js} +1 -1
  7. package/dist/assets/{SettingsWindow-Cs3xbqtf.js → SettingsWindow-L-jJDG3k.js} +1 -1
  8. package/dist/assets/{TerminalView-CLKpaKdm.js → TerminalView-CZYwjWYc.js} +1 -1
  9. package/dist/assets/index-Di3CDurc.css +1 -0
  10. package/dist/assets/index-DkRLSXEX.js +3 -0
  11. package/dist/assets/{main-B2rXVG8L.js → main-DmS7A2g8.js} +2 -2
  12. package/dist/assets/main-gqEqIL1b.js +214 -0
  13. package/dist/assets/miniChat-DZORfsku.js +2 -0
  14. package/dist/assets/mobile-DkitItmP.js +2 -0
  15. package/dist/assets/{renderElectronMiniChatApp-BLM-RCP0.js → renderElectronMiniChatApp-S7GCIhbH.js} +2 -2
  16. package/dist/assets/{renderMobileApp-BXScr4up.js → renderMobileApp-CxEnmaQL.js} +3 -3
  17. package/dist/assets/{useAppFontEffects-ByW8wOJM.js → useAppFontEffects-DkrfZHQv.js} +114 -114
  18. package/dist/assets/vendor--Dwc_TRgJ.css +1 -0
  19. package/dist/assets/{vendor-.bun-d5B0wgQr.js → vendor-.bun-CIlawBoH.js} +1 -1
  20. package/dist/index.html +5 -5
  21. package/dist/mini-chat.html +5 -5
  22. package/dist/mobile.html +5 -5
  23. package/package.json +1 -1
  24. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  25. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  26. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  27. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  28. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  29. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  30. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  31. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  32. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  33. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  34. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  35. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  36. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  37. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  38. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  39. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  40. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  41. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  42. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  43. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  44. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  45. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  46. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  47. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  48. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  49. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  50. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  51. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  52. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  53. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  54. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  55. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  56. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  57. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  58. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  59. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  60. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  61. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  62. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  63. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  64. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  65. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  66. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  67. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  68. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  69. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  70. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  71. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  72. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  73. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  74. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  75. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  76. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  77. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  78. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  79. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  80. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  81. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  82. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  83. package/dist/assets/MarkdownRendererImpl-CkGSBGo5.js +0 -8
  84. package/dist/assets/OnboardingScreen-laLzQZgy.js +0 -1
  85. package/dist/assets/index-68ujKCUc.js +0 -3
  86. package/dist/assets/index-C-aQ_xRH.css +0 -1
  87. package/dist/assets/main-CuEzPtRt.js +0 -214
  88. package/dist/assets/miniChat-DVXSR0vu.js +0 -2
  89. package/dist/assets/mobile-BgYrNCOf.js +0 -2
  90. package/dist/assets/vendor--V65Sl9C2.css +0 -1
@@ -1,3 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-d5B0wgQr.js","assets/vendor--V65Sl9C2.css"])))=>i.map(i=>d[i]);
2
- import{_ as fo,c as po,a as xe,d as je,p as fr,b as pr,e as hr,R as Me}from"./vendor-.bun-d5B0wgQr.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 mr=()=>null,yr="",Y="",gt=0,z=null,ke=0;const ho=1e4,Ne=t=>typeof t!="string"?"":t.trim(),mo=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_CLIENT_TOKEN__;return Ne(t)},yo=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},go=(t,e)=>{const r=typeof t=="string"&&t.trim()?t.trim():yo();if(!r)return e;try{return new URL(e,`${r.replace(/\/+$/,"")}/`).toString()}catch{return e}},Le=()=>{Y="",gt=0},wo=()=>{ke+=1,z=null,Le()},gr=t=>{const e=Ne(t);yr=e,wo(),mr=()=>e?{type:"bearer",token:e}:null},wr=()=>yr||mo(),bo=(t,e)=>{const r=Ne(t);if(!r||typeof e!="number"||!Number.isFinite(e)){Le();return}Y=r,gt=e},br=()=>!Y||gt<=Date.now()+ho?(Le(),""):Y,So=()=>{const t=br();return!t&&(wr()||typeof window<"u")&&wt().catch(()=>{}),t},Sr=async()=>{const t=await mr(),e=t?.type==="bearer"?Ne(t.token):wr();return e?{type:"bearer",token:e}:null},wt=async t=>{const e=br();if(e)return e;if(z)return z;const r=ke,n=(async()=>{const i=await Sr(),s=new Headers;i?.type==="bearer"&&s.set("Authorization",`Bearer ${i.token}`);const a=await fetch(go(t,"/auth/url-token"),{method:"POST",headers:s,credentials:"include"});if(!a.ok)throw r===ke&&Le(),new Error(`Failed to mint runtime URL auth token (${a.status})`);const c=await a.json().catch(()=>null),d=typeof c?.token=="string"?c.token.trim():"",l=typeof c?.expiresAt=="number"?c.expiresAt:0;if(r!==ke)throw new Error("Runtime URL auth token response is stale");if(bo(d,l),!Y)throw new Error("Runtime URL auth token response was invalid");return Y})().finally(()=>{z===n&&(z=null)});return z=n,z},To=async t=>{const e=new Headers(t);if(e.has("Authorization"))return e;const r=await Sr();return r?.type==="bearer"&&e.set("Authorization",`Bearer ${r.token}`),e},bt=/^[a-z][a-z\d+.-]*:\/\//i,vo=t=>{const e=t.trim();return e?e.startsWith("/")?e:`/${e}`:"/"},rt=t=>typeof t!="string"?"":t.trim().replace(/\/+$/,""),ko=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return rt(t)},Do=t=>{const e=t.currentHref?.();return e||(typeof window<"u"?window.location.href||window.location.origin:"")},ot=(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))},Eo=(t,e)=>{if(!e)return t;const r=new URLSearchParams;ot({searchParams:r},e);const o=r.toString();return o?t.includes("?")?`${t}&${o}`:`${t}?${o}`:t},Ot=(t,e,r)=>{if(bt.test(e)){const i=new URL(e);return ot(i,r),i.toString()}const o=vo(e);if(!t)return Eo(o,r);const n=new URL(o,`${t}/`);return ot(n,r),n.toString()},$e=t=>{const e=So();if(!e)return t;if(bt.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)}`},Po=(t,e)=>{const r=bt.test(t)?new URL(t):new URL(t,Do(e));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},St=(t={})=>{const e=rt(t.apiBaseUrl),r=rt(t.realtimeBaseUrl),o=()=>e||ko(),n=()=>r||o(),i=(a,c)=>Ot(o(),a,c),s=(a,c)=>Ot(n(),a,c);return{api:i,authenticatedAsset:(a,c)=>$e(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)=>$e(s(a,c)),websocket:(a,c)=>Po($e(s(a,c)),t)}};let Ae=St();const D=()=>Ae,Mo=t=>{Ae=t},Tr=t=>(Ae=St(t),Ae),ae=t=>t.startsWith("/api/")||t==="/api"||t.startsWith("/auth/")||t==="/auth"||t==="/health",Ao=()=>typeof window>"u"?"":window.location.origin||"",vr=t=>{if(typeof window>"u")return!1;const e=Ao();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}},kr=t=>/^[a-z][a-z\d+.-]*:\/\//i.test(t),Co=(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))},De=t=>{try{const e=D().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;const r=new URL(e);return t.origin!==r.origin?!1:ae(t.pathname)}catch{return!1}},Ge=t=>{if(ae(t))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;try{const e=new URL(t);return vr(e)&&ae(e.pathname)}catch{return!1}},Oo=(t,e)=>{try{const r=new URL(t);if(!vr(r))return t;const o=W(`${r.pathname}${r.search}`,e);return!kr(o)&&(r.protocol==="http:"||r.protocol==="https:")?(Co(r,e),r.toString()):r.hash?`${o}${r.hash}`:o}catch{return t}},W=(t,e)=>t==="/health"?D().health(e):t.startsWith("/auth/")||t==="/auth"?D().auth(t,e):ae(t)?D().api(t,e):/^[a-z][a-z\d+.-]*:\/\//i.test(t)?Oo(t,e):t,Io=t=>{const e=t instanceof Request?t.url:t.toString();if(!kr(e))return ae(e);try{return De(new URL(e))}catch{return!1}},$=async(t,e,r=!0)=>{const o=new Headers(t);return e&&new Headers(e).forEach((n,i)=>o.set(i,n)),r?To(o):o},Ro=(t,e)=>{if(typeof t=="string")return W(t,e);if(t instanceof URL)return W(t.toString(),e);const r=W(t.url,e);return r===t.url?t:new Request(r,t)},Fo=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,pe=new Map,_o=(t,e,r)=>r||t!=="GET"||e.includes("/event")||!Fo.test(e)?null:`GET ${e}`,u=async(t,e={})=>{const{query:r,...o}=e,n=Ro(t,r),i=n instanceof Request?n.headers:void 0,s=await $(i,o.headers,Io(n)),a=()=>n instanceof Request?fetch(new Request(n,{...o,headers:s})):fetch(n,{...o,headers:s}),c=n instanceof Request?n.url:n instanceof URL?n.toString():String(n),d=String(o.method??(n instanceof Request?n.method:"GET")).toUpperCase(),l=o.signal!=null||n instanceof Request,f=_o(d,c,l);if(!f)return a();const y=pe.get(f);if(y)return y.then(w=>w.clone());const m=a();return pe.set(f,m),m.then(()=>pe.delete(f),()=>pe.delete(f)),m.then(w=>w.clone())};let It=!1;const xo=()=>{if(It||typeof window>"u")return;It=!0;const t=window.fetch.bind(window);window.fetch=async(e,r)=>{if(typeof e=="string"){if(!Ge(e)){try{const n=new URL(e);if(De(n)){const i=await $(void 0,r?.headers);return t(e,{...r,headers:i})}}catch{}return t(e,r)}const o=await $(void 0,r?.headers);return t(W(e),{...r,headers:o})}if(e instanceof URL){const o=e.toString();if(!Ge(o)){if(De(e)){const i=await $(void 0,r?.headers);return t(e,{...r,headers:i})}return t(e,r)}const n=await $(void 0,r?.headers);return t(W(o),{...r,headers:n})}if(e instanceof Request){if(!Ge(e.url)){try{const s=new URL(e.url);if(De(s)){const a=await $(e.headers,r?.headers);return t(new Request(e,{...r,headers:a}))}}catch{}return t(e,r)}const o=await $(e.headers,r?.headers),n=W(e.url),i=n===e.url?e:new Request(n,e);return t(new Request(i,{...r,headers:o}))}return t(e,r)}},nt="openchamber:runtime-endpoint-changed";let Ce="",ce="";const Tt=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"}`}},Dr=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_API_BASE_URL__;return typeof t=="string"?t.trim():""},Er=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof t=="string"?t.trim():""},Pr=(t,e)=>{if(!t||!e)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}},vt=()=>Ce||Dr(),Be=()=>{if(ce)return ce;const t=vt();return Pr(t,Er())?"local":Tt(t)},jo=(t={})=>{if(Ce||ce)return;const e=t.apiBaseUrl?.trim()||Dr();e&&(Ce=e,ce=t.runtimeKey?.trim()||(Pr(e,Er())?"local":Tt(e)))},da=t=>{const e=t.apiBaseUrl.trim(),r=vt(),o=Be(),n=t.runtimeKey?.trim()||Tt(e);if(Ce=e,ce=n,typeof window<"u"){const i=window;i.__OPENCHAMBER_API_BASE_URL__=e,i.__OPENCHAMBER_CLIENT_TOKEN__=t.clientToken||void 0}Tr({apiBaseUrl:e,realtimeBaseUrl:e}),gr(t.clientToken||null),wt(e).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(nt,{detail:{apiBaseUrl:e,previousApiBaseUrl:r,runtimeKey:n,previousRuntimeKey:o}}))},No=t=>{if(typeof window>"u")return()=>{};const e=r=>{t(r.detail)};return window.addEventListener(nt,e),()=>window.removeEventListener(nt,e)},Lo=["local","remote",null],Bo=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Mr(t){if(!t||typeof t!="object")return{valid:!1};const e=t,r=e.target,o=e.status;if(r!==null&&(typeof r!="string"||!Lo.includes(r)))return{valid:!1};if(typeof o!="string"||!Bo.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 ua(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 fa(t){return t.isDesktopShell?t.bootOutcomeKnown?t.bootViewIsMain===!1?!0:t.isInitialized:!1:t.isInitialized}function pa(t){return t.isDesktopShell&&!t.isDesktopLocalOriginActive}function Uo(){if(Ho()!=="valid")return null;const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,r=Mr(e);return r.valid?r.outcome:null}function Ho(){if(typeof window>"u")return"not-injected";const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return t==null?"not-injected":Mr(t).valid?"valid":"malformed"}let it=null;const ha=t=>{it=t},Ue=()=>it||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),zo=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,ee=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,Ar=()=>zo()?.runtime==="electron",E=()=>typeof ee()?.invoke=="function",Cr=()=>Ar()&&E(),C=async(t,e)=>{const r=ee();return typeof r?.invoke!="function"?null:r.invoke(t,e??{})},ma=async()=>{if(!Cr()||!I())return null;try{const t=await C("desktop_get_launch_at_login");return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to get launch at login status",t),null}},ya=async t=>{if(!Cr()||!I())return null;try{const e=await C("desktop_set_launch_at_login",{enabled:t});return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to set launch at login status",e),null}},Rt=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}}},We=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}}},$o=t=>t.replace(/^\[|\]$/g,"").toLowerCase(),te=t=>{const e=$o(t);return e==="localhost"||e==="127.0.0.1"||e==="::1"},I=()=>{if(typeof window>"u"||!Or())return!1;if(Be()==="local")return!0;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=We(t),r=We(vt());if(!r&&e&&Uo()?.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&&te(e.hostname)&&te(r.hostname)}const o=We(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&&te(e.hostname)&&te(o.hostname)}const n=Rt(t),i=Rt(window.location.origin)||window.location.origin;return n&&i&&n===i?!0:!!(o&&te(o.hostname))},Or=()=>typeof window>"u"?!1:Ar(),ga=async()=>{if(!Or())return!1;try{return await C("desktop_start_window_drag"),!0}catch{return!1}},He=()=>Ue()?.runtime?.isVSCode===!0,wa=()=>{const e=Ue()?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!He()},Ir=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},ba=async t=>{if(E()&&I())try{const e=await ee()?.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}},Rr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Sa=async t=>{if(E()&&I())try{const e=await ee()?.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(!Rr(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"}},Ta=async t=>{const e=typeof t=="string"?t.trim():"";if(!e)return{success:!1,error:"Path is required"};if(!E()||!I())return{success:!1,error:"Native file access not available"};try{const r=await ee()?.grantFileAccess?.(e);if(!Rr(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)}}},va=async t=>({success:!0}),ka=async t=>({success:!0}),Da=async()=>{if(!E())return null;try{return await C("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates",t),null}},Ea=async t=>{if(!E())return!1;const e=ee();let r=null,o=0,n;try{return typeof t=="function"&&e?.listen&&(r=await e.listen("openchamber:update-progress",i=>{const s=i?.payload;if(!s||typeof s!="object")return;const a=s,c=typeof a.event=="string"?a.event:null,d=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){o=0,n=typeof d?.contentLength=="number"?d.contentLength:void 0,t({downloaded:o,total:n});return}if(c==="Progress"){const l=d?.downloaded,f=d?.total;typeof l=="number"&&(o=l),typeof f=="number"&&(n=f),t({downloaded:o,total:n});return}c==="Finished"&&t({downloaded:o,total:n})})),await C("desktop_download_and_install_update"),!0}catch(i){return console.warn("Failed to download update",i),!1}finally{if(r)try{const i=r();i instanceof Promise&&await i}catch{}}},Pa=async()=>E()?Go():!1,Go=async()=>{if(!E())return!1;try{return await C("desktop_restart"),!0}catch(t){return console.warn("Failed to restart desktop app",t),!1}},Ma=async()=>{if(!E()||!I())return null;try{const t=await C("desktop_get_lan_address");return typeof t=="string"&&t.trim().length>0?t.trim():null}catch(t){return console.warn("Failed to get desktop LAN address",t),null}},Wo=async(t,e)=>{if(!E()||!I())return!1;const r=t?.trim();if(!r)return!1;try{return await C("desktop_open_path",{path:r,app:typeof e=="string"&&e.trim().length>0?e.trim():void 0}),!0}catch(o){return console.warn("Failed to open path",o),!1}},Aa=async t=>{if(!E()||!I())return!1;const e=t?.trim();if(!e)return!1;try{return await C("desktop_reveal_path",{path:e}),!0}catch{return Wo(e)}},Ca=async(t,e)=>{if(!E()||!I())return null;const r=t?.trim();if(!r)return null;try{const o=await C("desktop_save_markdown_file",{defaultFileName:r,content:e});return typeof o=="string"&&o.trim().length>0?o:null}catch(o){return console.warn("Failed to save markdown file",o),null}},Oa=async(t,e,r)=>{if(!E()||!I())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await C("desktop_open_in_app",{projectPath:o,appId:n,appName:i}),!0}catch(s){return console.warn("Failed to open project in app",s),!1}},Ia=async(t,e,r)=>{if(!E()||!I())return!1;const o=t?.trim(),n=e?.trim(),i=r?.trim();if(!o||!n||!i)return!1;try{return await C("desktop_open_file_in_app",{filePath:o,appId:n,appName:i}),!0}catch(s){return console.warn("Failed to open file in app",s),!1}},Ra=async(t,e)=>{if(!E()||!I())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const r=Array.isArray(t)?t.filter(o=>typeof o=="string"):[];if(r.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await C("desktop_get_installed_apps",{apps:r,force:e===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=o;return Array.isArray(n.apps)?{apps:n.apps.filter(s=>s&&typeof s=="object").map(s=>{const a=s;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(s=>s.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(o){return console.warn("Failed to fetch installed apps",o),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Ft=500,Fr=()=>{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}},Fa=()=>Fr(),G=(t,e)=>{if(!Fr())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>Ft&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Ft)},qo=()=>{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__=qo);const _a=async(t,e,r)=>{const o=typeof performance<"u"?performance.now():Date.now();G(`${t}:start`,r);try{const n=await e(),i=typeof performance<"u"?performance.now():Date.now();return G(`${t}:end`,{durationMs:Math.round(i-o)}),n}catch(n){const i=typeof performance<"u"?performance.now():Date.now();throw G(`${t}:error`,{durationMs:Math.round(i-o),error:n instanceof Error?n.message:String(n)}),n}},Ko=3,Vo=3e4,Jo=1e3,_r=32e3,Qo=3,Yo=3600*1e3,Xo=600*1e3,xr=new Set([429,502,503,504]),X=new Map;function Zo(){const t=Date.now();for(const[e,r]of X)r.consecutiveErrors===0&&t-r.lastErrorAt>Yo&&X.delete(e)}typeof setInterval<"u"&&setInterval(Zo,Xo).unref?.();function en(t){let e=X.get(t);return e||(e={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Vo},X.set(t,e)),e}function tn(t){if(!t)return;const e=X.get(t);e&&(e.consecutiveErrors=0,e.lastErrorAt=0)}function _t(t,e){if(!t)return;const r=en(t);r.consecutiveErrors+=1,r.lastErrorAt=Date.now(),rn(e)&&r.consecutiveErrors>=Ko&&(r.circuitOpen=!0,r.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${t} after ${r.consecutiveErrors} consecutive errors`))}function rn(t){return t!==void 0&&xr.has(t)}function jr(t){const e=X.get(t);return e?.circuitOpen?Date.now()-e.circuitOpenAt>=e.circuitCooldownMs?(e.circuitOpen=!1,e.consecutiveErrors=0,e.circuitCooldownMs=Math.min(e.circuitCooldownMs*2,_r*4),!1):!0:!1}function on(t,e,r){return!(!xr.has(e)||r>=Qo-1||jr(t))}function nn(t){if(!(!t||!jr(t)))throw new Error(`Provider ${t} is temporarily unavailable after repeated errors. Please retry shortly.`)}function xt(t){const e=Jo*2**t;return Math.min(e,_r)}const jt="/api";function ie(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function P(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${ie(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 K(t,e){if(t.error){const r=t.response?.status,o=new Error(`${e} failed${r?` (${r})`:""}: ${ie(t.error)}`);throw r!==void 0&&(o.status=r),o}return t.data}const sn=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Nt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",an=14;let Lt=0,qe=0;const cn=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+=Nt[e[o]%Nt.length];return r},Bt=t=>{const e=Date.now();e!==Lt&&(Lt=e,qe=0),qe+=1;const r=BigInt(e)*BigInt(4096)+BigInt(qe),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}${cn(an)}`},ln=t=>t instanceof DOMException&&t.name==="AbortError"||t instanceof TypeError,Ut=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(sn.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}},Ht=()=>{try{return D().api("/api")}catch{return null}},Ke=t=>po({...t,fetch:u}),V=t=>t.replace(/\\/g,"/"),zt=400,$t=()=>{const t=Ue();return t&&t.runtime?.isDesktop&&t.files?t.files:null};class dn{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;listDirectoryCache=new Map;constructor(e=jt){const o=Ht()||e;this.baseUrl=Ut(o),this.client=Ke({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const e=Ht(),r=Ut(e||jt);r!==this.baseUrl&&(this.baseUrl=r,this.client=Ke({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),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=Ke({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&&G("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:r??null}),this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(e,r){const o=async()=>{if(e==null)return r();const i=this.currentDirectory,s=this.normalizeCandidatePath(e)??e;this.currentDirectory=s;try{return await r()}finally{this.currentDirectory===s&&(this.currentDirectory=i)}},n=this.directoryContextQueue.then(o,o);return this.directoryContextQueue=n.then(()=>{},()=>{}),n}getApiClient(){return this.client}async getSystemInfo(){const e=new Set,r=n=>{const i=this.normalizeCandidatePath(n);i&&e.add(i)};try{const i=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;i&&(r(i.directory),r(i.worktree),r(i.state))}catch(n){console.debug("Failed to load path info:",n)}if(!e.size)try{const n=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);r(n.data?.worktree)}catch(n){console.debug("Failed to load project info:",n)}if(!e.size)try{(await this.listSessions()).forEach(i=>r(i.directory))}catch(n){console.debug("Failed to inspect sessions for system info:",n)}if(r(this.currentDirectory),typeof window<"u")try{r(window.localStorage.getItem("lastDirectory")),r(window.localStorage.getItem("homeDirectory"))}catch{}if(!e.size&&typeof process<"u"&&typeof process.cwd=="function"&&r(process.cwd()),!e.size)return{homeDirectory:"/",username:void 0};const[o]=Array.from(e);return this.deriveHomeDirectory(o)}async probeDirectory(e){const r=this.normalizeCandidatePath(e);if(!r)return!1;try{const n=(await this.client.path.get({directory:r})).data,i=typeof n?.directory=="string"?n.directory:null;return!!(i&&i.trim().length>0)}catch{return!1}}async listSessions(){const e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data:[]}async createSession(e,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,n=await this.client.session.create({...o?{directory:o}:{},parentID:e?.parentID,title:e?.title,metadata:e?.metadata});return P(n,"session.create")}async getSession(e,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,n=await this.client.session.get({sessionID:e,...o?{directory:o}:{}});return P(n,"session.get")}async deleteSession(e,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,n=await this.client.session.delete({sessionID:e,...o?{directory:o}:{}});return K(n,"session.delete")===!0}async updateSession(e,r,o){const n=this.normalizeCandidatePath(o)??this.currentDirectory,i={...r.title!==void 0?{title:r.title}:{},...r.metadata!==void 0?{metadata:r.metadata}:{},...r.time?.archived!==void 0&&r.time.archived!==null?{time:{archived:r.time.archived}}:{}},s=await this.client.session.update({sessionID:e,...n?{directory:n}:{},...i});return P(s,"session.update")}async getSessionMessages(e,r){const o=await this.client.session.messages({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof r=="number"?{limit:r}:{}});return P(o,"session.messages")}async getSessionTodos(e){try{const r=await this.client.session.todo({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(r.error)return[];const o=r.data;return!o||!Array.isArray(o)?[]:o}catch{return[]}}shouldNormalizeToTextPlain(e){if(!e)return!1;const r=e.toLowerCase();return r.startsWith("text/")&&r!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(r)}isHeicMime(e){if(!e)return!1;const r=e.toLowerCase();return r==="image/heic"||r==="image/heif"}async convertHeicToJpeg(e){try{const r=(await fo(async()=>{const{default:f}=await import("./vendor-.bun-d5B0wgQr.js").then(y=>y.h);return{default:f}},__vite__mapDeps([0,1]))).default,o=e.url.indexOf(",");if(o===-1)return e;const n=e.url.substring(o+1),i=atob(n),s=new Uint8Array(i.length);for(let f=0;f<i.length;f++)s[f]=i.charCodeAt(f);const a=new Blob([s],{type:e.mime}),c=await r({blob:a,toType:"image/jpeg",quality:.9}),d=await new Promise((f,y)=>{const m=new FileReader;m.onload=()=>f(m.result),m.onerror=y,m.readAsDataURL(c)});let l=e.filename;return l&&(l=l.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:l,url:d}}catch(r){return console.warn("Failed to convert HEIC to JPEG:",r),e}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let r=e.url;if(e.url.startsWith("data:")){const o=e.url.indexOf(",");if(o!==-1){const n=e.url.substring(5,o),i=e.url.substring(o);r=`data:${n.replace(/^[^;,]+/,"text/plain")}${i}`}}return{mime:"text/plain",filename:e.filename,url:r}}async toNormalizedFilePartInput(e){const r=await this.normalizeFilePart(e);return{...e.id?{id:e.id}:{},type:"file",mime:r.mime,filename:r.filename,url:r.url}}async sendMessage(e){const r=e.messageId??Bt("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}),nn(e.providerID);let i;for(let s=0;s<3;s++){try{const l=await this.client.session.promptAsync({sessionID:e.id,...n?{directory:n}:{},model:{providerID:e.providerID,modelID:e.modelID},agent:e.agent,variant:e.variant,messageID:r,...e.format?{format:e.format}:{},parts:o});if(l.response instanceof Response)i=l.response;else if(l.error){const f=l.response?.status||500;i=new Response(JSON.stringify(l.error),{status:f})}else i=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){if(s<2&&ln(l)){const f=xt(s);console.warn(`[prompt] fetch failed for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${f}ms`,l?.message),await new Promise(y=>setTimeout(y,f));continue}throw _t(e.providerID),l}if(i.ok)return tn(e.providerID),r;if(on(e.providerID,i.status,s)){const l=xt(s);console.warn(`[prompt] ${i.status} for ${e.providerID}/${e.modelID} (attempt ${s+1}/3), retrying in ${l}ms`),await new Promise(f=>setTimeout(f,l));continue}let a="";try{a=await i.text()}catch{}const c=a&&a.trim().length>0?`: ${a.trim()}`:"",d=new Error(`Failed to send message (${i.status})${c}`);throw _t(e.providerID,i.status),d}throw new Error("Failed to send message after retries")}async sendCommand(e){const r=e.messageId??Bt("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 K(i,"session.command"),r}async abortSession(e){return!!(await this.client.session.abort({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(e){const r=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,o=await this.client.session.shell({sessionID:e.sessionId,...r?{directory:r}:{},messageID:e.messageId,agent:e.agent,model:e.model,command:e.command});return P(o,"session.shell")}async revertSession(e,r,o,n){const i=this.normalizeCandidatePath(n)??this.currentDirectory,s=await this.client.session.revert({sessionID:e,...i?{directory:i}:{},messageID:r,partID:o});return P(s,"session.revert")}async summarizeSession(e,r,o,n){const i=this.normalizeCandidatePath(n)??this.currentDirectory,s=await this.client.session.summarize({sessionID:e,...i?{directory:i}:{},providerID:r,modelID:o});return K(s,"session.summarize")===!0}async unrevertSession(e){const r=await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return P(r,"session.unrevert")}async forkSession(e,r,o){const n=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.fork({sessionID:e,...n?{directory:n}:{},messageID:r});return P(i,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e){try{const r=typeof e=="string"?e.trim():"",o=await this.client.session.status(r?{directory:r}:void 0);return o.error||!o.data||typeof o.data!="object"?null:o.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const e=await u("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const r=await e.json().catch(()=>null);return!r||typeof r!="object"?null:r}catch{return null}}async listToolIds(e){try{const r=typeof e?.directory=="string"?e.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(r?{directory:r}:void 0)).data||[]).filter(i=>typeof i=="string"&&i!=="invalid")}catch{return[]}}async replyToPermission(e,r,o){const n=this.normalizeCandidatePath(o?.directory??null)??this.currentDirectory,i=await this.client.permission.reply({requestID:e,...n?{directory:n}:{},reply:r,...o?.message?{message:o.message}:{}});return K(i,"permission.reply")===!0}async listPendingPermissions(e){const r=[],o=async c=>{const d=typeof c=="string"?c.trim():"",l=await this.client.permission.list(d?{directory:d}:void 0);if(l.error)throw new Error(`permission.list failed: ${ie(l.error)}`);return l.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&n.add(d)}for(const c of n)r.push(o(c));const i=await Promise.all(r),s=[],a=new Set;for(const c of i)for(const d of c){if(!d||typeof d!="object")continue;const l=d.id;typeof l!="string"||l.length===0||a.has(l)||(a.add(l),s.push(d))}return s}async replyToQuestion(e,r,o){const n=!Array.isArray(r)||r.length===0?[]:Array.isArray(r[0])?r:[r],i=this.normalizeCandidatePath(o)??this.currentDirectory,s=await this.client.question.reply({requestID:e,...i?{directory:i}:{},answers:n});return K(s,"question.reply")===!0}async rejectQuestion(e){const r=await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return K(r,"question.reject")===!0}async listPendingQuestions(e){const r=[],o=async c=>{const d=typeof c=="string"?c.trim():"",l=await this.client.question.list(d?{directory:d}:void 0);if(l.error)throw new Error(`question.list failed: ${ie(l.error)}`);return l.data||[]};r.push(o(null));const n=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&n.add(d)}for(const c of n)r.push(o(c));const i=await Promise.all(r),s=[],a=new Set;for(const c of i)for(const d of c){if(!d||typeof d!="object")continue;const l=d.id;typeof l!="string"||l.length===0||a.has(l)||(a.add(l),s.push(d))}return s}async getConfig(){const e=await this.client.config.get();if(!e.data)throw new Error("Failed to get config");return e.data}async updateConfig(e){const r=await this.client.config.update({config:e});return P(r,"global.config.update")}async updateConfigPartial(e){const r=await this.getConfig(),o=e(r);return await this.updateConfig(o)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(e){const r=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,o=r??"",n=this.configProvidersInFlight.get(o);if(n)return n;const i=(async()=>{const s=await this.client.config.providers(r?{directory:r}:void 0);return P(s,"config.providers")})();this.configProvidersInFlight.set(o,i);try{return await i}finally{this.configProvidersInFlight.delete(o)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(e){const r=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,o=r??"",n=this.listAgentsInFlight.get(o);if(n)return n;const i=(async()=>{const s=r?{directory:r}:void 0,a=await this.client.app.agents(s);if(!a.error&&Array.isArray(a.data)&&a.data.length>0)return a.data;const c=await u("/api/agent",{...r?{query:{directory:r}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${ie(a.error)}`):new Error(`agent.list failed (${c.status})`);const d=await c.json().catch(()=>null);if(!Array.isArray(d))throw new Error("agent.list failed: invalid response");return d})();this.listAgentsInFlight.set(o,i);try{return await i}finally{this.listAgentsInFlight.delete(o)}}async readFile(e){try{const r=await this.client.file.read({path:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(P(r,"file.read"))}catch{return`// Content of ${e}
3
- // This would be loaded from the server`}}async listFiles(e){try{const r=e||this.currentDirectory||"/",o=await this.client.file.list({path:r,...this.currentDirectory?{directory:this.currentDirectory}:{}}),n=P(o,"file.list");return Array.isArray(n)?n:[]}catch{return[]}}async listCommands(){const e=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(P(e,"command.list")||[]).map(o=>({name:o.name,description:o.description,agent:o.agent,model:o.model,source:o.source}))}async listCommandsWithDetails(){const e=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(P(e,"command.list")||[]).map(o=>({name:o.name,description:o.description,agent:o.agent,model:o.model,source:o.source,template:o.template}))}async listSkillsWithDetails(){try{const r=(await this.client.app.skills(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;if(!Array.isArray(r))return[];const o=[];for(const n of r){const i=typeof n.name=="string"?n.name.trim():"",s=typeof n.location=="string"?n.location:"";if(!i||!s)continue;const a={name:i,location:s};typeof n.description=="string"&&(a.description=n.description),typeof n.content=="string"&&(a.content=n.content),o.push(a)}return o}catch{return[]}}async getCommandDetails(e){try{const r=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(r.data){const o=r.data.find(n=>n.name===e);if(o)return{name:o.name,template:o.template,description:o.description,agent:o.agent,model:o.model}}return null}catch{return null}}async checkHealth(){try{const e=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,r=e==="/api"||e.endsWith("/api")?"/api/opencode/health":`${e}/opencode/health`;G("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:r});const o=await u(r);if(G("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const n=await o.json();return G("opencodeClient.checkHealth:result",{healthy:n?.healthy}),n?.healthy===!0}catch{return!1}}async createDirectory(e,r){const o=$t();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"?V(e.trim()):""}|${r?.respectGitignore?"1":"0"}`,i=Date.now(),s=this.listDirectoryCache.get(n);if(s&&s.expiresAt>i)return s.entries;const a=this.listDirectoryInFlight.get(n);if(a)return a;const d=(async()=>{const l=$t();if(l)try{const f=await l.listDirectory(e||"",r);if(!f||!Array.isArray(f.entries))return[];const y=f.entries.map(m=>({name:m.name,path:V(m.path),isDirectory:!!m.isDirectory,isFile:!m.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:y,expiresAt:Date.now()+zt}),y}catch(f){throw console.error("Failed to list directory contents:",f),f}try{const f=new URLSearchParams;e&&e.trim().length>0&&f.set("path",e),r?.respectGitignore&&f.set("respectGitignore","true");const y=f.toString(),m=await u(`${this.baseUrl}/fs/list${y?`?${y}`:""}`);if(!m.ok){const b=await m.json().catch(()=>({})),v=typeof b.error=="string"?b.error:"Failed to list directory";throw new Error(v)}const w=await m.json();if(!w||!Array.isArray(w.entries))return[];const g=w.entries;return this.listDirectoryCache.set(n,{entries:g,expiresAt:Date.now()+zt}),g}catch(f){throw console.error("Failed to list directory contents:",f),f}})().finally(()=>{this.listDirectoryInFlight.get(n)===d&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,d),d}async searchFiles(e,r){const o=typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():this.currentDirectory,n=o?V(o):null,i=o?this.getScopedApiClient(o):this.client;try{const s=await i.find.files({query:e,limit:typeof r?.limit=="number"&&Number.isFinite(r.limit)?r.limit:void 0,dirs:r?.dirs===!1||r?.type==="file"?"false":"true",type:r?.type});return(Array.isArray(s?.data)?s.data:[]).map(c=>{const d=V(c),l=d.split("/").filter(Boolean).pop()||d,f=V(n?`${n}/${d}`:d);return{name:l,path:f,relativePath:d,extension:l.includes(".")?l.split(".").pop()?.toLowerCase():void 0}})}catch(s){throw console.error("Failed to search files:",s),s}}async getFilesystemHome(){const e=Be();if(!e||e==="local"){const r=await Ir();if(r)return r}try{const r=await u(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){const n=await r.json().catch(()=>({})),i=typeof n.error=="string"&&n.error.length>0?n.error:"Failed to resolve home directory";throw new Error(i)}const o=await r.json();return o&&typeof o.home=="string"&&o.home.length>0?o.home:null}catch(r){return console.warn("Failed to resolve filesystem home directory:",r),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!="string"||!e.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",e),null;const r=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",r,"with path:",e);try{const o=await u(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})}),n=await o.json().catch(()=>null);if(!o.ok){const i=n??{},s=typeof i.error=="string"&&i.error.length>0?i.error:"Failed to update OpenCode working directory";throw new Error(s)}return n&&typeof n=="object"?n:{success:!0,restarted:!1,path:e}}catch(o){throw console.warn("Failed to update OpenCode working directory:",o),o}}}const B=new dn,un=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 Ve=null,Je=null;const Nr=t=>{if(typeof window>"u")return null;try{return window[t]??null}catch{return null}},Oe=()=>{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}}},fn=()=>{const t=Nr("localStorage");if(!t)return Oe();const e=Oe();let r=!0;const o=()=>{r=!1};return{getItem:d=>{if(r)try{const l=t.getItem(d);if(l!==null)return l}catch{o()}return e.getItem(d)},setItem:(d,l)=>{if(r)try{t.setItem(d,l),e.removeItem(d);return}catch{o();try{t.removeItem(d)}catch{}}e.setItem(d,l)},removeItem:d=>{try{t.removeItem(d)}catch{o()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:d=>{if(r)try{return t.key(d)}catch{o()}return e.key(d)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},q=()=>(Ve||(Ve=fn()),Ve),pn=()=>{const t=Nr("sessionStorage");if(!t)return Oe();const e=Oe();let r=!0;const o=()=>{r=!1};return{getItem:d=>{if(r)try{const l=t.getItem(d);if(l!==null)return l}catch{o()}return e.getItem(d)},setItem:(d,l)=>{if(r)try{t.setItem(d,l),e.removeItem(d);return}catch{o();try{t.removeItem(d)}catch{}}e.setItem(d,l)},removeItem:d=>{try{t.removeItem(d)}catch{o()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{o()}e.clear()},key:d=>{if(r)try{return t.key(d)}catch{o()}return e.key(d)},get length(){if(r)try{return t.length+e.length}catch{o()}return e.length}}},xa=()=>(Je||(Je=pn()),Je),hn={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},ja={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Gt(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const he={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)"}}},Qe={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...he.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qe.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...he.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qe.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...he.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qe.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...he.tool.inline})},mn=[{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'}],yn=[{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'}],Lr=t=>Object.fromEntries(t.map(e=>[e.id,e])),gn=Lr(mn),wn=Lr(yn),bn="ibm-plex-sans",Sn="ibm-plex-mono",Br=t=>typeof t=="string"&&t in gn,Ur=t=>typeof t=="string"&&t in wn,st="openchamber.mobileKeyboardMode",Tn='meta[name="viewport"]',Wt="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Na=()=>!0;function ze(t,e="resize-content"){return t==="native"||t==="resize-content"?t:e}const vn=t=>ze(t)==="resize-content"?`${Wt}, interactive-widget=resizes-content`:Wt,kn=()=>{if(typeof window>"u")return"resize-content";try{return ze(localStorage.getItem(st))}catch{return"resize-content"}},Hr=t=>{const e=ze(t);if(typeof window<"u")try{e==="resize-content"?localStorage.removeItem(st):localStorage.setItem(st,e)}catch{}return e},La=t=>{const e=Hr(t);if(typeof document>"u")return e;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",e);const r=document.querySelector(Tn);if(r instanceof HTMLMetaElement){const o=vn(e);r.getAttribute("content")!==o&&r.setAttribute("content",o)}return e};function qt(t){return t==="vim"?"vim":"default"}const me={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}"}},L={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},ye=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,Dn=t=>{if(!t||typeof t!="object")return!1;const e=t;return ye(e.completion,me.completion)&&ye(e.error,me.error)&&ye(e.question,me.question)&&ye(e.subtask,me.subtask)},kt=380,En=380,Pn=1400,zr=12,Kt=120,re=280,oe=360,Mn=860,Ye=new Map,Xe=t=>(t??Be()).trim()||"default",k=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),r=e.startsWith("//");let o=e.replace(/\/+$/g,"");return o=o.replace(/\/+/g,"/"),r&&!o.startsWith("//")&&(o=`/${o}`),o===""?e.startsWith("/")?"/":"":o},$r=t=>Number.isFinite(t)?Math.min(Pn,Math.max(En,Math.round(t))):kt,Ie=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.replace(/\\/g,"/"):null},Gr=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.length>Kt?e.slice(0,Kt):e:null},An=(t,e)=>(t==="file"||t==="preview")&&e||t,Wr=(t,e,r)=>{if(t==="diff")return t;if(typeof r=="string"){const o=r.trim();if(o)return o}return An(t,e)},qr=(t,e)=>e===t?t:`${t}:${e}`,Kr=t=>{const e=Ie(t.targetPath),r=Wr(t.mode,e,t.dedupeKey);return{id:qr(t.mode,r),mode:t.mode,targetPath:e,dedupeKey:r,label:Gr(t.label),readOnly:t.readOnly===!0,stagedDiff:t.stagedDiff===!0,touchedAt:Date.now()}},Vr=(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))},Jr=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=Ie(typeof n.targetPath=="string"?n.targetPath:null),s=Wr(n.mode,i,typeof n.dedupeKey=="string"?n.dedupeKey:null),a=qr(n.mode,s);!a||r.has(a)||(r.add(a),e.push({id:a,mode:n.mode,targetPath:i,dedupeKey:s,label:Gr(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},le=(t,e)=>e&&t.some(r=>r.id===e)?e:t.length===0?null:t[t.length-1].id,U=t=>{if(t){const e=Jr(t.tabs),r=le(e,t.activeTabId);return{...t,tabs:e,activeTabId:r,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:kt,touchedAt:Date.now()}},Cn=(t,e)=>{const r=Kr(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=Vr(n,zr,i);return{...t,isOpen:!0,tabs:s,activeTabId:le(s,i),touchedAt:Date.now()}},On=(t,e)=>{const r=t.tabs.filter(n=>n.id!==e),o=t.activeTabId===e?r[r.length-1]?.id??null:le(r,t.activeTabId);return{...t,tabs:r,activeTabId:o,isOpen:r.length>0?t.isOpen:!1,touchedAt:Date.now()}},In=(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},Rn=(t,e,r)=>({...t,tabs:t.tabs.map(o=>o.id===e?{...o,targetPath:r}:o)}),Ze=t=>{if(!t||typeof t!="object")return{};const e=t,r={};for(const[o,n]of Object.entries(e)){const i=k(o);if(!i||!n||typeof n!="object")continue;const s=n;let a=Jr(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=[Kr({mode:s.mode,targetPath:typeof s.targetPath=="string"?s.targetPath:null,dedupeKey:typeof s.dedupeKey=="string"?s.dedupeKey:null,label:typeof s.label=="string"?s.label:null})],c=a[0]?.id??null);const d=le(a,c),l=Vr(a,zr,d);r[i]={isOpen:s.isOpen===!0,expanded:s.expanded===!0,tabs:l,activeTabId:le(l,d),width:$r(typeof s.width=="number"?s.width:kt),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}}return r},H=(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},Q=xe()(je(fr((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:re,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:oe,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:bn,monoFont:Sn,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:kn(),favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...L.completion},error:{...L.error},question:{...L.question},subtask:{...L.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:re}:{isSidebarOpen:o}})},setSidebarOpen:r=>{t(o=>o.isSidebarOpen===r?r&&!o.hasManuallyResizedLeftSidebar&&o.sidebarWidth!==re?{isSidebarOpen:r,sidebarWidth:re}:o:r&&!o.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:re}:{isSidebarOpen:r})},setSidebarWidth:r=>{t({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(r=>{const o=!r.isRightSidebarOpen;return o&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:o,rightSidebarWidth:oe}:{isRightSidebarOpen:o}})},setRightSidebarOpen:r=>{t(o=>{if(o.isRightSidebarOpen===r)return o;const n=r&&!o.hasManuallyResizedRightSidebar&&o.rightSidebarWidth!==oe;return{isRightSidebarOpen:r,rightSidebarWidth:n?oe:o.rightSidebarWidth}})},setRightSidebarWidth:r=>{const o=Math.min(Mn,Math.max(oe,r));t({rightSidebarWidth:o,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:r=>{t({rightSidebarTab:r})},openContextPanelTab:(r,o)=>{const n=k((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=U(s),c={...i.contextPanelByDirectory,[n]:Cn(a,o)};return{contextPanelByDirectory:H(c,20)}})},openContextDiff:(r,o,n=!1)=>{const i=k((r||"").trim()),s=(o||"").trim();!i||!s||e().openContextPanelTab(i,{mode:"diff",targetPath:s,stagedDiff:n})},openContextFile:(r,o)=>{const n=k((r||"").trim()),i=Ie(o);!n||!i||(e().openContextPanelTab(n,{mode:"file",targetPath:i}),e().setPendingFileFocusPath(i),e().setPendingFileNavigation(null))},openContextFileAtLine:(r,o,n,i)=>{const s=k((r||"").trim()),a=Ie(o),c=Number.isFinite(n)?Math.max(1,Math.trunc(n)):1,d=Number.isFinite(i)?Math.max(1,Math.trunc(i)):1;!s||!a||(e().openContextPanelTab(s,{mode:"file",targetPath:a}),e().setPendingFileFocusPath(null),e().setPendingFileNavigation({path:a,line:c,column:d}))},openContextOverview:r=>{const o=k((r||"").trim());o&&e().openContextPanelTab(o,{mode:"context"})},openContextPlan:r=>{const o=k((r||"").trim());o&&e().openContextPanelTab(o,{mode:"plan"})},openContextPreview:(r,o)=>{const n=k((r||"").trim()),i=(o||"").trim();if(!n||!i)return;let s=null;try{const a=new URL(i);(a.protocol==="http:"||a.protocol==="https:")&&(s=a.host||a.hostname||"Preview")}catch{}e().openContextPanelTab(n,{mode:"preview",targetPath:i,dedupeKey:i,label:s})},openContextBrowser:(r,o="")=>{const n=k((r||"").trim());if(!n)return;const i=typeof o=="string"&&o.trim().length>0?o.trim():"";e().openContextPanelTab(n,{mode:"browser",targetPath:i,dedupeKey:"desktop-browser",label:"Browser"})},setContextPanelTabTargetPath:(r,o,n)=>{const i=k((r||"").trim()),s=(o||"").trim();!i||!s||t(a=>{const c=a.contextPanelByDirectory[i];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[i]:Rn(c,s,n)}}:a})},setActiveContextPanelTab:(r,o)=>{const n=k((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=U(a);if(!c.tabs.some(l=>l.id===i)||c.activeTabId===i&&c.isOpen)return s;const d={...s.contextPanelByDirectory,[n]:{...c,isOpen:!0,activeTabId:i,touchedAt:Date.now(),tabs:c.tabs.map(l=>l.id===i?{...l,touchedAt:Date.now()}:l)}};return{contextPanelByDirectory:H(d,20)}})},reorderContextPanelTabs:(r,o,n)=>{const i=k((r||"").trim()),s=(o||"").trim(),a=(n||"").trim();!i||!s||!a||t(c=>{const d=c.contextPanelByDirectory[i],l=U(d);if(!l.tabs.some(m=>m.id===s)||!l.tabs.some(m=>m.id===a))return c;const f=In(l,s,a);if(f.tabs===l.tabs)return c;const y={...c.contextPanelByDirectory,[i]:f};return{contextPanelByDirectory:H(y,20)}})},closeContextPanelTab:(r,o)=>{const n=k((r||"").trim()),i=(o||"").trim();!n||!i||t(s=>{const a=s.contextPanelByDirectory[n],c=U(a);if(!c.tabs.some(l=>l.id===i))return s;const d={...s.contextPanelByDirectory,[n]:On(c,i)};return{contextPanelByDirectory:H(d,20)}})},closeContextPanel:r=>{const o=k((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o];if(!i||!i.isOpen)return n;const s={...n.contextPanelByDirectory,[o]:{...U(i),isOpen:!1}};return{contextPanelByDirectory:H(s,20)}})},toggleContextPanelExpanded:r=>{const o=k((r||"").trim());o&&t(n=>{const i=n.contextPanelByDirectory[o],s=U(i),a={...n.contextPanelByDirectory,[o]:{...s,expanded:!s.expanded}};return{contextPanelByDirectory:H(a,20)}})},setContextPanelWidth:(r,o)=>{const n=k((r||"").trim());n&&t(i=>{const s=i.contextPanelByDirectory[n],a=U(s),c={...i.contextPanelByDirectory,[n]:{...a,width:$r(o)}};return{contextPanelByDirectory:H(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)||(Ye.set(Xe(),r),t({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{Ye.set(Xe(r),e().activeMainTab)},restoreForRuntimeSwitch:r=>{const o=Ye.get(Xe(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(hn);if(n===1){for(const[s]of i)o.style.removeProperty(Gt(s));return}for(const[s,a]of i){const c=parseFloat(a);Number.isFinite(c)&&o.style.setProperty(Gt(s),`${c*n}rem`)}},applyPadding:()=>{const{padding:r}=e(),o=document.documentElement,n=r/100;if(n===1){o.style.removeProperty("--padding-scale"),o.style.removeProperty("--line-height-tight"),o.style.removeProperty("--line-height-normal"),o.style.removeProperty("--line-height-relaxed"),o.style.removeProperty("--line-height-loose");return}const i=Math.sqrt(n);o.style.setProperty("--padding-scale",i.toString());const s=1+(n-1)*.15;o.style.setProperty("--line-height-tight",(1.25*s).toFixed(3)),o.style.setProperty("--line-height-normal",(1.5*s).toFixed(3)),o.style.setProperty("--line-height-relaxed",(1.625*s).toFixed(3)),o.style.setProperty("--line-height-loose",(2*s).toFixed(3))},setDiffLayoutPreference:r=>{t({diffLayoutPreference:r})},setDiffFileLayout:(r,o)=>{t(n=>({diffFileLayout:{...n.diffFileLayout,[r]:o}}))},setDiffWrapLines:r=>{t({diffWrapLines:r})},setGitChangesViewMode:r=>{t({gitChangesViewMode:r})},setInputBarOffset:r=>{t({inputBarOffset:r})},setMobileKeyboardMode:r=>{t(o=>o.mobileKeyboardMode===r?o:{mobileKeyboardMode:r})},toggleFavoriteModel:(r,o)=>{t(n=>n.favoriteModels.some(s=>s.providerID===r&&s.modelID===o)?{favoriteModels:n.favoriteModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{favoriteModels:[{providerID:r,modelID:o},...n.favoriteModels]})},reorderFavoriteModel:(r,o,n,i)=>{t(s=>{const a=s.favoriteModels.findIndex(f=>f.providerID===r&&f.modelID===o),c=s.favoriteModels.findIndex(f=>f.providerID===n&&f.modelID===i);if(a===-1||c===-1||a===c)return s;const d=s.favoriteModels.slice(),[l]=d.splice(a,1);return l?(d.splice(c,0,l),{favoriteModels:d}):s})},toggleHiddenModel:(r,o)=>{t(n=>n.hiddenModels.some(s=>s.providerID===r&&s.modelID===o)?{hiddenModels:n.hiddenModels.filter(s=>!(s.providerID===r&&s.modelID===o))}:{hiddenModels:[{providerID:r,modelID:o},...n.hiddenModels]})},isHiddenModel:(r,o)=>{const{hiddenModels:n}=e();return n.some(i=>i.providerID===r&&i.modelID===o)},hideAllModels:(r,o)=>{t(n=>{const i=n.hiddenModels.filter(a=>a.providerID!==r);return{hiddenModels:[...o.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:r,modelID:a})),...i]}})},showAllModels:r=>{t(o=>({hiddenModels:o.hiddenModels.filter(n=>n.providerID!==r)}))},toggleModelProviderCollapsed:r=>{const o=typeof r=="string"?r.trim():"";o&&t(n=>n.collapsedModelProviders.includes(o)?{collapsedModelProviders:n.collapsedModelProviders.filter(s=>s!==o)}:{collapsedModelProviders:[...n.collapsedModelProviders,o]})},setModelProvidersCollapsed:(r,o)=>{const n=Array.from(new Set(r.filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)));n.length!==0&&t(i=>{const s=new Set(n),a=i.collapsedModelProviders.filter(c=>!s.has(c));return{collapsedModelProviders:o?[...a,...n]:a}})},isFavoriteModel:(r,o)=>{const{favoriteModels:n}=e();return n.some(i=>i.providerID===r&&i.modelID===o)},addRecentModel:(r,o)=>{t(n=>{const i=n.recentModels.filter(s=>!(s.providerID===r&&s.modelID===o));return{recentModels:[{providerID:r,modelID:o},...i].slice(0,5)}})},addRecentAgent:r=>{const o=typeof r=="string"?r.trim():"";o&&t(n=>{if(n.recentAgents.includes(o))return n;const i=n.recentAgents;return{recentAgents:[o,...i].slice(0,5)}})},addRecentEffort:(r,o,n)=>{const i=typeof r=="string"?r.trim():"",s=typeof o=="string"?o.trim():"";if(!i||!s)return;const a=`${i}/${s}`,c=typeof n=="string"&&n.trim().length>0?n.trim():"default";t(d=>{const l=d.recentEfforts[a]??[];if(l.includes(c))return d;const f=l;return{recentEfforts:{...d.recentEfforts,[a]:[c,...f].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(r=>{const o={};if(r.isBottomTerminalOpen&&!r.hasManuallyResizedBottomTerminal){const n=Math.floor(window.innerHeight*.32);r.bottomTerminalHeight!==n&&(o.bottomTerminalHeight=n)}return Object.keys(o).length>0?o:r})},applyTheme:()=>{const{theme:r}=e(),o=document.documentElement;if(o.classList.remove("light","dark"),r==="system"){const n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(n)}else o.classList.add(r)},setMultiRunLauncherOpen:r=>{t(o=>({isMultiRunLauncherOpen:r,multiRunLauncherPrefillPrompt:r?o.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:r=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:r,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:r=>{t({isTimelineDialogOpen:r})},setImagePreviewOpen:r=>{t({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{t({nativeNotificationsEnabled:r})},setNotificationMode:r=>{t({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{t({showTerminalQuickKeysOnDesktop:r})},setNotifyOnSubtasks:r=>{t({notifyOnSubtasks:r})},setNotifyOnCompletion:r=>{t({notifyOnCompletion:r})},setNotifyOnError:r=>{t({notifyOnError:r})},setNotifyOnQuestion:r=>{t({notifyOnQuestion:r})},setNotificationTemplates:r=>{t({notificationTemplates:r})},setSummarizeLastMessage:r=>{t({summarizeLastMessage:r})},setSummaryThreshold:r=>{t({summaryThreshold:r})},setSummaryLength:r=>{t({summaryLength:r})},setMaxLastMessageLength:r=>{t({maxLastMessageLength:r})},setPersistChatDraft:r=>{t({persistChatDraft:r})},setShowOpenCodeUpdateNotifications:r=>{t({showOpenCodeUpdateNotifications:r})},setInputSpellcheckEnabled:r=>{t({inputSpellcheckEnabled:r})},setWideChatLayoutEnabled:r=>{t({wideChatLayoutEnabled:r})},setShowToolFileIcons:r=>{t({showToolFileIcons:r})},setShowTurnChangedFiles:r=>{t({showTurnChangedFiles:r})},setShowExpandedBashTools:r=>{t({showExpandedBashTools:r})},setShowExpandedEditTools:r=>{t({showExpandedEditTools:r})},setTimeFormatPreference:r=>{t({timeFormatPreference:r})},setWeekStartPreference:r=>{t({weekStartPreference:r})},setMermaidRenderingMode:r=>{t({mermaidRenderingMode:r})},setUserMessageRenderingMode:r=>{t({userMessageRenderingMode:r})},setCollapsibleUserMessages:r=>{t({collapsibleUserMessages:r})},setStickyUserHeader:r=>{t({stickyUserHeader:r})},setExpandedEditorToolbar:r=>{t({expandedEditorToolbar:r})},setShowSplitAssistantMessageActions:r=>{t({showSplitAssistantMessageActions:r})},setIsMobileSessionStatusBarCollapsed:r=>{t({isMobileSessionStatusBarCollapsed:r})},setMobileSessionPanelOpen:r=>{t({mobileSessionPanelOpen:r})},setMobileSessionFilterProjectId:r=>{t({mobileSessionFilterProjectId:r})},setReportUsage:r=>{t({reportUsage:r})},viewPagerPage:"center",setViewPagerPage:r=>{t({viewPagerPage:r}),t(r==="left"?{isSessionSwitcherOpen:!0,isRightSidebarOpen:!1}:r==="right"?{isRightSidebarOpen:!0,isSessionSwitcherOpen:!1}:{isSessionSwitcherOpen:!1,isRightSidebarOpen:!1})},setShortcutOverride:(r,o)=>{t(n=>({shortcutOverrides:{...n.shortcutOverrides,[r]:o}}))},clearShortcutOverride:r=>{t(o=>{const n={...o.shortcutOverrides};return delete n[r],{shortcutOverrides:n}})},resetAllShortcutOverrides:()=>{t({shortcutOverrides:{}})},setFileEditorKeymap:r=>{t({fileEditorKeymap:qt(r)})},toggleExpandedInput:()=>{t(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{t({isExpandedInput:r})}}),{name:"ui-store",storage:pr(()=>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&&Dn(r.notificationTemplates)&&(r.notificationTemplates={completion:{...L.completion},error:{...L.error},question:{...L.question},subtask:{...L.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=Ze(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=Ze(r.contextPanelByDirectory)),e<7&&(r.contextPanelByDirectory=Ze(r.contextPanelByDirectory)),e<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=qt(r.fileEditorKeymap),r},partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isRightSidebarOpen:t.isRightSidebarOpen,rightSidebarWidth:t.rightSidebarWidth,rightSidebarTab:t.rightSidebarTab,contextPanelByDirectory:t.contextPanelByDirectory,isBottomTerminalOpen:t.isBottomTerminalOpen,isBottomTerminalExpanded:t.isBottomTerminalExpanded,bottomTerminalHeight:t.bottomTerminalHeight,notesPanelHeight:t.notesPanelHeight,todoPanelHeight:t.todoPanelHeight,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,settingsPage:t.settingsPage,settingsHasOpenedOnce:t.settingsHasOpenedOnce,settingsProjectsSelectedId:t.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:t.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,showDeletionDialog:t.showDeletionDialog,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,sessionRetentionAction:t.sessionRetentionAction,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,fontSize:t.fontSize,globalDraftStarters:t.globalDraftStarters,terminalFontSize:t.terminalFontSize,uiFont:t.uiFont,monoFont:t.monoFont,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,gitChangesViewMode:t.gitChangesViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,showTerminalQuickKeysOnDesktop:t.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,persistChatDraft:t.persistChatDraft,showOpenCodeUpdateNotifications:t.showOpenCodeUpdateNotifications,inputSpellcheckEnabled:t.inputSpellcheckEnabled,wideChatLayoutEnabled:t.wideChatLayoutEnabled,showToolFileIcons:t.showToolFileIcons,showTurnChangedFiles:t.showTurnChangedFiles,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,timeFormatPreference:t.timeFormatPreference,weekStartPreference:t.weekStartPreference,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,collapsibleUserMessages:t.collapsibleUserMessages,stickyUserHeader:t.stickyUserHeader,expandedEditorToolbar:t.expandedEditorToolbar,showSplitAssistantMessageActions:t.showSplitAssistantMessageActions,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed,mobileSessionFilterProjectId:t.mobileSessionFilterProjectId,shortcutOverrides:t.shortcutOverrides,fileEditorKeymap:t.fileEditorKeymap})}),{name:"ui-store"})),Fn=xe()(je(fr((t,e)=>({queuedMessages:{},queueModeEnabled:!0,addToQueue:(r,o)=>{const i={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:o.content,attachments:o.attachments,createdAt:Date.now(),sendConfig:o.sendConfig};t(s=>{const a=s.queuedMessages[r]??[];return{queuedMessages:{...s.queuedMessages,[r]:[...a,i]}}})},removeFromQueue:(r,o)=>{t(n=>{const s=(n.queuedMessages[r]??[]).filter(a=>a.id!==o);if(s.length===0){const{[r]:a,...c}=n.queuedMessages;return{queuedMessages:c}}return{queuedMessages:{...n.queuedMessages,[r]:s}}})},popToInput:(r,o)=>{const s=(e().queuedMessages[r]??[]).find(a=>a.id===o);return s?(t(a=>{const d=(a.queuedMessages[r]??[]).filter(l=>l.id!==o);if(d.length===0){const{[r]:l,...f}=a.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...a.queuedMessages,[r]:d}}}),s):null},clearQueue:r=>{t(o=>{const{[r]:n,...i}=o.queuedMessages;return{queuedMessages:i}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:r=>{t({queueModeEnabled:r}),N({queueModeEnabled:r})},getQueueForSession:r=>e().queuedMessages[r]??[]}),{name:"message-queue-store",storage:pr(()=>q()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),Qr="directoryTreeShowHidden",at="directory-show-hidden-change",Vt=()=>{if(typeof window>"u")return!0;try{const t=q().getItem(Qr);return t===null?!0:t==="true"}catch{return!0}},_n=()=>{typeof window>"u"||window.dispatchEvent(new Event(at))},xn=(t,e={})=>{if(!(typeof window>"u")){try{q().setItem(Qr,t?"true":"false"),_n()}catch{}e.persist!==!1&&N({directoryShowHidden:t})}},Ba=()=>{const t=hr.c(2),[e,r]=Me.useState(Vt);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(Vt())};return window.addEventListener("storage",i),window.addEventListener(at,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(at,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),Me.useEffect(o,n),e},Yr="filesViewShowGitignored",ct="files-view-show-gitignored-change",Jt=()=>{if(typeof window>"u")return!1;try{return q().getItem(Yr)==="true"}catch{return!1}},jn=()=>{typeof window>"u"||window.dispatchEvent(new Event(ct))},Nn=(t,e={})=>{if(!(typeof window>"u")){try{q().setItem(Yr,t?"true":"false"),jn()}catch{}e.persist!==!1&&N({filesViewShowGitignored:t})}},Ua=()=>{const t=hr.c(2),[e,r]=Me.useState(Jt);let o,n;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{if(typeof window>"u")return;const i=()=>{r(Jt())};return window.addEventListener("storage",i),window.addEventListener(ct,i),()=>{window.removeEventListener("storage",i),window.removeEventListener(ct,i)}},n=[],t[0]=o,t[1]=n):(o=t[0],n=t[1]),Me.useEffect(o,n),e},Ln=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},Bn=t=>{if(!t||typeof t!="object")return null;const e=t;return{showReasoningTraces:e.showReasoningTraces,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks}},Un=t=>{const e=Q.getState();typeof t.showReasoningTraces=="boolean"&&e.setShowReasoningTraces(t.showReasoningTraces),typeof t.collapsibleThinkingBlocks=="boolean"&&e.setCollapsibleThinkingBlocks(t.collapsibleThinkingBlocks)},Hn=async()=>{if(typeof window>"u")return null;const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const e=JSON.parse(t),r=Bn(e);return Ln(r)}catch(e){return console.warn("Failed to parse stored appearance preferences:",e),null}},Xr=[{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"}],zn=new Map(Xr.map(t=>[t.name,t])),Ha=t=>zn.get(t),za=Xr.map(t=>({type:"command",name:t.name})),$a="terminal-box",Ga="book-open",Wa=t=>`${t.type}:${t.name}`,qa=(t,e)=>t.type===e.type&&t.name===e.name,Ka=t=>{const e=t.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):t},Zr=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},$n=t=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=t}catch{}},lt=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),$n(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"&&Hr(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))}},dt=t=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))},Gn=t=>{if(!Array.isArray(t))return;const e=[],r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const n=o,i=typeof n.id=="string"?n.id.trim():"",s=typeof n.label=="string"?n.label.trim():"",a=typeof n.source=="string"?n.source.trim():"",c=typeof n.subpath=="string"?n.subpath.trim():"",d=typeof n.gitIdentityId=="string"?n.gitIdentityId.trim():"";!i||!s||!a||r.has(i)||(r.add(i),e.push({id:i,label:s,source:a,...c?{subpath:c}:{},...d?{gitIdentityId:d}:{}}))}return e},Wn=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},qn=(t,e)=>{const r=Object.entries(t),o=Object.entries(e);return r.length!==o.length?!1:r.every(([n,i])=>e[n]===i)},Kn=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Vn=t=>{if(typeof t!="string")return null;const e=t.trim();return e&&Kn.test(e)?e.toLowerCase():null},Jn=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=un(a);if(!c||r.has(c)||o.has(a))continue;r.add(c),o.add(a);const d={id:c,path:a};if(typeof i.label=="string"&&i.label.trim().length>0&&(d.label=i.label.trim()),typeof i.icon=="string"&&i.icon.trim().length>0&&(d.icon=i.icon.trim()),i.iconImage===null)d.iconImage=null;else if(i.iconImage&&typeof i.iconImage=="object"){const l=i.iconImage,f=typeof l.mime=="string"?l.mime.trim():"",y=typeof l.updatedAt=="number"&&Number.isFinite(l.updatedAt)?Math.max(0,Math.round(l.updatedAt)):0,m=l.source==="custom"||l.source==="auto"?l.source:null;f&&y>0&&m&&(d.iconImage={mime:f,updatedAt:y,source:m})}if(typeof i.color=="string"&&i.color.trim().length>0&&(d.color=i.color.trim()),i.iconBackground===null)d.iconBackground=null;else{const l=Vn(i.iconBackground);l&&(d.iconBackground=l)}typeof i.addedAt=="number"&&Number.isFinite(i.addedAt)&&i.addedAt>=0&&(d.addedAt=i.addedAt),typeof i.lastOpenedAt=="number"&&Number.isFinite(i.lastOpenedAt)&&i.lastOpenedAt>=0&&(d.lastOpenedAt=i.lastOpenedAt),typeof i.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=i.sidebarCollapsed),e.push(d)}return e.length>0?e:void 0},Qn=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},Yn=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},Qt=(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},eo=()=>{const t=Q.persist;if(t&&typeof t=="object")return t},to=()=>Ue()?.settings??null,ut=t=>{const e=Q.getState(),r=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,o=typeof window<"u"?window.__zustand_config_store__??null:null,n=Fn.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=Zr(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),Br(t.uiFont)&&t.uiFont!==e.uiFont&&e.setUiFont(t.uiFont),Ur(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&&!qn(t.shortcutOverrides,e.shortcutOverrides)&&Q.setState({shortcutOverrides:t.shortcutOverrides}),typeof t.mobileKeyboardMode=="string"){const i=ze(t.mobileKeyboardMode,e.mobileKeyboardMode);i!==e.mobileKeyboardMode&&e.setMobileKeyboardMode(i)}if(o&&r){const i={};(t.sttProvider==="browser"||t.sttProvider==="server")&&t.sttProvider!==r.sttProvider&&(i.sttProvider=t.sttProvider),typeof t.sttServerUrl=="string"&&t.sttServerUrl!==r.sttServerUrl&&(i.sttServerUrl=t.sttServerUrl),typeof t.sttModel=="string"&&t.sttModel!==r.sttModel&&(i.sttModel=t.sttModel),typeof t.sttLanguage=="string"&&t.sttLanguage!==r.sttLanguage&&(i.sttLanguage=t.sttLanguage),typeof t.sttSilenceThresholdDb=="number"&&Number.isFinite(t.sttSilenceThresholdDb)&&t.sttSilenceThresholdDb!==r.sttSilenceThresholdDb&&(i.sttSilenceThresholdDb=t.sttSilenceThresholdDb),typeof t.sttSilenceHoldMs=="number"&&Number.isFinite(t.sttSilenceHoldMs)&&t.sttSilenceHoldMs!==r.sttSilenceHoldMs&&(i.sttSilenceHoldMs=t.sttSilenceHoldMs),typeof t.sttTranscribeOnStop=="boolean"&&t.sttTranscribeOnStop!==r.sttTranscribeOnStop&&(i.sttTranscribeOnStop=t.sttTranscribeOnStop),Object.keys(i).length>0&&o.setState(i)}if(Array.isArray(t.favoriteModels)){const i=e.favoriteModels,s=t.favoriteModels;i.length===s.length&&i.every((c,d)=>c.providerID===s[d]?.providerID&&c.modelID===s[d]?.modelID)||Q.setState({favoriteModels:s})}if(Array.isArray(t.recentModels)){const i=e.recentModels,s=t.recentModels;i.length===s.length&&i.every((c,d)=>c.providerID===s[d]?.providerID&&c.modelID===s[d]?.modelID)||Q.setState({recentModels:s})}typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&t.diffLayoutPreference!==e.diffLayoutPreference&&e.setDiffLayoutPreference(t.diffLayoutPreference),typeof t.gitChangesViewMode=="string"&&(t.gitChangesViewMode==="flat"||t.gitChangesViewMode==="tree")&&t.gitChangesViewMode!==e.gitChangesViewMode&&e.setGitChangesViewMode(t.gitChangesViewMode),typeof t.directoryShowHidden=="boolean"&&xn(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&Nn(t.filesViewShowGitignored,{persist:!1})},Yt=t=>{if(!t||typeof t!="object")return null;const e=t,r={};if(typeof e.themeId=="string"&&e.themeId.length>0&&(r.themeId=e.themeId),(e.useSystemTheme===!0||e.useSystemTheme===!1)&&(r.useSystemTheme=e.useSystemTheme),typeof e.themeVariant=="string"&&(e.themeVariant==="light"||e.themeVariant==="dark")&&(r.themeVariant=e.themeVariant),typeof e.lightThemeId=="string"&&e.lightThemeId.length>0&&(r.lightThemeId=e.lightThemeId),typeof e.darkThemeId=="string"&&e.darkThemeId.length>0&&(r.darkThemeId=e.darkThemeId),typeof e.lastDirectory=="string"&&e.lastDirectory.length>0&&(r.lastDirectory=e.lastDirectory),typeof e.homeDirectory=="string"&&e.homeDirectory.length>0&&(r.homeDirectory=e.homeDirectory),typeof e.opencodeBinary=="string"){const l=e.opencodeBinary.trim();r.opencodeBinary=l.length>0?l:void 0}typeof e.desktopLanAccessEnabled=="boolean"&&(r.desktopLanAccessEnabled=e.desktopLanAccessEnabled);const o=Jn(e.projects);if(o&&(r.projects=o),typeof e.activeProjectId=="string"&&e.activeProjectId.length>0&&(r.activeProjectId=e.activeProjectId),Array.isArray(e.securityScopedBookmarks)&&(r.securityScopedBookmarks=e.securityScopedBookmarks.filter(l=>typeof l=="string"&&l.length>0)),Array.isArray(e.pinnedDirectories)&&(r.pinnedDirectories=Array.from(new Set(e.pinnedDirectories.filter(l=>typeof l=="string"&&l.length>0)))),Array.isArray(e.draftStarters)&&(r.draftStarters=Zr(e.draftStarters)),typeof e.showReasoningTraces=="boolean"&&(r.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&(r.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled=="boolean"&&(r.autoDeleteEnabled=e.autoDeleteEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)&&(r.autoDeleteAfterDays=e.autoDeleteAfterDays),(e.sessionRetentionAction==="archive"||e.sessionRetentionAction==="delete")&&(r.sessionRetentionAction=e.sessionRetentionAction),typeof e.tunnelProvider=="string"){const l=e.tunnelProvider.trim().toLowerCase();l.length>0&&(r.tunnelProvider=l)}if(typeof e.tunnelMode=="string"){const l=e.tunnelMode.trim().toLowerCase();(l==="quick"||l==="managed-remote"||l==="managed-local")&&(r.tunnelMode=l)}if(e.tunnelBootstrapTtlMs===null?r.tunnelBootstrapTtlMs=null:typeof e.tunnelBootstrapTtlMs=="number"&&Number.isFinite(e.tunnelBootstrapTtlMs)&&(r.tunnelBootstrapTtlMs=e.tunnelBootstrapTtlMs),typeof e.tunnelSessionTtlMs=="number"&&Number.isFinite(e.tunnelSessionTtlMs)&&(r.tunnelSessionTtlMs=e.tunnelSessionTtlMs),e.managedLocalTunnelConfigPath===null)r.managedLocalTunnelConfigPath=null;else if(typeof e.managedLocalTunnelConfigPath=="string"){const l=e.managedLocalTunnelConfigPath.trim();r.managedLocalTunnelConfigPath=l.length>0?l:null}typeof e.managedRemoteTunnelHostname=="string"&&(r.managedRemoteTunnelHostname=e.managedRemoteTunnelHostname.trim()),e.managedRemoteTunnelToken===null?r.managedRemoteTunnelToken=null:typeof e.managedRemoteTunnelToken=="string"&&(r.managedRemoteTunnelToken=e.managedRemoteTunnelToken.trim());const n=Qn(e.managedRemoteTunnelPresets);if(n&&(r.managedRemoteTunnelPresets=n),typeof e.managedRemoteTunnelSelectedPresetId=="string"){const l=e.managedRemoteTunnelSelectedPresetId.trim();r.managedRemoteTunnelSelectedPresetId=l.length>0?l:void 0}const i=Yn(e.managedRemoteTunnelPresetTokens);if(i&&(r.managedRemoteTunnelPresetTokens=i),typeof e.defaultModel=="string"&&e.defaultModel.length>0&&(r.defaultModel=e.defaultModel),typeof e.defaultVariant=="string"&&e.defaultVariant.length>0&&(r.defaultVariant=e.defaultVariant),typeof e.defaultAgent=="string"&&e.defaultAgent.length>0&&(r.defaultAgent=e.defaultAgent),typeof e.autoCreateWorktree=="boolean"&&(r.autoCreateWorktree=e.autoCreateWorktree),typeof e.gitmojiEnabled=="boolean"&&(r.gitmojiEnabled=e.gitmojiEnabled),typeof e.queueModeEnabled=="boolean"&&(r.queueModeEnabled=e.queueModeEnabled),typeof e.showDeletionDialog=="boolean"&&(r.showDeletionDialog=e.showDeletionDialog),typeof e.nativeNotificationsEnabled=="boolean"&&(r.nativeNotificationsEnabled=e.nativeNotificationsEnabled),typeof e.notificationMode=="string"&&(e.notificationMode==="always"||e.notificationMode==="hidden-only")&&(r.notificationMode=e.notificationMode),typeof e.notifyOnSubtasks=="boolean"&&(r.notifyOnSubtasks=e.notifyOnSubtasks),typeof e.notifyOnCompletion=="boolean"&&(r.notifyOnCompletion=e.notifyOnCompletion),typeof e.notifyOnError=="boolean"&&(r.notifyOnError=e.notifyOnError),typeof e.notifyOnQuestion=="boolean"&&(r.notifyOnQuestion=e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates=="object"){const l=e.notificationTemplates,f=b=>{const v=l[b];if(!v||typeof v!="object")return;const M=v,O=typeof M.title=="string"?M.title:"",A=typeof M.message=="string"?M.message:"";return{title:O,message:A}},y=f("completion"),m=f("error"),w=f("question"),g=f("subtask");(y||m||w||g)&&(r.notificationTemplates={completion:y??{title:"Task Complete",message:"Your task has finished."},error:m??{title:"Error Occurred",message:"An error occurred while processing your task."},question:w??{title:"Input Needed",message:"Please provide input to continue."},subtask:g??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof e.summarizeLastMessage=="boolean"&&(r.summarizeLastMessage=e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&(r.summaryThreshold=Math.max(0,Math.round(e.summaryThreshold))),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&(r.summaryLength=Math.max(10,Math.round(e.summaryLength))),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&(r.maxLastMessageLength=Math.max(10,Math.round(e.maxLastMessageLength))),typeof e.usageAutoRefresh=="boolean"&&(r.usageAutoRefresh=e.usageAutoRefresh),typeof e.usageRefreshIntervalMs=="number"&&Number.isFinite(e.usageRefreshIntervalMs)&&(r.usageRefreshIntervalMs=e.usageRefreshIntervalMs),(e.usageDisplayMode==="usage"||e.usageDisplayMode==="remaining")&&(r.usageDisplayMode=e.usageDisplayMode),typeof e.usageShowPredValues=="boolean"&&(r.usageShowPredValues=e.usageShowPredValues),Array.isArray(e.usageDropdownProviders)&&(r.usageDropdownProviders=e.usageDropdownProviders.filter(l=>typeof l=="string"&&l.length>0)),e.usageSelectedModels&&typeof e.usageSelectedModels=="object"){const l={};for(const[f,y]of Object.entries(e.usageSelectedModels))Array.isArray(y)&&(l[f]=y.filter(m=>typeof m=="string"));Object.keys(l).length>0&&(r.usageSelectedModels=l)}if(e.usageCollapsedFamilies&&typeof e.usageCollapsedFamilies=="object"){const l={};for(const[f,y]of Object.entries(e.usageCollapsedFamilies))Array.isArray(y)&&(l[f]=y.filter(m=>typeof m=="string"));Object.keys(l).length>0&&(r.usageCollapsedFamilies=l)}if(e.usageExpandedFamilies&&typeof e.usageExpandedFamilies=="object"){const l={};for(const[f,y]of Object.entries(e.usageExpandedFamilies))Array.isArray(y)&&(l[f]=y.filter(m=>typeof m=="string"));Object.keys(l).length>0&&(r.usageExpandedFamilies=l)}if(e.usageModelGroups&&typeof e.usageModelGroups=="object"){const l={};for(const[f,y]of Object.entries(e.usageModelGroups))if(y&&typeof y=="object"){const m=y,w={};Array.isArray(m.customGroups)&&(w.customGroups=m.customGroups.filter(g=>g&&typeof g=="object").map(g=>({id:String(g.id??""),label:String(g.label??""),models:Array.isArray(g.models)?g.models.filter(b=>typeof b=="string"):[],order:typeof g.order=="number"?g.order:0}))),m.modelAssignments&&typeof m.modelAssignments=="object"&&(w.modelAssignments=Object.fromEntries(Object.entries(m.modelAssignments).filter(([,g])=>typeof g=="string").map(([g,b])=>[g,String(b)]))),m.renamedGroups&&typeof m.renamedGroups=="object"&&(w.renamedGroups=Object.fromEntries(Object.entries(m.renamedGroups).filter(([,g])=>typeof g=="string").map(([g,b])=>[g,String(b)]))),Object.keys(w).length>0&&(l[f]=w)}Object.keys(l).length>0&&(r.usageModelGroups=l)}typeof e.inputSpellcheckEnabled=="boolean"&&(r.inputSpellcheckEnabled=e.inputSpellcheckEnabled),typeof e.showOpenCodeUpdateNotifications=="boolean"&&(r.showOpenCodeUpdateNotifications=e.showOpenCodeUpdateNotifications),typeof e.openCodeUpdateToastDismissedVersion=="string"&&(r.openCodeUpdateToastDismissedVersion=e.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof e.showToolFileIcons=="boolean"&&(r.showToolFileIcons=e.showToolFileIcons),typeof e.showTurnChangedFiles=="boolean"&&(r.showTurnChangedFiles=e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&(r.showExpandedBashTools=e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&(r.showExpandedEditTools=e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&(r.timeFormatPreference=e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&(r.weekStartPreference=e.weekStartPreference),typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&(r.chatRenderMode=e.chatRenderMode),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&(r.messageStreamTransport=e.messageStreamTransport),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&(r.activityRenderMode=e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&(r.mermaidRenderingMode=e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&(r.userMessageRenderingMode=e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&(r.collapsibleUserMessages=e.collapsibleUserMessages),typeof e.stickyUserHeader=="boolean"&&(r.stickyUserHeader=e.stickyUserHeader),typeof e.wideChatLayoutEnabled=="boolean"&&(r.wideChatLayoutEnabled=e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&(r.showSplitAssistantMessageActions=e.showSplitAssistantMessageActions),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&(r.fontSize=e.fontSize),typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&(r.terminalFontSize=e.terminalFontSize),Br(e.uiFont)&&(r.uiFont=e.uiFont),Ur(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=Wn(e.shortcutOverrides);s&&(r.shortcutOverrides=s),typeof e.mobileKeyboardMode=="string"&&(e.mobileKeyboardMode==="native"||e.mobileKeyboardMode==="resize-content")&&(r.mobileKeyboardMode=e.mobileKeyboardMode);const a=Qt(e.favoriteModels,64);a&&(r.favoriteModels=a);const c=Qt(e.recentModels,16);if(c&&(r.recentModels=c),typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&(r.diffLayoutPreference=e.diffLayoutPreference),typeof e.gitChangesViewMode=="string"&&(e.gitChangesViewMode==="flat"||e.gitChangesViewMode==="tree")&&(r.gitChangesViewMode=e.gitChangesViewMode),typeof e.directoryShowHidden=="boolean"&&(r.directoryShowHidden=e.directoryShowHidden),typeof e.filesViewShowGitignored=="boolean"&&(r.filesViewShowGitignored=e.filesViewShowGitignored),typeof e.openInAppId=="string"&&e.openInAppId.length>0&&(r.openInAppId=e.openInAppId),typeof e.pwaAppName=="string"){const l=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);r.pwaAppName=l.length>0?l:""}const d=Gn(e.skillCatalogs);return d&&(r.skillCatalogs=d),typeof e.reportUsage=="boolean"&&(r.reportUsage=e.reportUsage),typeof e.globalBehaviorPrompt=="string"&&(r.globalBehaviorPrompt=e.globalBehaviorPrompt),typeof e.responseStyleEnabled=="boolean"&&(r.responseStyleEnabled=e.responseStyleEnabled),typeof e.responseStylePreset=="string"&&(e.responseStylePreset==="concise"||e.responseStylePreset==="detailed"||e.responseStylePreset==="mentor"||e.responseStylePreset==="pushback"||e.responseStylePreset==="noFiller"||e.responseStylePreset==="matchEnergy"||e.responseStylePreset==="warmPeer"||e.responseStylePreset==="custom")&&(r.responseStylePreset=e.responseStylePreset),typeof e.responseStyleCustomInstructions=="string"&&(r.responseStyleCustomInstructions=e.responseStyleCustomInstructions),(e.sttProvider==="browser"||e.sttProvider==="server")&&(r.sttProvider=e.sttProvider),typeof e.sttServerUrl=="string"&&(r.sttServerUrl=e.sttServerUrl.trim()),typeof e.sttModel=="string"&&(r.sttModel=e.sttModel.trim()),typeof e.sttLanguage=="string"&&(r.sttLanguage=e.sttLanguage.trim()),typeof e.sttSilenceThresholdDb=="number"&&Number.isFinite(e.sttSilenceThresholdDb)&&(r.sttSilenceThresholdDb=e.sttSilenceThresholdDb),typeof e.sttSilenceHoldMs=="number"&&Number.isFinite(e.sttSilenceHoldMs)&&(r.sttSilenceHoldMs=e.sttSilenceHoldMs),typeof e.sttTranscribeOnStop=="boolean"&&(r.sttTranscribeOnStop=e.sttTranscribeOnStop),r};let J=null,ne=null;const Xn=2e3,Zn=async()=>J&&Date.now()-J.at<Xn?J.value:ne||(ne=(async()=>{const t=to();if(t)try{const e=await t.load(),r=Yt(e.settings);return J={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=Yt(r);return J={value:o,at:Date.now()},o}catch(e){return console.warn("Failed to load shared settings from server:",e),null}})().finally(()=>{ne=null}),ne),Va=async()=>{if(typeof window>"u")return;const t=eo(),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{lt(o)}catch(n){console.warn("persistToLocalStorage failed:",n)}await e();try{ut(o)}catch(n){console.warn("applyDesktopUiPreferences failed:",n)}dt(o)};try{const o=await Zn();o&&await r(o)}catch(o){console.warn("Failed to synchronise settings:",o)}};let Re=null,Ee=null;const ei=200,ti=async()=>{const t=Re;if(Re=null,Ee=null,!t||Object.keys(t).length===0)return;const e=to();if(e)try{const r=await e.save(t);r&&(lt(r),ut(r),dt(r));return}catch(r){console.warn("Failed to update settings via runtime settings API:",r)}try{const r=await u("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!r.ok){console.warn("Failed to update shared settings via API:",r.status,r.statusText);return}const o=await r.json().catch(()=>null);o&&(lt(o),ut(o),dt(o),J=null)}catch(r){console.warn("Failed to update shared settings via API:",r)}},N=async t=>{typeof window>"u"||(Re={...Re??{},...t},Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{ti()},ei))},Ja=async()=>{if(typeof window>"u")return;const t=eo();try{const e=await Hn();if(!e)return;const r=()=>Un(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)}},ri=3e4,oi=40,ni=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])},Xt=(t,e)=>{try{const r=JSON.parse(t);return Array.isArray(r)&&r[0]===e}catch{return!1}},si=xe()(je((t,e)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(r,o,n=ni,i){if(!r||r.trim().length===0)return[];const s=r.trim(),a=typeof o=="string"?o.trim():"",c=!!i?.includeHidden,d=i?.respectGitignore??!0,l=i?.type==="directory"?"directory":"file",f=ii(s,a,n,c,d,l),y=Date.now(),m=e().cache[f];if(m&&y-m.timestamp<ri)return m.files;const w=e().inFlight[f];if(w)return w;const g=B.searchFiles(a,{directory:s,limit:n,includeHidden:c,respectGitignore:d,dirs:l!=="file",type:l}).then(b=>(t(v=>{if(v.inFlight[f]!==g)return v;const M={...v.cache,[f]:{files:b,timestamp:Date.now()}},O=v.cacheKeys.filter(A=>A!==f);for(O.push(f);O.length>oi;){const A=O.shift();A&&delete M[A]}return{cache:M,cacheKeys:O}}),b)).finally(()=>{t(b=>{if(b.inFlight[f]!==g)return b;const v={...b.inFlight};return delete v[f],{inFlight:v}})});return t(b=>({inFlight:{...b.inFlight,[f]:g}})),g},invalidateDirectory(r){if(!r||r.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=r.trim();t(n=>{const i={...n.cache},s=n.cacheKeys.filter(d=>Xt(d,o)?(delete i[d],!1):!0),a=Object.entries(n.inFlight).filter(([d])=>!Xt(d,o)),c=Object.fromEntries(a);return{cache:i,cacheKeys:s,inFlight:c}})}}),{name:"file-search-store"})),ai=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},ft="openchamber_stream_perf",fe=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(ft)==="1"}catch{return!1}},Zt=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),ci=()=>{if(!fe()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const t=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:t,lastUpdatedAt:t}}return window.__openchamberStreamPerfState},ro=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),Dt=(t,e)=>{const r=ci();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()},Qa=t=>{if(!(typeof window>"u"))try{if(t){window.localStorage.setItem(ft,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(ft),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},Ya=()=>{typeof window>"u"||(fe()&&(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()}))},Xa=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberStreamPerfState;return!fe()||!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:ro(t.counters)}},Za=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=window.__openchamberVsCodeStreamPerfState;if(!fe()||!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:ro(t.counters)}},ec=(t,e=1)=>{Dt(t,e)},tc=(t,e)=>{Dt(t,e)},rc=(t,e)=>{if(!fe())return e();const r=Zt();try{return e()}finally{Dt(t,Zt()-r)}};var li={};let F=null,er=0;const R=q(),tr=R.getItem("lastDirectory"),di=typeof tr=="string"&&tr.length>0,ge=t=>{try{si.getState().invalidateDirectory(t)}catch(e){console.warn("Failed to invalidate file search cache:",e)}},Z=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},ui=(t,e)=>{const r=t.trim();return r.startsWith("~")?r==="~"?e||r:(r.startsWith("~/")||r.startsWith("~\\"))&&e?`${e}${r.slice(1)}`:r:r},Pe=(t,e)=>{const r=ui(t,e);return Z(r)},fi=()=>{const t=R.getItem("homeDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=Z(t);return e.length>0?e:null},pi=()=>{const t=R.getItem("lastDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=Z(t);return e.length>0?e:null},hi=()=>{if(typeof process>"u")return null;const t=li,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=Z(e);return o.length>0?o:null}const r=process?.cwd?.();if(typeof r=="string"&&r.trim().length>0){const o=Z(r);return o.length>0?o:null}return null},Fe=()=>{if(typeof window<"u"){if(F)return F;const e=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(e&&e.length>0)return F=e,R.setItem("homeDirectory",e),e;const r=fi();if(r&&!He())return F=r,r}const t=hi();return t||"/"},mi=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},yi=t=>(F=t,typeof window<"u"&&R.setItem("homeDirectory",t),N({homeDirectory:t}),t),pt=async()=>{const t=o=>{const n=mi(o);return n?yi(n):null};try{const o=await B.getFilesystemHome(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain filesystem home directory:",o)}try{const o=await B.getSystemInfo(),n=t(o?.homeDirectory);if(n)return n}catch(o){console.warn("Failed to get home directory from system info:",o)}try{const o=await Ir(),n=t(o);if(n)return n}catch(o){console.warn("Failed to obtain desktop-integrated home directory:",o)}const e=Fe(),r=t(e);return r||e},gi=()=>{if(!He())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const e=Z(t);return e.length>0?e:null},de=gi()||Fe(),_e=(()=>{const t=pi();return t&&!He()?Pe(t,de):de})();_e&&B.setDirectory(_e);const wi=!!(de&&de!=="/"),ht=xe()(je((t,e)=>({currentDirectory:_e,directoryHistory:[_e],historyIndex:0,homeDirectory:de,hasPersistedDirectory:di,isHomeReady:wi,isSwitchingDirectory:!1,setDirectory:(r,o)=>{const n=F||e().homeDirectory||R.getItem("homeDirectory"),i=Pe(r,n);ai()&&console.log("[DirectoryStore] setDirectory called with path:",i),B.setDirectory(i),ge(),t(s=>{const a=[...s.directoryHistory.slice(0,s.historyIndex+1),i];return R.setItem("lastDirectory",i),N({lastDirectory:i}),{currentDirectory:i,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const r=e();if(r.historyIndex>0){const o=r.historyIndex-1,n=r.directoryHistory[o];B.setDirectory(n),ge(),R.setItem("lastDirectory",n),N({lastDirectory:n}),t({currentDirectory:n,historyIndex:o,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const r=e();if(r.historyIndex<r.directoryHistory.length-1){const o=r.historyIndex+1,n=r.directoryHistory[o];B.setDirectory(n),ge(),R.setItem("lastDirectory",n),N({lastDirectory:n}),t({currentDirectory:n,historyIndex:o,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:r,setDirectory:o}=e(),n=F||e().homeDirectory||Fe();if(r===n||r==="/")return;const i=r.endsWith("/")?r.slice(0,-1):r,s=i.lastIndexOf("/");if(s===-1){const a=F||Fe();o(a)}else o(s===0?"/":i.substring(0,s))},goHome:async()=>{const r=F||e().homeDirectory||await pt();e().setDirectory(r)},synchronizeHomeDirectory:r=>{const o=e(),n=r;F=n;const i=o.homeDirectory!==n,s=R.getItem("lastDirectory"),a=typeof s=="string"&&s.length>0,c=!a&&(o.currentDirectory==="/"||o.currentDirectory===o.homeDirectory||!o.currentDirectory);if(!i&&!c){o.isHomeReady||t({isHomeReady:!0});return}const d=typeof n=="string"&&n!==""&&n!=="/",l=o.currentDirectory?Pe(o.currentDirectory,n):o.currentDirectory,f=o.directoryHistory.map(g=>Pe(g,n)),y=f.some((g,b)=>g!==o.directoryHistory[b]),m=!!(l&&l!==o.currentDirectory),w={homeDirectory:n,hasPersistedDirectory:a,isHomeReady:d};if(c?(w.currentDirectory=n,w.directoryHistory=[n],w.historyIndex=0,w.isSwitchingDirectory=!1):(m||y)&&(w.currentDirectory=l,w.directoryHistory=f,w.historyIndex=Math.min(o.historyIndex,f.length-1),w.isSwitchingDirectory=!1),t(()=>w),(c||m)&&d){const g=c?n:l;B.setDirectory(g),ge(),R.setItem("lastDirectory",g),N({lastDirectory:g})}N({homeDirectory:n})}}),{name:"directory-store"}));typeof window<"u"&&(pt().then(t=>{ht.getState().synchronizeHomeDirectory(t)}),No(()=>{F=null;const t=++er;pt().then(e=>{t===er&&ht.getState().synchronizeHomeDirectory(e)})}));const oo=1,_=1,we=0,no="/api/terminal/ws",bi=1200,Si=250,Ti=2e4,vi=5e3,et="__openchamberTerminalTransportState",ki=new TextEncoder,rr=new TextDecoder,Et=t=>D().websocket(t),tt=t=>{const e=ki.encode(JSON.stringify(t)),r=new Uint8Array(e.length+1);return r[0]=oo,r.set(e,1),r},ue=t=>t?((t.transports??[]).includes("ws")||t.preferred==="ws")&&typeof t.ws?.path=="string"&&t.ws.path.length>0:!1,Pt=t=>t.streamCapability?.ws?.path??t.inputCapability?.ws?.path??no,Di=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 Ei{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(bi);if(!o||o.readyState!==_)return!1;try{return this.boundSessionId!==e&&(this.requestedSessionId=e,o.send(tt({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===_||this.socket.readyState===we)?!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===_)return this.socket;if(this.ensureConnected(),this.socket&&this.socket.readyState===_)return this.socket;const r=await Promise.race([this.openPromise??Promise.resolve(null),new Promise(o=>{setTimeout(()=>o(null),e)})]);return r&&r.readyState===_?r:this.socket&&this.socket.readyState===_?this.socket:null}ensureConnected(){this.closed||!this.socketUrl||this.socket&&(this.socket.readyState===_||this.socket.readyState===we)||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===we&&(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!==_)){this.requestedSessionId=e.sessionId;try{this.socket.send(tt({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()*Si),d=a+c;this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},d)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}sendControl(e){if(!this.socket||this.socket.readyState!==_)return!1;try{return this.socket.send(tt(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})},Ti)}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]===oo){this.handleControlMessage(r);return}const o=await this.asText(e);if(!o)return;const n=this.getActiveSubscription();n&&n.onEvent({type:"data",data:o})}handleControlMessage(e){if(e.length<2)return;let r;try{r=JSON.parse(rr.decode(e.subarray(1)))}catch{this.handleSocketFailure(new Error("Terminal websocket control parse failed"));return}const o=this.getActiveSubscription();switch(r.t){case"ok":this.bindActiveSession();return;case"po":return;case"d":{const n=r.s??this.boundSessionId??this.requestedSessionId;if(!o||!n||n!==o.sessionId)return;typeof r.i=="number"&&Number.isFinite(r.i)&&this.replayCursorBySession.set(n,Math.max(this.replayCursorBySession.get(n)??0,Math.trunc(r.i))),typeof r.d=="string"&&r.d.length>0&&o.onEvent({type:"data",data:r.d});return}case"bok":{if(this.boundSessionId=r.s??this.requestedSessionId,!o)return;o.retryCount=0,o.connected=!0,this.clearConnectionTimeout(o),o.onEvent({type:"connected",runtime:r.runtime,ptyBackend:r.ptyBackend});return}case"x":{if(!o){this.boundSessionId=null;return}if(r.s&&r.s!==o.sessionId)return;o.connected=!1,this.clearConnectionTimeout(o),this.boundSessionId=null,this.requestedSessionId=null,this.replayCursorBySession.delete(o.sessionId),o.onEvent({type:"exit",exitCode:r.exitCode,signal:r.signal??null});return}case"e":{const n=Di(r.c),i=r.f===!0||r.c==="SESSION_NOT_FOUND";(r.c==="NOT_BOUND"||r.c==="SESSION_NOT_FOUND")&&(this.boundSessionId=null),o&&(o.connected=!1,i&&this.clearConnectionTimeout(o),o.onError?.(n,i)),r.f===!0&&this.handleSocketFailure(n);return}default:return}}async asUint8Array(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return e;if(typeof Blob<"u"&&e instanceof Blob){const r=await e.arrayBuffer();return new Uint8Array(r)}return null}async asText(e){if(typeof e=="string")return e;const r=await this.asUint8Array(e);return r?rr.decode(r):""}handleSocketFailure(e){this.boundSessionId=null,this.requestedSessionId=null,this.resetConnection(),this.scheduleReconnect(e)}resetConnection(){if(this.openPromise=null,this.stopKeepalive(),this.socket){const e=this.socket;this.socket=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,(e.readyState===_||e.readyState===we)&&e.close()}this.boundSessionId=null}}const j=()=>{const t=globalThis;return t[et]||(t[et]={inputCapability:null,streamCapability:null,manager:null}),t[et]},Mt=()=>{const t=j();return t.manager||(t.manager=new Ei),t.manager},io=t=>{const e=j();if(e.inputCapability=t?.input??null,e.streamCapability=t?.stream??null,!ue(e.inputCapability)&&!ue(e.streamCapability)){e.manager?.close(),e.manager=null;return}const r=Et(Pt(e));if(!r)return;Mt().configure(r)},Pi=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 Mi(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 io(r.capabilities),r}const or=(t,e,r,o={})=>{const n=o.maxRetries??3,i=o.initialRetryDelay??1e3,s=o.maxRetryDelay??8e3,a=o.connectionTimeout??1e4;let c=null,d=0,l=null,f=null,y=!1,m=!1;const w=()=>{l&&(clearTimeout(l),l=null),f&&(clearTimeout(f),f=null)},g=()=>{y||(y=!0,w(),c&&(c.close(),c=null))},b=(M,O)=>{if(!(y||m)){if(d<n&&!O){d+=1;const A=Math.min(i*Math.pow(2,d-1),s);e({type:"reconnecting",attempt:d,maxAttempts:n}),l=setTimeout(()=>{!y&&!m&&v()},A);return}r?.(M,!0),g()}},v=()=>{if(y||m||c&&c.readyState!==EventSource.CLOSED)return;c=new EventSource(D().sse(`/api/terminal/${t}/stream`));let M=!1;f=setTimeout(()=>{!M&&c?.readyState!==EventSource.OPEN&&(c?.close(),b(new Error("Connection timeout"),!1))},a),c.onopen=()=>{M||(M=!0,d=0,w(),e({type:"connected"}))},c.onmessage=O=>{try{const A=JSON.parse(O.data);A.type==="exit"&&(j().manager?.unbindSession(t),m=!0,g()),e(A)}catch(A){r?.(A,!1)}},c.onerror=()=>{w();const O=m||c?.readyState===EventSource.CLOSED;c?.close(),c=null,m||b(new Error("Terminal stream connection error"),O)}};return v(),g};function Ai(t,e,r,o={}){const n=j();if(!ue(n.streamCapability))return or(t,e,r,o);const i=Mt(),s=Et(Pt(n));return s?(i.configure(s),i.subscribe(t,e,r,o)):or(t,e,r,o)}async function Ci(t,e){const r=j();r.manager&&await r.manager.sendInput(t,e)||await Pi(t,e)}async function Oi(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 Ii(t){j().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 Ri(t,e){j().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 io(o.capabilities),o}async function Fi(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&&j().manager?.unbindSession(t.sessionId)}function oc(){const t=j();t.manager?.close(),t.manager=null,t.inputCapability=null,t.streamCapability=null}function nc(){const t=j();if(t.inputCapability&&t.streamCapability&&!ue(t.inputCapability)&&!ue(t.streamCapability))return;const e=Pt(t)||no,r=Et(e);if(!r)return;const o=Mt();o.isConnectedOrConnecting(r)||(o.configure(r),o.prime())}const _i=t=>{const e=t?.retry;return{maxRetries:e?.maxRetries??3,initialRetryDelay:e?.initialDelayMs??1e3,maxRetryDelay:e?.maxDelayMs??8e3,connectionTimeout:t?.connectionTimeoutMs??1e4}},xi=()=>({async createSession(t){return Mi(t)},connect(t,e,r){const o=Ai(t,e.onEvent,e.onError,_i(r));return{close:()=>o()}},async sendInput(t,e){await Ci(t,e)},async resize(t){await Oi(t.sessionId,t.cols,t.rows)},async close(t){await Ii(t)},async restartSession(t,e){return Ri(t,{cwd:e.cwd??"",cols:e.cols,rows:e.rows})},async forceKill(t){await Fi(t)}}),p="/api/git",ji=1200,Ni=5e3,nr=new Map,be=new Map,ir=new Map,Se=new Map,mt=t=>t.trim();function h(t,e,r){const o={...r};return e&&(o.directory=e),D().api(t,o)}async function Li(t){const e=mt(t),r=Date.now(),o=ir.get(e);if(o&&o.expiresAt>r)return o.value;const n=Se.get(e);if(n)return n;const i=(async()=>{const s=await u(h(`${p}/check`,t));if(!s.ok)throw new Error(`Failed to check git repository: ${s.statusText}`);const c=!!(await s.json()).isGitRepository;return ir.set(e,{value:c,expiresAt:Date.now()+Ni}),c})();Se.set(e,i);try{return await i}finally{Se.get(e)===i&&Se.delete(e)}}async function Bi(t,e){const r=e?.mode,o=r==="light"?`${mt(t)}::light`:mt(t),n=Date.now(),i=nr.get(o);if(i&&i.expiresAt>n)return i.value;const s=be.get(o);if(s)return s;const a=(async()=>{const c=await u(h(`${p}/status`,t,r?{mode:r}:void 0));if(!c.ok)throw new Error(`Failed to get git status: ${c.statusText}`);const d=await c.json();return nr.set(o,{value:d,expiresAt:Date.now()+ji}),d})();be.set(o,a);try{return await a}finally{be.get(o)===a&&be.delete(o)}}async function ic(t){const e=await u(h(`${p}/primary-root`,t));if(!e.ok)throw new Error(`Failed to resolve git primary root: ${e.statusText}`);const r=await e.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:t}}async function sc(t){const e=await u(h(`${p}/toplevel`,t));if(!e.ok)throw new Error(`Failed to resolve git toplevel: ${e.statusText}`);const r=await e.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:t}}async function ac(t,e){const r=await u(h(`${p}/commit-summaries`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:e})});if(!r.ok)throw new Error(`Failed to get git commit summaries: ${r.statusText}`);const o=await r.json().catch(()=>({}));return{commits:Array.isArray(o.commits)?o.commits.map(n=>({sha:typeof n.sha=="string"?n.sha:"",short:typeof n.short=="string"?n.short:"",subject:typeof n.subject=="string"?n.subject:""})).filter(n=>n.sha&&n.short):[]}}async function Ui(t,e){const{path:r,staged:o,contextLines:n}=e;if(!r)throw new Error("path is required to fetch git diff");const i=await u(h(`${p}/diff`,t,{path:r,staged:o?"true":void 0,context:n}));if(!i.ok)throw new Error(`Failed to get git diff: ${i.statusText}`);return i.json()}async function Hi(t,e){const{path:r,staged:o}=e;if(!r)throw new Error("path is required to fetch git file diff");const n=await u(h(`${p}/file-diff`,t,{path:r,staged:o?"true":void 0}));if(!n.ok)throw new Error(`Failed to get git file diff: ${n.statusText}`);return n.json()}async function zi(t,e,r){if(!e)throw new Error("path is required to revert git changes");const o=await u(h(`${p}/revert`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,scope:r?.scope})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to revert git changes")}}async function $i(t,e){await so(t,[e])}async function so(t,e){const r=e.map(n=>n.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to stage git changes");const o=await u(h(`${p}/stage`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to stage git changes")}}async function Gi(t,e){await ao(t,[e])}async function ao(t,e){const r=e.map(n=>n.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to unstage git changes");const o=await u(h(`${p}/unstage`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to unstage git changes")}}async function Wi(t,e,r){await At(t,e,r,"stage")}async function qi(t,e,r){await At(t,e,r,"unstage")}async function Ki(t,e,r){await At(t,e,r,"discard")}async function At(t,e,r,o){if(!e)throw new Error("path is required to apply a git hunk");if(typeof r!="string"||!r.trim())throw new Error("patch is required to apply a git hunk");const n=await u(h(`${p}/apply-hunk`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,patch:r,action:o})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to apply git hunk")}}async function Vi(t){if(!t)return!1;const e=await u(h(`${p}/worktree-type`,t));if(!e.ok)throw new Error(`Failed to detect worktree type: ${e.statusText}`);return!!(await e.json()).linked}async function Ji(t){const e=await u(h(`${p}/branches`,t));if(!e.ok)throw new Error(`Failed to get branches: ${e.statusText}`);return e.json()}async function Qi(t,e){if(!e?.branch)throw new Error("branch is required to delete a branch");const r=await u(h(`${p}/branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete branch")}return r.json()}async function Yi(t,e){if(!e?.branch)throw new Error("branch is required to delete remote branch");const r=await u(h(`${p}/remote-branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete remote branch")}return r.json()}async function Xi(t,e){const r=e?.remote?.trim();if(!r)throw new Error("remote is required to remove a remote");const o=await u(h(`${p}/remotes`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to remove remote")}return o.json()}async function Zi(t,e,r){if(!Array.isArray(e)||e.length===0)throw new Error("No files provided to generate commit message");const o={files:e};r?.zenModel&&(o.zenModel=r.zenModel),r?.providerId&&(o.providerId=r.providerId),r?.modelId&&(o.modelId=r.modelId);const n=await u(h(`${p}/commit-message`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!n.ok){const c=await n.json().catch(()=>({error:n.statusText}));console.error("[git-generation][browser] http error",{status:n.status,statusText:n.statusText,error:c});const d=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${d}`)}const i=await n.json();if(!i?.message||typeof i.message!="object")throw new Error("Malformed commit generation response");const s=typeof i.message.subject=="string"&&i.message.subject.trim().length>0?i.message.subject.trim():"",a=Array.isArray(i.message.highlights)?i.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:s,highlights:a}}}async function es(t,e){const{base:r,head:o,context:n,zenModel:i,providerId:s,modelId:a}=e;if(!r||!o)throw new Error("base and head are required");const c={base:r,head:o};n?.trim()&&(c.context=n.trim()),i&&(c.zenModel=i),s&&(c.providerId=s),a&&(c.modelId=a);const d=await u(h(`${p}/pr-description`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){const m=await d.json().catch(()=>({error:d.statusText}));throw new Error(m.error||"Failed to generate PR description")}const l=await d.json().catch(()=>null),f=typeof l?.title=="string"?l.title:"",y=typeof l?.body=="string"?l.body:"";if(!f&&!y)throw new Error("Malformed PR description response");return{title:f,body:y}}async function sr(t){const e=await u(h(`${p}/worktrees`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to list worktrees")}return e.json()}async function ar(t,e){const r=await u(h(`${p}/worktrees/validate`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to validate worktree")}return r.json()}async function ts(t){const e=await u(h(`${p}/worktrees/bootstrap-status`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to get worktree bootstrap status")}return e.json()}async function rs(t,e){const r=await u(h(`${p}/worktrees/preview`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to preview worktree")}return r.json()}async function cr(t,e){const r=await u(h(`${p}/worktrees`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create worktree")}return r.json()}async function lr(t,e){const r=await u(h(`${p}/worktrees`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e??{})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete worktree")}return r.json()}async function os(t,e,r={}){const o=await u(h(`${p}/commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e,addAll:r.addAll??!1,files:r.files,stageFiles:r.stageFiles})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to create commit")}return o.json()}async function ns(t,e={}){const r=await u(h(`${p}/push`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to push")}return r.json()}async function is(t,e={}){const r=await u(h(`${p}/pull`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to pull")}return r.json()}async function ss(t,e={}){const r=await u(h(`${p}/fetch`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to fetch")}return r.json()}async function as(t){const e=await u(h(`${p}/stashes`,t));if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to list stashes")}return e.json()}async function cs(t,e){const r=await u(h(`${p}/stashes/file-counts`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to count stash files")}return r.json()}async function co(t,e={}){const r=await u(h(`${p}/stash`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to stash changes")}return r.json()}const Ct=async(t,e,r)=>{const o=await u(h(`${p}/${e}`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||`Failed to ${e}`)}return o.json()},ls=(t,e)=>Ct(t,"stash/apply",e),lo=(t,e)=>Ct(t,"stash/pop",e),ds=(t,e)=>Ct(t,"stash/drop",e);async function us(t,e){const r=await u(h(`${p}/checkout`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to checkout branch")}return r.json()}async function fs(t,e,r){const o=await u(h(`${p}/branches`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,startPoint:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to create branch")}return o.json()}async function ps(t,e,r){const o=await u(h(`${p}/branches/rename`,t),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:e,newName:r})});if(!o.ok){const n=await o.json().catch(()=>({error:o.statusText}));throw new Error(n.error||"Failed to rename branch")}return o.json()}async function hs(t,e={}){const r=await u(h(`${p}/log`,t,{maxCount:e.maxCount,from:e.from,to:e.to,file:e.file,all:e.all?"true":void 0}));if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(`Failed to get git log: ${o.error||r.statusText}`)}return r.json()}async function ms(t,e){const r=await u(h(`${p}/commit-files`,t,{hash:e}));if(!r.ok)throw new Error(`Failed to get commit files: ${r.statusText}`);return r.json()}async function cc(t,e,r,o){const n=await u(h(`${p}/commit-file-diff`,t,{hash:e,path:r,binary:o?"true":void 0}));if(!n.ok)throw new Error(`Failed to get commit file diff: ${n.statusText}`);return n.json()}async function ys(){const t=await u(h(`${p}/identities`,void 0));if(!t.ok)throw new Error(`Failed to get git identities: ${t.statusText}`);return t.json()}async function gs(t){const e=await u(h(`${p}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to create git identity")}return e.json()}async function ws(t,e){const r=await u(h(`${p}/identities/${t}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to update git identity")}return r.json()}async function bs(t){const e=await u(h(`${p}/identities/${t}`,void 0),{method:"DELETE"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to delete git identity")}}async function Ss(t){if(!t)return null;const e=await u(h(`${p}/current-identity`,t));if(!e.ok)throw new Error(`Failed to get current git identity: ${e.statusText}`);const r=await e.json();return r?{userName:r.userName??null,userEmail:r.userEmail??null,sshCommand:r.sshCommand??null}:null}async function Ts(t){if(!t)return!1;const e=await u(h(`${p}/has-local-identity`,t));if(!e.ok)throw new Error(`Failed to check local identity: ${e.statusText}`);return(await e.json().catch(()=>null))?.hasLocalIdentity===!0}async function lc(){const t=await u(h(`${p}/global-identity`,void 0));if(!t.ok)throw new Error(`Failed to get global git identity: ${t.statusText}`);const e=await t.json();return!e||!e.userName&&!e.userEmail?null:{userName:e.userName??null,userEmail:e.userEmail??null,sshCommand:e.sshCommand??null}}async function vs(t,e){const r=await u(h(`${p}/set-identity`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to set git identity")}return r.json()}async function dc(){const t=await u(h(`${p}/discover-credentials`,void 0));if(!t.ok)throw new Error(`Failed to discover git credentials: ${t.statusText}`);return t.json()}async function uc(t,e){if(!t)return null;const r=await u(h(`${p}/remote-url`,t,{remote:e}));return r.ok?(await r.json()).url??null:null}async function ks(t){const e=await u(h(`${p}/remotes`,t));if(!e.ok)throw new Error(`Failed to get remotes: ${e.statusText}`);return e.json()}async function Ds(t,e){const r=await u(h(`${p}/rebase`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rebase")}return r.json()}async function Es(t){const e=await u(h(`${p}/rebase/abort`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to abort rebase")}return e.json()}async function Ps(t,e){const r=await u(h(`${p}/merge`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to merge")}return r.json()}async function Ms(t,e){const r=await u(h(`${p}/checkout-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to checkout commit")}return r.json()}async function As(t,e){const r=await u(h(`${p}/cherry-pick`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to cherry-pick")}return r.json()}async function Cs(t,e){const r=await u(h(`${p}/revert-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to revert commit")}return r.json()}async function Os(t,e,r,o){const n=await u(h(`${p}/reset-to-commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:e,mode:r,force:o})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to reset")}return n.json()}async function Is(t){const e=await u(h(`${p}/merge/abort`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to abort merge")}return e.json()}async function Rs(t){const e=await u(h(`${p}/rebase/continue`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to continue rebase")}return e.json()}async function Fs(t){const e=await u(h(`${p}/merge/continue`,t),{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({error:e.statusText}));throw new Error(r.error||"Failed to continue merge")}return e.json()}async function _s(t,e){return await co(t,{message:e?.message}),{success:!0}}async function xs(t){return await lo(t,{ref:"stash@{0}"}),{success:!0}}async function js(t){const e=await u(h(`${p}/conflict-details`,t));if(!e.ok)throw new Error(`Failed to get conflict details: ${e.statusText}`);return e.json()}async function Ns(t,e){const r=await u(`${p}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t,worktreeRoot:e})});if(!r.ok)throw new Error(`Failed to validate worktree directory: ${r.statusText}`);return r.json()}async function Ls(t){const e=await u(`${p}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!e.ok)throw new Error(`Failed to canonicalize worktree state: ${e.statusText}`);return e.json()}const Bs=()=>({checkIsGitRepository:Li,getGitStatus:Bi,getGitDiff:Ui,getGitFileDiff:Hi,revertGitFile:zi,stageGitFile:$i,stageGitFiles:so,unstageGitFile:Gi,unstageGitFiles:ao,stageGitHunk:Wi,unstageGitHunk:qi,revertGitHunk:Ki,isLinkedWorktree:Vi,getGitBranches:Ji,deleteGitBranch:Qi,deleteRemoteBranch:Yi,removeRemote:Xi,generateCommitMessage:Zi,generatePullRequestDescription:es,listGitWorktrees:sr,validateGitWorktree:ar,createGitWorktree:cr,deleteGitWorktree:lr,validateWorktreeDirectory:Ns,canonicalizeWorktreeState:Ls,createGitCommit(t,e,r){return os(t,e,r)},gitPush:ns,gitPull:is,gitFetch:ss,listGitStashes:as,countGitStashFiles:cs,stashGitChanges:co,applyGitStash:ls,popGitStash:lo,dropGitStash:ds,checkoutBranch:us,createBranch:fs,renameBranch:ps,getGitLog(t,e){return hs(t,e)},getCommitFiles:ms,getCurrentGitIdentity:Ss,hasLocalIdentity:Ts,setGitIdentity:vs,getGitIdentities:ys,createGitIdentity:gs,updateGitIdentity:ws,deleteGitIdentity:bs,getRemotes:ks,rebase:Ds,abortRebase:Es,continueRebase:Rs,merge:Ps,abortMerge:Is,continueMerge:Fs,checkoutCommit:Ms,cherryPick:As,revertCommit:Cs,resetToCommit:Os,stash:_s,stashPop:xs,getConflictDetails:js,worktree:{list:sr,validate:ar,bootstrapStatus:ts,preview:rs,create:cr,remove:lr}}),T=t=>t.replace(/\\/g,"/"),Us=(t,e)=>{const r=T(e?.directory||e?.path||t),o=Array.isArray(e?.entries)?e.entries:[];return{directory:r,entries:o.filter(n=>!!(n&&typeof n.name=="string"&&typeof n.path=="string")).map(n=>({name:n.name,path:T(n.path),isDirectory:!!n.isDirectory}))}},x=(t,e)=>{const r=e||t?.();return r?{"x-opencode-directory":r}:void 0},Hs=({urls:t,getDirectory:e})=>({async listDirectory(r,o){const n=T(r),i=new URLSearchParams;n&&i.set("path",n),o?.respectGitignore&&i.set("respectGitignore","true");const s=await u(t.api("/api/fs/list",i),{headers:x(e)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));throw new Error(c.error||"Failed to list directory")}const a=await s.json();return Us(n,a)},async search(r){const o=new URLSearchParams,n=T(r.directory);n&&o.set("directory",n),o.set("query",r.query),o.set("dirs","false"),o.set("type","file"),typeof r.maxResults=="number"&&Number.isFinite(r.maxResults)&&o.set("limit",String(r.maxResults));const i=await u(t.api("/api/find/file",o),{headers:x(e)});if(!i.ok){const c=await i.json().catch(()=>({error:i.statusText}));throw new Error(c.error||"Failed to search files")}const s=await i.json();return(Array.isArray(s)?s:[]).map(c=>({path:T(`${n}/${c}`),preview:[T(c)]}))},async createDirectory(r){const o=T(r),n=await u(t.api("/api/fs/mkdir"),{method:"POST",headers:{"Content-Type":"application/json",...x(e)},body:JSON.stringify({path:o})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to create directory")}const i=await n.json();return{success:!!i?.success,path:typeof i?.path=="string"?T(i.path):o}},async statFile(r,o){const n=T(r),i=new URLSearchParams({path:n});o?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),o?.outsideFileGrant&&i.set("outsideFileGrant",o.outsideFileGrant);const s=await u(t.api("/api/fs/stat",i),{headers:x(e,o?.directory)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));throw new Error(c.error||"Failed to stat file")}const a=await s.json().catch(()=>({}));return{path:typeof a.path=="string"?T(a.path):n,isFile:!!a.isFile,size:typeof a.size=="number"?a.size:0,mtimeMs:typeof a.mtimeMs=="number"?a.mtimeMs:void 0}},async readFile(r,o){const n=T(r),i=new URLSearchParams({path:n});o?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),o?.outsideFileGrant&&i.set("outsideFileGrant",o.outsideFileGrant),o?.optional&&i.set("optional","true");const s=await u(t.api("/api/fs/read",i),{cache:o?.optional?"no-store":"default",headers:x(e,o?.directory)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));throw new Error(c.error||"Failed to read file")}return{content:await s.text(),path:n}},async writeFile(r,o){const n=T(r),i=await u(t.api("/api/fs/write"),{method:"POST",headers:{"Content-Type":"application/json",...x(e)},body:JSON.stringify({path:n,content:o})});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||"Failed to write file")}const s=await i.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?T(s.path):n}},async delete(r){const o=T(r),n=await u(t.api("/api/fs/delete"),{method:"POST",headers:{"Content-Type":"application/json",...x(e)},body:JSON.stringify({path:o})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to delete file")}return{success:!!(await n.json().catch(()=>({}))).success}},async rename(r,o){const n=await u(t.api("/api/fs/rename"),{method:"POST",headers:{"Content-Type":"application/json",...x(e)},body:JSON.stringify({oldPath:r,newPath:o})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to rename file")}const i=await n.json().catch(()=>({}));return{success:!!i.success,path:typeof i.path=="string"?T(i.path):o}},async revealPath(r){const o=await u(t.api("/api/fs/reveal"),{method:"POST",headers:{"Content-Type":"application/json",...x(e)},body:JSON.stringify({path:T(r)})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to reveal path")}return{success:!!(await o.json().catch(()=>({}))).success}},async downloadFile(r){const o=T(r),n=await u("/api/fs/raw",{query:{path:o,download:!0},headers:x(e)});if(!n.ok)throw new Error(`Download failed (${n.status})`);const i=await n.blob(),s=URL.createObjectURL(i),a=document.createElement("a");a.href=s,a.download=o.split("/").pop()||"file",document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(s),100)}}),dr="/api/config/settings",zs="/api/config/reload",ur=t=>!t||typeof t!="object"?{}:t,$s=()=>({async load(){const t=await u(dr,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load settings: ${t.statusText}`);return{settings:ur(await t.json().catch(()=>({}))),source:"web"}},async save(t){const e=await u(dr,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!e.ok){const o=await e.json().catch(()=>({error:e.statusText}));throw new Error(o.error||"Failed to save settings")}return ur(await e.json().catch(()=>({})))},async restartOpenCode(){const t=await u(zs,{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}}}),Gs=()=>({async requestDirectoryAccess(t){return{success:!0,path:t.path}},async startAccessingDirectory(t){return{success:!0}},async stopAccessingDirectory(t){return{success:!0}}}),Ws=1500,yt=5e3,qs="openchamber-notification-claim:",se=new Map,Ks=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Vs=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("|")},Js=t=>{for(const[e,r]of se)t-r>yt&&se.delete(e)},Qs=t=>{const e=Vs(t);if(!e)return!0;const r=Date.now();Js(r);const o=se.get(e)??0;if(r-o<yt)return!1;try{if(typeof window<"u"&&window.localStorage){const n=`${qs}${e}`,i=Number(window.localStorage.getItem(n)??"0");if(Number.isFinite(i)&&r-i<yt)return se.set(e,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(n),window.localStorage.setItem(n,String(r))}}catch{}return se.set(e,r),!0},uo=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),Ws)})])??t}catch{return t}},Ys=async t=>{const e=await uo();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}},Xs=async()=>{const t=await uo();if(!t||!("pushManager"in t)||!t.pushManager)return!1;try{return!!await t.pushManager.getSubscription()}catch{return!1}},Zs=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(!Ks()&&await Xs()||!Qs(t))return!0;try{return await Ys(t)||new Notification(t?.title??"OpenChamber",{body:t?.body,tag:t?.tag}),!0}catch(e){return console.warn("Failed to send notification",e),!1}},ea=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}},ta=()=>({async notifyAgentCompletion(t){return await ea(t)||await Zs(t)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),ra=()=>({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()}}),Te=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 Te("/api/push/vapid-public-key")},async subscribe(t){return Te("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async unsubscribe(t){return Te("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async setVisibility(t){return Te("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})}}),S=async t=>await t.json().catch(()=>null),na=({urls:t})=>({async authStatus(){const e=await u("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await S(e);if(!e.ok||!r)throw new Error(r?.error||e.statusText||"Failed to load GitHub status");return r},async authStart(){const e=await u("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),r=await S(e);if(!e.ok||!r||!("deviceCode"in r))throw new Error(r?.error||e.statusText||"Failed to start GitHub auth");return r},async authComplete(e){const r=await u("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:e})}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to complete GitHub auth");return o},async authDisconnect(){const e=await u("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),r=await S(e);if(!e.ok)throw new Error(r?.error||e.statusText||"Failed to disconnect GitHub");return{removed:!!r?.removed}},async authActivate(e){const r=await u("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:e})}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to activate GitHub account");return o},async authSetGhCliDisabled(e){const r=await u("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:e})}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to update gh CLI setting");return{disabled:!!o.disabled}},async me(){const e=await u("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),r=await S(e);if(!e.ok||!r)throw new Error(r?.error||e.statusText||"Failed to fetch GitHub user");return r},async prStatus(e,r,o,n){const i=new URLSearchParams({directory:e,branch:r,...o?{remote:o}:{},...n?.force?{force:"true"}:{}}),s=await u(`/api/github/pr/status?${i.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await S(s);if(!s.ok||!a)throw new Error(a?.error||s.statusText||"Failed to load PR status");return a},async prCreate(e){const r=await u("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to create PR");return o},async prUpdate(e){const r=await u("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to update PR");return o},async prMerge(e){const r=await u("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to merge PR");return o},async prReady(e){const r=await u("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to mark PR ready");return o},async repoUpstream(e){const r=await u(`/api/github/repo/upstream?directory=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await S(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to detect upstream repo");return o},async repoBranches(e,r){const o=await u(`/api/github/repo/branches?owner=${encodeURIComponent(e)}&repo=${encodeURIComponent(r)}`,{method:"GET",headers:{Accept:"application/json"}}),n=await S(o);if(!o.ok||!n)throw new Error(n?.error||o.statusText||"Failed to fetch repo branches");return n.branches??[]},async prsList(e,r){const o=r?.page??1,n=new URLSearchParams({directory:e,page:String(o)});r?.query&&n.set("query",r.query);const i=await u(`/api/github/pulls/list?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),s=await S(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load pull requests");return s},async prContext(e,r,o){const n=new URLSearchParams({directory:e,number:String(r)});o?.includeDiff&&n.set("diff","1"),o?.includeCheckDetails&&n.set("checkDetails","1"),o?.sourceRepo?.owner&&o.sourceRepo.repo&&(n.set("owner",o.sourceRepo.owner),n.set("repo",o.sourceRepo.repo));const i=await u(t.api("/api/github/pulls/context",n),{method:"GET",headers:{Accept:"application/json"}}),s=await S(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load pull request context");return s},async issuesList(e,r){const o=r?.page??1,n=new URLSearchParams({directory:e,page:String(o)});r?.query&&n.set("query",r.query);const i=await u(`/api/github/issues/list?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),s=await S(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issues");return s},async issueGet(e,r,o){const n=new URLSearchParams({directory:e,number:String(r)});o?.sourceRepo?.owner&&o.sourceRepo.repo&&(n.set("owner",o.sourceRepo.owner),n.set("repo",o.sourceRepo.repo));const i=await u(t.api("/api/github/issues/get",n),{method:"GET",headers:{Accept:"application/json"}}),s=await S(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issue");return s},async issueComments(e,r,o){const n=new URLSearchParams({directory:e,number:String(r)});o?.sourceRepo?.owner&&o.sourceRepo.repo&&(n.set("owner",o.sourceRepo.owner),n.set("repo",o.sourceRepo.repo));const i=await u(t.api("/api/github/issues/comments",n),{method:"GET",headers:{Accept:"application/json"}}),s=await S(i);if(!i.ok||!s)throw new Error(s?.error||i.statusText||"Failed to load issue comments");return s}}),ve=async t=>await t.json().catch(()=>null),ia=()=>({async listClients(){const t=await u("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),e=await ve(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 ve(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 ve(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 ve(t);if(!t.ok||!e)throw new Error(e?.error||t.statusText||"Failed to clear revoked clients");return e}}),sa=()=>({api:(...t)=>D().api(...t),authenticatedAsset:(...t)=>D().authenticatedAsset(...t),auth:(...t)=>D().auth(...t),health:(...t)=>D().health(...t),rawFile:(...t)=>D().rawFile(...t),sse:(...t)=>D().sse(...t),websocket:(...t)=>D().websocket(...t)}),aa=(t={})=>{const e=t.urls??St();Mo(e);const r=sa();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:xi(),git:Bs(),files:Hs({urls:r,getDirectory:()=>ht.getState().currentDirectory}),settings:$s(),permissions:Gs(),notifications:ta(),github:na({urls:r}),push:oa(),clientAuth:ia(),tools:ra()}},ca=(t,e)=>{if(!t||!e)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}},fc=()=>{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=Tr({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return jo({apiBaseUrl:t,runtimeKey:ca(t,r)?"local":null}),gr(e||null),wt(t||void 0).catch(()=>{}),xo(),aa({urls:o})};export{Pa as $,Fi as A,oe as B,Sa as C,q as D,Ba as E,Ua as F,si as G,Ia as H,wa as I,No as J,Ca as K,Aa as L,Xa as M,Za as N,Ya as O,G as P,Fa as Q,Mn as R,Ho as S,Uo as T,ua as U,Qa as V,La as W,oc as X,fa as Y,pa as Z,Go as _,vt as a,is as a$,Da as a0,Ea as a1,Ar as a2,da as a3,Nn as a4,Fn as a5,Na as a6,mn as a7,bn as a8,yn as a9,os as aA,gs as aB,cr as aC,Qi as aD,bs as aE,lr as aF,Yi as aG,dc as aH,ds as aI,cc as aJ,ms as aK,js as aL,Ss as aM,Ji as aN,ac as aO,Ui as aP,Hi as aQ,ys as aR,hs as aS,Bi as aT,ts as aU,lc as aV,uc as aW,ks as aX,ar as aY,sr as aZ,ss as a_,Sn as aa,xn as ab,ze as ac,ma as ad,Ma as ae,ya as af,ba as ag,va as ah,ka as ai,un as aj,ai as ak,_a as al,Le as am,Be as an,Is as ao,Es as ap,ls as aq,Ls as ar,Li as as,us as at,Ms as au,As as av,Fs as aw,Rs as ax,cs as ay,fs as az,Q as b,ns as b0,Ts as b1,Vi as b2,as as b3,Ps as b4,lo as b5,rs as b6,Ds as b7,Xi as b8,ps as b9,$a as bA,Ka as bB,Ga as bC,za as bD,Wa as bE,Xr as bF,qa as bG,ec as bH,tc as bI,Ta as bJ,rc as bK,gn as bL,wn as bM,nc as bN,Os as ba,ic as bb,sc as bc,Cs as bd,zi as be,Ki as bf,vs as bg,$i as bh,so as bi,Wi as bj,_s as bk,co as bl,xs as bm,Gi as bn,ao as bo,qi as bp,ws as bq,Ns as br,E as bs,ja as bt,hn as bu,he as bv,Qe as bw,Zr as bx,Ir as by,Ha as bz,fc as c,ha as d,u as e,N as f,D as g,Or as h,Ja as i,I as j,Ra as k,Oa as l,Wo as m,xa as n,B as o,Ii as p,Ue as q,wt as r,Va as s,Ai as t,ht as u,Cr as v,He as w,C as x,wr as y,ga as z};