openfox 1.6.37 → 1.6.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{auto-compaction-CQ66MD6K.js → auto-compaction-SCLHKKGA.js} +7 -7
- package/dist/{chat-handler-EJR4GKYO.js → chat-handler-7ARMDWRH.js} +11 -11
- package/dist/{chunk-26PIZX2A.js → chunk-5NJ5NQH5.js} +5 -5
- package/dist/{chunk-XKFPU2FA.js → chunk-7JPKRM6M.js} +2 -2
- package/dist/{chunk-AV45GQ7B.js → chunk-BHSTSA7U.js} +3 -3
- package/dist/{chunk-3EHGGBWE.js → chunk-BLNFJ22S.js} +7 -1
- package/dist/{chunk-VGFTDBWZ.js → chunk-CRSOJ2YA.js} +2 -2
- package/dist/{chunk-WJ2DPSZK.js → chunk-DSI2ZSZQ.js} +31 -31
- package/dist/{chunk-EEPU4INU.js → chunk-LIMBYVO4.js} +192 -14
- package/dist/{chunk-ZGTXED6Q.js → chunk-NBBX64KC.js} +2 -2
- package/dist/{chunk-RN2O6JK7.js → chunk-O2BOWZKC.js} +2 -2
- package/dist/{chunk-VFHCB5MC.js → chunk-TBSTW3PW.js} +4 -4
- package/dist/{chunk-PMDJEJYY.js → chunk-YVQ6DP5Y.js} +107 -15
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/{events-LI4NAFRZ.js → events-FHPSSSE4.js} +4 -4
- package/dist/{folding-HRZMWP4H.js → folding-NEZWWL7K.js} +4 -2
- package/dist/{orchestrator-PCWZF3E5.js → orchestrator-FKVRAIIA.js} +8 -8
- package/dist/package.json +1 -1
- package/dist/{processor-7L64YPQC.js → processor-KR5GNW3S.js} +7 -7
- package/dist/{project-creator-HY32FPFV.js → project-creator-LASKNQPA.js} +3 -3
- package/dist/{projects-GSMMEVSO.js → projects-HEUOWNSR.js} +3 -3
- package/dist/{protocol-BYM6rZvW.d.ts → protocol-Ct6VfOIJ.d.ts} +1 -0
- package/dist/{serve-VZE2CPZ2.js → serve-OGLLAEMY.js} +10 -10
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +9 -9
- package/dist/{settings-3K6P2JN6.js → settings-TWK27GYE.js} +3 -3
- package/dist/shared/index.d.ts +2 -2
- package/dist/{tools-25TQ5NQY.js → tools-6XOZHTF7.js} +7 -7
- package/dist/web/assets/{index-DapVnjIC.js → index-BCHSC7BY.js} +1 -1
- package/dist/web/assets/index-D0LRgk0o.css +32 -0
- package/dist/web/index.html +2 -2
- package/dist/web/sw.js +1 -1
- package/package.json +1 -1
- package/dist/web/assets/index-CWFxAdkp.css +0 -32
|
@@ -54,7 +54,7 @@ Error generating stack: `+h.message+`
|
|
|
54
54
|
*
|
|
55
55
|
* This source code is licensed under the MIT license found in the
|
|
56
56
|
* LICENSE file in the root directory of this source tree.
|
|
57
|
-
*/var kx;function i1(){if(kx)return Md;kx=1;var e=Zl();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var i=typeof Object.is=="function"?Object.is:r,s=e.useState,c=e.useEffect,u=e.useLayoutEffect,f=e.useDebugValue;function l(m,b){var _=b(),E=s({inst:{value:_,getSnapshot:b}}),C=E[0].inst,y=E[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),f(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!i(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:l;return Md.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Md}var Ex;function s1(){return Ex||(Ex=1,Od.exports=i1()),Od.exports}var a1=s1();const o1=KS.useInsertionEffect,l1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",c1=l1?P.useLayoutEffect:P.useEffect,u1=o1||c1,vb=e=>{const r=P.useRef([e,(...i)=>r[0](...i)]).current;return u1(()=>{r[0]=e}),r[1]},d1="popstate",jh="pushState",Nh="replaceState",h1="hashchange",jx=[d1,jh,Nh,h1],f1=e=>{for(const r of jx)addEventListener(r,e);return()=>{for(const r of jx)removeEventListener(r,e)}},bb=(e,r)=>a1.useSyncExternalStore(f1,e,r),Nx=()=>location.search,p1=({ssrSearch:e}={})=>bb(Nx,e!=null?()=>e:Nx),Tx=()=>location.pathname,m1=({ssrPath:e}={})=>bb(Tx,e!=null?()=>e:Tx),g1=(e,{replace:r=!1,state:i=null}={})=>history[r?Nh:jh](i,"",e),x1=(e={})=>[m1(e),g1],Ax=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ax]>"u"){for(const e of[jh,Nh]){const r=history[e];history[e]=function(){const i=r.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),i}}Object.defineProperty(window,Ax,{value:!0})}const v1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",yb=(e="")=>e==="/"?"":e,b1=(e,r)=>e[0]==="~"?e.slice(1):yb(r)+e,y1=(e="",r)=>v1(Dx(yb(e)),Dx(r)),Dx=e=>{try{return decodeURI(e)}catch{return e}},_b={hook:x1,searchHook:p1,parser:r1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,i)=>e(r,i)},Sb=P.createContext(_b),Hs=()=>P.useContext(Sb),wb={},Cb=P.createContext(wb),_1=()=>P.useContext(Cb),Ql=e=>{const[r,i]=e.hook(e);return[y1(e.base,r),vb((s,c)=>e.aroundNav(i,b1(s,e.base),c))]},ur=()=>Ql(Hs()),Th=(e,r,i,s)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",s),f=c.exec(i)||[],[l,...d]=f;return l!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):f.groups;let g={...d};return p&&Object.assign(g,p),g})(),...s?[l]:[]]:[!1,null]},Ah=e=>Th(Hs().parser,e,ur()[0]),S1=({children:e,...r})=>{var g,m,b;const i=Hs(),s=r.hook?_b:i;let c=s;const[u,f=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=f,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let l=P.useRef({}),d=l.current,p=d;for(let _ in s){const E=_==="base"?s[_]+(r[_]??""):r[_]??s[_];d===p&&E!==p[_]&&(l.current=p={...p}),p[_]=E,(E!==s[_]||E!==c[_])&&(c=p)}return P.createElement(Sb.Provider,{value:c,children:e})},Lx=({children:e,component:r},i)=>r?P.createElement(r,{params:i}):typeof e=="function"?e(i):e,w1=e=>{let r=P.useRef(wb);const i=r.current;return r.current=Object.keys(e).length!==Object.keys(i).length||Object.entries(e).some(([s,c])=>c!==i[s])?e:i},Oa=({path:e,nest:r,match:i,...s})=>{const c=Hs(),[u]=Ql(c),[f,l,d]=i??Th(c.parser,e,u,r),p=w1({..._1(),...l});if(!f)return null;const g=d?P.createElement(S1,{base:d},Lx(s,p)):Lx(s,p);return P.createElement(Cb.Provider,{value:p,children:g})},Mn=P.forwardRef((e,r)=>{const i=Hs(),[s,c]=Ql(i),{to:u="",href:f=u,onClick:l,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...E}=e,C=vb(x=>{x.ctrlKey||x.metaKey||x.altKey||x.shiftKey||x.button!==0||(l==null||l(x),x.defaultPrevented||(x.preventDefault(),c(f,e)))}),y=i.hrefs(f[0]==="~"?f.slice(1):i.base+f,i);return d&&P.isValidElement(p)?P.cloneElement(p,{onClick:C,href:y}):P.createElement("a",{...E,onClick:C,href:y,className:g!=null&&g.call?g(s===f):g,children:p,ref:r})}),kb=e=>Array.isArray(e)?e.flatMap(r=>kb(r&&r.type===P.Fragment?r.props.children:r)):[e],C1=({children:e,location:r})=>{const i=Hs(),[s]=Ql(i);for(const c of kb(e)){let u=0;if(P.isValidElement(c)&&(u=Th(i.parser,c.props.path,r||s,c.props.nest))[0])return P.cloneElement(c,{match:u})}return null},Rx=e=>{let r;const i=new Set,s=(p,g)=>{const m=typeof p=="function"?p(r):p;if(!Object.is(m,r)){const b=r;r=g??(typeof m!="object"||m===null)?m:Object.assign({},r,m),i.forEach(_=>_(r,b))}},c=()=>r,l={setState:s,getState:c,getInitialState:()=>d,subscribe:p=>(i.add(p),()=>i.delete(p))},d=r=e(s,c,l);return l},k1=(e=>e?Rx(e):Rx),E1=e=>e;function j1(e,r=E1){const i=dn.useSyncExternalStore(e.subscribe,dn.useCallback(()=>r(e.getState()),[e,r]),dn.useCallback(()=>r(e.getInitialState()),[e,r]));return dn.useDebugValue(i),i}const Ox=e=>{const r=k1(e),i=s=>j1(r,s);return Object.assign(i,r),i},Yn=(e=>e?Ox(e):Ox);async function ke(e,r={}){const i=localStorage.getItem("openfox_token"),s={...r.headers instanceof Headers?Object.fromEntries(r.headers.entries()):r.headers,...i?{"x-session-token":i}:{}};return fetch(e,{...r,headers:s})}function N1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Eb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class T1{constructor(r){ar(this,"ws",null);ar(this,"handlers",new Set);ar(this,"statusHandler",null);ar(this,"baseUrl");ar(this,"isReconnecting",!1);ar(this,"connectingPromise",null);ar(this,"lastCloseCode",0);ar(this,"reconnectAttempts",0);ar(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const i=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${i}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,i;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((s,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const f=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(f),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),s()},this.ws.onclose=l=>{var d,p,g;clearTimeout(f),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(f),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);N1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,i){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=Eb(),c={id:s,type:r,payload:i};return this.ws.send(JSON.stringify(c)),s}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const A1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,qt=new T1(A1),di=async(e,r,i)=>{try{const s=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}};function jb(e){let r=null;function i(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return i}let El=[];const cr=Yn()((e,r)=>{function i(){if(El.length===0)return;const c=El;El=[],e(u=>({logs:[...u.logs,...c]}))}const s=jb(i);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:f,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:f.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const f=c.payload;if(f.workdir!==u)return;El.push({stream:f.stream,content:f.content}),s();break}case"devServer.state":{const f=c.payload;if(f.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:f.state,errorMessage:f.errorMessage}:l.status}));break}}}}});function D1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function Mx(e,r,i){const s=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){const c=await s.json();throw new Error(c.error??"Failed to update model")}return s.json()}function Ix(e,r,i,s){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===i?{...u,...s,source:"user"}:u)}:c)}const L1=3e4;function R1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const At=Yn((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const i=await ke("/api/config");if(!i.ok)throw new Error("Failed to fetch config");const s=await i.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(i){e({error:i instanceof Error?i.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const i=await ke("/api/model/refresh",{method:"POST"});if(!i.ok)throw new Error("Failed to refresh model");const s=await i.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(i){console.error("Failed to refresh model:",i)}},activateProvider:async i=>{const{activeProviderId:s,providers:c}=r();if(i===s)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${i}/activate`,{method:"POST"});if(!u.ok){const l=await u.json();throw new Error(l.error??"Failed to activate provider")}const f=await u.json();return e({activeProviderId:f.activeProviderId,model:f.model,backend:f.backend,providers:c.map(l=>({...l,isActive:l.id===f.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(i,s)=>{const{providers:c}=r();e({activeProviderId:i,model:s,defaultModelSelection:`${i}/${s}`,providers:c.map(u=>({...u,isActive:u.id===i}))})},updateModelContext:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,{contextWindow:c}),{providers:f}=r();return e({providers:Ix(f,i,s,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,c),{providers:f}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...D1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0})};return e({providers:Ix(f,i,s,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async i=>{e({activating:!0,error:null});try{const s=await ke(`/api/providers/${i}/refresh`,{method:"POST"});if(!s.ok){const f=await s.json();throw new Error(f.error??"Failed to refresh models")}const c=await s.json(),{providers:u}=r();return e({providers:u.map(f=>f.id===i?{...f,models:c.models}:f),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:i,refreshModel:s}=r();if(i)return;const c=setInterval(()=>{s()},L1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:i}=r();i&&(clearInterval(i),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:i,activeProviderId:s}=r();return i.find(c=>c.id===s)},getModelContext:i=>{const{providers:s,activeProviderId:c}=r(),u=s.find(l=>l.id===c);if(!u)return 2e5;const f=u.models.find(l=>l.id===i);return(f==null?void 0:f.contextWindow)??2e5}})),Vt=Yn((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await ke("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(i,s)=>{try{const c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i,workdir:s})});if(!c.ok)return null;const u=await c.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async i=>{try{const s=await ke(`/api/projects/${i}`);if(!s.ok)return null;const c=await s.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(i,s)=>{var c;try{const u=await ke(`/api/projects/${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok)return null;const f=await u.json();return((c=r().currentProject)==null?void 0:c.id)===i&&e({currentProject:f.project}),await r().listProjects(),f.project}catch{return null}},deleteProject:async i=>{var s;try{return(await ke(`/api/projects/${i}`,{method:"DELETE"})).ok?(await r().listProjects(),((s=r().currentProject)==null?void 0:s.id)===i&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let jl=[];const Va=Yn()((e,r)=>{function i(){if(jl.length===0)return;const c=jl;jl=[],e(u=>{const f={...u.logs};for(const l of c){const d=f[l.processId]??[];f[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:f}})}const s=jb(i);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(f=>({processes:f.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(f=>f.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([f])=>f!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,f)=>{jl.push({processId:c,stream:u,content:f}),s()},setLogs:(c,u)=>e(f=>({logs:{...f.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:f,name:l,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:f,sessionId:"",name:l,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const f=u.processId,l=u.stream,d=u.content;r().appendLog(f,l,d);break}case"backgroundProcess.exited":{const f=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===f?{...p,status:"exited",exitCode:l}:p)}));break}case"backgroundProcess.removed":{const f=u.processId;r().removeProcess(f);break}}}}}),Et={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars"};function Nl(e,r){return i=>({loading:{...i.loading,[e]:r}})}function Bx(e,r){return i=>({settings:{...i.settings,[e]:r},loading:{...i.loading,[e]:!1}})}const O1=[Et.DISPLAY_SHOW_THINKING,Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Et.DISPLAY_SHOW_STATS,Et.DISPLAY_SHOW_AGENT_DEFINITIONS,Et.DISPLAY_SHOW_WORKFLOW_BARS];function Nb(){return{showThinking:en(e=>e.settings[Et.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:en(e=>e.settings[Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:en(e=>e.settings[Et.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:en(e=>e.settings[Et.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:en(e=>e.settings[Et.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true"}}const en=Yn(e=>({settings:{},loading:{},getSetting:async r=>{e(Nl(r,!0));try{const s=await(await ke(`/api/settings/${r}`)).json();return e(Bx(r,s.value??"")),s.value}catch{return e(Nl(r,!1)),null}},setSetting:async(r,i)=>{e(Nl(r,!0));try{const c=await(await ke(`/api/settings/${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:i})})).json();e(Bx(r,c.value??""))}catch{e(Nl(r,!1))}}})),M1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],I1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Tb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ci={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},Ab={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ch={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ci},waiting_for_user:{...ci},phase_done:{...ci},phase_blocked:{...ci},new_message:{...Ab}},agentOverrides:{}};function Db(e,r,i){var u;const s=e.events[r];if(!i)return s;const c=(u=e.agentOverrides[i])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??s.soundEnabled,browserNotification:c.browserNotification??s.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:s.customSoundUrl}:s}const Oi=Yn((e,r)=>({settings:ch,loaded:!1,load:()=>{en.getState().getSetting(Et.NOTIFICATION_SETTINGS);const s=en.subscribe(u=>{const f=u.settings[Et.NOTIFICATION_SETTINGS];if(f!==void 0)try{const l=JSON.parse(f);e({settings:zx(l),loaded:!0})}catch{e({loaded:!0})}}),c=en.getState().settings[Et.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:zx(u),loaded:!0})}catch{e({loaded:!0})}return s},update:i=>{e({settings:i}),Id(i)},updateEvent:(i,s)=>{const c=r().settings,u={...c,events:{...c.events,[i]:{...c.events[i],...s}}};e({settings:u}),Id(u)},updateAgentOverride:(i,s,c)=>{var d;const u=r().settings,f={...u.agentOverrides};if(c===null){if(f[i]){const p={...f[i]};delete p[s],Object.keys(p).length===0?delete f[i]:f[i]=p}}else f[i]={...f[i],[s]:{...((d=f[i])==null?void 0:d[s])??{},...c}};const l={...u,agentOverrides:f};e({settings:l}),Id(l)}}));function Id(e){en.getState().setSetting(Et.NOTIFICATION_SETTINGS,JSON.stringify(e))}function zx(e){var r,i,s,c,u;return{soundEnabled:e.soundEnabled??ch.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ch.browserNotificationEnabled,events:{complete:{...ci,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ci,...(i=e.events)==null?void 0:i.waiting_for_user},phase_done:{...ci,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...ci,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Ab,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Hx=new Map;function B1(e){let r=Hx.get(e);return r||(r=new Audio(e),r.volume=.5,Hx.set(e,r)),r}let Lb=typeof Notification<"u"?Notification.permission:"denied";function z1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Lb=e,e))}const H1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},P1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function F1(e){typeof Notification>"u"||Lb==="granted"&&(document.hasFocus()||new Notification(H1[e],{body:P1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function oo(e,r){const{settings:i}=Oi.getState(),s=Db(i,e,r);if(i.soundEnabled&&s.soundEnabled){const c=s.customSoundUrl??Tb[e],u=B1(c);u.currentTime=0,u.play().catch(()=>{})}i.browserNotificationEnabled&&s.browserNotification&&F1(e)}const U1=e=>oo("complete",e),$1=e=>oo("phase_done",e),q1=e=>oo("phase_blocked",e),Px=e=>oo("waiting_for_user",e),W1=e=>oo("new_message",e);let Ma=!1,or=null;const Bd=new Set,$t={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ms=null,un=null;function zd(){Ms===null&&(Ms=requestAnimationFrame(()=>{Ms=null,un==null||un()}))}function Ai(){Ms!==null&&(cancelAnimationFrame(Ms),Ms=null)}function zt(e,r){return r!==null&&e.sessionId===r}function G1(e,r,i){return e.id!==void 0||zt(e,r)||i===!0&&e.sessionId!==void 0}function V1(e,r){return e.includes(r)?e:[...e,r]}function Ia(e,r){return e.filter(i=>i!==r)}function K1(e,r){const i=e.find(c=>c.id===r.id),s=i?{...i,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return i?e.map(c=>c.id===r.id?s:c):[s,...e]}function Y1(e,r,i){return e.map(s=>{const c=(i==null?void 0:i.id)===s.id?i:null,u=r.find(f=>f.id===s.id);return{...s,title:s.title??(u==null?void 0:u.title),mode:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??s.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??s.phase,isRunning:(c==null?void 0:c.isRunning)??(u==null?void 0:u.isRunning)??s.isRunning,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}const Fx=new Map;function Wa(e,r){var u;const i=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,s=e.sessions.find(f=>f.id===r),c=(i==null?void 0:i.mode)??(s==null?void 0:s.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function X1(e,r){if(e.type==="chat.done"){const i=e.payload,s=Wa(r,e.sessionId),c=i.agentType??s;i.reason==="complete"&&U1(c),i.reason==="waiting_for_user"&&Px(c);return}if(e.type==="chat.path_confirmation"){const i=Wa(r,e.sessionId);Px(i);return}if(e.type==="task.completed"){const i=Wa(r,e.sessionId);$1(i);return}if(e.type==="phase.changed"&&e.sessionId){const i=e.payload,s=Fx.get(e.sessionId)??null;if(Fx.set(e.sessionId,i.phase),s===i.phase)return;const c=Wa(r,e.sessionId);i.phase==="blocked"&&q1(c)}}const Ce=Yn((e,r)=>(un=()=>{const i=$t;if(!i.messageId)return;const s=i.deltaContent.length>0,c=i.thinkingContent.length>0,u=i.toolOutput.length>0;if(!s&&!c&&!u)return;const f=i.deltaContent,l=i.thinkingContent,d=i.toolOutput;i.deltaContent="",i.thinkingContent="",i.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===i.messageId){let b={...g};if(s&&(b.content=b.content+f),c&&(b.thinkingContent=(b.thinkingContent??"")+l),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(x=>x.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(x=>({stream:x.stream,content:x.content}))]})});const E=d.filter(C=>!_.has(C.callId));E.length>0&&$t.toolOutput.push(...E)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var x;if(C.id!==i.messageId)return C;const y=(x=C.toolCalls)==null?void 0:x.map(v=>{const S=d.filter(j=>j.callId===v.id);return S.length===0?v:(b.add(v.id),{...v,streamingOutput:[...v.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content}))]})});return{...C,toolCalls:y}}),E=d.filter(C=>!b.has(C.callId));return E.length>0&&$t.toolOutput.push(...E),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{if(r().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(s&&!qt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}qt.onStatusChange(c=>{var u;if(e({connectionStatus:c}),c==="connected"){r().listSessions(void 0);const f=(u=r().currentSession)==null?void 0:u.id;f&&r().loadSession(f)}});try{if(await qt.connect(),!Ma){Ma=!0;const c=r().handleServerMessage;or=qt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=qt.getLastCloseCode();if(!qt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async i=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:c}=await s.json();qt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Vt.getState(),{fetchConfig:f}=At.getState();u(),f(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{qt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(i,s)=>{try{e({pendingSessionCreate:!0});const c=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:i,title:s})});if(!c.ok)return e({pendingSessionCreate:!1}),null;const u=await c.json();return qt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async i=>{try{const s=r().currentSession;!s||s.id!==i?(Ai(),e({currentSession:null,unreadSessionIds:Ia(r().unreadSessionIds,i),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:Ia(r().unreadSessionIds,i)});const c=await ke(`/api/sessions/${i}`);if(!c.ok)return;const u=await c.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),qt.send("session.load",{sessionId:i});try{const f=await ke(`/api/sessions/${i}/background-processes`);if(f.ok){const l=await f.json();Va.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(i,s=20)=>{try{const c=new URLSearchParams;c.set("limit",String(s)),i&&c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e({sessions:f.sessions??[],sessionsHasMore:i?f.hasMore??!1:!0})}catch{}},loadMoreSessions:async i=>{const s=r();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(s.sessions.length)),c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e(l=>({sessions:[...l.sessions,...f.sessions??[]],sessionsHasMore:f.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async i=>{var s;try{return(await ke(`/api/sessions/${i}`,{method:"DELETE"})).ok?(await r().listSessions(),((s=r().currentSession)==null?void 0:s.id)===i&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async i=>{try{return(await ke(`/api/projects/${i}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Ai(),e(i=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:i.currentSession?Ia(i.unreadSessionIds,i.currentSession.id):i.unreadSessionIds}))},sendMessage:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},stopGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i&&!r().abortInProgress){Ai(),un==null||un(),e({abortInProgress:!0});try{await ke(`/api/sessions/${i}/stop`,{method:"POST"})}catch(c){console.error("Error stopping generation:",c)}}},continueGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i){e({streamingMessageId:null});try{await ke(`/api/sessions/${i}/continue`,{method:"POST"})}catch(c){console.error("Error continuing generation:",c)}}},launchRunner:(i,s,c)=>{e({streamingMessageId:null});const u={};i!=null&&i.trim()&&(u.content=i),s&&s.length>0&&(u.attachments=s),c&&(u.workflowId=c),qt.send("runner.launch",u)},switchMode:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:i})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:i})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(i,s,c)=>{e({streamingMessageId:null});const u={};i&&(u.workflowId=i),s!=null&&s.trim()&&(u.content=s),c&&c.length>0&&(u.attachments=c),qt.send("mode.accept",u)},editCriteria:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:i})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{qt.send("context.compact",{})},setSessionProvider:async(i,s)=>{var c;try{const u=(c=r().currentSession)==null?void 0:c.id;if(!u)return null;const f=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:i,...s?{model:s}:{}})});if(!f.ok)return null;const l=await f.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:i=>{e({contextState:i})},updateSubAgentContextState:(i,s)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[i]:s}}))},clearSubAgentContextState:i=>{e(s=>{const c={...s.subAgentContextStates};return delete c[i],{subAgentContextStates:c}})},confirmPath:async(i,s,c=!1)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,approved:s,alwaysAllow:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(i,s)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,answer:s})})}catch(f){console.error("Error answering question:",f)}e({pendingQuestion:null})}},queueAsap:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const f=await(await ke(`/api/sessions/${s}/queue/${i}`,{method:"DELETE"})).json();f.queueState&&e({queuedMessages:f.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:i=>{var f,l,d,p,g,m,b,_,E,C,y,x,v,S,j,T,N,D,A,I,B,q,V,W;const s=r();X1(i,s);const c=((f=s.currentSession)==null?void 0:f.id)??null,u=()=>{const O=i.sessionId;!O||O===c||e(F=>({unreadSessionIds:V1(F.unreadSessionIds,O)}))};switch(i.type){case"session.state":{const O=i.payload;if(!G1(i,c,s.pendingSessionCreate))break;Ai();const F=O.messages.find(L=>L.isStreaming)??null,H=r().pendingSessionCreate===!0,Z=O.pendingConfirmations??[],M=s.pendingPathConfirmation??(Z.length>0?Z[0]??null:null);if(e({currentSession:O.session,sessions:K1(r().sessions,O.session),unreadSessionIds:Ia(r().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(F==null?void 0:F.id)??null,streamingMessage:F,currentTodos:[],pendingPathConfirmation:M,error:null,...H?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId&&O.session.providerModel){const L=At.getState();L.providers.find($=>$.id===O.session.providerId)&&L.syncFromSession(O.session.providerId,O.session.providerModel)}break}case"session.list":{const O=i.payload;e(F=>({sessions:Y1(O.sessions,F.sessions,F.currentSession)}));break}case"session.deleted":{const O=i.payload;e(F=>({unreadSessionIds:Ia(F.unreadSessionIds,O.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const O=i.payload,F=i.sessionId,H=(l=r().currentSession)==null?void 0:l.id,Z=F&&F!==H;e(K=>({sessions:K.sessions.map(M=>M.id===F?{...M,isRunning:O.isRunning}:M)})),Z||e(K=>({currentSession:K.currentSession?{...K.currentSession,isRunning:O.isRunning}:null,...O.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!zt(i,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const O=i.payload;e(F=>F.messages.some(H=>H.id===O.message.id)?F:{messages:[...F.messages,O.message],streamingMessageId:O.message.isStreaming?O.message.id:F.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:F.streamingMessage});break}case"chat.message_updated":{if(!zt(i,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const O=i.payload,F=O.updates.isStreaming===!1&&r().streamingMessageId===O.messageId;F&&(Ai(),un==null||un()),e(H=>{const Z=H.streamingMessage,K=F;if(Z&&Z.id===O.messageId){const M={...Z,...O.updates};return{messages:H.messages.map(L=>L.id===O.messageId?M:L),streamingMessageId:K?null:H.streamingMessageId,streamingMessage:K?null:{...Z,...O.updates}}}return{messages:H.messages.map(M=>M.id===O.messageId?{...M,...O.updates}:M),streamingMessageId:K?null:H.streamingMessageId}});break}case"chat.delta":{if(!zt(i,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const O=i.payload;if(!Bd.has(O.messageId)){Bd.add(O.messageId);const F=Wa(r(),i.sessionId);W1(F)}$t.messageId=O.messageId,$t.deltaContent+=O.content,zd();break}case"chat.thinking":{if(!zt(i,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.thinkingContent+=O.content,zd();break}case"chat.tool_preparing":{if(!zt(i,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const O=i.payload;e(F=>{const H=F.streamingMessage;return H&&H.id===O.messageId?{streamingMessage:{...H,preparingToolCalls:[...H.preparingToolCalls??[],{index:O.index,name:O.name}]}}:{messages:F.messages.map(Z=>Z.id===O.messageId?{...Z,preparingToolCalls:[...Z.preparingToolCalls??[],{index:O.index,name:O.name}]}:Z)}});break}case"chat.tool_call":{if(!zt(i,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const O=i.payload,F=H=>{var M;const Z=(M=H.preparingToolCalls)==null?void 0:M.filter((L,z)=>{var $;return L.name===O.tool?($=H.preparingToolCalls)==null?void 0:$.slice(0,z).some(re=>re.name===O.tool):!0}),K=$t.toolOutput.filter(L=>L.callId===O.callId);return K.length>0&&($t.toolOutput=$t.toolOutput.filter(L=>L.callId!==O.callId)),{...H,toolCalls:[...H.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...K.length>0?{streamingOutput:K.map(L=>({stream:L.stream,content:L.content}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};e(H=>{const Z=H.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:H.messages.map(K=>K.id===O.messageId?F(K):K)}});break}case"chat.tool_output":{if(!zt(i,((E=r().currentSession)==null?void 0:E.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),zd();break}case"chat.tool_result":{if(!zt(i,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const O=i.payload,F=H=>{var K;const Z=(K=H.toolCalls)==null?void 0:K.map(M=>M.id===O.callId?{...M,result:O.result}:M);return{...H,toolCalls:Z}};e(H=>{const Z=H.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:H.messages.map(K=>K.id===O.messageId?F(K):K)}});break}case"chat.vision_fallback":{if(!zt(i,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const O=i.payload;e(F=>{const H=`${O.messageId}-${O.attachmentId}`,Z={...F.visionFallbackByMessage};return Z[H]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:Z}});break}case"chat.todo":{if(!zt(i,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const O=i.payload;e({currentTodos:O.todos});break}case"chat.summary":{if(!zt(i,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,summary:O.summary}:null}));break}case"chat.progress":{if(!zt(i,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const O=i.payload;console.log("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!zt(i,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const O=i.payload;console.log("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!zt(i,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Ai(),un==null||un();const O=i.payload,F=O.stats;$t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[],Bd.delete(O.messageId),e(H=>{const Z=H.streamingMessage,K=Z&&Z.id===O.messageId?{...Z,isStreaming:!1,stats:F??Z.stats}:null;return{messages:H.messages.map(M=>M.id===O.messageId?K??{...M,isStreaming:!1,stats:F??M.stats}:M),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!zt(i,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Ai(),un==null||un();const O=i.payload;console.error("Chat error:",O.error,"recoverable:",O.recoverable),O.recoverable||($t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[]),e(F=>({error:{code:"CHAT_ERROR",message:O.error},streamingMessageId:O.recoverable?F.streamingMessageId:null,...O.recoverable?{}:{messages:F.streamingMessage?F.messages.map(H=>H.id===F.streamingMessage.id?F.streamingMessage:H):F.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!zt(i,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const O=i.payload;e({pendingPathConfirmation:{callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason}});break}case"chat.ask_user":{if(!zt(i,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const O=i.payload;e({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!zt(i,((I=r().currentSession)==null?void 0:I.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=i.payload,F=i.sessionId,H=(B=r().currentSession)==null?void 0:B.id,Z=F&&F!==H;e(K=>({sessions:K.sessions.map(M=>M.id===F?{...M,phase:O.phase}:M)})),Z||e(K=>({currentSession:K.currentSession?{...K.currentSession,phase:O.phase}:null}));break}case"criteria.updated":{if(!zt(i,((q=r().currentSession)==null?void 0:q.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,criteria:O.criteria}:null}));break}case"context.state":{const O=i.payload,F=zt(i,((V=r().currentSession)==null?void 0:V.id)??null);O.subAgentId?F&&r().updateSubAgentContextState(O.subAgentId,O.context):F?e({contextState:O.context}):u();break}case"session.name_generated":{const O=i.payload,F=i.sessionId,H=(W=r().currentSession)==null?void 0:W.id;e(Z=>{const K=Z.sessions.map(L=>L.id===F?{...L,title:O.name,updatedAt:new Date().toISOString()}:L),M=H===F?Z.currentSession?{...Z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:Z.currentSession;return{sessions:K,currentSession:M}});break}case"queue.state":{const O=i.payload;e({queuedMessages:O.messages});break}case"devServer.output":case"devServer.state":{cr.getState().handleMessage(i);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Va.getState().handleMessage(i.type,i.payload);break}case"error":{const O=i.payload;console.error("Server error:",O),e({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}}));function Rb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function Z1(){return Ce(e=>e.queuedMessages)}function Q1(){return Ce(e=>e.abortInProgress)}function J1(){const e=Ce(s=>s.connect),r=Ce(s=>s.connectionStatus),i=Oi(s=>s.load);return P.useEffect(()=>{e()},[e]),P.useEffect(()=>{r==="connected"&&i()},[r,i]),{connectionStatus:r}}function ew({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function Ob({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function tw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function nw({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function rw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Or({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function Mr({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function iw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function Jl({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function sw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function Dh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function ec({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function Fl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function aw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function ow({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function cw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function uw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Ux({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function Mb({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function dw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function hw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Ib({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Bb({className:e="",size:r="md"}){const i=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${i} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const zb=Bb,Hb=Bb;function fw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function pw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function mw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function gw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function xw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function vw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function bw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Pb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Fb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function _w({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Sw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function uh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function $x(e,r){const i=qt.ws;!i||i.readyState!==WebSocket.OPEN||i.send(JSON.stringify({id:uh(),type:e,payload:r}))}const Jn=Yn((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:i=>e({isOpen:i}),toggleOpen:()=>e(i=>({isOpen:!i.isOpen})),setWorkdir:i=>e({workdir:i}),fetchSessions:async()=>{try{const i=await ke("/api/terminals");if(i.ok){const s=await i.json();e({sessions:s});const c=qt.ws;if(c&&c.readyState===WebSocket.OPEN)for(const u of s)c.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async i=>{try{const s=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:i??r().workdir??void 0})});if(s.ok){const c=await s.json();e(f=>({sessions:[...f.sessions,c]}));const u=qt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:c.id}}))}}catch(s){console.error("Failed to create terminal:",s)}},writeSession:(i,s)=>{$x("terminal.write",{sessionId:i,data:s})},resizeSession:(i,s,c)=>{$x("terminal.resize",{sessionId:i,cols:s,rows:c})},killSession:async i=>{try{(await ke(`/api/terminals/${i}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.sessions.filter(u=>u.id!==i)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:i=>{switch(i.type){case"terminal.exit":{const{sessionId:s}=i.payload||{};s&&e(c=>{const u=c.sessions.filter(f=>f.id!==s);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));qt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&Jn.getState().handleMessage(e)});var tc=xb();const nc=P.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:i="",...s},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${i}`,...s,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));nc.displayName="IconButton";const ww="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",Bs=P.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:ww,title:"Edit",...e}));Bs.displayName="EditButton";const Cw="M6 18L18 6M6 6l12 12",Lh=P.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Cw,...e}));Lh.displayName="CloseButton";const kw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:i="md",minHeight:s,children:c,footer:u,className:f,onClose:l,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=P.useState(!1),E=d!==void 0,C=E?d:b,y=P.useCallback(()=>{E||_(!0)},[E]),x=P.useCallback(()=>{E||_(!1),l==null||l()},[E,l]);P.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&x()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,x,g]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:f,children:e}):o.jsx("span",{onClick:y,className:f,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,C&&(typeof document<"u"?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?x:void 0}),o.jsxs("div",{className:`relative w-full ${kw[i]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Lh,{onClick:x,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const it=P.forwardRef(({variant:e="secondary",size:r="md",className:i="",children:s,...c},u)=>{const f="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={primary:"bg-accent-primary/25 text-white hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${f} ${l[e]} ${d[r]} ${i}`,...c,children:s})});it.displayName="Button";function Ew({value:e,defaultUrl:r,disabled:i,onChange:s}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,disabled:i,onChange:u=>{const f=u.target.value;s(f===r?null:f)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:I1.map(({url:u,label:f})=>o.jsx("option",{value:u,title:f,children:f.split(" ")[0]},u))}),o.jsx(Mr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const qx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function jw(){const e=Oi(d=>d.settings),r=Oi(d=>d.update),i=Oi(d=>d.updateEvent),s=Oi(d=>d.updateAgentOverride),c=Oi(d=>d.load);P.useEffect(()=>{c()},[c]);const u=async()=>{await z1()==="granted"&&r({...e,browserNotificationEnabled:!0})},f=(d,p,g,m)=>{d==="general"?i(p,{[g]:m}):s(d,p,{[g]:m})},l=(d,p,g)=>{d==="general"?i(p,{customSoundUrl:g}):s(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(Wx,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(Wx,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),qx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:M1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),qx.map(p=>{const g=Db(e,d.key,p.key==="general"?void 0:p.key),m=Tb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>f(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>f(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Ew,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>l(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function Wx({label:e,description:r,checked:i,onChange:s}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${i?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:c=>{c.preventDefault(),s(!i)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${i?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Rh(e,r){r({loading:!0});try{const s=await(await ke(e)).json();r({defaults:s.defaults??[],userItems:s.userItems??[],loading:!1})}catch{r({loading:!1})}}const Dr=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Rh("/api/skills",e)},toggleSkill:async i=>{try{const c=await(await ke(`/api/skills/${i}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(f=>f.id===i?{...f,enabled:c.enabled}:f),userItems:u.userItems.map(f=>f.id===i?{...f,enabled:c.enabled}:f)}))}catch{}},fetchSkill:async i=>{try{const s=await ke(`/api/skills/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/skills/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createSkill:async i=>{const s=await di("POST","/api/skills",i);return s.success&&await r().fetchSkills(),s},updateSkill:async(i,s)=>{const c=await di("PUT",`/api/skills/${i}`,s);return c.success&&await r().fetchSkills(),c},deleteSkill:async i=>{try{const s=await ke(`/api/skills/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async i=>{try{const s=await ke(`/api/skills/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Oh(){const[e,r]=P.useState({id:null,type:null}),i=P.useCallback(u=>r({id:u,type:"delete"}),[]),s=P.useCallback(()=>r({id:null,type:null}),[]),c=P.useCallback((u,f)=>e.id===u&&e.type===f,[e.id,e.type]);return{requestDelete:i,clearConfirm:s,isConfirming:c}}function Mh({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function Ih({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Pb,{})})}function Qa({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(Jl,{})})}function Mi({label:e,value:r,onChange:i,placeholder:s,readOnly:c,hint:u,mono:f}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:l=>i(l.target.value),readOnly:c,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"font-mono":""} ${c?"opacity-60":""}`})]})}function Nw({onCancel:e,onSave:r,saving:i,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:r,disabled:i||s,children:i?"Saving...":"Save"})]})}function Bh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Ub({description:e,onNew:r,newLabel:i="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:r,children:i})})]})}function $b({isBuiltIn:e,isConfirmingDelete:r,onView:i,onEdit:s,onDuplicate:c,onDelete:u,children:f}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:f}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&i&&o.jsx("button",{onClick:i,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:c}),!e&&s&&o.jsx(Bs,{onClick:s}),!e&&(r?o.jsx(Mh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>u==null?void 0:u()}))]})]})}function Tw({id:e,name:r,description:i,isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d}){return o.jsxs($b,{isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),i&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:i})]})}function qb({loading:e,hasItems:r,loadingLabel:i,emptyLabel:s,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:i}):r?o.jsx("div",{className:"space-y-4",children:c}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function Wb({name:e,id:r,nameLabel:i="Name",idLabel:s="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:f,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:i,value:e,onChange:p,placeholder:c,hint:f}),o.jsx(Mi,{label:s,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Gb(e={}){const{initialData:r={}}=e,[i,s]=P.useState("list"),[c,u]=P.useState(null),[f,l]=P.useState(""),[d,p]=P.useState(!1),[g,m]=P.useState(r),b=P.useCallback(()=>{m(r),l(""),u(null)},[r]),_=P.useCallback(x=>{s(x),x==="list"&&b()},[b]),E=P.useCallback(x=>{m(v=>typeof x=="function"?x(v):x)},[]),C=P.useCallback((x,v={})=>{u(x),s("edit"),m({...v}),l("")},[]),y=P.useCallback(()=>{u(null),s("edit"),m(r),l("")},[r]);return{view:i,editingId:c,formError:f,saving:d,formData:g,setView:_,setEditingId:u,setFormError:l,setFormData:E,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function zh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function Gx({skill:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsx(Tw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f})}function Aw({isOpen:e}){const r=Dr(O=>O.defaults),i=Dr(O=>O.userItems),s=Dr(O=>O.loading),c=Dr(O=>O.fetchSkills),u=Dr(O=>O.fetchSkill),f=Dr(O=>O.fetchDefaultContent),l=Dr(O=>O.createSkill),d=Dr(O=>O.updateSkill),p=Dr(O=>O.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:E,setView:C,setEditingId:y,setFormError:x,setFormData:v,setSaving:S}=Gb(),{clearConfirm:j}=Oh();P.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const T=(O,F,H,Z)=>{v({name:Z??O.metadata.name,id:H??O.metadata.id,description:O.metadata.description??"",version:O.metadata.version??"1.0.0",prompt:O.prompt,isReadOnly:F})},N=async O=>{if(r.some(H=>H.id===O)){const H=await f(O);if(!H)return;T(H,!0),y(O),x(""),C("edit")}else{const H=await u(O);if(!H)return;T(H,!0),y(O),x(""),C("edit")}},D=async O=>{const H=r.some(K=>K.id===O)?await f(O):await u(O);if(!H)return;const Z=`${O}-copy-${Date.now()}`;T(H,!1,Z,`${H.metadata.name} (copy)`),y(null),x(""),C("edit")},A=()=>{v({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},I=async O=>{const F=await u(O);F&&(T(F,!1),y(O),x(""),C("edit"))},B=async O=>{await p(O),j()},q=async()=>{const O=m??E.id;if(!O||!E.name||!E.prompt){x("Name, ID, and prompt are required.");return}S(!0),x("");const F={metadata:{id:O,name:E.name,description:E.description,version:E.version},prompt:E.prompt},H=m?await d(m,F):await l(F);if(S(!1),!H.success){x(H.error??"Failed to save skill.");return}C("list")},V=O=>{v(F=>({...F,name:O})),m||v(F=>({...F,id:O.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=E.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?E.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Bh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(Wb,{name:E.name,id:E.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:V,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:E.description,onChange:O=>v(F=>({...F,description:O})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Mi,{label:"Version",value:E.version,onChange:O=>v(F=>({...F,version:O})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:E.prompt,onChange:O=>v(F=>({...F,prompt:O.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(it,{variant:"primary",onClick:()=>{v(O=>({...O,name:O.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(it,{variant:"primary",onClick:q,disabled:_||!E.name||!E.id||!E.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Ub,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs(qb,{loading:s,hasItems:r.length>0||i.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(O.id),onDuplicate:()=>D(O.id)},O.id))})]}),i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:i.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(O.id),onEdit:()=>I(O.id),onDuplicate:()=>D(O.id),onDelete:()=>B(O.id)},O.id))})]})]})]})}function Dw({isOpen:e,onClose:r}){const[i,s]=P.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(Ba,{label:"Instructions",active:i==="instructions",onClick:()=>s("instructions")}),o.jsx(Ba,{label:"Skills",active:i==="skills",onClick:()=>s("skills")}),o.jsx(Ba,{label:"Notifications",active:i==="notifications",onClick:()=>s("notifications")}),o.jsx(Ba,{label:"Display",active:i==="display",onClick:()=>s("display")}),o.jsx(Ba,{label:"Advanced",active:i==="advanced",onClick:()=>s("advanced")})]}),i==="instructions"&&o.jsx(Ow,{isOpen:e}),i==="skills"&&o.jsx(Aw,{isOpen:e}),i==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(jw,{})}),i==="display"&&o.jsx(Rw,{}),i==="advanced"&&o.jsx(Lw,{onClose:r})]})})}function Lw({onClose:e}){const[,r]=ur();function i(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(it,{variant:"secondary",onClick:i,children:"Launch Onboarding"})]})})}function Rw(){const e=en(g=>g.settings),r=en(g=>g.loading),i=en(g=>g.getSetting),s=en(g=>g.setSetting),c=r[Et.DISPLAY_SHOW_THINKING]??!1,u=[{key:Et.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:Et.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:Et.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:Et.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],f=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[l,d]=P.useState(()=>Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])));P.useEffect(()=>{u.forEach(g=>i(g.key))},[i]),P.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])))},[JSON.stringify(f)]);const p=async g=>{const m=String(!l[g]);d(b=>({...b,[g]:!b[g]})),await s(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})})}function Ba({label:e,active:r,onClick:i}){return o.jsx("button",{onClick:i,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Ow({isOpen:e}){const r=en(y=>y.settings),i=en(y=>y.loading),s=en(y=>y.getSetting),c=en(y=>y.setSetting),u=r[Et.GLOBAL_INSTRUCTIONS]??"",f=i[Et.GLOBAL_INSTRUCTIONS]??!1,[l,d]=P.useState(u),[p,g]=P.useState(!1),[m,b]=P.useState(!1);P.useEffect(()=>{e&&s(Et.GLOBAL_INSTRUCTIONS)},[e,s]),P.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),c(Et.GLOBAL_INSTRUCTIONS,l),b(!1),g(!1)},E=()=>{d(u),g(!1)},C=f||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:E,disabled:!p,children:"Discard"}),o.jsx(it,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var Hd={exports:{}},Vx;function Mw(){return Vx||(Vx=1,(function(e,r){(function(i,s){e.exports=s()})(globalThis,(()=>(()=>{var i={4567:function(f,l,d){var p=this&&this.__decorate||function(v,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,S,j,T);else for(var I=v.length-1;I>=0;I--)(N=v[I])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(v,S){return function(j,T){S(j,T,v)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),E=d(4725),C=d(2585),y=d(3656);let x=l.AccessibilityManager=class extends _.Disposable{constructor(v,S,j,T){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
57
|
+
*/var kx;function i1(){if(kx)return Md;kx=1;var e=Zl();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var i=typeof Object.is=="function"?Object.is:r,s=e.useState,c=e.useEffect,u=e.useLayoutEffect,f=e.useDebugValue;function l(m,b){var _=b(),E=s({inst:{value:_,getSnapshot:b}}),C=E[0].inst,y=E[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),f(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!i(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:l;return Md.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Md}var Ex;function s1(){return Ex||(Ex=1,Od.exports=i1()),Od.exports}var a1=s1();const o1=KS.useInsertionEffect,l1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",c1=l1?P.useLayoutEffect:P.useEffect,u1=o1||c1,vb=e=>{const r=P.useRef([e,(...i)=>r[0](...i)]).current;return u1(()=>{r[0]=e}),r[1]},d1="popstate",jh="pushState",Nh="replaceState",h1="hashchange",jx=[d1,jh,Nh,h1],f1=e=>{for(const r of jx)addEventListener(r,e);return()=>{for(const r of jx)removeEventListener(r,e)}},bb=(e,r)=>a1.useSyncExternalStore(f1,e,r),Nx=()=>location.search,p1=({ssrSearch:e}={})=>bb(Nx,e!=null?()=>e:Nx),Tx=()=>location.pathname,m1=({ssrPath:e}={})=>bb(Tx,e!=null?()=>e:Tx),g1=(e,{replace:r=!1,state:i=null}={})=>history[r?Nh:jh](i,"",e),x1=(e={})=>[m1(e),g1],Ax=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ax]>"u"){for(const e of[jh,Nh]){const r=history[e];history[e]=function(){const i=r.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),i}}Object.defineProperty(window,Ax,{value:!0})}const v1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",yb=(e="")=>e==="/"?"":e,b1=(e,r)=>e[0]==="~"?e.slice(1):yb(r)+e,y1=(e="",r)=>v1(Dx(yb(e)),Dx(r)),Dx=e=>{try{return decodeURI(e)}catch{return e}},_b={hook:x1,searchHook:p1,parser:r1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,i)=>e(r,i)},Sb=P.createContext(_b),Hs=()=>P.useContext(Sb),wb={},Cb=P.createContext(wb),_1=()=>P.useContext(Cb),Ql=e=>{const[r,i]=e.hook(e);return[y1(e.base,r),vb((s,c)=>e.aroundNav(i,b1(s,e.base),c))]},ur=()=>Ql(Hs()),Th=(e,r,i,s)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",s),f=c.exec(i)||[],[l,...d]=f;return l!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):f.groups;let g={...d};return p&&Object.assign(g,p),g})(),...s?[l]:[]]:[!1,null]},Ah=e=>Th(Hs().parser,e,ur()[0]),S1=({children:e,...r})=>{var g,m,b;const i=Hs(),s=r.hook?_b:i;let c=s;const[u,f=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=f,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let l=P.useRef({}),d=l.current,p=d;for(let _ in s){const E=_==="base"?s[_]+(r[_]??""):r[_]??s[_];d===p&&E!==p[_]&&(l.current=p={...p}),p[_]=E,(E!==s[_]||E!==c[_])&&(c=p)}return P.createElement(Sb.Provider,{value:c,children:e})},Lx=({children:e,component:r},i)=>r?P.createElement(r,{params:i}):typeof e=="function"?e(i):e,w1=e=>{let r=P.useRef(wb);const i=r.current;return r.current=Object.keys(e).length!==Object.keys(i).length||Object.entries(e).some(([s,c])=>c!==i[s])?e:i},Oa=({path:e,nest:r,match:i,...s})=>{const c=Hs(),[u]=Ql(c),[f,l,d]=i??Th(c.parser,e,u,r),p=w1({..._1(),...l});if(!f)return null;const g=d?P.createElement(S1,{base:d},Lx(s,p)):Lx(s,p);return P.createElement(Cb.Provider,{value:p,children:g})},Mn=P.forwardRef((e,r)=>{const i=Hs(),[s,c]=Ql(i),{to:u="",href:f=u,onClick:l,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...E}=e,C=vb(x=>{x.ctrlKey||x.metaKey||x.altKey||x.shiftKey||x.button!==0||(l==null||l(x),x.defaultPrevented||(x.preventDefault(),c(f,e)))}),y=i.hrefs(f[0]==="~"?f.slice(1):i.base+f,i);return d&&P.isValidElement(p)?P.cloneElement(p,{onClick:C,href:y}):P.createElement("a",{...E,onClick:C,href:y,className:g!=null&&g.call?g(s===f):g,children:p,ref:r})}),kb=e=>Array.isArray(e)?e.flatMap(r=>kb(r&&r.type===P.Fragment?r.props.children:r)):[e],C1=({children:e,location:r})=>{const i=Hs(),[s]=Ql(i);for(const c of kb(e)){let u=0;if(P.isValidElement(c)&&(u=Th(i.parser,c.props.path,r||s,c.props.nest))[0])return P.cloneElement(c,{match:u})}return null},Rx=e=>{let r;const i=new Set,s=(p,g)=>{const m=typeof p=="function"?p(r):p;if(!Object.is(m,r)){const b=r;r=g??(typeof m!="object"||m===null)?m:Object.assign({},r,m),i.forEach(_=>_(r,b))}},c=()=>r,l={setState:s,getState:c,getInitialState:()=>d,subscribe:p=>(i.add(p),()=>i.delete(p))},d=r=e(s,c,l);return l},k1=(e=>e?Rx(e):Rx),E1=e=>e;function j1(e,r=E1){const i=dn.useSyncExternalStore(e.subscribe,dn.useCallback(()=>r(e.getState()),[e,r]),dn.useCallback(()=>r(e.getInitialState()),[e,r]));return dn.useDebugValue(i),i}const Ox=e=>{const r=k1(e),i=s=>j1(r,s);return Object.assign(i,r),i},Yn=(e=>e?Ox(e):Ox);async function ke(e,r={}){const i=localStorage.getItem("openfox_token"),s={...r.headers instanceof Headers?Object.fromEntries(r.headers.entries()):r.headers,...i?{"x-session-token":i}:{}};return fetch(e,{...r,headers:s})}function N1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Eb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class T1{constructor(r){ar(this,"ws",null);ar(this,"handlers",new Set);ar(this,"statusHandler",null);ar(this,"baseUrl");ar(this,"isReconnecting",!1);ar(this,"connectingPromise",null);ar(this,"lastCloseCode",0);ar(this,"reconnectAttempts",0);ar(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const i=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${i}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,i;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((s,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const f=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(f),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),s()},this.ws.onclose=l=>{var d,p,g;clearTimeout(f),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(f),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);N1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,i){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=Eb(),c={id:s,type:r,payload:i};return this.ws.send(JSON.stringify(c)),s}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const A1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,qt=new T1(A1),di=async(e,r,i)=>{try{const s=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}};function jb(e){let r=null;function i(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return i}let El=[];const cr=Yn()((e,r)=>{function i(){if(El.length===0)return;const c=El;El=[],e(u=>({logs:[...u.logs,...c]}))}const s=jb(i);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:f,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:f.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const f=c.payload;if(f.workdir!==u)return;El.push({stream:f.stream,content:f.content}),s();break}case"devServer.state":{const f=c.payload;if(f.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:f.state,errorMessage:f.errorMessage}:l.status}));break}}}}});function D1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function Mx(e,r,i){const s=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){const c=await s.json();throw new Error(c.error??"Failed to update model")}return s.json()}function Ix(e,r,i,s){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===i?{...u,...s,source:"user"}:u)}:c)}const L1=3e4;function R1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const At=Yn((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const i=await ke("/api/config");if(!i.ok)throw new Error("Failed to fetch config");const s=await i.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(i){e({error:i instanceof Error?i.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const i=await ke("/api/model/refresh",{method:"POST"});if(!i.ok)throw new Error("Failed to refresh model");const s=await i.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(i){console.error("Failed to refresh model:",i)}},activateProvider:async i=>{const{activeProviderId:s,providers:c}=r();if(i===s)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${i}/activate`,{method:"POST"});if(!u.ok){const l=await u.json();throw new Error(l.error??"Failed to activate provider")}const f=await u.json();return e({activeProviderId:f.activeProviderId,model:f.model,backend:f.backend,providers:c.map(l=>({...l,isActive:l.id===f.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(i,s)=>{const{providers:c}=r();e({activeProviderId:i,model:s,defaultModelSelection:`${i}/${s}`,providers:c.map(u=>({...u,isActive:u.id===i}))})},updateModelContext:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,{contextWindow:c}),{providers:f}=r();return e({providers:Ix(f,i,s,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,c),{providers:f}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...D1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0})};return e({providers:Ix(f,i,s,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async i=>{e({activating:!0,error:null});try{const s=await ke(`/api/providers/${i}/refresh`,{method:"POST"});if(!s.ok){const f=await s.json();throw new Error(f.error??"Failed to refresh models")}const c=await s.json(),{providers:u}=r();return e({providers:u.map(f=>f.id===i?{...f,models:c.models}:f),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:i,refreshModel:s}=r();if(i)return;const c=setInterval(()=>{s()},L1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:i}=r();i&&(clearInterval(i),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:i,activeProviderId:s}=r();return i.find(c=>c.id===s)},getModelContext:i=>{const{providers:s,activeProviderId:c}=r(),u=s.find(l=>l.id===c);if(!u)return 2e5;const f=u.models.find(l=>l.id===i);return(f==null?void 0:f.contextWindow)??2e5}})),Vt=Yn((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await ke("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(i,s)=>{try{const c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i,workdir:s})});if(!c.ok)return null;const u=await c.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async i=>{try{const s=await ke(`/api/projects/${i}`);if(!s.ok)return null;const c=await s.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(i,s)=>{var c;try{const u=await ke(`/api/projects/${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok)return null;const f=await u.json();return((c=r().currentProject)==null?void 0:c.id)===i&&e({currentProject:f.project}),await r().listProjects(),f.project}catch{return null}},deleteProject:async i=>{var s;try{return(await ke(`/api/projects/${i}`,{method:"DELETE"})).ok?(await r().listProjects(),((s=r().currentProject)==null?void 0:s.id)===i&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let jl=[];const Va=Yn()((e,r)=>{function i(){if(jl.length===0)return;const c=jl;jl=[],e(u=>{const f={...u.logs};for(const l of c){const d=f[l.processId]??[];f[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:f}})}const s=jb(i);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(f=>({processes:f.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(f=>f.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([f])=>f!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,f)=>{jl.push({processId:c,stream:u,content:f}),s()},setLogs:(c,u)=>e(f=>({logs:{...f.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:f,name:l,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:f,sessionId:"",name:l,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const f=u.processId,l=u.stream,d=u.content;r().appendLog(f,l,d);break}case"backgroundProcess.exited":{const f=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===f?{...p,status:"exited",exitCode:l}:p)}));break}case"backgroundProcess.removed":{const f=u.processId;r().removeProcess(f);break}}}}}),Et={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars"};function Nl(e,r){return i=>({loading:{...i.loading,[e]:r}})}function Bx(e,r){return i=>({settings:{...i.settings,[e]:r},loading:{...i.loading,[e]:!1}})}const O1=[Et.DISPLAY_SHOW_THINKING,Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Et.DISPLAY_SHOW_STATS,Et.DISPLAY_SHOW_AGENT_DEFINITIONS,Et.DISPLAY_SHOW_WORKFLOW_BARS];function Nb(){return{showThinking:en(e=>e.settings[Et.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:en(e=>e.settings[Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:en(e=>e.settings[Et.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:en(e=>e.settings[Et.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:en(e=>e.settings[Et.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true"}}const en=Yn(e=>({settings:{},loading:{},getSetting:async r=>{e(Nl(r,!0));try{const s=await(await ke(`/api/settings/${r}`)).json();return e(Bx(r,s.value??"")),s.value}catch{return e(Nl(r,!1)),null}},setSetting:async(r,i)=>{e(Nl(r,!0));try{const c=await(await ke(`/api/settings/${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:i})})).json();e(Bx(r,c.value??""))}catch{e(Nl(r,!1))}}})),M1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],I1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Tb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ci={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},Ab={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ch={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ci},waiting_for_user:{...ci},phase_done:{...ci},phase_blocked:{...ci},new_message:{...Ab}},agentOverrides:{}};function Db(e,r,i){var u;const s=e.events[r];if(!i)return s;const c=(u=e.agentOverrides[i])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??s.soundEnabled,browserNotification:c.browserNotification??s.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:s.customSoundUrl}:s}const Oi=Yn((e,r)=>({settings:ch,loaded:!1,load:()=>{en.getState().getSetting(Et.NOTIFICATION_SETTINGS);const s=en.subscribe(u=>{const f=u.settings[Et.NOTIFICATION_SETTINGS];if(f!==void 0)try{const l=JSON.parse(f);e({settings:zx(l),loaded:!0})}catch{e({loaded:!0})}}),c=en.getState().settings[Et.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:zx(u),loaded:!0})}catch{e({loaded:!0})}return s},update:i=>{e({settings:i}),Id(i)},updateEvent:(i,s)=>{const c=r().settings,u={...c,events:{...c.events,[i]:{...c.events[i],...s}}};e({settings:u}),Id(u)},updateAgentOverride:(i,s,c)=>{var d;const u=r().settings,f={...u.agentOverrides};if(c===null){if(f[i]){const p={...f[i]};delete p[s],Object.keys(p).length===0?delete f[i]:f[i]=p}}else f[i]={...f[i],[s]:{...((d=f[i])==null?void 0:d[s])??{},...c}};const l={...u,agentOverrides:f};e({settings:l}),Id(l)}}));function Id(e){en.getState().setSetting(Et.NOTIFICATION_SETTINGS,JSON.stringify(e))}function zx(e){var r,i,s,c,u;return{soundEnabled:e.soundEnabled??ch.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ch.browserNotificationEnabled,events:{complete:{...ci,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ci,...(i=e.events)==null?void 0:i.waiting_for_user},phase_done:{...ci,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...ci,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Ab,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Hx=new Map;function B1(e){let r=Hx.get(e);return r||(r=new Audio(e),r.volume=.5,Hx.set(e,r)),r}let Lb=typeof Notification<"u"?Notification.permission:"denied";function z1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Lb=e,e))}const H1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},P1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function F1(e){typeof Notification>"u"||Lb==="granted"&&(document.hasFocus()||new Notification(H1[e],{body:P1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function oo(e,r){const{settings:i}=Oi.getState(),s=Db(i,e,r);if(i.soundEnabled&&s.soundEnabled){const c=s.customSoundUrl??Tb[e],u=B1(c);u.currentTime=0,u.play().catch(()=>{})}i.browserNotificationEnabled&&s.browserNotification&&F1(e)}const U1=e=>oo("complete",e),$1=e=>oo("phase_done",e),q1=e=>oo("phase_blocked",e),Px=e=>oo("waiting_for_user",e),W1=e=>oo("new_message",e);let Ma=!1,or=null;const Bd=new Set,$t={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ms=null,un=null;function zd(){Ms===null&&(Ms=requestAnimationFrame(()=>{Ms=null,un==null||un()}))}function Ai(){Ms!==null&&(cancelAnimationFrame(Ms),Ms=null)}function zt(e,r){return r!==null&&e.sessionId===r}function G1(e,r,i){return e.id!==void 0||zt(e,r)||i===!0&&e.sessionId!==void 0}function V1(e,r){return e.includes(r)?e:[...e,r]}function Ia(e,r){return e.filter(i=>i!==r)}function K1(e,r){const i=e.find(c=>c.id===r.id),s=i?{...i,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return i?e.map(c=>c.id===r.id?s:c):[s,...e]}function Y1(e,r,i){return e.map(s=>{const c=(i==null?void 0:i.id)===s.id?i:null,u=r.find(f=>f.id===s.id);return{...s,title:s.title??(u==null?void 0:u.title),mode:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??s.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??s.phase,isRunning:(c==null?void 0:c.isRunning)??(u==null?void 0:u.isRunning)??s.isRunning,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}const Fx=new Map;function Wa(e,r){var u;const i=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,s=e.sessions.find(f=>f.id===r),c=(i==null?void 0:i.mode)??(s==null?void 0:s.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function X1(e,r){if(e.type==="chat.done"){const i=e.payload,s=Wa(r,e.sessionId),c=i.agentType??s;i.reason==="complete"&&U1(c),i.reason==="waiting_for_user"&&Px(c);return}if(e.type==="chat.path_confirmation"){const i=Wa(r,e.sessionId);Px(i);return}if(e.type==="task.completed"){const i=Wa(r,e.sessionId);$1(i);return}if(e.type==="phase.changed"&&e.sessionId){const i=e.payload,s=Fx.get(e.sessionId)??null;if(Fx.set(e.sessionId,i.phase),s===i.phase)return;const c=Wa(r,e.sessionId);i.phase==="blocked"&&q1(c)}}const Ce=Yn((e,r)=>(un=()=>{const i=$t;if(!i.messageId)return;const s=i.deltaContent.length>0,c=i.thinkingContent.length>0,u=i.toolOutput.length>0;if(!s&&!c&&!u)return;const f=i.deltaContent,l=i.thinkingContent,d=i.toolOutput;i.deltaContent="",i.thinkingContent="",i.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===i.messageId){let b={...g};if(s&&(b.content=b.content+f),c&&(b.thinkingContent=(b.thinkingContent??"")+l),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(x=>x.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(x=>({stream:x.stream,content:x.content,timestamp:Date.now()}))]})});const E=d.filter(C=>!_.has(C.callId));E.length>0&&$t.toolOutput.push(...E)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var x;if(C.id!==i.messageId)return C;const y=(x=C.toolCalls)==null?void 0:x.map(v=>{const S=d.filter(j=>j.callId===v.id);return S.length===0?v:(b.add(v.id),{...v,streamingOutput:[...v.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content,timestamp:Date.now()}))]})});return{...C,toolCalls:y}}),E=d.filter(C=>!b.has(C.callId));return E.length>0&&$t.toolOutput.push(...E),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{if(r().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(s&&!qt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}qt.onStatusChange(c=>{var u;if(e({connectionStatus:c}),c==="connected"){r().listSessions(void 0);const f=(u=r().currentSession)==null?void 0:u.id;f&&r().loadSession(f)}});try{if(await qt.connect(),!Ma){Ma=!0;const c=r().handleServerMessage;or=qt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=qt.getLastCloseCode();if(!qt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async i=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:c}=await s.json();qt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Vt.getState(),{fetchConfig:f}=At.getState();u(),f(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{qt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(i,s)=>{try{e({pendingSessionCreate:!0});const c=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:i,title:s})});if(!c.ok)return e({pendingSessionCreate:!1}),null;const u=await c.json();return qt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async i=>{try{const s=r().currentSession;!s||s.id!==i?(Ai(),e({currentSession:null,unreadSessionIds:Ia(r().unreadSessionIds,i),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:Ia(r().unreadSessionIds,i)});const c=await ke(`/api/sessions/${i}`);if(!c.ok)return;const u=await c.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),qt.send("session.load",{sessionId:i});try{const f=await ke(`/api/sessions/${i}/background-processes`);if(f.ok){const l=await f.json();Va.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(i,s=20)=>{try{const c=new URLSearchParams;c.set("limit",String(s)),i&&c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e({sessions:f.sessions??[],sessionsHasMore:i?f.hasMore??!1:!0})}catch{}},loadMoreSessions:async i=>{const s=r();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(s.sessions.length)),c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e(l=>({sessions:[...l.sessions,...f.sessions??[]],sessionsHasMore:f.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async i=>{var s;try{return(await ke(`/api/sessions/${i}`,{method:"DELETE"})).ok?(await r().listSessions(),((s=r().currentSession)==null?void 0:s.id)===i&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async i=>{try{return(await ke(`/api/projects/${i}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Ai(),e(i=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:i.currentSession?Ia(i.unreadSessionIds,i.currentSession.id):i.unreadSessionIds}))},sendMessage:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},stopGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i&&!r().abortInProgress){Ai(),un==null||un(),e({abortInProgress:!0});try{await ke(`/api/sessions/${i}/stop`,{method:"POST"})}catch(c){console.error("Error stopping generation:",c)}}},continueGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i){e({streamingMessageId:null});try{await ke(`/api/sessions/${i}/continue`,{method:"POST"})}catch(c){console.error("Error continuing generation:",c)}}},launchRunner:(i,s,c)=>{e({streamingMessageId:null});const u={};i!=null&&i.trim()&&(u.content=i),s&&s.length>0&&(u.attachments=s),c&&(u.workflowId=c),qt.send("runner.launch",u)},switchMode:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:i})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:i})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(i,s,c)=>{e({streamingMessageId:null});const u={};i&&(u.workflowId=i),s!=null&&s.trim()&&(u.content=s),c&&c.length>0&&(u.attachments=c),qt.send("mode.accept",u)},editCriteria:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:i})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{qt.send("context.compact",{})},setSessionProvider:async(i,s)=>{var c;try{const u=(c=r().currentSession)==null?void 0:c.id;if(!u)return null;const f=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:i,...s?{model:s}:{}})});if(!f.ok)return null;const l=await f.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:i=>{e({contextState:i})},updateSubAgentContextState:(i,s)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[i]:s}}))},clearSubAgentContextState:i=>{e(s=>{const c={...s.subAgentContextStates};return delete c[i],{subAgentContextStates:c}})},confirmPath:async(i,s,c=!1)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,approved:s,alwaysAllow:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(i,s)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,answer:s})})}catch(f){console.error("Error answering question:",f)}e({pendingQuestion:null})}},queueAsap:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const f=await(await ke(`/api/sessions/${s}/queue/${i}`,{method:"DELETE"})).json();f.queueState&&e({queuedMessages:f.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:i=>{var f,l,d,p,g,m,b,_,E,C,y,x,v,S,j,T,N,D,A,I,B,q,V,W;const s=r();X1(i,s);const c=((f=s.currentSession)==null?void 0:f.id)??null,u=()=>{const O=i.sessionId;!O||O===c||e(F=>({unreadSessionIds:V1(F.unreadSessionIds,O)}))};switch(i.type){case"session.state":{const O=i.payload;if(!G1(i,c,s.pendingSessionCreate))break;Ai();const F=O.messages.find(L=>L.isStreaming)??null,H=r().pendingSessionCreate===!0,Z=O.pendingConfirmations??[],M=s.pendingPathConfirmation??(Z.length>0?Z[0]??null:null);if(e({currentSession:O.session,sessions:K1(r().sessions,O.session),unreadSessionIds:Ia(r().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(F==null?void 0:F.id)??null,streamingMessage:F,currentTodos:[],pendingPathConfirmation:M,error:null,...H?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId&&O.session.providerModel){const L=At.getState();L.providers.find($=>$.id===O.session.providerId)&&L.syncFromSession(O.session.providerId,O.session.providerModel)}break}case"session.list":{const O=i.payload;e(F=>({sessions:Y1(O.sessions,F.sessions,F.currentSession)}));break}case"session.deleted":{const O=i.payload;e(F=>({unreadSessionIds:Ia(F.unreadSessionIds,O.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const O=i.payload,F=i.sessionId,H=(l=r().currentSession)==null?void 0:l.id,Z=F&&F!==H;e(K=>({sessions:K.sessions.map(M=>M.id===F?{...M,isRunning:O.isRunning}:M)})),Z||e(K=>({currentSession:K.currentSession?{...K.currentSession,isRunning:O.isRunning}:null,...O.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!zt(i,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const O=i.payload;e(F=>F.messages.some(H=>H.id===O.message.id)?F:{messages:[...F.messages,O.message],streamingMessageId:O.message.isStreaming?O.message.id:F.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:F.streamingMessage});break}case"chat.message_updated":{if(!zt(i,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const O=i.payload,F=O.updates.isStreaming===!1&&r().streamingMessageId===O.messageId;F&&(Ai(),un==null||un()),e(H=>{const Z=H.streamingMessage,K=F;if(Z&&Z.id===O.messageId){const M={...Z,...O.updates};return{messages:H.messages.map(L=>L.id===O.messageId?M:L),streamingMessageId:K?null:H.streamingMessageId,streamingMessage:K?null:{...Z,...O.updates}}}return{messages:H.messages.map(M=>M.id===O.messageId?{...M,...O.updates}:M),streamingMessageId:K?null:H.streamingMessageId}});break}case"chat.delta":{if(!zt(i,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const O=i.payload;if(!Bd.has(O.messageId)){Bd.add(O.messageId);const F=Wa(r(),i.sessionId);W1(F)}$t.messageId=O.messageId,$t.deltaContent+=O.content,zd();break}case"chat.thinking":{if(!zt(i,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.thinkingContent+=O.content,zd();break}case"chat.tool_preparing":{if(!zt(i,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const O=i.payload;e(F=>{const H=F.streamingMessage;return H&&H.id===O.messageId?{streamingMessage:{...H,preparingToolCalls:[...H.preparingToolCalls??[],{index:O.index,name:O.name}]}}:{messages:F.messages.map(Z=>Z.id===O.messageId?{...Z,preparingToolCalls:[...Z.preparingToolCalls??[],{index:O.index,name:O.name}]}:Z)}});break}case"chat.tool_call":{if(!zt(i,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const O=i.payload,F=H=>{var M;const Z=(M=H.preparingToolCalls)==null?void 0:M.filter((L,z)=>{var $;return L.name===O.tool?($=H.preparingToolCalls)==null?void 0:$.slice(0,z).some(re=>re.name===O.tool):!0}),K=$t.toolOutput.filter(L=>L.callId===O.callId);return K.length>0&&($t.toolOutput=$t.toolOutput.filter(L=>L.callId!==O.callId)),{...H,toolCalls:[...H.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...K.length>0?{streamingOutput:K.map(L=>({stream:L.stream,content:L.content,timestamp:Date.now()}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};e(H=>{const Z=H.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:H.messages.map(K=>K.id===O.messageId?F(K):K)}});break}case"chat.tool_output":{if(!zt(i,((E=r().currentSession)==null?void 0:E.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),zd();break}case"chat.tool_result":{if(!zt(i,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const O=i.payload,F=H=>{var K;const Z=(K=H.toolCalls)==null?void 0:K.map(M=>M.id===O.callId?{...M,result:O.result}:M);return{...H,toolCalls:Z}};e(H=>{const Z=H.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:H.messages.map(K=>K.id===O.messageId?F(K):K)}});break}case"chat.vision_fallback":{if(!zt(i,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const O=i.payload;e(F=>{const H=`${O.messageId}-${O.attachmentId}`,Z={...F.visionFallbackByMessage};return Z[H]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:Z}});break}case"chat.todo":{if(!zt(i,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const O=i.payload;e({currentTodos:O.todos});break}case"chat.summary":{if(!zt(i,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,summary:O.summary}:null}));break}case"chat.progress":{if(!zt(i,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const O=i.payload;console.log("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!zt(i,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const O=i.payload;console.log("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!zt(i,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Ai(),un==null||un();const O=i.payload,F=O.stats;$t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[],Bd.delete(O.messageId),e(H=>{const Z=H.streamingMessage,K=Z&&Z.id===O.messageId?{...Z,isStreaming:!1,stats:F??Z.stats}:null;return{messages:H.messages.map(M=>M.id===O.messageId?K??{...M,isStreaming:!1,stats:F??M.stats}:M),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!zt(i,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Ai(),un==null||un();const O=i.payload;console.error("Chat error:",O.error,"recoverable:",O.recoverable),O.recoverable||($t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[]),e(F=>({error:{code:"CHAT_ERROR",message:O.error},streamingMessageId:O.recoverable?F.streamingMessageId:null,...O.recoverable?{}:{messages:F.streamingMessage?F.messages.map(H=>H.id===F.streamingMessage.id?F.streamingMessage:H):F.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!zt(i,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const O=i.payload;e({pendingPathConfirmation:{callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason}});break}case"chat.ask_user":{if(!zt(i,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const O=i.payload;e({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!zt(i,((I=r().currentSession)==null?void 0:I.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=i.payload,F=i.sessionId,H=(B=r().currentSession)==null?void 0:B.id,Z=F&&F!==H;e(K=>({sessions:K.sessions.map(M=>M.id===F?{...M,phase:O.phase}:M)})),Z||e(K=>({currentSession:K.currentSession?{...K.currentSession,phase:O.phase}:null}));break}case"criteria.updated":{if(!zt(i,((q=r().currentSession)==null?void 0:q.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,criteria:O.criteria}:null}));break}case"context.state":{const O=i.payload,F=zt(i,((V=r().currentSession)==null?void 0:V.id)??null);O.subAgentId?F&&r().updateSubAgentContextState(O.subAgentId,O.context):F?e({contextState:O.context}):u();break}case"session.name_generated":{const O=i.payload,F=i.sessionId,H=(W=r().currentSession)==null?void 0:W.id;e(Z=>{const K=Z.sessions.map(L=>L.id===F?{...L,title:O.name,updatedAt:new Date().toISOString()}:L),M=H===F?Z.currentSession?{...Z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:Z.currentSession;return{sessions:K,currentSession:M}});break}case"queue.state":{const O=i.payload;e({queuedMessages:O.messages});break}case"devServer.output":case"devServer.state":{cr.getState().handleMessage(i);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Va.getState().handleMessage(i.type,i.payload);break}case"error":{const O=i.payload;console.error("Server error:",O),e({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}}));function Rb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function Z1(){return Ce(e=>e.queuedMessages)}function Q1(){return Ce(e=>e.abortInProgress)}function J1(){const e=Ce(s=>s.connect),r=Ce(s=>s.connectionStatus),i=Oi(s=>s.load);return P.useEffect(()=>{e()},[e]),P.useEffect(()=>{r==="connected"&&i()},[r,i]),{connectionStatus:r}}function ew({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function Ob({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function tw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function nw({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function rw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Or({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function Mr({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function iw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function Jl({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function sw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function Dh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function ec({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function Fl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function aw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function ow({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function cw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function uw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Ux({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function Mb({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function dw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function hw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Ib({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Bb({className:e="",size:r="md"}){const i=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${i} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const zb=Bb,Hb=Bb;function fw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function pw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function mw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function gw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function xw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function vw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function bw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Pb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Fb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function _w({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Sw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function uh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function $x(e,r){const i=qt.ws;!i||i.readyState!==WebSocket.OPEN||i.send(JSON.stringify({id:uh(),type:e,payload:r}))}const Jn=Yn((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:i=>e({isOpen:i}),toggleOpen:()=>e(i=>({isOpen:!i.isOpen})),setWorkdir:i=>e({workdir:i}),fetchSessions:async()=>{try{const i=await ke("/api/terminals");if(i.ok){const s=await i.json();e({sessions:s});const c=qt.ws;if(c&&c.readyState===WebSocket.OPEN)for(const u of s)c.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async i=>{try{const s=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:i??r().workdir??void 0})});if(s.ok){const c=await s.json();e(f=>({sessions:[...f.sessions,c]}));const u=qt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:c.id}}))}}catch(s){console.error("Failed to create terminal:",s)}},writeSession:(i,s)=>{$x("terminal.write",{sessionId:i,data:s})},resizeSession:(i,s,c)=>{$x("terminal.resize",{sessionId:i,cols:s,rows:c})},killSession:async i=>{try{(await ke(`/api/terminals/${i}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.sessions.filter(u=>u.id!==i)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:i=>{switch(i.type){case"terminal.exit":{const{sessionId:s}=i.payload||{};s&&e(c=>{const u=c.sessions.filter(f=>f.id!==s);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));qt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&Jn.getState().handleMessage(e)});var tc=xb();const nc=P.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:i="",...s},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${i}`,...s,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));nc.displayName="IconButton";const ww="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",Bs=P.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:ww,title:"Edit",...e}));Bs.displayName="EditButton";const Cw="M6 18L18 6M6 6l12 12",Lh=P.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Cw,...e}));Lh.displayName="CloseButton";const kw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:i="md",minHeight:s,children:c,footer:u,className:f,onClose:l,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=P.useState(!1),E=d!==void 0,C=E?d:b,y=P.useCallback(()=>{E||_(!0)},[E]),x=P.useCallback(()=>{E||_(!1),l==null||l()},[E,l]);P.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&x()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,x,g]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:f,children:e}):o.jsx("span",{onClick:y,className:f,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,C&&(typeof document<"u"?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?x:void 0}),o.jsxs("div",{className:`relative w-full ${kw[i]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Lh,{onClick:x,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const it=P.forwardRef(({variant:e="secondary",size:r="md",className:i="",children:s,...c},u)=>{const f="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={primary:"bg-accent-primary/25 text-white hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${f} ${l[e]} ${d[r]} ${i}`,...c,children:s})});it.displayName="Button";function Ew({value:e,defaultUrl:r,disabled:i,onChange:s}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,disabled:i,onChange:u=>{const f=u.target.value;s(f===r?null:f)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:I1.map(({url:u,label:f})=>o.jsx("option",{value:u,title:f,children:f.split(" ")[0]},u))}),o.jsx(Mr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const qx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function jw(){const e=Oi(d=>d.settings),r=Oi(d=>d.update),i=Oi(d=>d.updateEvent),s=Oi(d=>d.updateAgentOverride),c=Oi(d=>d.load);P.useEffect(()=>{c()},[c]);const u=async()=>{await z1()==="granted"&&r({...e,browserNotificationEnabled:!0})},f=(d,p,g,m)=>{d==="general"?i(p,{[g]:m}):s(d,p,{[g]:m})},l=(d,p,g)=>{d==="general"?i(p,{customSoundUrl:g}):s(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(Wx,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(Wx,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),qx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:M1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),qx.map(p=>{const g=Db(e,d.key,p.key==="general"?void 0:p.key),m=Tb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>f(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>f(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Ew,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>l(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function Wx({label:e,description:r,checked:i,onChange:s}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${i?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:c=>{c.preventDefault(),s(!i)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${i?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Rh(e,r){r({loading:!0});try{const s=await(await ke(e)).json();r({defaults:s.defaults??[],userItems:s.userItems??[],loading:!1})}catch{r({loading:!1})}}const Dr=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Rh("/api/skills",e)},toggleSkill:async i=>{try{const c=await(await ke(`/api/skills/${i}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(f=>f.id===i?{...f,enabled:c.enabled}:f),userItems:u.userItems.map(f=>f.id===i?{...f,enabled:c.enabled}:f)}))}catch{}},fetchSkill:async i=>{try{const s=await ke(`/api/skills/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/skills/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createSkill:async i=>{const s=await di("POST","/api/skills",i);return s.success&&await r().fetchSkills(),s},updateSkill:async(i,s)=>{const c=await di("PUT",`/api/skills/${i}`,s);return c.success&&await r().fetchSkills(),c},deleteSkill:async i=>{try{const s=await ke(`/api/skills/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async i=>{try{const s=await ke(`/api/skills/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Oh(){const[e,r]=P.useState({id:null,type:null}),i=P.useCallback(u=>r({id:u,type:"delete"}),[]),s=P.useCallback(()=>r({id:null,type:null}),[]),c=P.useCallback((u,f)=>e.id===u&&e.type===f,[e.id,e.type]);return{requestDelete:i,clearConfirm:s,isConfirming:c}}function Mh({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function Ih({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Pb,{})})}function Qa({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(Jl,{})})}function Mi({label:e,value:r,onChange:i,placeholder:s,readOnly:c,hint:u,mono:f}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:l=>i(l.target.value),readOnly:c,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"font-mono":""} ${c?"opacity-60":""}`})]})}function Nw({onCancel:e,onSave:r,saving:i,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:r,disabled:i||s,children:i?"Saving...":"Save"})]})}function Bh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Ub({description:e,onNew:r,newLabel:i="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:r,children:i})})]})}function $b({isBuiltIn:e,isConfirmingDelete:r,onView:i,onEdit:s,onDuplicate:c,onDelete:u,children:f}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:f}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&i&&o.jsx("button",{onClick:i,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:c}),!e&&s&&o.jsx(Bs,{onClick:s}),!e&&(r?o.jsx(Mh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>u==null?void 0:u()}))]})]})}function Tw({id:e,name:r,description:i,isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d}){return o.jsxs($b,{isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),i&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:i})]})}function qb({loading:e,hasItems:r,loadingLabel:i,emptyLabel:s,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:i}):r?o.jsx("div",{className:"space-y-4",children:c}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function Wb({name:e,id:r,nameLabel:i="Name",idLabel:s="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:f,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:i,value:e,onChange:p,placeholder:c,hint:f}),o.jsx(Mi,{label:s,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Gb(e={}){const{initialData:r={}}=e,[i,s]=P.useState("list"),[c,u]=P.useState(null),[f,l]=P.useState(""),[d,p]=P.useState(!1),[g,m]=P.useState(r),b=P.useCallback(()=>{m(r),l(""),u(null)},[r]),_=P.useCallback(x=>{s(x),x==="list"&&b()},[b]),E=P.useCallback(x=>{m(v=>typeof x=="function"?x(v):x)},[]),C=P.useCallback((x,v={})=>{u(x),s("edit"),m({...v}),l("")},[]),y=P.useCallback(()=>{u(null),s("edit"),m(r),l("")},[r]);return{view:i,editingId:c,formError:f,saving:d,formData:g,setView:_,setEditingId:u,setFormError:l,setFormData:E,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function zh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function Gx({skill:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsx(Tw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f})}function Aw({isOpen:e}){const r=Dr(O=>O.defaults),i=Dr(O=>O.userItems),s=Dr(O=>O.loading),c=Dr(O=>O.fetchSkills),u=Dr(O=>O.fetchSkill),f=Dr(O=>O.fetchDefaultContent),l=Dr(O=>O.createSkill),d=Dr(O=>O.updateSkill),p=Dr(O=>O.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:E,setView:C,setEditingId:y,setFormError:x,setFormData:v,setSaving:S}=Gb(),{clearConfirm:j}=Oh();P.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const T=(O,F,H,Z)=>{v({name:Z??O.metadata.name,id:H??O.metadata.id,description:O.metadata.description??"",version:O.metadata.version??"1.0.0",prompt:O.prompt,isReadOnly:F})},N=async O=>{if(r.some(H=>H.id===O)){const H=await f(O);if(!H)return;T(H,!0),y(O),x(""),C("edit")}else{const H=await u(O);if(!H)return;T(H,!0),y(O),x(""),C("edit")}},D=async O=>{const H=r.some(K=>K.id===O)?await f(O):await u(O);if(!H)return;const Z=`${O}-copy-${Date.now()}`;T(H,!1,Z,`${H.metadata.name} (copy)`),y(null),x(""),C("edit")},A=()=>{v({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},I=async O=>{const F=await u(O);F&&(T(F,!1),y(O),x(""),C("edit"))},B=async O=>{await p(O),j()},q=async()=>{const O=m??E.id;if(!O||!E.name||!E.prompt){x("Name, ID, and prompt are required.");return}S(!0),x("");const F={metadata:{id:O,name:E.name,description:E.description,version:E.version},prompt:E.prompt},H=m?await d(m,F):await l(F);if(S(!1),!H.success){x(H.error??"Failed to save skill.");return}C("list")},V=O=>{v(F=>({...F,name:O})),m||v(F=>({...F,id:O.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=E.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?E.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Bh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(Wb,{name:E.name,id:E.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:V,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:E.description,onChange:O=>v(F=>({...F,description:O})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Mi,{label:"Version",value:E.version,onChange:O=>v(F=>({...F,version:O})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:E.prompt,onChange:O=>v(F=>({...F,prompt:O.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(it,{variant:"primary",onClick:()=>{v(O=>({...O,name:O.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(it,{variant:"primary",onClick:q,disabled:_||!E.name||!E.id||!E.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Ub,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs(qb,{loading:s,hasItems:r.length>0||i.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(O.id),onDuplicate:()=>D(O.id)},O.id))})]}),i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:i.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(O.id),onEdit:()=>I(O.id),onDuplicate:()=>D(O.id),onDelete:()=>B(O.id)},O.id))})]})]})]})}function Dw({isOpen:e,onClose:r}){const[i,s]=P.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(Ba,{label:"Instructions",active:i==="instructions",onClick:()=>s("instructions")}),o.jsx(Ba,{label:"Skills",active:i==="skills",onClick:()=>s("skills")}),o.jsx(Ba,{label:"Notifications",active:i==="notifications",onClick:()=>s("notifications")}),o.jsx(Ba,{label:"Display",active:i==="display",onClick:()=>s("display")}),o.jsx(Ba,{label:"Advanced",active:i==="advanced",onClick:()=>s("advanced")})]}),i==="instructions"&&o.jsx(Ow,{isOpen:e}),i==="skills"&&o.jsx(Aw,{isOpen:e}),i==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(jw,{})}),i==="display"&&o.jsx(Rw,{}),i==="advanced"&&o.jsx(Lw,{onClose:r})]})})}function Lw({onClose:e}){const[,r]=ur();function i(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(it,{variant:"secondary",onClick:i,children:"Launch Onboarding"})]})})}function Rw(){const e=en(g=>g.settings),r=en(g=>g.loading),i=en(g=>g.getSetting),s=en(g=>g.setSetting),c=r[Et.DISPLAY_SHOW_THINKING]??!1,u=[{key:Et.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:Et.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:Et.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:Et.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],f=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[l,d]=P.useState(()=>Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])));P.useEffect(()=>{u.forEach(g=>i(g.key))},[i]),P.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])))},[JSON.stringify(f)]);const p=async g=>{const m=String(!l[g]);d(b=>({...b,[g]:!b[g]})),await s(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})})}function Ba({label:e,active:r,onClick:i}){return o.jsx("button",{onClick:i,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Ow({isOpen:e}){const r=en(y=>y.settings),i=en(y=>y.loading),s=en(y=>y.getSetting),c=en(y=>y.setSetting),u=r[Et.GLOBAL_INSTRUCTIONS]??"",f=i[Et.GLOBAL_INSTRUCTIONS]??!1,[l,d]=P.useState(u),[p,g]=P.useState(!1),[m,b]=P.useState(!1);P.useEffect(()=>{e&&s(Et.GLOBAL_INSTRUCTIONS)},[e,s]),P.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),c(Et.GLOBAL_INSTRUCTIONS,l),b(!1),g(!1)},E=()=>{d(u),g(!1)},C=f||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:E,disabled:!p,children:"Discard"}),o.jsx(it,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var Hd={exports:{}},Vx;function Mw(){return Vx||(Vx=1,(function(e,r){(function(i,s){e.exports=s()})(globalThis,(()=>(()=>{var i={4567:function(f,l,d){var p=this&&this.__decorate||function(v,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,S,j,T);else for(var I=v.length-1;I>=0;I--)(N=v[I])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(v,S){return function(j,T){S(j,T,v)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),E=d(4725),C=d(2585),y=d(3656);let x=l.AccessibilityManager=class extends _.Disposable{constructor(v,S,j,T){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
58
58
|
`)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,_.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(v){for(let S=0;S<v;S++)this._handleChar(" ")}_handleChar(v){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==v&&(this._charsToAnnounce+=v):this._charsToAnnounce+=v,v===`
|
|
59
59
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(v){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(v)||this._charsToConsume.push(v)}_refreshRows(v,S){this._liveRegionDebouncer.refresh(v,S,this._terminal.rows)}_renderRows(v,S){const j=this._terminal.buffer,T=j.lines.length.toString();for(let N=v;N<=S;N++){const D=j.lines.get(j.ydisp+N),A=[],I=(D==null?void 0:D.translateToString(!0,void 0,void 0,A))||"",B=(j.ydisp+N+1).toString(),q=this._rowElements[N];q&&(I.length===0?(q.innerText=" ",this._rowColumns.set(q,[0,1])):(q.textContent=I,this._rowColumns.set(q,A)),q.setAttribute("aria-posinset",B),q.setAttribute("aria-setsize",T))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(v,S){const j=v.target,T=this._rowElements[S===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(S===0?"1":`${this._terminal.buffer.lines.length}`)||v.relatedTarget!==T)return;let N,D;if(S===0?(N=j,D=this._rowElements.pop(),this._rowContainer.removeChild(D)):(N=this._rowElements.shift(),D=j,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),D.removeEventListener("focus",this._bottomBoundaryFocusListener),S===0){const A=this._createAccessibilityTreeNode();this._rowElements.unshift(A),this._rowContainer.insertAdjacentElement("afterbegin",A)}else{const A=this._createAccessibilityTreeNode();this._rowElements.push(A),this._rowContainer.appendChild(A)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(S===0?-1:1),this._rowElements[S===0?1:this._rowElements.length-2].focus(),v.preventDefault(),v.stopImmediatePropagation()}_handleSelectionChange(){var I;if(this._rowElements.length===0)return;const v=document.getSelection();if(!v)return;if(v.isCollapsed)return void(this._rowContainer.contains(v.anchorNode)&&this._terminal.clearSelection());if(!v.anchorNode||!v.focusNode)return void console.error("anchorNode and/or focusNode are null");let S={node:v.anchorNode,offset:v.anchorOffset},j={node:v.focusNode,offset:v.focusOffset};if((S.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||S.node===j.node&&S.offset>j.offset)&&([S,j]=[j,S]),S.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(S={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(S.node))return;const T=this._rowElements.slice(-1)[0];if(j.node.compareDocumentPosition(T)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(j={node:T,offset:((I=T.textContent)==null?void 0:I.length)??0}),!this._rowContainer.contains(j.node))return;const N=({node:B,offset:q})=>{const V=B instanceof Text?B.parentNode:B;let W=parseInt(V==null?void 0:V.getAttribute("aria-posinset"),10)-1;if(isNaN(W))return console.warn("row is invalid. Race condition?"),null;const O=this._rowColumns.get(V);if(!O)return console.warn("columns is null. Race condition?"),null;let F=q<O.length?O[q]:O.slice(-1)[0]+1;return F>=this._terminal.cols&&(++W,F=0),{row:W,column:F}},D=N(S),A=N(j);if(D&&A){if(D.row>A.row||D.row===A.row&&D.column>=A.column)throw new Error("invalid range");this._terminal.select(D.column,D.row,(A.row-D.row)*this._terminal.cols-D.column+A.column)}}_handleResize(v){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let S=this._rowContainer.children.length;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);for(;this._rowElements.length>v;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const v=this._coreBrowserService.mainDocument.createElement("div");return v.setAttribute("role","listitem"),v.tabIndex=-1,this._refreshRowDimensions(v),v}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let v=0;v<this._terminal.rows;v++)this._refreshRowDimensions(this._rowElements[v])}}_refreshRowDimensions(v){v.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=x=p([g(1,C.IInstantiationService),g(2,E.ICoreBrowserService),g(3,E.IRenderService)],x)},3614:(f,l)=>{function d(b){return b.replace(/\r?\n/g,"\r")}function p(b,_){return _?"\x1B[200~"+b+"\x1B[201~":b}function g(b,_,E,C){b=p(b=d(b),E.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),E.triggerDataEvent(b,!0),_.value=""}function m(b,_,E){const C=E.getBoundingClientRect(),y=b.clientX-C.left-10,x=b.clientY-C.top-10;_.style.width="20px",_.style.height="20px",_.style.left=`${y}px`,_.style.top=`${x}px`,_.style.zIndex="1000",_.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=d,l.bracketTextForPaste=p,l.copyHandler=function(b,_){b.clipboardData&&b.clipboardData.setData("text/plain",_.selectionText),b.preventDefault()},l.handlePasteEvent=function(b,_,E,C){b.stopPropagation(),b.clipboardData&&g(b.clipboardData.getData("text/plain"),_,E,C)},l.paste=g,l.moveTextAreaUnderMouseCursor=m,l.rightClickHandler=function(b,_,E,C,y){m(b,_,E),y&&C.rightClickSelect(b),_.value=C.selectionText,_.select()}},7239:(f,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const p=d(1505);l.ColorContrastCache=class{constructor(){this._color=new p.TwoKeyMap,this._css=new p.TwoKeyMap}setCss(g,m,b){this._css.set(g,m,b)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,b){this._color.set(g,m,b)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(f,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(d,p,g,m){d.addEventListener(p,g,m);let b=!1;return{dispose:()=>{b||(b=!0,d.removeEventListener(p,g,m))}}}},3551:function(f,l,d){var p=this&&this.__decorate||function(x,v,S,j){var T,N=arguments.length,D=N<3?v:j===null?j=Object.getOwnPropertyDescriptor(v,S):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(x,v,S,j);else for(var A=x.length-1;A>=0;A--)(T=x[A])&&(D=(N<3?T(D):N>3?T(v,S,D):T(v,S))||D);return N>3&&D&&Object.defineProperty(v,S,D),D},g=this&&this.__param||function(x,v){return function(S,j){v(S,j,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const m=d(3656),b=d(8460),_=d(844),E=d(2585),C=d(4725);let y=l.Linkifier=class extends _.Disposable{get currentLink(){return this._currentLink}constructor(x,v,S,j,T){super(),this._element=x,this._mouseService=v,this._renderService=S,this._bufferService=j,this._linkProviderService=T,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new b.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new b.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,_.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,_.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(x){this._lastMouseEvent=x;const v=this._positionFromMouseEvent(x,this._element,this._mouseService);if(!v)return;this._isMouseOut=!1;const S=x.composedPath();for(let j=0;j<S.length;j++){const T=S[j];if(T.classList.contains("xterm"))break;if(T.classList.contains("xterm-hover"))return}this._lastBufferCell&&v.x===this._lastBufferCell.x&&v.y===this._lastBufferCell.y||(this._handleHover(v),this._lastBufferCell=v)}_handleHover(x){if(this._activeLine!==x.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(x,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,x)||(this._clearCurrentLink(),this._askForLink(x,!0))}_askForLink(x,v){var j,T;this._activeProviderReplies&&v||((j=this._activeProviderReplies)==null||j.forEach((N=>{N==null||N.forEach((D=>{D.link.dispose&&D.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=x.y);let S=!1;for(const[N,D]of this._linkProviderService.linkProviders.entries())v?(T=this._activeProviderReplies)!=null&&T.get(N)&&(S=this._checkLinkProviderResult(N,x,S)):D.provideLinks(x.y,(A=>{var B,q;if(this._isMouseOut)return;const I=A==null?void 0:A.map((V=>({link:V})));(B=this._activeProviderReplies)==null||B.set(N,I),S=this._checkLinkProviderResult(N,x,S),((q=this._activeProviderReplies)==null?void 0:q.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(x.y,this._activeProviderReplies)}))}_removeIntersectingLinks(x,v){const S=new Set;for(let j=0;j<v.size;j++){const T=v.get(j);if(T)for(let N=0;N<T.length;N++){const D=T[N],A=D.link.range.start.y<x?0:D.link.range.start.x,I=D.link.range.end.y>x?this._bufferService.cols:D.link.range.end.x;for(let B=A;B<=I;B++){if(S.has(B)){T.splice(N--,1);break}S.add(B)}}}}_checkLinkProviderResult(x,v,S){var N;if(!this._activeProviderReplies)return S;const j=this._activeProviderReplies.get(x);let T=!1;for(let D=0;D<x;D++)this._activeProviderReplies.has(D)&&!this._activeProviderReplies.get(D)||(T=!0);if(!T&&j){const D=j.find((A=>this._linkAtPosition(A.link,v)));D&&(S=!0,this._handleNewLink(D))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!S)for(let D=0;D<this._activeProviderReplies.size;D++){const A=(N=this._activeProviderReplies.get(D))==null?void 0:N.find((I=>this._linkAtPosition(I.link,v)));if(A){S=!0,this._handleNewLink(A);break}}return S}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(x){if(!this._currentLink)return;const v=this._positionFromMouseEvent(x,this._element,this._mouseService);v&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,v)&&this._currentLink.link.activate(x,this._currentLink.link.text)}_clearCurrentLink(x,v){this._currentLink&&this._lastMouseEvent&&(!x||!v||this._currentLink.link.range.start.y>=x&&this._currentLink.link.range.end.y<=v)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,_.disposeArray)(this._linkCacheDisposables))}_handleNewLink(x){if(!this._lastMouseEvent)return;const v=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);v&&this._linkAtPosition(x.link,v)&&(this._currentLink=x,this._currentLink.state={decorations:{underline:x.link.decorations===void 0||x.link.decorations.underline,pointerCursor:x.link.decorations===void 0||x.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,x.link,this._lastMouseEvent),x.link.decorations={},Object.defineProperties(x.link.decorations,{pointerCursor:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.pointerCursor},set:S=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==S&&(this._currentLink.state.decorations.pointerCursor=S,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",S))}},underline:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.underline},set:S=>{var j,T,N;(j=this._currentLink)!=null&&j.state&&((N=(T=this._currentLink)==null?void 0:T.state)==null?void 0:N.decorations.underline)!==S&&(this._currentLink.state.decorations.underline=S,this._currentLink.state.isHovered&&this._fireUnderlineEvent(x.link,S))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((S=>{if(!this._currentLink)return;const j=S.start===0?0:S.start+1+this._bufferService.buffer.ydisp,T=this._bufferService.buffer.ydisp+1+S.end;if(this._currentLink.link.range.start.y>=j&&this._currentLink.link.range.end.y<=T&&(this._clearCurrentLink(j,T),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(x,v,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!0),this._currentLink.state.decorations.pointerCursor&&x.classList.add("xterm-cursor-pointer")),v.hover&&v.hover(S,v.text)}_fireUnderlineEvent(x,v){const S=x.range,j=this._bufferService.buffer.ydisp,T=this._createLinkUnderlineEvent(S.start.x-1,S.start.y-j-1,S.end.x,S.end.y-j-1,void 0);(v?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(T)}_linkLeave(x,v,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!1),this._currentLink.state.decorations.pointerCursor&&x.classList.remove("xterm-cursor-pointer")),v.leave&&v.leave(S,v.text)}_linkAtPosition(x,v){const S=x.range.start.y*this._bufferService.cols+x.range.start.x,j=x.range.end.y*this._bufferService.cols+x.range.end.x,T=v.y*this._bufferService.cols+v.x;return S<=T&&T<=j}_positionFromMouseEvent(x,v,S){const j=S.getCoords(x,v,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(x,v,S,j,T){return{x1:x,y1:v,x2:S,y2:j,cols:this._bufferService.cols,fg:T}}};l.Linkifier=y=p([g(1,C.IMouseService),g(2,C.IRenderService),g(3,E.IBufferService),g(4,C.ILinkProviderService)],y)},9042:(f,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(f,l,d){var p=this&&this.__decorate||function(C,y,x,v){var S,j=arguments.length,T=j<3?y:v===null?v=Object.getOwnPropertyDescriptor(y,x):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(C,y,x,v);else for(var N=C.length-1;N>=0;N--)(S=C[N])&&(T=(j<3?S(T):j>3?S(y,x,T):S(y,x))||T);return j>3&&T&&Object.defineProperty(y,x,T),T},g=this&&this.__param||function(C,y){return function(x,v){y(x,v,C)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const m=d(511),b=d(2585);let _=l.OscLinkProvider=class{constructor(C,y,x){this._bufferService=C,this._optionsService=y,this._oscLinkService=x}provideLinks(C,y){var I;const x=this._bufferService.buffer.lines.get(C-1);if(!x)return void y(void 0);const v=[],S=this._optionsService.rawOptions.linkHandler,j=new m.CellData,T=x.getTrimmedLength();let N=-1,D=-1,A=!1;for(let B=0;B<T;B++)if(D!==-1||x.hasContent(B)){if(x.loadCell(B,j),j.hasExtendedAttrs()&&j.extended.urlId){if(D===-1){D=B,N=j.extended.urlId;continue}A=j.extended.urlId!==N}else D!==-1&&(A=!0);if(A||D!==-1&&B===T-1){const q=(I=this._oscLinkService.getLinkData(N))==null?void 0:I.uri;if(q){const V={start:{x:D+1,y:C},end:{x:B+(A||B!==T-1?0:1),y:C}};let W=!1;if(!(S!=null&&S.allowNonHttpProtocols))try{const O=new URL(q);["http:","https:"].includes(O.protocol)||(W=!0)}catch{W=!0}W||v.push({text:q,range:V,activate:(O,F)=>S?S.activate(O,F,V):E(0,F),hover:(O,F)=>{var H;return(H=S==null?void 0:S.hover)==null?void 0:H.call(S,O,F,V)},leave:(O,F)=>{var H;return(H=S==null?void 0:S.leave)==null?void 0:H.call(S,O,F,V)}})}A=!1,j.hasExtendedAttrs()&&j.extended.urlId?(D=B,N=j.extended.urlId):(D=-1,N=-1)}}y(v)}};function E(C,y){if(confirm(`Do you want to navigate to ${y}?
|
|
60
60
|
|