@amd-gaia/agent-ui 0.18.0 → 0.18.1

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.
@@ -485,7 +485,7 @@ Error generating stack: `+l.message+`
485
485
  * LICENSE file in the root directory of this source tree.
486
486
  */var vo=p,Mw=Pw;function Rw(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var $w=typeof Object.is=="function"?Object.is:Rw,Fw=Mw.useSyncExternalStore,Ow=vo.useRef,Uw=vo.useEffect,Bw=vo.useMemo,Hw=vo.useDebugValue;vy.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var l=Ow(null);if(l.current===null){var a={hasValue:!1,value:null};l.current=a}else a=l.current;l=Bw(function(){function c(m){if(!u){if(u=!0,d=m,m=r(m),i!==void 0&&a.hasValue){var g=a.value;if(i(g,m))return f=g}return f=m}if(g=f,$w(d,m))return g;var v=r(m);return i!==void 0&&i(g,v)?(d=m,g):(d=m,f=v)}var u=!1,d,f,h=n===void 0?null:n;return[function(){return c(t())},h===null?void 0:function(){return c(h())}]},[t,n,r,i]);var o=Fw(e,l[0],l[1]);return Uw(function(){a.hasValue=!0,a.value=o},[o]),Hw(o),o};xy.exports=vy;var Vw=xy.exports;const Ww=to(Vw),by={},{useDebugValue:Gw}=Gi,{useSyncExternalStoreWithSelector:qw}=Ww;let Dm=!1;const Qw=e=>e;function Kw(e,t=Qw,n){(by?"production":void 0)!=="production"&&n&&!Dm&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Dm=!0);const r=qw(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Gw(r),r}const Am=e=>{(by?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?Nw(e):e,n=(r,i)=>Kw(t,r,i);return Object.assign(n,t),n},jy=e=>e?Am(e):Am,we=jy((e,t)=>({agents:[],activeAgentId:(()=>{try{return localStorage.getItem("gaia-active-agent-id")||"chat"}catch{return"chat"}})(),setAgents:n=>e({agents:n}),setActiveAgentId:n=>{try{localStorage.setItem("gaia-active-agent-id",n)}catch{}e({activeAgentId:n})},sessions:[],currentSessionId:null,pendingDeleteIds:[],setSessions:n=>e(r=>({sessions:n.filter(i=>!r.pendingDeleteIds.includes(i.id))})),setCurrentSession:n=>e({currentSessionId:n}),addSession:n=>e(r=>({sessions:[n,...r.sessions]})),removeSession:n=>e(r=>({sessions:r.sessions.filter(i=>i.id!==n),currentSessionId:r.currentSessionId===n?null:r.currentSessionId,messages:r.currentSessionId===n?[]:r.messages})),updateSessionInList:(n,r)=>e(i=>({sessions:i.sessions.map(l=>l.id===n?{...l,...r}:l)})),addPendingDelete:n=>e(r=>({pendingDeleteIds:[...r.pendingDeleteIds,n]})),removePendingDelete:n=>e(r=>({pendingDeleteIds:r.pendingDeleteIds.filter(i=>i!==n)})),messages:[],setMessages:n=>e({messages:n}),addMessage:n=>e(r=>({messages:[...r.messages,n]})),removeMessage:n=>e(r=>({messages:r.messages.filter(i=>i.id!==n)})),removeMessagesFrom:n=>e(r=>{const i=r.messages.findIndex(l=>l.id===n);return i===-1?r:{messages:r.messages.slice(0,i)}}),isStreaming:!1,streamingContent:"",setStreaming:n=>e({isStreaming:n}),appendStreamContent:n=>e(r=>({streamingContent:r.streamingContent+n})),setStreamContent:n=>e({streamingContent:n}),clearStreamContent:()=>e({streamingContent:""}),agentSteps:[],addAgentStep:n=>e(r=>({agentSteps:[...r.agentSteps.map(i=>({...i,active:!1})),n]})),updateLastAgentStep:n=>e(r=>{if(r.agentSteps.length===0)return r;const i=[...r.agentSteps];return i[i.length-1]={...i[i.length-1],...n},{agentSteps:i}}),appendThinkingContent:n=>e(r=>{if(r.agentSteps.length===0)return r;const i=[...r.agentSteps],l=i[i.length-1];return l.type!=="thinking"?r:(i[i.length-1]={...l,detail:(l.detail?l.detail+`
487
487
  `:"")+n,active:!0},{agentSteps:i})}),updateLastToolStep:n=>e(r=>{if(r.agentSteps.length===0)return r;const i=[...r.agentSteps];for(let l=i.length-1;l>=0;l--)if(i[l].type==="tool")return i[l]={...i[l],...n},{agentSteps:i};return r}),clearAgentSteps:()=>e({agentSteps:[]}),documents:[],setDocuments:n=>e({documents:n}),systemStatus:null,backendConnected:!0,setSystemStatus:n=>e({systemStatus:n}),setBackendConnected:n=>e({backendConnected:n}),theme:(()=>{try{return localStorage.getItem("gaia-chat-theme")||"dark"}catch{return"dark"}})(),showDocLibrary:!1,showFileBrowser:!1,showSettings:!1,showMemoryDashboard:!1,toggleTheme:()=>e(n=>{const r=n.theme==="dark"?"light":"dark";try{localStorage.setItem("gaia-chat-theme",r)}catch{}return document.documentElement.setAttribute("data-theme",r),{theme:r}}),sidebarOpen:typeof window<"u"?window.innerWidth>768:!0,sidebarCollapsed:(()=>{try{return typeof window<"u"&&localStorage.getItem("gaia-chat-sidebar-collapsed")==="true"}catch{return!1}})(),sidebarWidth:(()=>{try{return typeof window<"u"?parseInt(localStorage.getItem("gaia-chat-sidebar-width")||"300",10):300}catch{return 300}})(),isLoadingMessages:!1,pendingPrompt:null,setShowDocLibrary:n=>e({showDocLibrary:n}),setShowFileBrowser:n=>e({showFileBrowser:n}),setShowSettings:n=>e({showSettings:n}),setShowMemoryDashboard:n=>e({showMemoryDashboard:n}),toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),setSidebarOpen:n=>e({sidebarOpen:n}),toggleSidebarCollapsed:()=>e(n=>{const r=!n.sidebarCollapsed;try{localStorage.setItem("gaia-chat-sidebar-collapsed",String(r))}catch{}return{sidebarCollapsed:r}}),setSidebarCollapsed:n=>{try{localStorage.setItem("gaia-chat-sidebar-collapsed",String(n))}catch{}e({sidebarCollapsed:n})},setSidebarWidth:n=>{const r=Math.max(200,Math.min(500,n));try{localStorage.setItem("gaia-chat-sidebar-width",String(r))}catch{}e({sidebarWidth:r})},setLoadingMessages:n=>e({isLoadingMessages:n}),setPendingPrompt:n=>e({pendingPrompt:n})})),Yw=/^https?:\/\/(127\.0\.0\.1|localhost):\d+\/api$/,Xw="http://localhost:4200/api";function jd(){if(typeof window>"u")return"/api";if(window.location.protocol==="file:"){const e=new URLSearchParams(window.location.search).get("api");return e&&Yw.test(e)?e:Xw}return"/api"}const Jw={api:"#4fc3f7",store:"#ce93d8",chat:"#81c784",stream:"#ffb74d",ui:"#90a4ae",doc:"#a1887f",system:"#e57373",nav:"#fff176"},Zw={api:"fetch",store:"state",chat:"chat",stream:"stream",ui:"ui",doc:"docs",system:"sys",nav:"nav"},ya=(()=>{try{if(localStorage.getItem("gaia-debug")==="true")return!0;if(typeof location<"u"){const e=new URLSearchParams(location.search);if(e.has("debug")||e.has("verbose"))return!0}}catch{}return!1})();function _s(){const e=new Date;return e.toLocaleTimeString("en-US",{hour12:!1})+"."+String(e.getMilliseconds()).padStart(3,"0")}function kr(e){const t=Jw[e]||"#ccc",r=`%c[${Zw[e]||e}]`,i=`color: ${t}; font-weight: bold;`,l="color: #888; font-weight: normal;";return{info:(a,...o)=>{if(!ya)return;const c=_s();o.length>0?console.log(`${r} %c${c} %c${a}`,i,l,"color: inherit;",...o):console.log(`${r} %c${c} %c${a}`,i,l,"color: inherit;")},warn:(a,...o)=>{const c=_s();console.warn(`${r} %c${c} %c${a}`,i,l,"color: inherit;",...o)},error:(a,...o)=>{const c=_s();console.error(`${r} %c${c} %c${a}`,i,l,"color: inherit;",...o)},debug:(a,...o)=>{if(!ya)return;const c=_s();console.debug(`${r} %c${c} %c${a}`,i,l,"color: #999;",...o)},timed:(a,o,...c)=>{if(!ya)return;const u=Math.round(performance.now()-o),d=_s(),f=u>2e3?"color: #e57373;":u>500?"color: #ffb74d;":"color: #81c784;";c.length>0?console.log(`${r} %c${d} %c${a} %c(${u}ms)`,i,l,"color: inherit;",f,...c):console.log(`${r} %c${d} %c${a} %c(${u}ms)`,i,l,"color: inherit;",f)},time:()=>performance.now()}}const E={api:kr("api"),store:kr("store"),chat:kr("chat"),stream:kr("stream"),ui:kr("ui"),doc:kr("doc"),system:kr("system"),nav:kr("nav")};function e0(e){console.log("%c GAIA %c v"+e+" %c Local AI Desktop","background: #E23C40; color: white; font-weight: bold; padding: 4px 8px; border-radius: 4px 0 0 4px;","background: #333; color: #fff; padding: 4px 8px;","background: #1a1a1a; color: #888; padding: 4px 8px; border-radius: 0 4px 4px 0;"),console.log(ya?"%cVerbose logging enabled. Categories: [fetch] [state] [chat] [stream] [ui] [docs] [sys] [nav]":'%cVerbose logging: add ?debug to URL or run localStorage.setItem("gaia-debug","true")',"color: #666; font-style: italic;")}const ko=jd();function Sy(e,t){switch(e){case 403:return t||"Access denied.";case 404:return t||"The requested item was not found.";case 413:return t||"File too large to process.";case 500:return"Server error. Please try again.";case 502:return"Service unavailable. Is the backend running?";case 503:return t||"Service unavailable.";default:return t||`Request failed (HTTP ${e})`}}async function ye(e,t,n,r){const i=`${ko}${t}`,l=E.api.time();E.api.info(`${e} ${i}`,n!==void 0?{body:n}:"");const o={method:e,headers:{...r,...n!==void 0?{"Content-Type":"application/json"}:{}},body:n!==void 0?JSON.stringify(n):void 0};let c;try{c=await fetch(i,o)}catch(f){throw E.api.error(`${e} ${i} - network error`,f),f}if(!c.ok){const f=await c.text().catch(()=>"");E.api.error(`${e} ${i} - HTTP ${c.status}`,{errorText:f});let h=f;try{h=JSON.parse(f).detail||f}catch{}throw new Error(Sy(c.status,h))}if(!(c.headers.get("content-type")||"").includes("application/json")){E.api.timed(`${e} ${i} -> ${c.status} (no body)`,l);return}const d=await c.json();return E.api.timed(`${e} ${i} -> ${c.status}`,l,d),d}async function Sd(){return ye("GET","/system/status")}async function t0(){return ye("GET","/settings")}async function n0(e){return ye("PUT","/settings",e)}async function r0(e,t){return ye("POST","/system/load-model",{model_name:e,ctx_size:t})}async function i0(e,t=!1){return ye("POST","/system/download-model",{model_name:e,force:t})}async function Nd(){return ye("GET","/agents")}const mi={"x-gaia-ui":"1"};async function s0(){return ye("GET","/connectors")}async function Ny(e){return ye("GET",`/connectors/${e}`)}async function Cy(e,t){return ye("POST",`/connectors/${e}/authorize`,{scopes:t},mi)}async function _y(e,t){return ye("POST",`/connectors/${e}/configure`,{config:t},mi)}async function Cd(e){await ye("DELETE",`/connectors/${e}`,void 0,mi)}async function Ey(e){return ye("POST",`/connectors/${e}/enable`,{},mi)}async function Ty(e){return ye("POST",`/connectors/${e}/disable`,{},mi)}async function l0(){return ye("GET","/connectors/agent-mcps")}async function a0(e){return ye("GET",`/connectors/${e}/grants`)}async function o0(e,t,n){await ye("PUT",`/connectors/${e}/grants/${encodeURIComponent(t)}`,{scopes:n},mi)}async function c0(e,t){await ye("DELETE",`/connectors/${e}/grants/${encodeURIComponent(t)}`,void 0,mi)}async function u0(){return ye("GET","/sessions")}async function hu(e={}){return ye("POST","/sessions",e)}async function tc(e,t){return ye("PUT",`/sessions/${e}`,t)}async function zy(e){return ye("DELETE",`/sessions/${e}`)}async function d0(e){return ye("PATCH",`/sessions/${e}/private`)}async function As(e){return ye("GET",`/sessions/${e}/messages`)}async function f0(e){return ye("GET",`/sessions/${e}/export?format=markdown`)}async function m0(e,t){return ye("DELETE",`/sessions/${e}/messages/${t}`)}async function h0(e,t){return ye("DELETE",`/sessions/${e}/messages/${t}/and-below`)}const p0=new Set(["status","step","thinking","plan","tool_start","tool_end","tool_result","tool_args","tool_confirm","agent_error","permission_request","policy_alert"]);function Ly(e,t,n,r,i,l){let a;typeof n=="function"?a={onChunk:n,onAgentEvent:()=>{},onDone:()=>{},onError:h=>{E.stream.error("Unhandled stream error",h)}}:a=n;const o=new AbortController,c=E.stream.time();let u=0,d=0,f=0;return E.stream.info(`Starting SSE stream for session=${e}`,{messageLength:t.length}),fetch(`${ko}/chat/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:e,message:t,stream:!0,...l?{agent_type:l}:{}}),signal:o.signal}).then(async h=>{var x,k;if(E.stream.info(`SSE connection opened -> HTTP ${h.status}`),!h.ok){const j=await h.text().catch(()=>"");E.stream.error(`SSE connection failed: HTTP ${h.status}`,j),a.onError(new Error(`HTTP ${h.status}: ${j}`));return}const m=(x=h.body)==null?void 0:x.getReader();if(!m){E.stream.error("No response body reader available"),a.onError(new Error("No response body"));return}const g=new TextDecoder;let v="",w=!1;try{for(;;){const{done:j,value:z}=await m.read();if(j){E.stream.debug("SSE reader done (stream ended)");break}v+=g.decode(z,{stream:!0});const A=v.split(`
488
- `);v=A.pop()||"";for(const _ of A)if(_.startsWith("data: ")){const D=_.slice(6).trim();if(!D)continue;try{const C=JSON.parse(D);C.type==="chunk"?(u++,d+=(C.content||"").length,(u<=3||u%50===0)&&E.stream.debug(`Chunk #${u} (+${(C.content||"").length} chars)`),a.onChunk(C)):C.type==="answer"?a.onChunk(C):C.type==="done"?(w=!0,E.stream.timed(`Stream complete: ${u} chunks, ${d} chars, ${f} agent events`,c),a.onDone(C)):C.type==="error"?(E.stream.error("Stream error event:",C.content),a.onError(new Error(C.content||"Unknown error"))):C.type==="agent_created"?(E.stream.info(`Agent created: ${C.agent_id}`),(k=a.onAgentCreated)==null||k.call(a,C)):p0.has(C.type)?(f++,E.stream.debug(`Agent event: ${C.type}`,C),a.onAgentEvent(C)):E.stream.warn(`Unknown SSE event type: ${C.type}`,C)}catch{E.stream.warn("Malformed SSE data, skipping",{raw:D.slice(0,100)})}}}}finally{m.releaseLock()}w||(E.stream.timed(`SSE connection closed without done event: ${u} chunks, ${f} agent events`,c),a.onDone({type:"done"}))}).catch(h=>{h.name==="AbortError"?E.stream.warn(`Stream aborted by user after ${u} chunks`):(E.stream.error("Stream fetch error",h),a.onError(h))}),o}async function g0(e,t,n,r){return ye("POST","/chat/confirm",{session_id:e,confirm_id:t,action:n,remember:r})}async function Iy(e,t){return ye("POST","/chat/confirm-tool",{session_id:e,approved:t})}async function y0(e){return ye("POST","/chat/cancel",{session_id:e})}async function ji(){return ye("GET","/documents")}async function Dy(e){return ye("POST","/documents/upload-path",{filepath:e})}async function Ay(e){const t=`${ko}/documents/upload`,n=E.api.time();E.api.info(`POST ${t}`,{fileName:e.name,size:e.size});const r=new FormData;r.append("file",e);let i;try{i=await fetch(t,{method:"POST",body:r})}catch(a){throw E.api.error(`POST ${t} - network error`,a),a}if(!i.ok){const a=await i.text().catch(()=>"");E.api.error(`POST ${t} - HTTP ${i.status}`,{errorText:a});let o=a;try{o=JSON.parse(a).detail||a}catch{}throw new Error(Sy(i.status,o))}const l=await i.json();return E.api.timed(`POST ${t} -> ${i.status}`,n,l),l}async function x0(e){return ye("DELETE",`/documents/${e}`)}async function v0(e){return ye("GET",`/documents/${e}/status`)}async function k0(e){return ye("POST",`/documents/${e}/cancel`)}async function Qa(e,t){return ye("POST",`/sessions/${e}/documents`,{document_id:t})}async function w0(e,t){return ye("DELETE",`/sessions/${e}/documents/${t}`)}async function b0(e){const t=e?`?path=${encodeURIComponent(e)}`:"";return ye("GET",`/files/browse${t}`)}async function j0(e,t=!0){return ye("POST","/documents/index-folder",{folder_path:e,recursive:t})}async function _d(e,t=!0){return ye("POST","/files/open",{path:e,reveal:t})}async function Pm(e){const t=`${ko}/files/upload`,n=E.api.time();E.api.info(`POST ${t}`,{fileName:e.name,size:e.size});const r=new FormData;r.append("file",e);const i=await fetch(t,{method:"POST",body:r});if(!i.ok){const a=await i.text().catch(()=>"Upload failed");throw E.api.error(`POST ${t} - HTTP ${i.status}`,{errorText:a}),new Error(`Upload failed: ${a}`)}const l=await i.json();return E.api.timed(`POST ${t} -> ${i.status}`,n,l),l}async function S0(e,t,n){const r=new URLSearchParams({query:e});return t&&r.set("file_types",t),r.set("max_results",String(n)),ye("GET",`/files/search?${r}`)}async function N0(e,t){const n=new URLSearchParams({path:e});return ye("GET",`/files/preview?${n}`)}async function C0(){return ye("POST","/tunnel/start")}async function _0(){return ye("POST","/tunnel/stop")}async function Py(){return ye("GET","/tunnel/status")}async function E0(){return ye("GET","/mcp/status")}function Ri(e){return e.replace(/-/g,"").slice(0,7)}function T0(e,t){const n=t.replace(/^#/,"").toLowerCase();if(!n||n.length<4)return null;const r=e.find(i=>i.id.replace(/-/g,"").toLowerCase().startsWith(n));return r?r.id:null}const My=""+new URL("gaia-robot-NKaQnEIp.png",import.meta.url).href;function z0(e,t){e.stopPropagation(),e.preventDefault();const n=Ri(t),r=`${window.location.origin}${window.location.pathname}#${n}`;navigator.clipboard.writeText(r).then(()=>{E.ui.info(`Copied session link: ${r}`)}).catch(()=>{E.ui.warn("Clipboard write failed")})}function Mm({session:e,isActive:t,isPendingDelete:n,isDeleting:r,onSelect:i,onKeyDown:l,onDelete:a,formatTime:o}){const[c,u]=p.useState(!1),d=p.useCallback(f=>{z0(f,e.id),u(!0),setTimeout(()=>u(!1),1500)},[e.id]);return s.jsxs("div",{className:`session-item ${t?"active":""} ${r?"session-deleting":""}`,onClick:()=>i(e.id),onKeyDown:f=>l(f,e.id),role:"button",tabIndex:0,"aria-label":`Open task: ${e.title}`,"aria-current":t?"true":void 0,children:[s.jsxs("span",{className:"session-title",children:[e.private&&s.jsx(dy,{size:10,className:"session-private-icon","aria-label":"Private session"}),e.title]}),s.jsxs("a",{className:`session-hash ${c?"copied":""}`,href:`#${Ri(e.id)}`,onClick:d,title:c?"Copied!":`Copy link #${Ri(e.id)}`,"aria-label":`Copy link for session ${Ri(e.id)}`,children:["#",Ri(e.id)]}),s.jsx("span",{className:"session-time",children:o(e.updated_at)}),n?s.jsxs("button",{className:"session-delete confirm",onClick:f=>a(f,e.id),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&a(f,e.id)},title:"Click to confirm delete","aria-label":`Confirm delete: ${e.title}`,children:[s.jsx(ci,{size:12}),s.jsx("span",{className:"confirm-label",children:"Delete?"})]}):s.jsx("button",{className:"session-delete",onClick:f=>a(f,e.id),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&a(f,e.id)},title:"Delete","aria-label":`Delete: ${e.title}`,children:s.jsx(ci,{size:13})})]})}function L0({onNewTask:e,tunnelActive:t,tunnelLoading:n,onMobileToggle:r}){const{sessions:i,currentSessionId:l,setCurrentSession:a,removeSession:o,addSession:c,setMessages:u,theme:d,toggleTheme:f,setShowSettings:h,setShowMemoryDashboard:m,sidebarOpen:g,setSidebarOpen:v,setLoadingMessages:w,sidebarCollapsed:x,toggleSidebarCollapsed:k,sidebarWidth:j,setSidebarWidth:z,addPendingDelete:A,removePendingDelete:_}=we(),[D,C]=p.useState(""),[M,N]=p.useState(null),[U,O]=p.useState(null),[re,ie]=p.useState(!1),[X,xe]=p.useState(null),ce=p.useRef(null),T=p.useRef(null),P=p.useRef(null);p.useEffect(()=>{const L=()=>{var F;x?(k(),requestAnimationFrame(()=>{var Y;return(Y=T.current)==null?void 0:Y.focus()})):(F=T.current)==null||F.focus()};return window.addEventListener("gaia:focus-search",L),()=>window.removeEventListener("gaia:focus-search",L)},[x,k]);const b=D?i.filter(L=>L.title.toLowerCase().includes(D.toLowerCase())):i,J=p.useMemo(()=>{if(D)return null;const L=new Date,F=new Date(L.getFullYear(),L.getMonth(),L.getDate()).getTime(),Y=F-864e5,ue=F-7*864e5,he=[{label:"Today",sessions:[]},{label:"Yesterday",sessions:[]},{label:"Previous 7 Days",sessions:[]},{label:"Older",sessions:[]}];for(const H of b){const le=new Date(H.updated_at).getTime();le>=F?he[0].sessions.push(H):le>=Y?he[1].sessions.push(H):le>=ue?he[2].sessions.push(H):he[3].sessions.push(H)}return he.filter(H=>H.sessions.length>0)},[b,D]),B=p.useCallback(async L=>{var Y;if(L===l)return;const F=((Y=i.find(ue=>ue.id===L))==null?void 0:Y.title)||"?";E.nav.info(`Selecting session: "${F}" (${L})`),a(L),u([]),w(!0),window.innerWidth<=768&&v(!1);try{const ue=await As(L);if(!(we.getState().currentSessionId===L)){E.nav.debug(`Discarding stale message load for session=${L} (user switched away)`);return}u(ue.messages||[]),E.nav.info(`Loaded ${(ue.messages||[]).length} message(s) for "${F}"`)}catch(ue){E.nav.error(`Failed to load messages for session ${L}`,ue),u([])}finally{w(!1)}},[l,i,a,u,v,w]),S=p.useCallback(async(L,F)=>{L.stopPropagation(),L.preventDefault();const Y=i.find(he=>he.id===F),ue=(Y==null?void 0:Y.title)||"?";if(M===F){E.chat.info(`Deleting session: "${ue}" (${F})`),N(null),O(F),A(F),zy(F).then(()=>{E.chat.info(`Session deleted from backend: "${ue}"`),_(F)}).catch(H=>{E.chat.warn(`Backend delete failed for "${ue}"`,H),_(F)}),X!=null&&X.timer&&clearTimeout(X.timer);const he=setTimeout(()=>{xe(null)},5e3);Y&&xe({session:Y,timer:he}),setTimeout(()=>{o(F),O(null)},250);return}E.chat.debug(`Delete pending confirmation for: "${ue}" (${F})`),N(F),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>N(he=>he===F?null:he),3e3)},[M,i,o,X,A,_]),oe=p.useCallback(()=>{if(!X)return;clearTimeout(X.timer);const{session:L}=X;E.chat.info(`Undo delete: re-creating "${L.title}"`),_(L.id),hu({title:L.title}).then(F=>{c(F),E.chat.info(`Undo delete: re-created "${F.title}" (new id=${F.id})`)}).catch(F=>{E.chat.warn(`Undo delete failed for "${L.title}"`,F)}),xe(null)},[X,c,_]);p.useEffect(()=>{if(!M)return;const L=()=>N(null);return window.addEventListener("click",L,{once:!0}),()=>window.removeEventListener("click",L)},[M]);const pe=p.useCallback((L,F)=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),B(F))},[B]),ae=p.useRef(null),_e=p.useCallback(L=>{L.preventDefault(),ie(!0),E.ui.debug("Sidebar resize started");const F=L.clientX,Y=j,ue=H=>{const le=H.clientX-F;z(Y+le)},he=()=>{ie(!1),document.removeEventListener("mousemove",ue),document.removeEventListener("mouseup",he),document.body.style.cursor="",document.body.style.userSelect="",ae.current=null,E.ui.debug("Sidebar resize ended")};ae.current=he,document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",ue),document.addEventListener("mouseup",he)},[j,z]);p.useEffect(()=>()=>{ae.current&&ae.current(),P.current&&clearTimeout(P.current)},[]);const He=L=>{const F=new Date(L),ue=new Date().getTime()-F.getTime(),he=Math.floor(ue/6e4);if(he<1)return"now";if(he<60)return`${he}m`;const H=Math.floor(he/60);if(H<24)return`${H}h`;const le=Math.floor(H/24);return le<7?`${le}d`:F.toLocaleDateString(void 0,{month:"short",day:"numeric"})},Ge=typeof window<"u"&&window.innerWidth<=768?void 0:{width:x?56:j,minWidth:x?56:j};return s.jsxs("aside",{ref:ce,className:`sidebar ${g?"open":""} ${x?"collapsed":""} ${re?"resizing":""}`,style:Ge,role:"complementary","aria-label":"Task sidebar",children:[s.jsxs("div",{className:"sidebar-top",children:[s.jsxs("div",{className:"sidebar-brand",children:[s.jsx("div",{className:"brand-icon","aria-hidden":"true",children:s.jsx("img",{src:My,alt:"",width:28,height:28})}),s.jsxs("div",{className:"brand-text",children:[s.jsx("span",{className:"brand-name",children:"GAIA"}),s.jsxs("span",{className:"brand-version",children:["v","0.18.0"]}),s.jsx("span",{className:"beta-badge",children:"BETA"})]})]}),s.jsxs("div",{className:"sidebar-top-actions",children:[s.jsx("button",{className:"new-task-btn",onClick:e,title:"New Task","aria-label":"New Task",children:s.jsx(hl,{size:18})}),s.jsx("button",{className:"collapse-btn",onClick:k,title:x?"Expand sidebar":"Collapse sidebar","aria-label":x?"Expand sidebar":"Collapse sidebar",children:x?s.jsx(uw,{size:18}):s.jsx(cw,{size:18})})]})]}),s.jsxs("div",{className:"sidebar-search",children:[s.jsx(Fn,{size:14,className:"search-icon","aria-hidden":"true"}),s.jsx("input",{ref:T,type:"text",placeholder:"Search... (Ctrl+K)",value:D,onChange:L=>C(L.target.value),"aria-label":"Search tasks"})]}),s.jsxs("nav",{className:"session-list","aria-label":"Task sessions",children:[b.length===0&&s.jsx("div",{className:"empty-hint",children:D?"No results":"No tasks yet"}),J?J.map(L=>s.jsxs("div",{children:[s.jsx("div",{className:"session-group-label",children:L.label}),L.sessions.map(F=>s.jsx(Mm,{session:F,isActive:F.id===l,isPendingDelete:M===F.id,isDeleting:U===F.id,onSelect:B,onKeyDown:pe,onDelete:S,formatTime:He},F.id))]},L.label)):b.map(L=>s.jsx(Mm,{session:L,isActive:L.id===l,isPendingDelete:M===L.id,isDeleting:U===L.id,onSelect:B,onKeyDown:pe,onDelete:S,formatTime:He},L.id))]}),s.jsxs("div",{className:"sidebar-bottom",children:[s.jsxs("div",{className:"privacy-badge",children:[s.jsx("span",{className:"privacy-dot","aria-hidden":"true"}),s.jsx("span",{children:"100% Local"}),s.jsxs("span",{className:"version-badge",children:["v","0.18.0"]})]}),s.jsxs("div",{className:"sidebar-actions",children:[r&&s.jsx("button",{className:`btn-icon mobile-toggle-btn ${t?"active":""} ${n?"loading":""}`,onClick:r,disabled:n,title:t?"Stop mobile access":"Enable mobile access","aria-label":t?"Stop mobile access":"Enable mobile access",children:s.jsx(yy,{size:17})}),s.jsx("button",{className:"btn-icon",onClick:()=>m(!0),title:"Memory Dashboard","aria-label":"Memory Dashboard",children:s.jsx(Jr,{size:17})}),s.jsx("button",{className:"btn-icon",onClick:()=>h(!0),title:"Settings","aria-label":"Settings",children:s.jsx(pw,{size:17})}),s.jsx("button",{className:"btn-icon",onClick:f,title:"Toggle theme","aria-label":`Switch to ${d==="dark"?"light":"dark"} theme`,children:d==="dark"?s.jsx(kw,{size:17}):s.jsx(aw,{size:17})})]})]}),!x&&s.jsx("div",{className:"sidebar-resize-handle",onMouseDown:_e,title:"Drag to resize sidebar","aria-hidden":"true"}),X&&s.jsxs("div",{className:"toast toast-undo",role:"status",children:["Deleted “",X.session.title,"”",s.jsx("span",{className:"toast-action",onClick:oe,children:"Undo"})]})]})}function I0(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const D0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,A0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,P0={};function Rm(e,t){return(P0.jsx?A0:D0).test(e)}const M0=/[ \t\n\f\r]/g;function R0(e){return typeof e=="object"?e.type==="text"?$m(e.value):!1:$m(e)}function $m(e){return e.replace(M0,"")===""}class Sl{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Sl.prototype.normal={};Sl.prototype.property={};Sl.prototype.space=void 0;function Ry(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new Sl(n,r,t)}function pu(e){return e.toLowerCase()}class Yt{constructor(t,n){this.attribute=n,this.property=t}}Yt.prototype.attribute="";Yt.prototype.booleanish=!1;Yt.prototype.boolean=!1;Yt.prototype.commaOrSpaceSeparated=!1;Yt.prototype.commaSeparated=!1;Yt.prototype.defined=!1;Yt.prototype.mustUseProperty=!1;Yt.prototype.number=!1;Yt.prototype.overloadedBoolean=!1;Yt.prototype.property="";Yt.prototype.spaceSeparated=!1;Yt.prototype.space=void 0;let $0=0;const ke=hi(),at=hi(),gu=hi(),G=hi(),Ue=hi(),Wi=hi(),en=hi();function hi(){return 2**++$0}const yu=Object.freeze(Object.defineProperty({__proto__:null,boolean:ke,booleanish:at,commaOrSpaceSeparated:en,commaSeparated:Wi,number:G,overloadedBoolean:gu,spaceSeparated:Ue},Symbol.toStringTag,{value:"Module"})),nc=Object.keys(yu);class Ed extends Yt{constructor(t,n,r,i){let l=-1;if(super(t,n),Fm(this,"space",i),typeof r=="number")for(;++l<nc.length;){const a=nc[l];Fm(this,nc[l],(r&yu[a])===yu[a])}}}Ed.prototype.defined=!0;function Fm(e,t,n){n&&(e[t]=n)}function ls(e){const t={},n={};for(const[r,i]of Object.entries(e.properties)){const l=new Ed(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(l.mustUseProperty=!0),t[r]=l,n[pu(r)]=r,n[pu(l.attribute)]=r}return new Sl(t,n,e.space)}const $y=ls({properties:{ariaActiveDescendant:null,ariaAtomic:at,ariaAutoComplete:null,ariaBusy:at,ariaChecked:at,ariaColCount:G,ariaColIndex:G,ariaColSpan:G,ariaControls:Ue,ariaCurrent:null,ariaDescribedBy:Ue,ariaDetails:null,ariaDisabled:at,ariaDropEffect:Ue,ariaErrorMessage:null,ariaExpanded:at,ariaFlowTo:Ue,ariaGrabbed:at,ariaHasPopup:null,ariaHidden:at,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Ue,ariaLevel:G,ariaLive:null,ariaModal:at,ariaMultiLine:at,ariaMultiSelectable:at,ariaOrientation:null,ariaOwns:Ue,ariaPlaceholder:null,ariaPosInSet:G,ariaPressed:at,ariaReadOnly:at,ariaRelevant:null,ariaRequired:at,ariaRoleDescription:Ue,ariaRowCount:G,ariaRowIndex:G,ariaRowSpan:G,ariaSelected:at,ariaSetSize:G,ariaSort:null,ariaValueMax:G,ariaValueMin:G,ariaValueNow:G,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Fy(e,t){return t in e?e[t]:t}function Oy(e,t){return Fy(e,t.toLowerCase())}const F0=ls({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Wi,acceptCharset:Ue,accessKey:Ue,action:null,allow:null,allowFullScreen:ke,allowPaymentRequest:ke,allowUserMedia:ke,alt:null,as:null,async:ke,autoCapitalize:null,autoComplete:Ue,autoFocus:ke,autoPlay:ke,blocking:Ue,capture:null,charSet:null,checked:ke,cite:null,className:Ue,cols:G,colSpan:null,content:null,contentEditable:at,controls:ke,controlsList:Ue,coords:G|Wi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ke,defer:ke,dir:null,dirName:null,disabled:ke,download:gu,draggable:at,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ke,formTarget:null,headers:Ue,height:G,hidden:gu,high:G,href:null,hrefLang:null,htmlFor:Ue,httpEquiv:Ue,id:null,imageSizes:null,imageSrcSet:null,inert:ke,inputMode:null,integrity:null,is:null,isMap:ke,itemId:null,itemProp:Ue,itemRef:Ue,itemScope:ke,itemType:Ue,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ke,low:G,manifest:null,max:null,maxLength:G,media:null,method:null,min:null,minLength:G,multiple:ke,muted:ke,name:null,nonce:null,noModule:ke,noValidate:ke,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ke,optimum:G,pattern:null,ping:Ue,placeholder:null,playsInline:ke,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ke,referrerPolicy:null,rel:Ue,required:ke,reversed:ke,rows:G,rowSpan:G,sandbox:Ue,scope:null,scoped:ke,seamless:ke,selected:ke,shadowRootClonable:ke,shadowRootDelegatesFocus:ke,shadowRootMode:null,shape:null,size:G,sizes:null,slot:null,span:G,spellCheck:at,src:null,srcDoc:null,srcLang:null,srcSet:null,start:G,step:null,style:null,tabIndex:G,target:null,title:null,translate:null,type:null,typeMustMatch:ke,useMap:null,value:at,width:G,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Ue,axis:null,background:null,bgColor:null,border:G,borderColor:null,bottomMargin:G,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ke,declare:ke,event:null,face:null,frame:null,frameBorder:null,hSpace:G,leftMargin:G,link:null,longDesc:null,lowSrc:null,marginHeight:G,marginWidth:G,noResize:ke,noHref:ke,noShade:ke,noWrap:ke,object:null,profile:null,prompt:null,rev:null,rightMargin:G,rules:null,scheme:null,scrolling:at,standby:null,summary:null,text:null,topMargin:G,valueType:null,version:null,vAlign:null,vLink:null,vSpace:G,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ke,disableRemotePlayback:ke,prefix:null,property:null,results:G,security:null,unselectable:null},space:"html",transform:Oy}),O0=ls({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:en,accentHeight:G,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:G,amplitude:G,arabicForm:null,ascent:G,attributeName:null,attributeType:null,azimuth:G,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:G,by:null,calcMode:null,capHeight:G,className:Ue,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:G,diffuseConstant:G,direction:null,display:null,dur:null,divisor:G,dominantBaseline:null,download:ke,dx:null,dy:null,edgeMode:null,editable:null,elevation:G,enableBackground:null,end:null,event:null,exponent:G,externalResourcesRequired:null,fill:null,fillOpacity:G,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Wi,g2:Wi,glyphName:Wi,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:G,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:G,horizOriginX:G,horizOriginY:G,id:null,ideographic:G,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:G,k:G,k1:G,k2:G,k3:G,k4:G,kernelMatrix:en,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:G,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:G,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:G,overlineThickness:G,paintOrder:null,panose1:null,path:null,pathLength:G,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Ue,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:G,pointsAtY:G,pointsAtZ:G,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:en,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:en,rev:en,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:en,requiredFeatures:en,requiredFonts:en,requiredFormats:en,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:G,specularExponent:G,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:G,strikethroughThickness:G,string:null,stroke:null,strokeDashArray:en,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:G,strokeOpacity:G,strokeWidth:null,style:null,surfaceScale:G,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:en,tabIndex:G,tableValues:null,target:null,targetX:G,targetY:G,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:en,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:G,underlineThickness:G,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:G,values:null,vAlphabetic:G,vMathematical:G,vectorEffect:null,vHanging:G,vIdeographic:G,version:null,vertAdvY:G,vertOriginX:G,vertOriginY:G,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:G,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Fy}),Uy=ls({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),By=ls({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Oy}),Hy=ls({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),U0={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},B0=/[A-Z]/g,Om=/-[a-z]/g,H0=/^data[-\w.:]+$/i;function V0(e,t){const n=pu(t);let r=t,i=Yt;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&H0.test(t)){if(t.charAt(4)==="-"){const l=t.slice(5).replace(Om,G0);r="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=t.slice(4);if(!Om.test(l)){let a=l.replace(B0,W0);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=Ed}return new i(r,t)}function W0(e){return"-"+e.toLowerCase()}function G0(e){return e.charAt(1).toUpperCase()}const q0=Ry([$y,F0,Uy,By,Hy],"html"),Td=Ry([$y,O0,Uy,By,Hy],"svg");function Q0(e){return e.join(" ").trim()}var zd={},Um=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,K0=/\n/g,Y0=/^\s*/,X0=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,J0=/^:\s*/,Z0=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,eb=/^[;\s]*/,tb=/^\s+|\s+$/g,nb=`
488
+ `);v=A.pop()||"";for(const _ of A)if(_.startsWith("data: ")){const D=_.slice(6).trim();if(!D)continue;try{const C=JSON.parse(D);C.type==="chunk"?(u++,d+=(C.content||"").length,(u<=3||u%50===0)&&E.stream.debug(`Chunk #${u} (+${(C.content||"").length} chars)`),a.onChunk(C)):C.type==="answer"?a.onChunk(C):C.type==="done"?(w=!0,E.stream.timed(`Stream complete: ${u} chunks, ${d} chars, ${f} agent events`,c),a.onDone(C)):C.type==="error"?(E.stream.error("Stream error event:",C.content),a.onError(new Error(C.content||"Unknown error"))):C.type==="agent_created"?(E.stream.info(`Agent created: ${C.agent_id}`),(k=a.onAgentCreated)==null||k.call(a,C)):p0.has(C.type)?(f++,E.stream.debug(`Agent event: ${C.type}`,C),a.onAgentEvent(C)):E.stream.warn(`Unknown SSE event type: ${C.type}`,C)}catch{E.stream.warn("Malformed SSE data, skipping",{raw:D.slice(0,100)})}}}}finally{m.releaseLock()}w||(E.stream.timed(`SSE connection closed without done event: ${u} chunks, ${f} agent events`,c),a.onDone({type:"done"}))}).catch(h=>{h.name==="AbortError"?E.stream.warn(`Stream aborted by user after ${u} chunks`):(E.stream.error("Stream fetch error",h),a.onError(h))}),o}async function g0(e,t,n,r){return ye("POST","/chat/confirm",{session_id:e,confirm_id:t,action:n,remember:r})}async function Iy(e,t){return ye("POST","/chat/confirm-tool",{session_id:e,approved:t})}async function y0(e){return ye("POST","/chat/cancel",{session_id:e})}async function ji(){return ye("GET","/documents")}async function Dy(e){return ye("POST","/documents/upload-path",{filepath:e})}async function Ay(e){const t=`${ko}/documents/upload`,n=E.api.time();E.api.info(`POST ${t}`,{fileName:e.name,size:e.size});const r=new FormData;r.append("file",e);let i;try{i=await fetch(t,{method:"POST",body:r})}catch(a){throw E.api.error(`POST ${t} - network error`,a),a}if(!i.ok){const a=await i.text().catch(()=>"");E.api.error(`POST ${t} - HTTP ${i.status}`,{errorText:a});let o=a;try{o=JSON.parse(a).detail||a}catch{}throw new Error(Sy(i.status,o))}const l=await i.json();return E.api.timed(`POST ${t} -> ${i.status}`,n,l),l}async function x0(e){return ye("DELETE",`/documents/${e}`)}async function v0(e){return ye("GET",`/documents/${e}/status`)}async function k0(e){return ye("POST",`/documents/${e}/cancel`)}async function Qa(e,t){return ye("POST",`/sessions/${e}/documents`,{document_id:t})}async function w0(e,t){return ye("DELETE",`/sessions/${e}/documents/${t}`)}async function b0(e){const t=e?`?path=${encodeURIComponent(e)}`:"";return ye("GET",`/files/browse${t}`)}async function j0(e,t=!0){return ye("POST","/documents/index-folder",{folder_path:e,recursive:t})}async function _d(e,t=!0){return ye("POST","/files/open",{path:e,reveal:t})}async function Pm(e){const t=`${ko}/files/upload`,n=E.api.time();E.api.info(`POST ${t}`,{fileName:e.name,size:e.size});const r=new FormData;r.append("file",e);const i=await fetch(t,{method:"POST",body:r});if(!i.ok){const a=await i.text().catch(()=>"Upload failed");throw E.api.error(`POST ${t} - HTTP ${i.status}`,{errorText:a}),new Error(`Upload failed: ${a}`)}const l=await i.json();return E.api.timed(`POST ${t} -> ${i.status}`,n,l),l}async function S0(e,t,n){const r=new URLSearchParams({query:e});return t&&r.set("file_types",t),r.set("max_results",String(n)),ye("GET",`/files/search?${r}`)}async function N0(e,t){const n=new URLSearchParams({path:e});return ye("GET",`/files/preview?${n}`)}async function C0(){return ye("POST","/tunnel/start")}async function _0(){return ye("POST","/tunnel/stop")}async function Py(){return ye("GET","/tunnel/status")}async function E0(){return ye("GET","/mcp/status")}function Ri(e){return e.replace(/-/g,"").slice(0,7)}function T0(e,t){const n=t.replace(/^#/,"").toLowerCase();if(!n||n.length<4)return null;const r=e.find(i=>i.id.replace(/-/g,"").toLowerCase().startsWith(n));return r?r.id:null}const My=""+new URL("gaia-robot-NKaQnEIp.png",import.meta.url).href;function z0(e,t){e.stopPropagation(),e.preventDefault();const n=Ri(t),r=`${window.location.origin}${window.location.pathname}#${n}`;navigator.clipboard.writeText(r).then(()=>{E.ui.info(`Copied session link: ${r}`)}).catch(()=>{E.ui.warn("Clipboard write failed")})}function Mm({session:e,isActive:t,isPendingDelete:n,isDeleting:r,onSelect:i,onKeyDown:l,onDelete:a,formatTime:o}){const[c,u]=p.useState(!1),d=p.useCallback(f=>{z0(f,e.id),u(!0),setTimeout(()=>u(!1),1500)},[e.id]);return s.jsxs("div",{className:`session-item ${t?"active":""} ${r?"session-deleting":""}`,onClick:()=>i(e.id),onKeyDown:f=>l(f,e.id),role:"button",tabIndex:0,"aria-label":`Open task: ${e.title}`,"aria-current":t?"true":void 0,children:[s.jsxs("span",{className:"session-title",children:[e.private&&s.jsx(dy,{size:10,className:"session-private-icon","aria-label":"Private session"}),e.title]}),s.jsxs("a",{className:`session-hash ${c?"copied":""}`,href:`#${Ri(e.id)}`,onClick:d,title:c?"Copied!":`Copy link #${Ri(e.id)}`,"aria-label":`Copy link for session ${Ri(e.id)}`,children:["#",Ri(e.id)]}),s.jsx("span",{className:"session-time",children:o(e.updated_at)}),n?s.jsxs("button",{className:"session-delete confirm",onClick:f=>a(f,e.id),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&a(f,e.id)},title:"Click to confirm delete","aria-label":`Confirm delete: ${e.title}`,children:[s.jsx(ci,{size:12}),s.jsx("span",{className:"confirm-label",children:"Delete?"})]}):s.jsx("button",{className:"session-delete",onClick:f=>a(f,e.id),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&a(f,e.id)},title:"Delete","aria-label":`Delete: ${e.title}`,children:s.jsx(ci,{size:13})})]})}function L0({onNewTask:e,tunnelActive:t,tunnelLoading:n,onMobileToggle:r}){const{sessions:i,currentSessionId:l,setCurrentSession:a,removeSession:o,addSession:c,setMessages:u,theme:d,toggleTheme:f,setShowSettings:h,setShowMemoryDashboard:m,sidebarOpen:g,setSidebarOpen:v,setLoadingMessages:w,sidebarCollapsed:x,toggleSidebarCollapsed:k,sidebarWidth:j,setSidebarWidth:z,addPendingDelete:A,removePendingDelete:_}=we(),[D,C]=p.useState(""),[M,N]=p.useState(null),[U,O]=p.useState(null),[re,ie]=p.useState(!1),[X,xe]=p.useState(null),ce=p.useRef(null),T=p.useRef(null),P=p.useRef(null);p.useEffect(()=>{const L=()=>{var F;x?(k(),requestAnimationFrame(()=>{var Y;return(Y=T.current)==null?void 0:Y.focus()})):(F=T.current)==null||F.focus()};return window.addEventListener("gaia:focus-search",L),()=>window.removeEventListener("gaia:focus-search",L)},[x,k]);const b=D?i.filter(L=>L.title.toLowerCase().includes(D.toLowerCase())):i,J=p.useMemo(()=>{if(D)return null;const L=new Date,F=new Date(L.getFullYear(),L.getMonth(),L.getDate()).getTime(),Y=F-864e5,ue=F-7*864e5,he=[{label:"Today",sessions:[]},{label:"Yesterday",sessions:[]},{label:"Previous 7 Days",sessions:[]},{label:"Older",sessions:[]}];for(const H of b){const le=new Date(H.updated_at).getTime();le>=F?he[0].sessions.push(H):le>=Y?he[1].sessions.push(H):le>=ue?he[2].sessions.push(H):he[3].sessions.push(H)}return he.filter(H=>H.sessions.length>0)},[b,D]),B=p.useCallback(async L=>{var Y;if(L===l)return;const F=((Y=i.find(ue=>ue.id===L))==null?void 0:Y.title)||"?";E.nav.info(`Selecting session: "${F}" (${L})`),a(L),u([]),w(!0),window.innerWidth<=768&&v(!1);try{const ue=await As(L);if(!(we.getState().currentSessionId===L)){E.nav.debug(`Discarding stale message load for session=${L} (user switched away)`);return}u(ue.messages||[]),E.nav.info(`Loaded ${(ue.messages||[]).length} message(s) for "${F}"`)}catch(ue){E.nav.error(`Failed to load messages for session ${L}`,ue),u([])}finally{w(!1)}},[l,i,a,u,v,w]),S=p.useCallback(async(L,F)=>{L.stopPropagation(),L.preventDefault();const Y=i.find(he=>he.id===F),ue=(Y==null?void 0:Y.title)||"?";if(M===F){E.chat.info(`Deleting session: "${ue}" (${F})`),N(null),O(F),A(F),zy(F).then(()=>{E.chat.info(`Session deleted from backend: "${ue}"`),_(F)}).catch(H=>{E.chat.warn(`Backend delete failed for "${ue}"`,H),_(F)}),X!=null&&X.timer&&clearTimeout(X.timer);const he=setTimeout(()=>{xe(null)},5e3);Y&&xe({session:Y,timer:he}),setTimeout(()=>{o(F),O(null)},250);return}E.chat.debug(`Delete pending confirmation for: "${ue}" (${F})`),N(F),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>N(he=>he===F?null:he),3e3)},[M,i,o,X,A,_]),oe=p.useCallback(()=>{if(!X)return;clearTimeout(X.timer);const{session:L}=X;E.chat.info(`Undo delete: re-creating "${L.title}"`),_(L.id),hu({title:L.title}).then(F=>{c(F),E.chat.info(`Undo delete: re-created "${F.title}" (new id=${F.id})`)}).catch(F=>{E.chat.warn(`Undo delete failed for "${L.title}"`,F)}),xe(null)},[X,c,_]);p.useEffect(()=>{if(!M)return;const L=()=>N(null);return window.addEventListener("click",L,{once:!0}),()=>window.removeEventListener("click",L)},[M]);const pe=p.useCallback((L,F)=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),B(F))},[B]),ae=p.useRef(null),_e=p.useCallback(L=>{L.preventDefault(),ie(!0),E.ui.debug("Sidebar resize started");const F=L.clientX,Y=j,ue=H=>{const le=H.clientX-F;z(Y+le)},he=()=>{ie(!1),document.removeEventListener("mousemove",ue),document.removeEventListener("mouseup",he),document.body.style.cursor="",document.body.style.userSelect="",ae.current=null,E.ui.debug("Sidebar resize ended")};ae.current=he,document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",ue),document.addEventListener("mouseup",he)},[j,z]);p.useEffect(()=>()=>{ae.current&&ae.current(),P.current&&clearTimeout(P.current)},[]);const He=L=>{const F=new Date(L),ue=new Date().getTime()-F.getTime(),he=Math.floor(ue/6e4);if(he<1)return"now";if(he<60)return`${he}m`;const H=Math.floor(he/60);if(H<24)return`${H}h`;const le=Math.floor(H/24);return le<7?`${le}d`:F.toLocaleDateString(void 0,{month:"short",day:"numeric"})},Ge=typeof window<"u"&&window.innerWidth<=768?void 0:{width:x?56:j,minWidth:x?56:j};return s.jsxs("aside",{ref:ce,className:`sidebar ${g?"open":""} ${x?"collapsed":""} ${re?"resizing":""}`,style:Ge,role:"complementary","aria-label":"Task sidebar",children:[s.jsxs("div",{className:"sidebar-top",children:[s.jsxs("div",{className:"sidebar-brand",children:[s.jsx("div",{className:"brand-icon","aria-hidden":"true",children:s.jsx("img",{src:My,alt:"",width:28,height:28})}),s.jsxs("div",{className:"brand-text",children:[s.jsx("span",{className:"brand-name",children:"GAIA"}),s.jsxs("span",{className:"brand-version",children:["v","0.18.1"]}),s.jsx("span",{className:"beta-badge",children:"BETA"})]})]}),s.jsxs("div",{className:"sidebar-top-actions",children:[s.jsx("button",{className:"new-task-btn",onClick:e,title:"New Task","aria-label":"New Task",children:s.jsx(hl,{size:18})}),s.jsx("button",{className:"collapse-btn",onClick:k,title:x?"Expand sidebar":"Collapse sidebar","aria-label":x?"Expand sidebar":"Collapse sidebar",children:x?s.jsx(uw,{size:18}):s.jsx(cw,{size:18})})]})]}),s.jsxs("div",{className:"sidebar-search",children:[s.jsx(Fn,{size:14,className:"search-icon","aria-hidden":"true"}),s.jsx("input",{ref:T,type:"text",placeholder:"Search... (Ctrl+K)",value:D,onChange:L=>C(L.target.value),"aria-label":"Search tasks"})]}),s.jsxs("nav",{className:"session-list","aria-label":"Task sessions",children:[b.length===0&&s.jsx("div",{className:"empty-hint",children:D?"No results":"No tasks yet"}),J?J.map(L=>s.jsxs("div",{children:[s.jsx("div",{className:"session-group-label",children:L.label}),L.sessions.map(F=>s.jsx(Mm,{session:F,isActive:F.id===l,isPendingDelete:M===F.id,isDeleting:U===F.id,onSelect:B,onKeyDown:pe,onDelete:S,formatTime:He},F.id))]},L.label)):b.map(L=>s.jsx(Mm,{session:L,isActive:L.id===l,isPendingDelete:M===L.id,isDeleting:U===L.id,onSelect:B,onKeyDown:pe,onDelete:S,formatTime:He},L.id))]}),s.jsxs("div",{className:"sidebar-bottom",children:[s.jsxs("div",{className:"privacy-badge",children:[s.jsx("span",{className:"privacy-dot","aria-hidden":"true"}),s.jsx("span",{children:"100% Local"}),s.jsxs("span",{className:"version-badge",children:["v","0.18.1"]})]}),s.jsxs("div",{className:"sidebar-actions",children:[r&&s.jsx("button",{className:`btn-icon mobile-toggle-btn ${t?"active":""} ${n?"loading":""}`,onClick:r,disabled:n,title:t?"Stop mobile access":"Enable mobile access","aria-label":t?"Stop mobile access":"Enable mobile access",children:s.jsx(yy,{size:17})}),s.jsx("button",{className:"btn-icon",onClick:()=>m(!0),title:"Memory Dashboard","aria-label":"Memory Dashboard",children:s.jsx(Jr,{size:17})}),s.jsx("button",{className:"btn-icon",onClick:()=>h(!0),title:"Settings","aria-label":"Settings",children:s.jsx(pw,{size:17})}),s.jsx("button",{className:"btn-icon",onClick:f,title:"Toggle theme","aria-label":`Switch to ${d==="dark"?"light":"dark"} theme`,children:d==="dark"?s.jsx(kw,{size:17}):s.jsx(aw,{size:17})})]})]}),!x&&s.jsx("div",{className:"sidebar-resize-handle",onMouseDown:_e,title:"Drag to resize sidebar","aria-hidden":"true"}),X&&s.jsxs("div",{className:"toast toast-undo",role:"status",children:["Deleted “",X.session.title,"”",s.jsx("span",{className:"toast-action",onClick:oe,children:"Undo"})]})]})}function I0(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const D0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,A0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,P0={};function Rm(e,t){return(P0.jsx?A0:D0).test(e)}const M0=/[ \t\n\f\r]/g;function R0(e){return typeof e=="object"?e.type==="text"?$m(e.value):!1:$m(e)}function $m(e){return e.replace(M0,"")===""}class Sl{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Sl.prototype.normal={};Sl.prototype.property={};Sl.prototype.space=void 0;function Ry(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new Sl(n,r,t)}function pu(e){return e.toLowerCase()}class Yt{constructor(t,n){this.attribute=n,this.property=t}}Yt.prototype.attribute="";Yt.prototype.booleanish=!1;Yt.prototype.boolean=!1;Yt.prototype.commaOrSpaceSeparated=!1;Yt.prototype.commaSeparated=!1;Yt.prototype.defined=!1;Yt.prototype.mustUseProperty=!1;Yt.prototype.number=!1;Yt.prototype.overloadedBoolean=!1;Yt.prototype.property="";Yt.prototype.spaceSeparated=!1;Yt.prototype.space=void 0;let $0=0;const ke=hi(),at=hi(),gu=hi(),G=hi(),Ue=hi(),Wi=hi(),en=hi();function hi(){return 2**++$0}const yu=Object.freeze(Object.defineProperty({__proto__:null,boolean:ke,booleanish:at,commaOrSpaceSeparated:en,commaSeparated:Wi,number:G,overloadedBoolean:gu,spaceSeparated:Ue},Symbol.toStringTag,{value:"Module"})),nc=Object.keys(yu);class Ed extends Yt{constructor(t,n,r,i){let l=-1;if(super(t,n),Fm(this,"space",i),typeof r=="number")for(;++l<nc.length;){const a=nc[l];Fm(this,nc[l],(r&yu[a])===yu[a])}}}Ed.prototype.defined=!0;function Fm(e,t,n){n&&(e[t]=n)}function ls(e){const t={},n={};for(const[r,i]of Object.entries(e.properties)){const l=new Ed(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(l.mustUseProperty=!0),t[r]=l,n[pu(r)]=r,n[pu(l.attribute)]=r}return new Sl(t,n,e.space)}const $y=ls({properties:{ariaActiveDescendant:null,ariaAtomic:at,ariaAutoComplete:null,ariaBusy:at,ariaChecked:at,ariaColCount:G,ariaColIndex:G,ariaColSpan:G,ariaControls:Ue,ariaCurrent:null,ariaDescribedBy:Ue,ariaDetails:null,ariaDisabled:at,ariaDropEffect:Ue,ariaErrorMessage:null,ariaExpanded:at,ariaFlowTo:Ue,ariaGrabbed:at,ariaHasPopup:null,ariaHidden:at,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Ue,ariaLevel:G,ariaLive:null,ariaModal:at,ariaMultiLine:at,ariaMultiSelectable:at,ariaOrientation:null,ariaOwns:Ue,ariaPlaceholder:null,ariaPosInSet:G,ariaPressed:at,ariaReadOnly:at,ariaRelevant:null,ariaRequired:at,ariaRoleDescription:Ue,ariaRowCount:G,ariaRowIndex:G,ariaRowSpan:G,ariaSelected:at,ariaSetSize:G,ariaSort:null,ariaValueMax:G,ariaValueMin:G,ariaValueNow:G,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Fy(e,t){return t in e?e[t]:t}function Oy(e,t){return Fy(e,t.toLowerCase())}const F0=ls({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Wi,acceptCharset:Ue,accessKey:Ue,action:null,allow:null,allowFullScreen:ke,allowPaymentRequest:ke,allowUserMedia:ke,alt:null,as:null,async:ke,autoCapitalize:null,autoComplete:Ue,autoFocus:ke,autoPlay:ke,blocking:Ue,capture:null,charSet:null,checked:ke,cite:null,className:Ue,cols:G,colSpan:null,content:null,contentEditable:at,controls:ke,controlsList:Ue,coords:G|Wi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ke,defer:ke,dir:null,dirName:null,disabled:ke,download:gu,draggable:at,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ke,formTarget:null,headers:Ue,height:G,hidden:gu,high:G,href:null,hrefLang:null,htmlFor:Ue,httpEquiv:Ue,id:null,imageSizes:null,imageSrcSet:null,inert:ke,inputMode:null,integrity:null,is:null,isMap:ke,itemId:null,itemProp:Ue,itemRef:Ue,itemScope:ke,itemType:Ue,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ke,low:G,manifest:null,max:null,maxLength:G,media:null,method:null,min:null,minLength:G,multiple:ke,muted:ke,name:null,nonce:null,noModule:ke,noValidate:ke,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ke,optimum:G,pattern:null,ping:Ue,placeholder:null,playsInline:ke,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ke,referrerPolicy:null,rel:Ue,required:ke,reversed:ke,rows:G,rowSpan:G,sandbox:Ue,scope:null,scoped:ke,seamless:ke,selected:ke,shadowRootClonable:ke,shadowRootDelegatesFocus:ke,shadowRootMode:null,shape:null,size:G,sizes:null,slot:null,span:G,spellCheck:at,src:null,srcDoc:null,srcLang:null,srcSet:null,start:G,step:null,style:null,tabIndex:G,target:null,title:null,translate:null,type:null,typeMustMatch:ke,useMap:null,value:at,width:G,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Ue,axis:null,background:null,bgColor:null,border:G,borderColor:null,bottomMargin:G,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ke,declare:ke,event:null,face:null,frame:null,frameBorder:null,hSpace:G,leftMargin:G,link:null,longDesc:null,lowSrc:null,marginHeight:G,marginWidth:G,noResize:ke,noHref:ke,noShade:ke,noWrap:ke,object:null,profile:null,prompt:null,rev:null,rightMargin:G,rules:null,scheme:null,scrolling:at,standby:null,summary:null,text:null,topMargin:G,valueType:null,version:null,vAlign:null,vLink:null,vSpace:G,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ke,disableRemotePlayback:ke,prefix:null,property:null,results:G,security:null,unselectable:null},space:"html",transform:Oy}),O0=ls({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:en,accentHeight:G,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:G,amplitude:G,arabicForm:null,ascent:G,attributeName:null,attributeType:null,azimuth:G,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:G,by:null,calcMode:null,capHeight:G,className:Ue,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:G,diffuseConstant:G,direction:null,display:null,dur:null,divisor:G,dominantBaseline:null,download:ke,dx:null,dy:null,edgeMode:null,editable:null,elevation:G,enableBackground:null,end:null,event:null,exponent:G,externalResourcesRequired:null,fill:null,fillOpacity:G,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Wi,g2:Wi,glyphName:Wi,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:G,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:G,horizOriginX:G,horizOriginY:G,id:null,ideographic:G,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:G,k:G,k1:G,k2:G,k3:G,k4:G,kernelMatrix:en,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:G,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:G,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:G,overlineThickness:G,paintOrder:null,panose1:null,path:null,pathLength:G,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Ue,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:G,pointsAtY:G,pointsAtZ:G,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:en,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:en,rev:en,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:en,requiredFeatures:en,requiredFonts:en,requiredFormats:en,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:G,specularExponent:G,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:G,strikethroughThickness:G,string:null,stroke:null,strokeDashArray:en,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:G,strokeOpacity:G,strokeWidth:null,style:null,surfaceScale:G,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:en,tabIndex:G,tableValues:null,target:null,targetX:G,targetY:G,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:en,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:G,underlineThickness:G,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:G,values:null,vAlphabetic:G,vMathematical:G,vectorEffect:null,vHanging:G,vIdeographic:G,version:null,vertAdvY:G,vertOriginX:G,vertOriginY:G,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:G,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Fy}),Uy=ls({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),By=ls({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Oy}),Hy=ls({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),U0={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},B0=/[A-Z]/g,Om=/-[a-z]/g,H0=/^data[-\w.:]+$/i;function V0(e,t){const n=pu(t);let r=t,i=Yt;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&H0.test(t)){if(t.charAt(4)==="-"){const l=t.slice(5).replace(Om,G0);r="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=t.slice(4);if(!Om.test(l)){let a=l.replace(B0,W0);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=Ed}return new i(r,t)}function W0(e){return"-"+e.toLowerCase()}function G0(e){return e.charAt(1).toUpperCase()}const q0=Ry([$y,F0,Uy,By,Hy],"html"),Td=Ry([$y,O0,Uy,By,Hy],"svg");function Q0(e){return e.join(" ").trim()}var zd={},Um=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,K0=/\n/g,Y0=/^\s*/,X0=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,J0=/^:\s*/,Z0=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,eb=/^[;\s]*/,tb=/^\s+|\s+$/g,nb=`
489
489
  `,Bm="/",Hm="*",Qr="",rb="comment",ib="declaration";function sb(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function i(g){var v=g.match(K0);v&&(n+=v.length);var w=g.lastIndexOf(nb);r=~w?g.length-w:r+g.length}function l(){var g={line:n,column:r};return function(v){return v.position=new a(g),u(),v}}function a(g){this.start=g,this.end={line:n,column:r},this.source=t.source}a.prototype.content=e;function o(g){var v=new Error(t.source+":"+n+":"+r+": "+g);if(v.reason=g,v.filename=t.source,v.line=n,v.column=r,v.source=e,!t.silent)throw v}function c(g){var v=g.exec(e);if(v){var w=v[0];return i(w),e=e.slice(w.length),v}}function u(){c(Y0)}function d(g){var v;for(g=g||[];v=f();)v!==!1&&g.push(v);return g}function f(){var g=l();if(!(Bm!=e.charAt(0)||Hm!=e.charAt(1))){for(var v=2;Qr!=e.charAt(v)&&(Hm!=e.charAt(v)||Bm!=e.charAt(v+1));)++v;if(v+=2,Qr===e.charAt(v-1))return o("End of comment missing");var w=e.slice(2,v-2);return r+=2,i(w),e=e.slice(v),r+=2,g({type:rb,comment:w})}}function h(){var g=l(),v=c(X0);if(v){if(f(),!c(J0))return o("property missing ':'");var w=c(Z0),x=g({type:ib,property:Vm(v[0].replace(Um,Qr)),value:w?Vm(w[0].replace(Um,Qr)):Qr});return c(eb),x}}function m(){var g=[];d(g);for(var v;v=h();)v!==!1&&(g.push(v),d(g));return g}return u(),m()}function Vm(e){return e?e.replace(tb,Qr):Qr}var lb=sb,ab=ka&&ka.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zd,"__esModule",{value:!0});zd.default=cb;const ob=ab(lb);function cb(e,t){let n=null;if(!e||typeof e!="string")return n;const r=(0,ob.default)(e),i=typeof t=="function";return r.forEach(l=>{if(l.type!=="declaration")return;const{property:a,value:o}=l;i?t(a,o,l):o&&(n=n||{},n[a]=o)}),n}var wo={};Object.defineProperty(wo,"__esModule",{value:!0});wo.camelCase=void 0;var ub=/^--[a-zA-Z0-9_-]+$/,db=/-([a-z])/g,fb=/^[^-]+$/,mb=/^-(webkit|moz|ms|o|khtml)-/,hb=/^-(ms)-/,pb=function(e){return!e||fb.test(e)||ub.test(e)},gb=function(e,t){return t.toUpperCase()},Wm=function(e,t){return"".concat(t,"-")},yb=function(e,t){return t===void 0&&(t={}),pb(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(hb,Wm):e=e.replace(mb,Wm),e.replace(db,gb))};wo.camelCase=yb;var xb=ka&&ka.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},vb=xb(zd),kb=wo;function xu(e,t){var n={};return!e||typeof e!="string"||(0,vb.default)(e,function(r,i){r&&i&&(n[(0,kb.camelCase)(r,t)]=i)}),n}xu.default=xu;var wb=xu;const bb=to(wb),Vy=Wy("end"),Ld=Wy("start");function Wy(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function jb(e){const t=Ld(e),n=Vy(e);if(t&&n)return{start:t,end:n}}function Gs(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Gm(e.position):"start"in e||"end"in e?Gm(e):"line"in e||"column"in e?vu(e):""}function vu(e){return qm(e&&e.line)+":"+qm(e&&e.column)}function Gm(e){return vu(e&&e.start)+"-"+vu(e&&e.end)}function qm(e){return e&&typeof e=="number"?e:1}class At extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",l={},a=!1;if(n&&("line"in n&&"column"in n?l={place:n}:"start"in n&&"end"in n?l={place:n}:"type"in n?l={ancestors:[n],place:n.position}:l={...n}),typeof t=="string"?i=t:!l.cause&&t&&(a=!0,i=t.message,l.cause=t),!l.ruleId&&!l.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?l.ruleId=r:(l.source=r.slice(0,c),l.ruleId=r.slice(c+1))}if(!l.place&&l.ancestors&&l.ancestors){const c=l.ancestors[l.ancestors.length-1];c&&(l.place=c.position)}const o=l.place&&"start"in l.place?l.place.start:l.place;this.ancestors=l.ancestors||void 0,this.cause=l.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=o?o.line:void 0,this.name=Gs(l.place)||"1:1",this.place=l.place||void 0,this.reason=this.message,this.ruleId=l.ruleId||void 0,this.source=l.source||void 0,this.stack=a&&l.cause&&typeof l.cause.stack=="string"?l.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}At.prototype.file="";At.prototype.name="";At.prototype.reason="";At.prototype.message="";At.prototype.stack="";At.prototype.column=void 0;At.prototype.line=void 0;At.prototype.ancestors=void 0;At.prototype.cause=void 0;At.prototype.fatal=void 0;At.prototype.place=void 0;At.prototype.ruleId=void 0;At.prototype.source=void 0;const Id={}.hasOwnProperty,Sb=new Map,Nb=/[A-Z]/g,Cb=new Set(["table","tbody","thead","tfoot","tr"]),_b=new Set(["td","th"]),Gy="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Eb(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=Mb(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Pb(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Td:q0,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},l=qy(i,e,void 0);return l&&typeof l!="string"?l:i.create(e,i.Fragment,{children:l||void 0},void 0)}function qy(e,t,n){if(t.type==="element")return Tb(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return zb(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Ib(e,t,n);if(t.type==="mdxjsEsm")return Lb(e,t);if(t.type==="root")return Db(e,t,n);if(t.type==="text")return Ab(e,t)}function Tb(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=Td,e.schema=i),e.ancestors.push(t);const l=Ky(e,t.tagName,!1),a=Rb(e,t);let o=Ad(e,t);return Cb.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!R0(c):!0})),Qy(e,a,l,t),Dd(a,o),e.ancestors.pop(),e.schema=r,e.create(t,l,a,n)}function zb(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}gl(e,t.position)}function Lb(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);gl(e,t.position)}function Ib(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=Td,e.schema=i),e.ancestors.push(t);const l=t.name===null?e.Fragment:Ky(e,t.name,!0),a=$b(e,t),o=Ad(e,t);return Qy(e,a,l,t),Dd(a,o),e.ancestors.pop(),e.schema=r,e.create(t,l,a,n)}function Db(e,t,n){const r={};return Dd(r,Ad(e,t)),e.create(t,e.Fragment,r,n)}function Ab(e,t){return t.value}function Qy(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Dd(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Pb(e,t,n){return r;function r(i,l,a,o){const u=Array.isArray(a.children)?n:t;return o?u(l,a,o):u(l,a)}}function Mb(e,t){return n;function n(r,i,l,a){const o=Array.isArray(l.children),c=Ld(r);return t(i,l,a,o,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function Rb(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&Id.call(t.properties,i)){const l=Fb(e,i,t.properties[i]);if(l){const[a,o]=l;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&_b.has(t.tagName)?r=o:n[a]=o}}if(r){const l=n.style||(n.style={});l[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function $b(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const l=r.data.estree.body[0];l.type;const a=l.expression;a.type;const o=a.properties[0];o.type,Object.assign(n,e.evaluater.evaluateExpression(o.argument))}else gl(e,t.position);else{const i=r.name;let l;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,l=e.evaluater.evaluateExpression(o.expression)}else gl(e,t.position);else l=r.value===null?!0:r.value;n[i]=l}return n}function Ad(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:Sb;for(;++r<t.children.length;){const l=t.children[r];let a;if(e.passKeys){const c=l.type==="element"?l.tagName:l.type==="mdxJsxFlowElement"||l.type==="mdxJsxTextElement"?l.name:void 0;if(c){const u=i.get(c)||0;a=c+"-"+u,i.set(c,u+1)}}const o=qy(e,l,a);o!==void 0&&n.push(o)}return n}function Fb(e,t,n){const r=V0(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?I0(n):Q0(n)),r.property==="style"){let i=typeof n=="object"?n:Ob(e,String(n));return e.stylePropertyNameCase==="css"&&(i=Ub(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&r.space?U0[r.property]||r.property:r.attribute,n]}}function Ob(e,t){try{return bb(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,i=new At("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=Gy+"#cannot-parse-style-attribute",i}}function Ky(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const i=t.split(".");let l=-1,a;for(;++l<i.length;){const o=Rm(i[l])?{type:"Identifier",name:i[l]}:{type:"Literal",value:i[l]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(l&&o.type==="Literal"),optional:!1}:o}r=a}else r=Rm(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const i=r.value;return Id.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(r);gl(e)}function gl(e,t){const n=new At("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=Gy+"#cannot-handle-mdx-estrees-without-createevaluater",n}function Ub(e){const t={};let n;for(n in e)Id.call(e,n)&&(t[Bb(n)]=e[n]);return t}function Bb(e){let t=e.replace(Nb,Hb);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Hb(e){return"-"+e.toLowerCase()}const rc={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},Vb={};function Pd(e,t){const n=Vb,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Yy(e,r,i)}function Yy(e,t,n){if(Wb(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Qm(e.children,t,n)}return Array.isArray(e)?Qm(e,t,n):""}function Qm(e,t,n){const r=[];let i=-1;for(;++i<e.length;)r[i]=Yy(e[i],t,n);return r.join("")}function Wb(e){return!!(e&&typeof e=="object")}const Km=document.createElement("i");function Md(e){const t="&"+e+";";Km.innerHTML=t;const n=Km.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function sn(e,t,n,r){const i=e.length;let l=0,a;if(t<0?t=-t>i?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)a=Array.from(r),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);l<r.length;)a=r.slice(l,l+1e4),a.unshift(t,0),e.splice(...a),l+=1e4,t+=1e4}function fn(e,t){return e.length>0?(sn(e,e.length,0,t),e):t}const Ym={}.hasOwnProperty;function Xy(e){const t={};let n=-1;for(;++n<e.length;)Gb(t,e[n]);return t}function Gb(e,t){let n;for(n in t){const i=(Ym.call(e,n)?e[n]:void 0)||(e[n]={}),l=t[n];let a;if(l)for(a in l){Ym.call(i,a)||(i[a]=[]);const o=l[a];qb(i[a],Array.isArray(o)?o:o?[o]:[])}}}function qb(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);sn(e,0,0,r)}function Jy(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ln(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Ft=Hr(/[A-Za-z]/),It=Hr(/[\dA-Za-z]/),Qb=Hr(/[#-'*+\--9=?A-Z^-~]/);function Ka(e){return e!==null&&(e<32||e===127)}const ku=Hr(/\d/),Kb=Hr(/[\dA-Fa-f]/),Yb=Hr(/[!-/:-@[-`{-~]/);function fe(e){return e!==null&&e<-2}function Oe(e){return e!==null&&(e<0||e===32)}function Se(e){return e===-2||e===-1||e===32}const bo=Hr(new RegExp("\\p{P}|\\p{S}","u")),ui=Hr(/\s/);function Hr(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function as(e){const t=[];let n=-1,r=0,i=0;for(;++n<e.length;){const l=e.charCodeAt(n);let a="";if(l===37&&It(e.charCodeAt(n+1))&&It(e.charCodeAt(n+2)))i=2;else if(l<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(l))||(a=String.fromCharCode(l));else if(l>55295&&l<57344){const o=e.charCodeAt(n+1);l<56320&&o>56319&&o<57344?(a=String.fromCharCode(l,o),i=1):a="�"}else a=String.fromCharCode(l);a&&(t.push(e.slice(r,n),encodeURIComponent(a)),r=n+i+1,a=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function Te(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let l=0;return a;function a(c){return Se(c)?(e.enter(n),o(c)):t(c)}function o(c){return Se(c)&&l++<i?(e.consume(c),o):(e.exit(n),t(c))}}const Xb={tokenize:Jb};function Jb(e){const t=e.attempt(this.parser.constructs.contentInitial,r,i);let n;return t;function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),Te(e,t,"linePrefix")}function i(o){return e.enter("paragraph"),l(o)}function l(o){const c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,a(o)}function a(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return fe(o)?(e.consume(o),e.exit("chunkText"),l):(e.consume(o),a)}}const Zb={tokenize:ej},Xm={tokenize:tj};function ej(e){const t=this,n=[];let r=0,i,l,a;return o;function o(j){if(r<n.length){const z=n[r];return t.containerState=z[1],e.attempt(z[0].continuation,c,u)(j)}return u(j)}function c(j){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&k();const z=t.events.length;let A=z,_;for(;A--;)if(t.events[A][0]==="exit"&&t.events[A][1].type==="chunkFlow"){_=t.events[A][1].end;break}x(r);let D=z;for(;D<t.events.length;)t.events[D][1].end={..._},D++;return sn(t.events,A+1,0,t.events.slice(z)),t.events.length=D,u(j)}return o(j)}function u(j){if(r===n.length){if(!i)return h(j);if(i.currentConstruct&&i.currentConstruct.concrete)return g(j);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Xm,d,f)(j)}function d(j){return i&&k(),x(r),h(j)}function f(j){return t.parser.lazy[t.now().line]=r!==n.length,a=t.now().offset,g(j)}function h(j){return t.containerState={},e.attempt(Xm,m,g)(j)}function m(j){return r++,n.push([t.currentConstruct,t.containerState]),h(j)}function g(j){if(j===null){i&&k(),x(0),e.consume(j);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:l}),v(j)}function v(j){if(j===null){w(e.exit("chunkFlow"),!0),x(0),e.consume(j);return}return fe(j)?(e.consume(j),w(e.exit("chunkFlow")),r=0,t.interrupt=void 0,o):(e.consume(j),v)}function w(j,z){const A=t.sliceStream(j);if(z&&A.push(null),j.previous=l,l&&(l.next=j),l=j,i.defineSkip(j.start),i.write(A),t.parser.lazy[j.start.line]){let _=i.events.length;for(;_--;)if(i.events[_][1].start.offset<a&&(!i.events[_][1].end||i.events[_][1].end.offset>a))return;const D=t.events.length;let C=D,M,N;for(;C--;)if(t.events[C][0]==="exit"&&t.events[C][1].type==="chunkFlow"){if(M){N=t.events[C][1].end;break}M=!0}for(x(r),_=D;_<t.events.length;)t.events[_][1].end={...N},_++;sn(t.events,C+1,0,t.events.slice(D)),t.events.length=_}}function x(j){let z=n.length;for(;z-- >j;){const A=n[z];t.containerState=A[1],A[0].exit.call(t,e)}n.length=j}function k(){i.write([null]),l=void 0,i=void 0,t.containerState._closeFlow=void 0}}function tj(e,t,n){return Te(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ts(e){if(e===null||Oe(e)||ui(e))return 1;if(bo(e))return 2}function jo(e,t,n){const r=[];let i=-1;for(;++i<e.length;){const l=e[i].resolveAll;l&&!r.includes(l)&&(t=l(t,n),r.push(l))}return t}const wu={name:"attention",resolveAll:nj,tokenize:rj};function nj(e,t){let n=-1,r,i,l,a,o,c,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const f={...e[r][1].end},h={...e[n][1].start};Jm(f,-c),Jm(h,c),a={type:c>1?"strongSequence":"emphasisSequence",start:f,end:{...e[r][1].end}},o={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:h},l={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?"strong":"emphasis",start:{...a.start},end:{...o.end}},e[r][1].end={...a.start},e[n][1].start={...o.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=fn(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=fn(u,[["enter",i,t],["enter",a,t],["exit",a,t],["enter",l,t]]),u=fn(u,jo(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=fn(u,[["exit",l,t],["enter",o,t],["exit",o,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=fn(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,sn(e,r-1,n-r+3,u),n=r+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function rj(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=ts(r);let l;return a;function a(c){return l=c,e.enter("attentionSequence"),o(c)}function o(c){if(c===l)return e.consume(c),o;const u=e.exit("attentionSequence"),d=ts(c),f=!d||d===2&&i||n.includes(c),h=!i||i===2&&d||n.includes(r);return u._open=!!(l===42?f:f&&(i||!h)),u._close=!!(l===42?h:h&&(d||!f)),t(c)}}function Jm(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const ij={name:"autolink",tokenize:sj};function sj(e,t,n){let r=0;return i;function i(m){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),l}function l(m){return Ft(m)?(e.consume(m),a):m===64?n(m):u(m)}function a(m){return m===43||m===45||m===46||It(m)?(r=1,o(m)):u(m)}function o(m){return m===58?(e.consume(m),r=0,c):(m===43||m===45||m===46||It(m))&&r++<32?(e.consume(m),o):(r=0,u(m))}function c(m){return m===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.exit("autolink"),t):m===null||m===32||m===60||Ka(m)?n(m):(e.consume(m),c)}function u(m){return m===64?(e.consume(m),d):Qb(m)?(e.consume(m),u):n(m)}function d(m){return It(m)?f(m):n(m)}function f(m){return m===46?(e.consume(m),r=0,d):m===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.exit("autolink"),t):h(m)}function h(m){if((m===45||It(m))&&r++<63){const g=m===45?h:f;return e.consume(m),g}return n(m)}}const Nl={partial:!0,tokenize:lj};function lj(e,t,n){return r;function r(l){return Se(l)?Te(e,i,"linePrefix")(l):i(l)}function i(l){return l===null||fe(l)?t(l):n(l)}}const Zy={continuation:{tokenize:oj},exit:cj,name:"blockQuote",tokenize:aj};function aj(e,t,n){const r=this;return i;function i(a){if(a===62){const o=r.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),l}return n(a)}function l(a){return Se(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function oj(e,t,n){const r=this;return i;function i(a){return Se(a)?Te(e,l,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):l(a)}function l(a){return e.attempt(Zy,t,n)(a)}}function cj(e){e.exit("blockQuote")}const ex={name:"characterEscape",tokenize:uj};function uj(e,t,n){return r;function r(l){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(l),e.exit("escapeMarker"),i}function i(l){return Yb(l)?(e.enter("characterEscapeValue"),e.consume(l),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(l)}}const tx={name:"characterReference",tokenize:dj};function dj(e,t,n){const r=this;let i=0,l,a;return o;function o(f){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),c}function c(f){return f===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(f),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),l=31,a=It,d(f))}function u(f){return f===88||f===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(f),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),l=6,a=Kb,d):(e.enter("characterReferenceValue"),l=7,a=ku,d(f))}function d(f){if(f===59&&i){const h=e.exit("characterReferenceValue");return a===It&&!Md(r.sliceSerialize(h))?n(f):(e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(f)&&i++<l?(e.consume(f),d):n(f)}}const Zm={partial:!0,tokenize:mj},eh={concrete:!0,name:"codeFenced",tokenize:fj};function fj(e,t,n){const r=this,i={partial:!0,tokenize:A};let l=0,a=0,o;return c;function c(_){return u(_)}function u(_){const D=r.events[r.events.length-1];return l=D&&D[1].type==="linePrefix"?D[2].sliceSerialize(D[1],!0).length:0,o=_,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(_)}function d(_){return _===o?(a++,e.consume(_),d):a<3?n(_):(e.exit("codeFencedFenceSequence"),Se(_)?Te(e,f,"whitespace")(_):f(_))}function f(_){return _===null||fe(_)?(e.exit("codeFencedFence"),r.interrupt?t(_):e.check(Zm,v,z)(_)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(_))}function h(_){return _===null||fe(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),f(_)):Se(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Te(e,m,"whitespace")(_)):_===96&&_===o?n(_):(e.consume(_),h)}function m(_){return _===null||fe(_)?f(_):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(_))}function g(_){return _===null||fe(_)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),f(_)):_===96&&_===o?n(_):(e.consume(_),g)}function v(_){return e.attempt(i,z,w)(_)}function w(_){return e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),x}function x(_){return l>0&&Se(_)?Te(e,k,"linePrefix",l+1)(_):k(_)}function k(_){return _===null||fe(_)?e.check(Zm,v,z)(_):(e.enter("codeFlowValue"),j(_))}function j(_){return _===null||fe(_)?(e.exit("codeFlowValue"),k(_)):(e.consume(_),j)}function z(_){return e.exit("codeFenced"),t(_)}function A(_,D,C){let M=0;return N;function N(X){return _.enter("lineEnding"),_.consume(X),_.exit("lineEnding"),U}function U(X){return _.enter("codeFencedFence"),Se(X)?Te(_,O,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(X):O(X)}function O(X){return X===o?(_.enter("codeFencedFenceSequence"),re(X)):C(X)}function re(X){return X===o?(M++,_.consume(X),re):M>=a?(_.exit("codeFencedFenceSequence"),Se(X)?Te(_,ie,"whitespace")(X):ie(X)):C(X)}function ie(X){return X===null||fe(X)?(_.exit("codeFencedFence"),D(X)):C(X)}}}function mj(e,t,n){const r=this;return i;function i(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l)}function l(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}const ic={name:"codeIndented",tokenize:pj},hj={partial:!0,tokenize:gj};function pj(e,t,n){const r=this;return i;function i(u){return e.enter("codeIndented"),Te(e,l,"linePrefix",5)(u)}function l(u){const d=r.events[r.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?c(u):fe(u)?e.attempt(hj,a,c)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||fe(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),o)}function c(u){return e.exit("codeIndented"),t(u)}}function gj(e,t,n){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?n(a):fe(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):Te(e,l,"linePrefix",5)(a)}function l(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):fe(a)?i(a):n(a)}}const yj={name:"codeText",previous:vj,resolve:xj,tokenize:kj};function xj(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="codeTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function vj(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function kj(e,t,n){let r=0,i,l;return a;function a(f){return e.enter("codeText"),e.enter("codeTextSequence"),o(f)}function o(f){return f===96?(e.consume(f),r++,o):(e.exit("codeTextSequence"),c(f))}function c(f){return f===null?n(f):f===32?(e.enter("space"),e.consume(f),e.exit("space"),c):f===96?(l=e.enter("codeTextSequence"),i=0,d(f)):fe(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(f))}function u(f){return f===null||f===32||f===96||fe(f)?(e.exit("codeTextData"),c(f)):(e.consume(f),u)}function d(f){return f===96?(e.consume(f),i++,d):i===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(f)):(l.type="codeTextData",u(f))}}class wj{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const l=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&Es(this.left,r),l.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Es(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Es(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);Es(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Es(this.left,n.reverse())}}}function Es(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function nx(e){const t={};let n=-1,r,i,l,a,o,c,u;const d=new wj(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(r=d.get(n),n&&r[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(c=r[1]._tokenizer.events,l=0,l<c.length&&c[l][1].type==="lineEndingBlank"&&(l+=2),l<c.length&&c[l][1].type==="content"))for(;++l<c.length&&c[l][1].type!=="content";)c[l][1].type==="chunkText"&&(c[l][1]._isInFirstContentOfListItem=!0,l++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,bj(d,n)),n=t[n],u=!0);else if(r[1]._container){for(l=n,i=void 0;l--;)if(a=d.get(l),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(i&&(d.get(i)[1].type="lineEndingBlank"),a[1].type="lineEnding",i=l);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;i&&(r[1].end={...d.get(i)[1].start},o=d.slice(i,n),o.unshift(r),d.splice(i,n-i+1,o))}}return sn(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function bj(e,t){const n=e.get(t)[1],r=e.get(t)[2];let i=t-1;const l=[];let a=n._tokenizer;a||(a=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,c=[],u={};let d,f,h=-1,m=n,g=0,v=0;const w=[v];for(;m;){for(;e.get(++i)[1]!==m;);l.push(i),m._tokenizer||(d=r.sliceStream(m),m.next||d.push(null),f&&a.defineSkip(m.start),m._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),m._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),f=m,m=m.next}for(m=n;++h<o.length;)o[h][0]==="exit"&&o[h-1][0]==="enter"&&o[h][1].type===o[h-1][1].type&&o[h][1].start.line!==o[h][1].end.line&&(v=h+1,w.push(v),m._tokenizer=void 0,m.previous=void 0,m=m.next);for(a.events=[],m?(m._tokenizer=void 0,m.previous=void 0):w.pop(),h=w.length;h--;){const x=o.slice(w[h],w[h+1]),k=l.pop();c.push([k,k+x.length-1]),e.splice(k,2,x)}for(c.reverse(),h=-1;++h<c.length;)u[g+c[h][0]]=g+c[h][1],g+=c[h][1]-c[h][0]-1;return u}const jj={resolve:Nj,tokenize:Cj},Sj={partial:!0,tokenize:_j};function Nj(e){return nx(e),e}function Cj(e,t){let n;return r;function r(o){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),i(o)}function i(o){return o===null?l(o):fe(o)?e.check(Sj,a,l)(o):(e.consume(o),i)}function l(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function a(o){return e.consume(o),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,i}}function _j(e,t,n){const r=this;return i;function i(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Te(e,l,"linePrefix")}function l(a){if(a===null||fe(a))return n(a);const o=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):e.interrupt(r.parser.constructs.flow,n,t)(a)}}function rx(e,t,n,r,i,l,a,o,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return f;function f(x){return x===60?(e.enter(r),e.enter(i),e.enter(l),e.consume(x),e.exit(l),h):x===null||x===32||x===41||Ka(x)?n(x):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),v(x))}function h(x){return x===62?(e.enter(l),e.consume(x),e.exit(l),e.exit(i),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),m(x))}function m(x){return x===62?(e.exit("chunkString"),e.exit(o),h(x)):x===null||x===60||fe(x)?n(x):(e.consume(x),x===92?g:m)}function g(x){return x===60||x===62||x===92?(e.consume(x),m):m(x)}function v(x){return!d&&(x===null||x===41||Oe(x))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),t(x)):d<u&&x===40?(e.consume(x),d++,v):x===41?(e.consume(x),d--,v):x===null||x===32||x===40||Ka(x)?n(x):(e.consume(x),x===92?w:v)}function w(x){return x===40||x===41||x===92?(e.consume(x),v):v(x)}}function ix(e,t,n,r,i,l){const a=this;let o=0,c;return u;function u(m){return e.enter(r),e.enter(i),e.consume(m),e.exit(i),e.enter(l),d}function d(m){return o>999||m===null||m===91||m===93&&!c||m===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?n(m):m===93?(e.exit(l),e.enter(i),e.consume(m),e.exit(i),e.exit(r),t):fe(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),f(m))}function f(m){return m===null||m===91||m===93||fe(m)||o++>999?(e.exit("chunkString"),d(m)):(e.consume(m),c||(c=!Se(m)),m===92?h:f)}function h(m){return m===91||m===92||m===93?(e.consume(m),o++,f):f(m)}}function sx(e,t,n,r,i,l){let a;return o;function o(h){return h===34||h===39||h===40?(e.enter(r),e.enter(i),e.consume(h),e.exit(i),a=h===40?41:h,c):n(h)}function c(h){return h===a?(e.enter(i),e.consume(h),e.exit(i),e.exit(r),t):(e.enter(l),u(h))}function u(h){return h===a?(e.exit(l),c(a)):h===null?n(h):fe(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),Te(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(h))}function d(h){return h===a||h===null||fe(h)?(e.exit("chunkString"),u(h)):(e.consume(h),h===92?f:d)}function f(h){return h===a||h===92?(e.consume(h),d):d(h)}}function qs(e,t){let n;return r;function r(i){return fe(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):Se(i)?Te(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const Ej={name:"definition",tokenize:zj},Tj={partial:!0,tokenize:Lj};function zj(e,t,n){const r=this;let i;return l;function l(m){return e.enter("definition"),a(m)}function a(m){return ix.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(m)}function o(m){return i=Ln(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),c):n(m)}function c(m){return Oe(m)?qs(e,u)(m):u(m)}function u(m){return rx(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(m)}function d(m){return e.attempt(Tj,f,f)(m)}function f(m){return Se(m)?Te(e,h,"whitespace")(m):h(m)}function h(m){return m===null||fe(m)?(e.exit("definition"),r.parser.defined.push(i),t(m)):n(m)}}function Lj(e,t,n){return r;function r(o){return Oe(o)?qs(e,i)(o):n(o)}function i(o){return sx(e,l,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function l(o){return Se(o)?Te(e,a,"whitespace")(o):a(o)}function a(o){return o===null||fe(o)?t(o):n(o)}}const Ij={name:"hardBreakEscape",tokenize:Dj};function Dj(e,t,n){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),i}function i(l){return fe(l)?(e.exit("hardBreakEscape"),t(l)):n(l)}}const Aj={name:"headingAtx",resolve:Pj,tokenize:Mj};function Pj(e,t){let n=e.length-2,r=3,i,l;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},l={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},sn(e,r,n-r+1,[["enter",i,t],["enter",l,t],["exit",l,t],["exit",i,t]])),e}function Mj(e,t,n){let r=0;return i;function i(d){return e.enter("atxHeading"),l(d)}function l(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&r++<6?(e.consume(d),a):d===null||Oe(d)?(e.exit("atxHeadingSequence"),o(d)):n(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||fe(d)?(e.exit("atxHeading"),t(d)):Se(d)?Te(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||Oe(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const Rj=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],th=["pre","script","style","textarea"],$j={concrete:!0,name:"htmlFlow",resolveTo:Uj,tokenize:Bj},Fj={partial:!0,tokenize:Vj},Oj={partial:!0,tokenize:Hj};function Uj(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Bj(e,t,n){const r=this;let i,l,a,o,c;return u;function u(S){return d(S)}function d(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),f}function f(S){return S===33?(e.consume(S),h):S===47?(e.consume(S),l=!0,v):S===63?(e.consume(S),i=3,r.interrupt?t:b):Ft(S)?(e.consume(S),a=String.fromCharCode(S),w):n(S)}function h(S){return S===45?(e.consume(S),i=2,m):S===91?(e.consume(S),i=5,o=0,g):Ft(S)?(e.consume(S),i=4,r.interrupt?t:b):n(S)}function m(S){return S===45?(e.consume(S),r.interrupt?t:b):n(S)}function g(S){const oe="CDATA[";return S===oe.charCodeAt(o++)?(e.consume(S),o===oe.length?r.interrupt?t:O:g):n(S)}function v(S){return Ft(S)?(e.consume(S),a=String.fromCharCode(S),w):n(S)}function w(S){if(S===null||S===47||S===62||Oe(S)){const oe=S===47,pe=a.toLowerCase();return!oe&&!l&&th.includes(pe)?(i=1,r.interrupt?t(S):O(S)):Rj.includes(a.toLowerCase())?(i=6,oe?(e.consume(S),x):r.interrupt?t(S):O(S)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(S):l?k(S):j(S))}return S===45||It(S)?(e.consume(S),a+=String.fromCharCode(S),w):n(S)}function x(S){return S===62?(e.consume(S),r.interrupt?t:O):n(S)}function k(S){return Se(S)?(e.consume(S),k):N(S)}function j(S){return S===47?(e.consume(S),N):S===58||S===95||Ft(S)?(e.consume(S),z):Se(S)?(e.consume(S),j):N(S)}function z(S){return S===45||S===46||S===58||S===95||It(S)?(e.consume(S),z):A(S)}function A(S){return S===61?(e.consume(S),_):Se(S)?(e.consume(S),A):j(S)}function _(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),c=S,D):Se(S)?(e.consume(S),_):C(S)}function D(S){return S===c?(e.consume(S),c=null,M):S===null||fe(S)?n(S):(e.consume(S),D)}function C(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||Oe(S)?A(S):(e.consume(S),C)}function M(S){return S===47||S===62||Se(S)?j(S):n(S)}function N(S){return S===62?(e.consume(S),U):n(S)}function U(S){return S===null||fe(S)?O(S):Se(S)?(e.consume(S),U):n(S)}function O(S){return S===45&&i===2?(e.consume(S),xe):S===60&&i===1?(e.consume(S),ce):S===62&&i===4?(e.consume(S),J):S===63&&i===3?(e.consume(S),b):S===93&&i===5?(e.consume(S),P):fe(S)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Fj,B,re)(S)):S===null||fe(S)?(e.exit("htmlFlowData"),re(S)):(e.consume(S),O)}function re(S){return e.check(Oj,ie,B)(S)}function ie(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),X}function X(S){return S===null||fe(S)?re(S):(e.enter("htmlFlowData"),O(S))}function xe(S){return S===45?(e.consume(S),b):O(S)}function ce(S){return S===47?(e.consume(S),a="",T):O(S)}function T(S){if(S===62){const oe=a.toLowerCase();return th.includes(oe)?(e.consume(S),J):O(S)}return Ft(S)&&a.length<8?(e.consume(S),a+=String.fromCharCode(S),T):O(S)}function P(S){return S===93?(e.consume(S),b):O(S)}function b(S){return S===62?(e.consume(S),J):S===45&&i===2?(e.consume(S),b):O(S)}function J(S){return S===null||fe(S)?(e.exit("htmlFlowData"),B(S)):(e.consume(S),J)}function B(S){return e.exit("htmlFlow"),t(S)}}function Hj(e,t,n){const r=this;return i;function i(a){return fe(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l):n(a)}function l(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}function Vj(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Nl,t,n)}}const Wj={name:"htmlText",tokenize:Gj};function Gj(e,t,n){const r=this;let i,l,a;return o;function o(b){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(b),c}function c(b){return b===33?(e.consume(b),u):b===47?(e.consume(b),A):b===63?(e.consume(b),j):Ft(b)?(e.consume(b),C):n(b)}function u(b){return b===45?(e.consume(b),d):b===91?(e.consume(b),l=0,g):Ft(b)?(e.consume(b),k):n(b)}function d(b){return b===45?(e.consume(b),m):n(b)}function f(b){return b===null?n(b):b===45?(e.consume(b),h):fe(b)?(a=f,ce(b)):(e.consume(b),f)}function h(b){return b===45?(e.consume(b),m):f(b)}function m(b){return b===62?xe(b):b===45?h(b):f(b)}function g(b){const J="CDATA[";return b===J.charCodeAt(l++)?(e.consume(b),l===J.length?v:g):n(b)}function v(b){return b===null?n(b):b===93?(e.consume(b),w):fe(b)?(a=v,ce(b)):(e.consume(b),v)}function w(b){return b===93?(e.consume(b),x):v(b)}function x(b){return b===62?xe(b):b===93?(e.consume(b),x):v(b)}function k(b){return b===null||b===62?xe(b):fe(b)?(a=k,ce(b)):(e.consume(b),k)}function j(b){return b===null?n(b):b===63?(e.consume(b),z):fe(b)?(a=j,ce(b)):(e.consume(b),j)}function z(b){return b===62?xe(b):j(b)}function A(b){return Ft(b)?(e.consume(b),_):n(b)}function _(b){return b===45||It(b)?(e.consume(b),_):D(b)}function D(b){return fe(b)?(a=D,ce(b)):Se(b)?(e.consume(b),D):xe(b)}function C(b){return b===45||It(b)?(e.consume(b),C):b===47||b===62||Oe(b)?M(b):n(b)}function M(b){return b===47?(e.consume(b),xe):b===58||b===95||Ft(b)?(e.consume(b),N):fe(b)?(a=M,ce(b)):Se(b)?(e.consume(b),M):xe(b)}function N(b){return b===45||b===46||b===58||b===95||It(b)?(e.consume(b),N):U(b)}function U(b){return b===61?(e.consume(b),O):fe(b)?(a=U,ce(b)):Se(b)?(e.consume(b),U):M(b)}function O(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(e.consume(b),i=b,re):fe(b)?(a=O,ce(b)):Se(b)?(e.consume(b),O):(e.consume(b),ie)}function re(b){return b===i?(e.consume(b),i=void 0,X):b===null?n(b):fe(b)?(a=re,ce(b)):(e.consume(b),re)}function ie(b){return b===null||b===34||b===39||b===60||b===61||b===96?n(b):b===47||b===62||Oe(b)?M(b):(e.consume(b),ie)}function X(b){return b===47||b===62||Oe(b)?M(b):n(b)}function xe(b){return b===62?(e.consume(b),e.exit("htmlTextData"),e.exit("htmlText"),t):n(b)}function ce(b){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),T}function T(b){return Se(b)?Te(e,P,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(b):P(b)}function P(b){return e.enter("htmlTextData"),a(b)}}const Rd={name:"labelEnd",resolveAll:Yj,resolveTo:Xj,tokenize:Jj},qj={tokenize:Zj},Qj={tokenize:eS},Kj={tokenize:tS};function Yj(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const i=r.type==="labelImage"?4:2;r.type="data",t+=i}}return e.length!==n.length&&sn(e,0,e.length,n),e}function Xj(e,t){let n=e.length,r=0,i,l,a,o;for(;n--;)if(i=e[n][1],l){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[n][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(l=n,i.type!=="labelLink")){r=2;break}}else i.type==="labelEnd"&&(a=n);const c={type:e[l][1].type==="labelLink"?"link":"image",start:{...e[l][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[l][1].start},end:{...e[a][1].end}},d={type:"labelText",start:{...e[l+r+2][1].end},end:{...e[a-2][1].start}};return o=[["enter",c,t],["enter",u,t]],o=fn(o,e.slice(l+1,l+r+3)),o=fn(o,[["enter",d,t]]),o=fn(o,jo(t.parser.constructs.insideSpan.null,e.slice(l+r+4,a-3),t)),o=fn(o,[["exit",d,t],e[a-2],e[a-1],["exit",u,t]]),o=fn(o,e.slice(a+1)),o=fn(o,[["exit",c,t]]),sn(e,l,e.length,o),e}function Jj(e,t,n){const r=this;let i=r.events.length,l,a;for(;i--;)if((r.events[i][1].type==="labelImage"||r.events[i][1].type==="labelLink")&&!r.events[i][1]._balanced){l=r.events[i][1];break}return o;function o(h){return l?l._inactive?f(h):(a=r.parser.defined.includes(Ln(r.sliceSerialize({start:l.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),c):n(h)}function c(h){return h===40?e.attempt(qj,d,a?d:f)(h):h===91?e.attempt(Qj,d,a?u:f)(h):a?d(h):f(h)}function u(h){return e.attempt(Kj,d,f)(h)}function d(h){return t(h)}function f(h){return l._balanced=!0,n(h)}}function Zj(e,t,n){return r;function r(f){return e.enter("resource"),e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),i}function i(f){return Oe(f)?qs(e,l)(f):l(f)}function l(f){return f===41?d(f):rx(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(f)}function a(f){return Oe(f)?qs(e,c)(f):d(f)}function o(f){return n(f)}function c(f){return f===34||f===39||f===40?sx(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(f):d(f)}function u(f){return Oe(f)?qs(e,d)(f):d(f)}function d(f){return f===41?(e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),e.exit("resource"),t):n(f)}}function eS(e,t,n){const r=this;return i;function i(o){return ix.call(r,e,l,a,"reference","referenceMarker","referenceString")(o)}function l(o){return r.parser.defined.includes(Ln(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(o):n(o)}function a(o){return n(o)}}function tS(e,t,n){return r;function r(l){return e.enter("reference"),e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),i}function i(l){return l===93?(e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),e.exit("reference"),t):n(l)}}const nS={name:"labelStartImage",resolveAll:Rd.resolveAll,tokenize:rS};function rS(e,t,n){const r=this;return i;function i(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),l}function l(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),a):n(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const iS={name:"labelStartLink",resolveAll:Rd.resolveAll,tokenize:sS};function sS(e,t,n){const r=this;return i;function i(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),l}function l(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const sc={name:"lineEnding",tokenize:lS};function lS(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),Te(e,t,"linePrefix")}}const xa={name:"thematicBreak",tokenize:aS};function aS(e,t,n){let r=0,i;return l;function l(u){return e.enter("thematicBreak"),a(u)}function a(u){return i=u,o(u)}function o(u){return u===i?(e.enter("thematicBreakSequence"),c(u)):r>=3&&(u===null||fe(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===i?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),Se(u)?Te(e,o,"whitespace")(u):o(u))}}const Vt={continuation:{tokenize:dS},exit:mS,name:"list",tokenize:uS},oS={partial:!0,tokenize:hS},cS={partial:!0,tokenize:fS};function uS(e,t,n){const r=this,i=r.events[r.events.length-1];let l=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(m){const g=r.containerState.type||(m===42||m===43||m===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!r.containerState.marker||m===r.containerState.marker:ku(m)){if(r.containerState.type||(r.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),m===42||m===45?e.check(xa,n,u)(m):u(m);if(!r.interrupt||m===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(m)}return n(m)}function c(m){return ku(m)&&++a<10?(e.consume(m),c):(!r.interrupt||a<2)&&(r.containerState.marker?m===r.containerState.marker:m===41||m===46)?(e.exit("listItemValue"),u(m)):n(m)}function u(m){return e.enter("listItemMarker"),e.consume(m),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||m,e.check(Nl,r.interrupt?n:d,e.attempt(oS,h,f))}function d(m){return r.containerState.initialBlankLine=!0,l++,h(m)}function f(m){return Se(m)?(e.enter("listItemPrefixWhitespace"),e.consume(m),e.exit("listItemPrefixWhitespace"),h):n(m)}function h(m){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(m)}}function dS(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Nl,i,l);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Te(e,t,"listItemIndent",r.containerState.size+1)(o)}function l(o){return r.containerState.furtherBlankLines||!Se(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(cS,t,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Te(e,e.attempt(Vt,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function fS(e,t,n){const r=this;return Te(e,i,"listItemIndent",r.containerState.size+1);function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?t(l):n(l)}}function mS(e){e.exit(this.containerState.type)}function hS(e,t,n){const r=this;return Te(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(l){const a=r.events[r.events.length-1];return!Se(l)&&a&&a[1].type==="listItemPrefixWhitespace"?t(l):n(l)}}const nh={name:"setextUnderline",resolveTo:pS,tokenize:gS};function pS(e,t){let n=e.length,r,i,l;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!l&&e[n][1].type==="definition"&&(l=n);const a={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",l?(e.splice(i,0,["enter",a,t]),e.splice(l+1,0,["exit",e[r][1],t]),e[r][1].end={...e[l][1].end}):e[r][1]=a,e.push(["exit",a,t]),e}function gS(e,t,n){const r=this;let i;return l;function l(u){let d=r.events.length,f;for(;d--;)if(r.events[d][1].type!=="lineEnding"&&r.events[d][1].type!=="linePrefix"&&r.events[d][1].type!=="content"){f=r.events[d][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||f)?(e.enter("setextHeadingLine"),i=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===i?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),Se(u)?Te(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||fe(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const yS={tokenize:xS};function xS(e){const t=this,n=e.attempt(Nl,r,e.attempt(this.parser.constructs.flowInitial,i,Te(e,e.attempt(this.parser.constructs.flow,i,e.attempt(jj,i)),"linePrefix")));return n;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const vS={resolveAll:ax()},kS=lx("string"),wS=lx("text");function lx(e){return{resolveAll:ax(e==="text"?bS:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],l=n.attempt(i,a,o);return a;function a(d){return u(d)?l(d):o(d)}function o(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),c}function c(d){return u(d)?(n.exit("data"),l(d)):(n.consume(d),c)}function u(d){if(d===null)return!0;const f=i[d];let h=-1;if(f)for(;++h<f.length;){const m=f[h];if(!m.previous||m.previous.call(r,r.previous))return!0}return!1}}}function ax(e){return t;function t(n,r){let i=-1,l;for(;++i<=n.length;)l===void 0?n[i]&&n[i][1].type==="data"&&(l=i,i++):(!n[i]||n[i][1].type!=="data")&&(i!==l+2&&(n[l][1].end=n[i-1][1].end,n.splice(l+2,i-l-2),i=l+2),l=void 0);return e?e(n,r):n}}function bS(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],i=t.sliceStream(r);let l=i.length,a=-1,o=0,c;for(;l--;){const u=i[l];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(u===-2)c=!0,o++;else if(u!==-1){l++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(o=0),o){const u={type:n===e.length||c||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:l?a:r.start._bufferIndex+a,_index:r.start._index+l,line:r.end.line,column:r.end.column-o,offset:r.end.offset-o},end:{...r.end}};r.end={...u.start},r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const jS={42:Vt,43:Vt,45:Vt,48:Vt,49:Vt,50:Vt,51:Vt,52:Vt,53:Vt,54:Vt,55:Vt,56:Vt,57:Vt,62:Zy},SS={91:Ej},NS={[-2]:ic,[-1]:ic,32:ic},CS={35:Aj,42:xa,45:[nh,xa],60:$j,61:nh,95:xa,96:eh,126:eh},_S={38:tx,92:ex},ES={[-5]:sc,[-4]:sc,[-3]:sc,33:nS,38:tx,42:wu,60:[ij,Wj],91:iS,92:[Ij,ex],93:Rd,95:wu,96:yj},TS={null:[wu,vS]},zS={null:[42,95]},LS={null:[]},IS=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:zS,contentInitial:SS,disable:LS,document:jS,flow:CS,flowInitial:NS,insideSpan:TS,string:_S,text:ES},Symbol.toStringTag,{value:"Module"}));function DS(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const i={},l=[];let a=[],o=[];const c={attempt:D(A),check:D(_),consume:k,enter:j,exit:z,interrupt:D(_,{interrupt:!0})},u={code:null,containerState:{},defineSkip:v,events:[],now:g,parser:e,previous:null,sliceSerialize:h,sliceStream:m,write:f};let d=t.tokenize.call(u,c);return t.resolveAll&&l.push(t),u;function f(U){return a=fn(a,U),w(),a[a.length-1]!==null?[]:(C(t,0),u.events=jo(l,u.events,u),u.events)}function h(U,O){return PS(m(U),O)}function m(U){return AS(a,U)}function g(){const{_bufferIndex:U,_index:O,line:re,column:ie,offset:X}=r;return{_bufferIndex:U,_index:O,line:re,column:ie,offset:X}}function v(U){i[U.line]=U.column,N()}function w(){let U;for(;r._index<a.length;){const O=a[r._index];if(typeof O=="string")for(U=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===U&&r._bufferIndex<O.length;)x(O.charCodeAt(r._bufferIndex));else x(O)}}function x(U){d=d(U)}function k(U){fe(U)?(r.line++,r.column=1,r.offset+=U===-3?2:1,N()):U!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===a[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=U}function j(U,O){const re=O||{};return re.type=U,re.start=g(),u.events.push(["enter",re,u]),o.push(re),re}function z(U){const O=o.pop();return O.end=g(),u.events.push(["exit",O,u]),O}function A(U,O){C(U,O.from)}function _(U,O){O.restore()}function D(U,O){return re;function re(ie,X,xe){let ce,T,P,b;return Array.isArray(ie)?B(ie):"tokenize"in ie?B([ie]):J(ie);function J(ae){return _e;function _e(He){const nt=He!==null&&ae[He],Ge=He!==null&&ae.null,L=[...Array.isArray(nt)?nt:nt?[nt]:[],...Array.isArray(Ge)?Ge:Ge?[Ge]:[]];return B(L)(He)}}function B(ae){return ce=ae,T=0,ae.length===0?xe:S(ae[T])}function S(ae){return _e;function _e(He){return b=M(),P=ae,ae.partial||(u.currentConstruct=ae),ae.name&&u.parser.constructs.disable.null.includes(ae.name)?pe():ae.tokenize.call(O?Object.assign(Object.create(u),O):u,c,oe,pe)(He)}}function oe(ae){return U(P,b),X}function pe(ae){return b.restore(),++T<ce.length?S(ce[T]):xe}}}function C(U,O){U.resolveAll&&!l.includes(U)&&l.push(U),U.resolve&&sn(u.events,O,u.events.length-O,U.resolve(u.events.slice(O),u)),U.resolveTo&&(u.events=U.resolveTo(u.events,u))}function M(){const U=g(),O=u.previous,re=u.currentConstruct,ie=u.events.length,X=Array.from(o);return{from:ie,restore:xe};function xe(){r=U,u.previous=O,u.currentConstruct=re,u.events.length=ie,o=X,N()}}function N(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function AS(e,t){const n=t.start._index,r=t.start._bufferIndex,i=t.end._index,l=t.end._bufferIndex;let a;if(n===i)a=[e[n].slice(r,l)];else{if(a=e.slice(n,i),r>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}l>0&&a.push(e[i].slice(0,l))}return a}function PS(e,t){let n=-1;const r=[];let i;for(;++n<e.length;){const l=e[n];let a;if(typeof l=="string")a=l;else switch(l){case-5:{a="\r";break}case-4:{a=`
490
490
  `;break}case-3:{a=`\r
491
491
  `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&i)continue;a=" ";break}default:a=String.fromCharCode(l)}i=l===-2,r.push(a)}return r.join("")}function MS(e){const r={constructs:Xy([IS,...(e||{}).extensions||[]]),content:i(Xb),defined:[],document:i(Zb),flow:i(yS),lazy:{},string:i(kS),text:i(wS)};return r;function i(l){return a;function a(o){return DS(r,l,o)}}}function RS(e){for(;!nx(e););return e}const rh=/[\0\t\n\r]/g;function $S(){let e=1,t="",n=!0,r;return i;function i(l,a,o){const c=[];let u,d,f,h,m;for(l=t+(typeof l=="string"?l.toString():new TextDecoder(a||void 0).decode(l)),f=0,t="",n&&(l.charCodeAt(0)===65279&&f++,n=void 0);f<l.length;){if(rh.lastIndex=f,u=rh.exec(l),h=u&&u.index!==void 0?u.index:l.length,m=l.charCodeAt(h),!u){t=l.slice(f);break}if(m===10&&f===h&&r)c.push(-3),r=void 0;else switch(r&&(c.push(-5),r=void 0),f<h&&(c.push(l.slice(f,h)),e+=h-f),m){case 0:{c.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,c.push(-2);e++<d;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:r=!0,e=1}f=h+1}return o&&(r&&c.push(-5),t&&c.push(t),c.push(null)),c}}const FS=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function OS(e){return e.replace(FS,US)}function US(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const i=n.charCodeAt(1),l=i===120||i===88;return Jy(n.slice(l?2:1),l?16:10)}return Md(n)||e}const ox={}.hasOwnProperty;function BS(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),HS(n)(RS(MS(n).document().write($S()(e,t,!0))))}function HS(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(Ae),autolinkProtocol:M,autolinkEmail:M,atxHeading:l(he),blockQuote:l(Ge),characterEscape:M,characterReference:M,codeFenced:l(L),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:l(L,a),codeText:l(F,a),codeTextData:M,data:M,codeFlowValue:M,definition:l(Y),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:l(ue),hardBreakEscape:l(H),hardBreakTrailing:l(H),htmlFlow:l(le,a),htmlFlowData:M,htmlText:l(le,a),htmlTextData:M,image:l(Pe),label:a,link:l(Ae),listItem:l(ut),listItemValue:h,listOrdered:l($e,f),listUnordered:l($e),paragraph:l(je),reference:S,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:l(he),strong:l(Je),thematicBreak:l(os)},exit:{atxHeading:c(),atxHeadingSequence:A,autolink:c(),autolinkEmail:nt,autolinkProtocol:He,blockQuote:c(),characterEscapeValue:N,characterReferenceMarkerHexadecimal:pe,characterReferenceMarkerNumeric:pe,characterReferenceValue:ae,characterReference:_e,codeFenced:c(w),codeFencedFence:v,codeFencedFenceInfo:m,codeFencedFenceMeta:g,codeFlowValue:N,codeIndented:c(x),codeText:c(X),codeTextData:N,data:N,definition:c(),definitionDestinationString:z,definitionLabelString:k,definitionTitleString:j,emphasis:c(),hardBreakEscape:c(O),hardBreakTrailing:c(O),htmlFlow:c(re),htmlFlowData:N,htmlText:c(ie),htmlTextData:N,image:c(ce),label:P,labelText:T,lineEnding:U,link:c(xe),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:oe,resourceDestinationString:b,resourceTitleString:J,resource:B,setextHeading:c(C),setextHeadingLineSequence:D,setextHeadingText:_,strong:c(),thematicBreak:c()}};cx(t,(e||{}).mdastExtensions||[]);const n={};return r;function r($){let Q={type:"root",children:[]};const de={stack:[Q],tokenStack:[],config:t,enter:o,exit:u,buffer:a,resume:d,data:n},ve=[];let be=-1;for(;++be<$.length;)if($[be][1].type==="listOrdered"||$[be][1].type==="listUnordered")if($[be][0]==="enter")ve.push(be);else{const wt=ve.pop();be=i($,wt,be)}for(be=-1;++be<$.length;){const wt=t[$[be][0]];ox.call(wt,$[be][1].type)&&wt[$[be][1].type].call(Object.assign({sliceSerialize:$[be][2].sliceSerialize},de),$[be][1])}if(de.tokenStack.length>0){const wt=de.tokenStack[de.tokenStack.length-1];(wt[1]||ih).call(de,void 0,wt[0])}for(Q.position={start:wr($.length>0?$[0][1].start:{line:1,column:1,offset:0}),end:wr($.length>0?$[$.length-2][1].end:{line:1,column:1,offset:0})},be=-1;++be<t.transforms.length;)Q=t.transforms[be](Q)||Q;return Q}function i($,Q,de){let ve=Q-1,be=-1,wt=!1,pt,qe,Pt,Xt;for(;++ve<=de;){const rt=$[ve];switch(rt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{rt[0]==="enter"?be++:be--,Xt=void 0;break}case"lineEndingBlank":{rt[0]==="enter"&&(pt&&!Xt&&!be&&!Pt&&(Pt=ve),Xt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Xt=void 0}if(!be&&rt[0]==="enter"&&rt[1].type==="listItemPrefix"||be===-1&&rt[0]==="exit"&&(rt[1].type==="listUnordered"||rt[1].type==="listOrdered")){if(pt){let Mt=ve;for(qe=void 0;Mt--;){const bt=$[Mt];if(bt[1].type==="lineEnding"||bt[1].type==="lineEndingBlank"){if(bt[0]==="exit")continue;qe&&($[qe][1].type="lineEndingBlank",wt=!0),bt[1].type="lineEnding",qe=Mt}else if(!(bt[1].type==="linePrefix"||bt[1].type==="blockQuotePrefix"||bt[1].type==="blockQuotePrefixWhitespace"||bt[1].type==="blockQuoteMarker"||bt[1].type==="listItemIndent"))break}Pt&&(!qe||Pt<qe)&&(pt._spread=!0),pt.end=Object.assign({},qe?$[qe][1].start:rt[1].end),$.splice(qe||ve,0,["exit",pt,rt[2]]),ve++,de++}if(rt[1].type==="listItemPrefix"){const Mt={type:"listItem",_spread:!1,start:Object.assign({},rt[1].start),end:void 0};pt=Mt,$.splice(ve,0,["enter",Mt,rt[2]]),ve++,de++,Pt=void 0,Xt=!0}}}return $[Q][1]._spread=wt,de}function l($,Q){return de;function de(ve){o.call(this,$(ve),ve),Q&&Q.call(this,ve)}}function a(){this.stack.push({type:"fragment",children:[]})}function o($,Q,de){this.stack[this.stack.length-1].children.push($),this.stack.push($),this.tokenStack.push([Q,de||void 0]),$.position={start:wr(Q.start),end:void 0}}function c($){return Q;function Q(de){$&&$.call(this,de),u.call(this,de)}}function u($,Q){const de=this.stack.pop(),ve=this.tokenStack.pop();if(ve)ve[0].type!==$.type&&(Q?Q.call(this,$,ve[0]):(ve[1]||ih).call(this,$,ve[0]));else throw new Error("Cannot close `"+$.type+"` ("+Gs({start:$.start,end:$.end})+"): it’s not open");de.position.end=wr($.end)}function d(){return Pd(this.stack.pop())}function f(){this.data.expectingFirstListItemValue=!0}function h($){if(this.data.expectingFirstListItemValue){const Q=this.stack[this.stack.length-2];Q.start=Number.parseInt(this.sliceSerialize($),10),this.data.expectingFirstListItemValue=void 0}}function m(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.lang=$}function g(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.meta=$}function v(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.value=$.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.value=$.replace(/(\r?\n|\r)$/g,"")}function k($){const Q=this.resume(),de=this.stack[this.stack.length-1];de.label=Q,de.identifier=Ln(this.sliceSerialize($)).toLowerCase()}function j(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.title=$}function z(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.url=$}function A($){const Q=this.stack[this.stack.length-1];if(!Q.depth){const de=this.sliceSerialize($).length;Q.depth=de}}function _(){this.data.setextHeadingSlurpLineEnding=!0}function D($){const Q=this.stack[this.stack.length-1];Q.depth=this.sliceSerialize($).codePointAt(0)===61?1:2}function C(){this.data.setextHeadingSlurpLineEnding=void 0}function M($){const de=this.stack[this.stack.length-1].children;let ve=de[de.length-1];(!ve||ve.type!=="text")&&(ve=Vr(),ve.position={start:wr($.start),end:void 0},de.push(ve)),this.stack.push(ve)}function N($){const Q=this.stack.pop();Q.value+=this.sliceSerialize($),Q.position.end=wr($.end)}function U($){const Q=this.stack[this.stack.length-1];if(this.data.atHardBreak){const de=Q.children[Q.children.length-1];de.position.end=wr($.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(Q.type)&&(M.call(this,$),N.call(this,$))}function O(){this.data.atHardBreak=!0}function re(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.value=$}function ie(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.value=$}function X(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.value=$}function xe(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const Q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=Q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function ce(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const Q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=Q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function T($){const Q=this.sliceSerialize($),de=this.stack[this.stack.length-2];de.label=OS(Q),de.identifier=Ln(Q).toLowerCase()}function P(){const $=this.stack[this.stack.length-1],Q=this.resume(),de=this.stack[this.stack.length-1];if(this.data.inReference=!0,de.type==="link"){const ve=$.children;de.children=ve}else de.alt=Q}function b(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.url=$}function J(){const $=this.resume(),Q=this.stack[this.stack.length-1];Q.title=$}function B(){this.data.inReference=void 0}function S(){this.data.referenceType="collapsed"}function oe($){const Q=this.resume(),de=this.stack[this.stack.length-1];de.label=Q,de.identifier=Ln(this.sliceSerialize($)).toLowerCase(),this.data.referenceType="full"}function pe($){this.data.characterReferenceType=$.type}function ae($){const Q=this.sliceSerialize($),de=this.data.characterReferenceType;let ve;de?(ve=Jy(Q,de==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ve=Md(Q);const be=this.stack[this.stack.length-1];be.value+=ve}function _e($){const Q=this.stack.pop();Q.position.end=wr($.end)}function He($){N.call(this,$);const Q=this.stack[this.stack.length-1];Q.url=this.sliceSerialize($)}function nt($){N.call(this,$);const Q=this.stack[this.stack.length-1];Q.url="mailto:"+this.sliceSerialize($)}function Ge(){return{type:"blockquote",children:[]}}function L(){return{type:"code",lang:null,meta:null,value:""}}function F(){return{type:"inlineCode",value:""}}function Y(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ue(){return{type:"emphasis",children:[]}}function he(){return{type:"heading",depth:0,children:[]}}function H(){return{type:"break"}}function le(){return{type:"html",value:""}}function Pe(){return{type:"image",title:null,url:"",alt:null}}function Ae(){return{type:"link",title:null,url:"",children:[]}}function $e($){return{type:"list",ordered:$.type==="listOrdered",start:null,spread:$._spread,children:[]}}function ut($){return{type:"listItem",spread:$._spread,checked:null,children:[]}}function je(){return{type:"paragraph",children:[]}}function Je(){return{type:"strong",children:[]}}function Vr(){return{type:"text",value:""}}function os(){return{type:"thematicBreak"}}}function wr(e){return{line:e.line,column:e.column,offset:e.offset}}function cx(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?cx(e,r):VS(e,r)}}function VS(e,t){let n;for(n in t)if(ox.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function ih(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Gs({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Gs({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Gs({start:t.start,end:t.end})+") is still open")}function WS(e){const t=this;t.parser=n;function n(r){return BS(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function GS(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function qS(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
@@ -520,7 +520,7 @@ Error generating stack: `+l.message+`
520
520
  ${c}
521
521
  \`\`\`
522
522
  ${u}`}function nE(e){if(!e)return e;let t=e;t=tE(t),t=t.replace(K_,""),t=Y_(t),t=t.replace(/<think>[\s\S]*?<\/think>/g,"");const n=(t.match(/\\n/g)||[]).length,r=(t.match(/\n/g)||[]).length;return n>2&&n>r*2&&(t=t.replace(/\\n/g,`
523
- `),t=t.replace(/\\"/g,'"')),t=Z_(t).trim(),t}function rE(e){if(!e)return"";const t=new Date(e),r=new Date().getTime()-t.getTime(),i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i}m ago`;const l=Math.floor(i/60);return l<24?`${l}h ago`:t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Ph(e){return e?new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",hour12:!0}):""}function iE(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}function Mh({message:e,isStreaming:t,showTerminalCursor:n,agentSteps:r,agentStepsActive:i,onDelete:l,onResend:a,latencyMs:o,agentName:c}){var A,_,D;const u=e.role==="assistant"&&Q_(e.content),d=p.useMemo(()=>nE(e.content),[e.content]),[f,h]=p.useState(!1),[m,g]=p.useState(!1),v=p.useRef(null),w=p.useRef(null);p.useEffect(()=>()=>{v.current&&clearTimeout(v.current),w.current&&clearTimeout(w.current)},[]);const x=p.useCallback(()=>{var C;if((C=navigator.clipboard)!=null&&C.writeText)navigator.clipboard.writeText(e.content).catch(()=>{});else{const M=document.createElement("textarea");M.value=e.content,M.style.position="fixed",M.style.opacity="0",document.body.appendChild(M),M.select(),document.execCommand("copy"),document.body.removeChild(M)}h(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>h(!1),2e3)},[e.content]),k=p.useCallback(()=>{if(!m){g(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>g(!1),3e3);return}g(!1),w.current&&clearTimeout(w.current),l==null||l(e.id)},[m,e.id,l]),j=p.useCallback(()=>{a==null||a(e)},[e,a]),z=e.created_at?`${e.role==="user"?"Sent":"Replied"} ${Ph(e.created_at)}`:void 0;return s.jsx("div",{className:`msg msg-${e.role} ${u?"msg-error":""}`,title:z,children:s.jsxs("div",{className:"msg-inner",children:[s.jsxs("div",{className:"msg-header",children:[s.jsx("div",{className:"msg-header-left",children:e.role==="assistant"&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"msg-avatar msg-avatar-assistant","aria-hidden":"true",children:s.jsx("img",{src:My,alt:""})}),s.jsx("span",{className:"msg-role-brand",children:"GAIA"}),(()=>{const M=((c==null?void 0:c.trim())??"").replace(/^gaia\b\s*/i,"");return M?s.jsx("span",{className:"msg-role-agent",children:M}):null})(),(t||e.created_at)&&s.jsx("span",{className:"msg-header-sep",children:"|"}),t&&s.jsx(q_,{active:!!i||!d}),!t&&e.created_at&&s.jsx("span",{className:"msg-timestamp",children:rE(e.created_at)})]})}),!t&&s.jsxs("div",{className:"msg-actions",children:[e.role==="user"&&a&&s.jsx("button",{className:"msg-action-btn",onClick:j,title:"Resend message","aria-label":"Resend message",children:s.jsx(Vs,{size:12})}),s.jsx("button",{className:`msg-copy ${f?"copied":""}`,onClick:x,title:f?"Copied!":"Copy message","aria-label":f?"Copied to clipboard":"Copy message",children:f?s.jsx(li,{size:12}):s.jsx(jl,{size:12})}),l&&s.jsx("button",{className:`msg-action-btn msg-delete ${m?"confirm":""}`,onClick:k,title:m?"Click again to confirm":"Delete message","aria-label":m?"Confirm delete message":"Delete message",children:s.jsx(ci,{size:12})})]})]}),s.jsxs("div",{className:"msg-body",children:[r&&r.length>0&&s.jsx(Bx,{steps:r,isActive:i??!1,variant:i?"inline":"summary"}),u&&s.jsxs("div",{className:"error-banner",children:[s.jsx(pn,{size:14}),s.jsx("span",{children:"Something went wrong"})]}),s.jsx(_u,{content:d,showCursor:(t||n)&&!!d&&!i}),e.role==="assistant"&&!t&&$_(d)&&s.jsx(O_,{}),e.role==="assistant"&&!t&&(e.stats||o!=null||e.created_at)&&s.jsxs("div",{className:"msg-stats","aria-label":"Message performance stats",children:[e.created_at&&s.jsx("span",{className:"msg-stats-ts",title:"Message timestamp",children:Ph(e.created_at)}),o!=null&&o>0&&s.jsx("span",{title:"Total response time",children:iE(o)}),((A=e.stats)==null?void 0:A.tokens_per_second)!=null&&e.stats.tokens_per_second>0&&s.jsxs("span",{title:"Tokens per second",children:[e.stats.tokens_per_second," tok/s"]}),((_=e.stats)==null?void 0:_.time_to_first_token)!=null&&e.stats.time_to_first_token>0&&s.jsxs("span",{title:"Time to first token",children:[(e.stats.time_to_first_token*1e3).toFixed(0),"ms TTFT"]}),((D=e.stats)==null?void 0:D.output_tokens)!=null&&e.stats.output_tokens>0&&s.jsxs("span",{title:"Input → output tokens",children:[(e.stats.input_tokens??0).toLocaleString()," → ",e.stats.output_tokens.toLocaleString()," tokens"]})]})]})]})})}function sE({lang:e,code:t}){const[n,r]=p.useState(!1),i=p.useRef(null);p.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const l=p.useCallback(()=>{var a;if((a=navigator.clipboard)!=null&&a.writeText)navigator.clipboard.writeText(t).catch(()=>{});else{const o=document.createElement("textarea");o.value=t,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o)}r(!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>r(!1),2e3)},[t]);return s.jsxs("div",{className:"code-block",children:[s.jsxs("div",{className:"code-header",children:[s.jsx("span",{className:"code-lang",children:e||"code"}),s.jsxs("button",{className:`code-copy ${n?"copied":""}`,onClick:l,title:n?"Copied!":"Copy","aria-label":n?"Copied to clipboard":"Copy code",children:[n?s.jsx(li,{size:13}):s.jsx(jl,{size:13}),s.jsx("span",{children:n?"Copied":"Copy"})]})]}),s.jsx("pre",{children:s.jsx("code",{children:t})})]})}const lE=/[A-Z]:[\\\/](?:[^\s*?"<>|,;)}\]]+[\\\/])*[^\s*?"<>|,;)}\]]*\.\w{1,5}/gi,aE=/[A-Z]:[\\\/](?:[^\s*?"<>|,;)}\]]+[\\\/])+/gi;function oE({path:e}){const t=n=>{n.preventDefault(),_d(e).catch(r=>{E.ui.error("Failed to open path",r)})};return s.jsxs("span",{className:"file-path-link",onClick:t,title:`Open in file explorer: ${e}`,role:"button",tabIndex:0,onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),t(n))},children:[s.jsx(Yn,{size:12,className:"file-path-icon"}),e]})}function cE(e){const t=new RegExp(`(${lE.source}|${aE.source})`,"gi"),n=[];let r=0,i;for(;(i=t.exec(e))!==null;)i.index>r&&n.push(e.slice(r,i.index)),n.push(s.jsx(oE,{path:i[0]},i.index)),r=t.lastIndex;return n.length===0?e:(r<e.length&&n.push(e.slice(r)),s.jsx(s.Fragment,{children:n}))}function br(e){return Gi.Children.map(e,t=>typeof t=="string"?cE(t):t)}const uE=/```(email[_-]pre[_-]scan)[ \t]*\r?\n([\s\S]*?)\r?\n```/;function _u({content:e,showCursor:t}){if(!e&&!t)return null;if(!e&&t)return s.jsx("span",{className:"cursor"});const n=uE.exec(e);if(n){const r=e.slice(0,n.index).trim(),i=n[2],l=e.slice(n.index+n[0].length).trim();try{const a=JSON.parse(i);if(Dh(a))return s.jsxs("div",{className:"md-content",children:[r&&s.jsx(_u,{content:r}),s.jsx(Ah,{payload:a}),l&&s.jsx(_u,{content:l}),t&&s.jsx("span",{className:"cursor"})]})}catch{}}return s.jsxs("div",{className:"md-content",children:[s.jsx(cN,{remarkPlugins:[S_],disallowedElements:[...hN],urlTransform:pN,components:{code({className:r,children:i,...l}){return s.jsx("code",{className:"inline-code",...l,children:i})},pre({children:r}){var l,a;const i=Gi.Children.toArray(r)[0];if(Gi.isValidElement(i)&&(i.type==="code"||((l=i.props)==null?void 0:l.className)!==void 0||typeof((a=i.props)==null?void 0:a.children)=="string")){const o=i.props,c=(o==null?void 0:o.className)||"",u=/language-([\w-]+)/.exec(c),d=String((o==null?void 0:o.children)||"").replace(/\n$/,""),f=(u==null?void 0:u[1])||"";if(f==="email_pre_scan"||f==="email-pre-scan")try{const h=JSON.parse(d);if(Dh(h))return s.jsx(Ah,{payload:h})}catch{}return s.jsx(sE,{lang:f,code:d})}return s.jsx("pre",{children:r})},table({children:r}){return s.jsx("div",{className:"md-table-wrap",children:s.jsx("table",{className:"md-table",children:r})})},a({href:r,children:i}){return s.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"md-link",children:i})},p({children:r}){return s.jsx("p",{className:"md-p",children:br(r)})},h1({children:r}){return s.jsx("h2",{className:"md-h2",children:br(r)})},h2({children:r}){return s.jsx("h3",{className:"md-h3",children:br(r)})},h3({children:r}){return s.jsx("h4",{className:"md-h4",children:br(r)})},ul({children:r}){return s.jsx("ul",{className:"md-ul",children:r})},ol({children:r}){return s.jsx("ol",{className:"md-ol",children:r})},li({children:r}){return s.jsx("li",{className:"md-li",children:br(r)})},blockquote({children:r}){return s.jsx("blockquote",{className:"md-blockquote",children:br(r)})},hr(){return s.jsx("hr",{className:"md-hr"})},td({children:r}){return s.jsx("td",{children:br(r)})},th({children:r}){return s.jsx("th",{children:br(r)})}},children:e}),t&&s.jsx("span",{className:"cursor"})]})}const dE=500,Za="gaia_always_allow_tools",ot=jy((e,t)=>({notifications:[],showPanel:!1,typeFilter:null,addNotification:n=>e(r=>({notifications:[n,...r.notifications].slice(0,dE)})),dismiss:n=>e(r=>({notifications:r.notifications.map(i=>i.id===n?{...i,dismissed:!0}:i)})),markRead:n=>e(r=>({notifications:r.notifications.map(i=>i.id===n?{...i,read:!0}:i)})),markAllRead:()=>e(n=>({notifications:n.notifications.map(r=>({...r,read:!0}))})),clearAll:()=>e({notifications:[]}),setShowPanel:n=>e({showPanel:n}),setTypeFilter:n=>e({typeFilter:n}),respondToPermission:async(n,r,i)=>{var c;const l=t().notifications.find(u=>u.id===n),a=l==null?void 0:l.agentId,o=window.gaiaAPI;if((c=o==null?void 0:o.notification)!=null&&c.respondPermission)try{await o.notification.respondPermission(n,r,i)}catch(u){console.error("[notificationStore] Failed to send permission response via IPC:",u);return}else if(a)try{await Iy(a,r==="allow")}catch(u){console.error("[notificationStore] Failed to send permission response via REST:",u);return}if(r==="allow"&&i&&l!=null&&l.tool){const u=JSON.parse(localStorage.getItem(Za)||"[]");u.includes(l.tool)||(u.push(l.tool),localStorage.setItem(Za,JSON.stringify(u)))}e(u=>({notifications:u.notifications.map(d=>d.id===n?{...d,response:r,respondedAt:Date.now(),read:!0}:d)}))}})),Hx=e=>e.notifications.filter(t=>!t.read&&!t.dismissed).length,fE=e=>{const t=e.notifications.filter(n=>!n.dismissed);return e.typeFilter?t.filter(n=>n.type===e.typeFilter):t},mE=e=>e.notifications.find(t=>t.type==="permission_request"&&!t.response&&!t.dismissed)??null,Vx="https://github.com/amd/gaia/issues/new",hE=[{label:"Image",extensions:new Set([".jpg",".jpeg",".png",".gif",".bmp",".tiff",".webp",".ico",".heic",".heif"]),message:"Image files cannot be indexed for text search.",alternatives:["Index PDFs that contain images — text is extracted automatically","Paste image descriptions or OCR text directly into the chat","Use GAIA's VLM agent for image analysis: gaia vlm"],featureTitle:"Support image file indexing and OCR"},{label:"Video",extensions:new Set([".mp4",".avi",".mkv",".mov",".wmv",".flv",".webm",".m4v"]),message:"Video files are not supported for indexing.",alternatives:["Extract subtitles or transcripts from videos and index those","Use GAIA's voice/talk mode for audio: gaia talk"],featureTitle:"Support video file indexing"},{label:"Audio",extensions:new Set([".mp3",".wav",".flac",".aac",".ogg",".wma",".m4a",".opus"]),message:"Audio files are not supported for indexing.",alternatives:["Use GAIA's voice mode for speech interaction: gaia talk","Transcribe audio to text first, then index the transcript"],featureTitle:"Support audio file transcription and indexing"},{label:"Archive",extensions:new Set([".zip",".rar",".7z",".tar",".gz",".bz2",".xz",".tgz"]),message:"Archive files must be extracted before indexing.",alternatives:["Extract the archive contents to a folder","Then index the folder or individual files from the Document Library"],featureTitle:"Support automatic archive extraction for indexing"},{label:"Executable",extensions:new Set([".exe",".msi",".dll",".so",".app",".dmg",".bin",".com"]),message:"Executable and binary files cannot be indexed.",alternatives:["Index source code files (.py, .js, .ts, .java, etc.) instead","Index documentation or README files from the project"],featureTitle:"Support binary file analysis"},{label:"Database",extensions:new Set([".sqlite",".db",".mdb",".accdb",".dbf"]),message:"Database files are not supported for direct indexing.",alternatives:["Export data to CSV or JSON format, then index those files","Use SQL queries to extract relevant data to a text file"],featureTitle:"Support database file indexing"},{label:"Microsoft Office",extensions:new Set([".doc",".docx",".ppt",".pptx",".xls"]),message:"Word, PowerPoint, and legacy Excel (.xls) files are not yet supported — GAIA does not currently ship parsers for these formats.",alternatives:["Save as PDF from Word or PowerPoint, then index the PDF","Re-save legacy .xls workbooks as .xlsx — GAIA supports modern Excel files"],featureTitle:"Support Microsoft Office (docx, pptx, xls) indexing"}];function Ks(e){const t=e.toLowerCase().startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`;for(const n of hE)if(n.extensions.has(t))return n;return null}const pE=new Set([".pdf",".txt",".md",".csv",".json",".xlsx",".html",".htm",".xml",".svg",".yaml",".yml",".py",".js",".ts",".java",".c",".cpp",".h",".rs",".go",".rb",".sh",".bat",".ps1",".log",".cfg",".ini",".toml"]);function eo(e){const t=e.toLowerCase().startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`;return pE.has(t)}function Wx(){const e="0.18.0",t=navigator.userAgent,n=navigator.platform||"unknown";return`**Environment:**
523
+ `),t=t.replace(/\\"/g,'"')),t=Z_(t).trim(),t}function rE(e){if(!e)return"";const t=new Date(e),r=new Date().getTime()-t.getTime(),i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i}m ago`;const l=Math.floor(i/60);return l<24?`${l}h ago`:t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Ph(e){return e?new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",hour12:!0}):""}function iE(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}function Mh({message:e,isStreaming:t,showTerminalCursor:n,agentSteps:r,agentStepsActive:i,onDelete:l,onResend:a,latencyMs:o,agentName:c}){var A,_,D;const u=e.role==="assistant"&&Q_(e.content),d=p.useMemo(()=>nE(e.content),[e.content]),[f,h]=p.useState(!1),[m,g]=p.useState(!1),v=p.useRef(null),w=p.useRef(null);p.useEffect(()=>()=>{v.current&&clearTimeout(v.current),w.current&&clearTimeout(w.current)},[]);const x=p.useCallback(()=>{var C;if((C=navigator.clipboard)!=null&&C.writeText)navigator.clipboard.writeText(e.content).catch(()=>{});else{const M=document.createElement("textarea");M.value=e.content,M.style.position="fixed",M.style.opacity="0",document.body.appendChild(M),M.select(),document.execCommand("copy"),document.body.removeChild(M)}h(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>h(!1),2e3)},[e.content]),k=p.useCallback(()=>{if(!m){g(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>g(!1),3e3);return}g(!1),w.current&&clearTimeout(w.current),l==null||l(e.id)},[m,e.id,l]),j=p.useCallback(()=>{a==null||a(e)},[e,a]),z=e.created_at?`${e.role==="user"?"Sent":"Replied"} ${Ph(e.created_at)}`:void 0;return s.jsx("div",{className:`msg msg-${e.role} ${u?"msg-error":""}`,title:z,children:s.jsxs("div",{className:"msg-inner",children:[s.jsxs("div",{className:"msg-header",children:[s.jsx("div",{className:"msg-header-left",children:e.role==="assistant"&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"msg-avatar msg-avatar-assistant","aria-hidden":"true",children:s.jsx("img",{src:My,alt:""})}),s.jsx("span",{className:"msg-role-brand",children:"GAIA"}),(()=>{const M=((c==null?void 0:c.trim())??"").replace(/^gaia\b\s*/i,"");return M?s.jsx("span",{className:"msg-role-agent",children:M}):null})(),(t||e.created_at)&&s.jsx("span",{className:"msg-header-sep",children:"|"}),t&&s.jsx(q_,{active:!!i||!d}),!t&&e.created_at&&s.jsx("span",{className:"msg-timestamp",children:rE(e.created_at)})]})}),!t&&s.jsxs("div",{className:"msg-actions",children:[e.role==="user"&&a&&s.jsx("button",{className:"msg-action-btn",onClick:j,title:"Resend message","aria-label":"Resend message",children:s.jsx(Vs,{size:12})}),s.jsx("button",{className:`msg-copy ${f?"copied":""}`,onClick:x,title:f?"Copied!":"Copy message","aria-label":f?"Copied to clipboard":"Copy message",children:f?s.jsx(li,{size:12}):s.jsx(jl,{size:12})}),l&&s.jsx("button",{className:`msg-action-btn msg-delete ${m?"confirm":""}`,onClick:k,title:m?"Click again to confirm":"Delete message","aria-label":m?"Confirm delete message":"Delete message",children:s.jsx(ci,{size:12})})]})]}),s.jsxs("div",{className:"msg-body",children:[r&&r.length>0&&s.jsx(Bx,{steps:r,isActive:i??!1,variant:i?"inline":"summary"}),u&&s.jsxs("div",{className:"error-banner",children:[s.jsx(pn,{size:14}),s.jsx("span",{children:"Something went wrong"})]}),s.jsx(_u,{content:d,showCursor:(t||n)&&!!d&&!i}),e.role==="assistant"&&!t&&$_(d)&&s.jsx(O_,{}),e.role==="assistant"&&!t&&(e.stats||o!=null||e.created_at)&&s.jsxs("div",{className:"msg-stats","aria-label":"Message performance stats",children:[e.created_at&&s.jsx("span",{className:"msg-stats-ts",title:"Message timestamp",children:Ph(e.created_at)}),o!=null&&o>0&&s.jsx("span",{title:"Total response time",children:iE(o)}),((A=e.stats)==null?void 0:A.tokens_per_second)!=null&&e.stats.tokens_per_second>0&&s.jsxs("span",{title:"Tokens per second",children:[e.stats.tokens_per_second," tok/s"]}),((_=e.stats)==null?void 0:_.time_to_first_token)!=null&&e.stats.time_to_first_token>0&&s.jsxs("span",{title:"Time to first token",children:[(e.stats.time_to_first_token*1e3).toFixed(0),"ms TTFT"]}),((D=e.stats)==null?void 0:D.output_tokens)!=null&&e.stats.output_tokens>0&&s.jsxs("span",{title:"Input → output tokens",children:[(e.stats.input_tokens??0).toLocaleString()," → ",e.stats.output_tokens.toLocaleString()," tokens"]})]})]})]})})}function sE({lang:e,code:t}){const[n,r]=p.useState(!1),i=p.useRef(null);p.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const l=p.useCallback(()=>{var a;if((a=navigator.clipboard)!=null&&a.writeText)navigator.clipboard.writeText(t).catch(()=>{});else{const o=document.createElement("textarea");o.value=t,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o)}r(!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>r(!1),2e3)},[t]);return s.jsxs("div",{className:"code-block",children:[s.jsxs("div",{className:"code-header",children:[s.jsx("span",{className:"code-lang",children:e||"code"}),s.jsxs("button",{className:`code-copy ${n?"copied":""}`,onClick:l,title:n?"Copied!":"Copy","aria-label":n?"Copied to clipboard":"Copy code",children:[n?s.jsx(li,{size:13}):s.jsx(jl,{size:13}),s.jsx("span",{children:n?"Copied":"Copy"})]})]}),s.jsx("pre",{children:s.jsx("code",{children:t})})]})}const lE=/[A-Z]:[\\\/](?:[^\s*?"<>|,;)}\]]+[\\\/])*[^\s*?"<>|,;)}\]]*\.\w{1,5}/gi,aE=/[A-Z]:[\\\/](?:[^\s*?"<>|,;)}\]]+[\\\/])+/gi;function oE({path:e}){const t=n=>{n.preventDefault(),_d(e).catch(r=>{E.ui.error("Failed to open path",r)})};return s.jsxs("span",{className:"file-path-link",onClick:t,title:`Open in file explorer: ${e}`,role:"button",tabIndex:0,onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),t(n))},children:[s.jsx(Yn,{size:12,className:"file-path-icon"}),e]})}function cE(e){const t=new RegExp(`(${lE.source}|${aE.source})`,"gi"),n=[];let r=0,i;for(;(i=t.exec(e))!==null;)i.index>r&&n.push(e.slice(r,i.index)),n.push(s.jsx(oE,{path:i[0]},i.index)),r=t.lastIndex;return n.length===0?e:(r<e.length&&n.push(e.slice(r)),s.jsx(s.Fragment,{children:n}))}function br(e){return Gi.Children.map(e,t=>typeof t=="string"?cE(t):t)}const uE=/```(email[_-]pre[_-]scan)[ \t]*\r?\n([\s\S]*?)\r?\n```/;function _u({content:e,showCursor:t}){if(!e&&!t)return null;if(!e&&t)return s.jsx("span",{className:"cursor"});const n=uE.exec(e);if(n){const r=e.slice(0,n.index).trim(),i=n[2],l=e.slice(n.index+n[0].length).trim();try{const a=JSON.parse(i);if(Dh(a))return s.jsxs("div",{className:"md-content",children:[r&&s.jsx(_u,{content:r}),s.jsx(Ah,{payload:a}),l&&s.jsx(_u,{content:l}),t&&s.jsx("span",{className:"cursor"})]})}catch{}}return s.jsxs("div",{className:"md-content",children:[s.jsx(cN,{remarkPlugins:[S_],disallowedElements:[...hN],urlTransform:pN,components:{code({className:r,children:i,...l}){return s.jsx("code",{className:"inline-code",...l,children:i})},pre({children:r}){var l,a;const i=Gi.Children.toArray(r)[0];if(Gi.isValidElement(i)&&(i.type==="code"||((l=i.props)==null?void 0:l.className)!==void 0||typeof((a=i.props)==null?void 0:a.children)=="string")){const o=i.props,c=(o==null?void 0:o.className)||"",u=/language-([\w-]+)/.exec(c),d=String((o==null?void 0:o.children)||"").replace(/\n$/,""),f=(u==null?void 0:u[1])||"";if(f==="email_pre_scan"||f==="email-pre-scan")try{const h=JSON.parse(d);if(Dh(h))return s.jsx(Ah,{payload:h})}catch{}return s.jsx(sE,{lang:f,code:d})}return s.jsx("pre",{children:r})},table({children:r}){return s.jsx("div",{className:"md-table-wrap",children:s.jsx("table",{className:"md-table",children:r})})},a({href:r,children:i}){return s.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"md-link",children:i})},p({children:r}){return s.jsx("p",{className:"md-p",children:br(r)})},h1({children:r}){return s.jsx("h2",{className:"md-h2",children:br(r)})},h2({children:r}){return s.jsx("h3",{className:"md-h3",children:br(r)})},h3({children:r}){return s.jsx("h4",{className:"md-h4",children:br(r)})},ul({children:r}){return s.jsx("ul",{className:"md-ul",children:r})},ol({children:r}){return s.jsx("ol",{className:"md-ol",children:r})},li({children:r}){return s.jsx("li",{className:"md-li",children:br(r)})},blockquote({children:r}){return s.jsx("blockquote",{className:"md-blockquote",children:br(r)})},hr(){return s.jsx("hr",{className:"md-hr"})},td({children:r}){return s.jsx("td",{children:br(r)})},th({children:r}){return s.jsx("th",{children:br(r)})}},children:e}),t&&s.jsx("span",{className:"cursor"})]})}const dE=500,Za="gaia_always_allow_tools",ot=jy((e,t)=>({notifications:[],showPanel:!1,typeFilter:null,addNotification:n=>e(r=>({notifications:[n,...r.notifications].slice(0,dE)})),dismiss:n=>e(r=>({notifications:r.notifications.map(i=>i.id===n?{...i,dismissed:!0}:i)})),markRead:n=>e(r=>({notifications:r.notifications.map(i=>i.id===n?{...i,read:!0}:i)})),markAllRead:()=>e(n=>({notifications:n.notifications.map(r=>({...r,read:!0}))})),clearAll:()=>e({notifications:[]}),setShowPanel:n=>e({showPanel:n}),setTypeFilter:n=>e({typeFilter:n}),respondToPermission:async(n,r,i)=>{var c;const l=t().notifications.find(u=>u.id===n),a=l==null?void 0:l.agentId,o=window.gaiaAPI;if((c=o==null?void 0:o.notification)!=null&&c.respondPermission)try{await o.notification.respondPermission(n,r,i)}catch(u){console.error("[notificationStore] Failed to send permission response via IPC:",u);return}else if(a)try{await Iy(a,r==="allow")}catch(u){console.error("[notificationStore] Failed to send permission response via REST:",u);return}if(r==="allow"&&i&&l!=null&&l.tool){const u=JSON.parse(localStorage.getItem(Za)||"[]");u.includes(l.tool)||(u.push(l.tool),localStorage.setItem(Za,JSON.stringify(u)))}e(u=>({notifications:u.notifications.map(d=>d.id===n?{...d,response:r,respondedAt:Date.now(),read:!0}:d)}))}})),Hx=e=>e.notifications.filter(t=>!t.read&&!t.dismissed).length,fE=e=>{const t=e.notifications.filter(n=>!n.dismissed);return e.typeFilter?t.filter(n=>n.type===e.typeFilter):t},mE=e=>e.notifications.find(t=>t.type==="permission_request"&&!t.response&&!t.dismissed)??null,Vx="https://github.com/amd/gaia/issues/new",hE=[{label:"Image",extensions:new Set([".jpg",".jpeg",".png",".gif",".bmp",".tiff",".webp",".ico",".heic",".heif"]),message:"Image files cannot be indexed for text search.",alternatives:["Index PDFs that contain images — text is extracted automatically","Paste image descriptions or OCR text directly into the chat","Use GAIA's VLM agent for image analysis: gaia vlm"],featureTitle:"Support image file indexing and OCR"},{label:"Video",extensions:new Set([".mp4",".avi",".mkv",".mov",".wmv",".flv",".webm",".m4v"]),message:"Video files are not supported for indexing.",alternatives:["Extract subtitles or transcripts from videos and index those","Use GAIA's voice/talk mode for audio: gaia talk"],featureTitle:"Support video file indexing"},{label:"Audio",extensions:new Set([".mp3",".wav",".flac",".aac",".ogg",".wma",".m4a",".opus"]),message:"Audio files are not supported for indexing.",alternatives:["Use GAIA's voice mode for speech interaction: gaia talk","Transcribe audio to text first, then index the transcript"],featureTitle:"Support audio file transcription and indexing"},{label:"Archive",extensions:new Set([".zip",".rar",".7z",".tar",".gz",".bz2",".xz",".tgz"]),message:"Archive files must be extracted before indexing.",alternatives:["Extract the archive contents to a folder","Then index the folder or individual files from the Document Library"],featureTitle:"Support automatic archive extraction for indexing"},{label:"Executable",extensions:new Set([".exe",".msi",".dll",".so",".app",".dmg",".bin",".com"]),message:"Executable and binary files cannot be indexed.",alternatives:["Index source code files (.py, .js, .ts, .java, etc.) instead","Index documentation or README files from the project"],featureTitle:"Support binary file analysis"},{label:"Database",extensions:new Set([".sqlite",".db",".mdb",".accdb",".dbf"]),message:"Database files are not supported for direct indexing.",alternatives:["Export data to CSV or JSON format, then index those files","Use SQL queries to extract relevant data to a text file"],featureTitle:"Support database file indexing"},{label:"Microsoft Office",extensions:new Set([".doc",".docx",".ppt",".pptx",".xls"]),message:"Word, PowerPoint, and legacy Excel (.xls) files are not yet supported — GAIA does not currently ship parsers for these formats.",alternatives:["Save as PDF from Word or PowerPoint, then index the PDF","Re-save legacy .xls workbooks as .xlsx — GAIA supports modern Excel files"],featureTitle:"Support Microsoft Office (docx, pptx, xls) indexing"}];function Ks(e){const t=e.toLowerCase().startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`;for(const n of hE)if(n.extensions.has(t))return n;return null}const pE=new Set([".pdf",".txt",".md",".csv",".json",".xlsx",".html",".htm",".xml",".svg",".yaml",".yml",".py",".js",".ts",".java",".c",".cpp",".h",".rs",".go",".rb",".sh",".bat",".ps1",".log",".cfg",".ini",".toml"]);function eo(e){const t=e.toLowerCase().startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`;return pE.has(t)}function Wx(){const e="0.18.1",t=navigator.userAgent,n=navigator.platform||"unknown";return`**Environment:**
524
524
  - GAIA Version: ${e}
525
525
  - Platform: ${n}
526
526
  - User Agent: ${t}
@@ -537,7 +537,7 @@ ${V}`:V}E.chat.info(`Sending message to session=${e}`,{length:ge.length,preview:
537
537
  ---
538
538
  *Unexpected error?* [Report it on GitHub](${Eu(Ce.slice(0,80))})`;Ce.includes("Lemonade")||Ce.includes("LLM")||Ce.includes("Could not get response")?ee="Could not reach the LLM server. Make sure Lemonade Server is running:\n\n```\nlemonade-server serve\n```\n\nThen try sending your message again."+dt:V instanceof TypeError||Ce.includes("fetch")||Ce.includes("Failed to fetch")||Ce.includes("NetworkError")?ee="Cannot connect to the GAIA server. Make sure the backend is running:\n\n```\ngaia chat --ui\n```"+dt:Ce.includes("500")?ee="The server encountered an error. This usually means Lemonade Server is not running or the model failed to load.\n\nStart Lemonade Server with:\n```\nlemonade-server serve\n```"+dt:Ce.includes("timed out")||Ce.includes("timeout")||Ce.includes("Timeout")?ee=`The request timed out. The query may be too complex — try breaking it into simpler questions.
539
539
 
540
- If Lemonade Server is running but responses are slow, the model may need more resources.`+dt:ee=`Error: ${Ce}`+dt;const Ie={id:Date.now()+2,session_id:e,role:"assistant",content:ee,created_at:new Date().toISOString(),rag_sources:null};a(Ie),h(!1),g(),z()},onAgentCreated:()=>{Nd().then(V=>we.getState().setAgents(V.agents||[])).catch(()=>{})}},void 0,void 0,ie);Zt.current=St},[pe,le,d,e,B,a,l,h,or,g,u,w,x,k,j,z,ie,xe]);cs.current=bn,p.useEffect(()=>{const I=q=>{var ge;const Z=(ge=q.detail)==null?void 0:ge.text;typeof Z=="string"&&Z.trim()&&cs.current(Z)};return window.addEventListener("gaia:send-message",I),()=>window.removeEventListener("gaia:send-message",I)},[]),p.useEffect(()=>{!d&&Jt.current&&Jt.current.focus()},[d]);const fr=p.useCallback(async I=>{d||(E.chat.info(`Deleting message ${I} from session=${e}`),je(I),setTimeout(async()=>{o(I),je(null);try{await m0(e,I)}catch(q){E.chat.error(`Failed to delete message ${I}`,q),As(e).then(te=>{we.getState().currentSessionId===e&&l(te.messages||[])}).catch(()=>{})}},250))},[e,d,o,l]),jt=p.useCallback(async I=>{if(d||I.role!=="user")return;const q=I.content;E.chat.info(`Resending message ${I.id} from session=${e}`,{preview:q.slice(0,80)}),c(I.id);try{await h0(e,I.id)}catch(te){E.chat.error(`Failed to delete messages from ${I.id}`,te),As(e).then(Z=>{we.getState().currentSessionId===e&&l(Z.messages||[])}).catch(()=>{});return}bn(q)},[e,d,c,l,bn]),mr=I=>{I.key==="Enter"&&!I.shiftKey&&(I.preventDefault(),bn())},ds=()=>{Ge((B==null?void 0:B.title)||""),He(!0)},Dn=async()=>{nt.trim()&&nt!==(B==null?void 0:B.title)&&(await tc(e,{title:nt.trim()}),u(e,{title:nt.trim()})),He(!1)},Wn=p.useCallback(async()=>{if(e)try{const I=await d0(e);u(e,{private:I.private})}catch(I){E.ui.warn("Failed to toggle private mode",I)}},[e,u]),hr=async()=>{try{const I=await f0(e),q=new Blob([I.content],{type:"text/markdown"}),te=URL.createObjectURL(q),Z=document.createElement("a");Z.href=te;const ge=((B==null?void 0:B.title)||"chat").replace(/[/\\:*?"<>|]/g,"_").slice(0,100);Z.download=`${ge}.md`,Z.click(),URL.revokeObjectURL(te)}catch(I){E.chat.error("Export failed",I)}},zl=p.useCallback(async(I,q)=>{I.stopPropagation();const te=A.find(Z=>Z.id===q);E.doc.info(`Detaching document from session: ${(te==null?void 0:te.filename)||q}`);try{await w0(e,q);const Z=we.getState().sessions.find(Ee=>Ee.id===e),ge=((Z==null?void 0:Z.document_ids)??[]).filter(Ee=>Ee!==q);u(e,{document_ids:ge}),ge.length<=3&&$e(!1),E.doc.info(`Detached document from session: ${(te==null?void 0:te.filename)||q}`)}catch(Z){E.doc.error(`Failed to detach document: ${(te==null?void 0:te.filename)||q}`,Z)}},[A,e,u]),Ll=p.useCallback(async I=>{if(I.preventDefault(),I.stopPropagation(),F(!1),I.dataTransfer.files.length!==0)for(const q of Array.from(I.dataTransfer.files)){E.doc.info(`Dropped on chat view: ${q.name}`);try{const te=await Ay(q);if(e&&(te!=null&&te.id))try{await Qa(e,te.id);const Z=we.getState().sessions.find(Ee=>Ee.id===e),ge=(Z==null?void 0:Z.document_ids)??[];ge.includes(te.id)||u(e,{document_ids:[...ge,te.id]}),E.doc.info(`Auto-attached "${q.name}" to session ${e}`)}catch(Z){E.doc.warn(`Could not attach dropped document to session: ${Z}`)}}catch(te){E.doc.error(`Upload failed: ${q.name}`,te)}}},[e,u]),fs=I=>{I.preventDefault(),I.stopPropagation(),F(!0)},_o=I=>{I.preventDefault(),I.stopPropagation(),F(!1)},pi=I=>{ae(I),bn(I)},pr=!N&&i.length===0&&!d,ms=p.useMemo(()=>{const I=new Map;let q;for(const te of i)if(te.role==="user"&&te.created_at)q=new Date(te.created_at).getTime();else if(te.role==="assistant"&&te.created_at&&q!==void 0){const Z=new Date(te.created_at).getTime();Z>q&&I.set(te.id,Z-q),q=void 0}return I},[i]);return s.jsxs("main",{className:`task-view ${L?"drag-active":""}`,onDrop:Ll,onDragOver:fs,onDragLeave:_o,children:[os&&s.jsx("div",{className:"dashboard-overlay",children:s.jsx(gE,{sessionId:e,onClose:()=>$(!1)})}),s.jsxs("header",{className:"task-header",children:[s.jsx("div",{className:"task-header-left",children:_e?s.jsx("input",{className:"title-edit",value:nt,onChange:I=>Ge(I.target.value),onBlur:Dn,onKeyDown:I=>I.key==="Enter"&&Dn(),autoFocus:!0,"aria-label":"Edit task title"}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"task-title",children:(B==null?void 0:B.title)||"New Task"}),s.jsx("button",{className:"btn-icon-sm",onClick:ds,title:"Rename","aria-label":"Rename task",children:s.jsx(fw,{size:13})})]})}),s.jsxs("div",{className:"chat-header-right",children:[s.jsxs("span",{className:`model-badge ${O!=null&&O.model_loaded?"":"no-model"}`,title:O!=null&&O.model_loaded&&(O!=null&&O.model_context_size)?`${O.model_loaded} · context window: ${O.model_context_size.toLocaleString()} tokens`:(O==null?void 0:O.model_loaded)||"No model loaded",children:[(O==null?void 0:O.model_loaded)||"No model loaded",(O==null?void 0:O.model_loaded)&&(O==null?void 0:O.model_context_size)!=null&&s.jsxs("span",{className:"model-ctx-size",children:[" · ",O.model_context_size%1024===0?`${O.model_context_size/1024}K`:O.model_context_size.toLocaleString()]})]}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>D(!0),title:"Documents","aria-label":"Attach documents",children:s.jsx(dw,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>C(!0),title:"Browse files","aria-label":"Browse files",children:s.jsx(_m,{size:15})}),s.jsx("button",{className:`btn-icon-sm${B!=null&&B.private?" active":""}`,onClick:Wn,title:B!=null&&B.private?"Private mode on — click to disable":"Enable private mode (nothing saved to memory)","aria-label":B!=null&&B.private?"Disable private mode":"Enable private mode","aria-pressed":!!(B!=null&&B.private),children:s.jsx(dy,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>M(!0),title:"Memory","aria-label":"Open memory dashboard",children:s.jsx(Jr,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:hr,title:"Export","aria-label":"Export task",children:s.jsx(oi,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>$(I=>!I),title:"Refresh dashboard","aria-label":"Refresh dashboard",children:s.jsx(Nm,{size:15})}),s.jsxs("button",{className:`notification-center-trigger ${b>0?"has-unread":""}`,onClick:()=>T(!ce),"aria-label":"Open notification center","aria-expanded":ce,title:"Notifications",children:[s.jsx(oy,{size:15}),b>0&&s.jsx("span",{className:"notification-center-trigger-badge",children:b>99?"99+":b})]})]})]}),oe.length>0&&(()=>{const I=[...oe].sort((Z,ge)=>{const Ee=Z.last_accessed_at||Z.indexed_at||"";return(ge.last_accessed_at||ge.indexed_at||"").localeCompare(Ee)}),q=Ae?I:I.slice(0,3),te=I.length-3;return s.jsxs("div",{className:`doc-context-bar${Ae?" doc-context-expanded":""}`,"aria-label":`${oe.length} indexed document${oe.length!==1?"s":""}`,children:[s.jsx(nr,{size:12,className:"doc-context-icon"}),s.jsxs("span",{className:"doc-context-label",onClick:()=>D(!0),title:"Click to manage documents",role:"button",tabIndex:0,children:[oe.length," indexed"]}),s.jsxs("div",{className:`doc-context-pills${Ae?" doc-context-pills-expanded":""}`,children:[q.map(Z=>s.jsxs("span",{className:"doc-pill",title:Z.filepath||Z.filename,children:[s.jsx($n,{size:9,className:"doc-pill-icon"}),s.jsx("span",{className:"doc-pill-name",children:Z.filename}),s.jsx("button",{className:"doc-pill-remove",onClick:ge=>zl(ge,Z.id),title:`Remove ${Z.filename} from this session`,"aria-label":`Remove ${Z.filename} from this session`,children:s.jsx(tt,{size:10})})]},Z.id)),!Ae&&te>0&&s.jsxs("button",{className:"doc-pill-more",onClick:Z=>{Z.stopPropagation(),$e(!0)},title:"Show all indexed files","aria-label":`Show ${te} more files`,children:["+",te," more"]}),Ae&&te>0&&s.jsx("button",{className:"doc-pill-collapse",onClick:Z=>{Z.stopPropagation(),$e(!1)},title:"Show fewer files","aria-label":"Collapse file list",children:"show less"})]})]})})(),s.jsxs("div",{className:"messages-scroll",ref:cn,onScroll:ur,children:[N&&s.jsx("div",{className:"skeleton-messages","aria-label":"Loading messages",children:[0,1,2].map(I=>s.jsxs("div",{className:"skeleton-msg",children:[s.jsxs("div",{className:"skeleton-header",children:[s.jsx("div",{className:"skeleton-avatar"}),s.jsx("div",{className:"skeleton-role"})]}),s.jsxs("div",{className:"skeleton-lines",children:[s.jsx("div",{className:"skeleton-line"}),s.jsx("div",{className:"skeleton-line"}),I!==2&&s.jsx("div",{className:"skeleton-line"})]})]},I))}),pr&&s.jsxs("div",{className:"empty-task",children:[s.jsx("div",{className:"empty-task-icon",children:s.jsx(fu,{size:36,strokeWidth:1.2})}),s.jsx("h4",{className:"empty-task-title",children:"What can I help you with?"}),s.jsx("p",{className:"empty-task-desc",children:"Ask about your documents, search files, or analyze data — powered by local AI."}),s.jsx("div",{className:"empty-task-suggestions",children:yE.map(I=>s.jsx("button",{className:"empty-task-chip",onClick:()=>pi(I),children:I},I))})]}),i.map((I,q)=>{const te=!d&&!Pt&&I.role==="assistant"&&i.slice(q+1).every(Ee=>Ee.role!=="assistant");if(Pt&&I.role==="assistant"&&q===i.length-1)return null;const ge=ms.get(I.id);return s.jsx("div",{className:ut===I.id?"msg-deleting":void 0,children:s.jsx(Mh,{message:I,showTerminalCursor:te,agentSteps:I.role==="assistant"?I.agentSteps:void 0,onDelete:d?void 0:fr,onResend:!d&&I.role==="user"?jt:void 0,latencyMs:ge,agentName:I.role==="assistant"?wt:void 0})},I.id)}),(d||Pt)&&s.jsx("div",{className:`streaming-bubble ${Pt?"stream-ending":"stream-active"}`,children:s.jsx(Mh,{message:{id:-1,session_id:e,role:"assistant",content:(d?f:rt.current)||"",created_at:"",rag_sources:null},isStreaming:d,showTerminalCursor:Pt,agentSteps:d?v:Mt.current,agentStepsActive:d&&v.some(I=>I.active),agentName:pt})}),s.jsx("div",{ref:xn})]}),Y&&s.jsx("button",{className:"scroll-bottom-btn",onClick:us,title:"Scroll to bottom","aria-label":"Scroll to bottom",children:s.jsx(Nm,{size:16})}),L&&s.jsxs("div",{className:"drag-overlay",children:[s.jsx(pl,{size:32,strokeWidth:1.5}),s.jsx("span",{children:"Drop files to index"})]}),Je&&s.jsxs("div",{className:"toast policy-alert-toast",role:"alert",children:[s.jsxs("span",{children:["Blocked: ",Je.tool," is restricted by policy."]}),Je.receiptId?s.jsx("button",{type:"button",className:"policy-alert-toast-link",onClick:()=>{const I=Je.receiptId;I&&(P("policy_alert"),T(!0),window.setTimeout(()=>{var q;(q=document.getElementById(kE(I)))==null||q.scrollIntoView({behavior:"smooth",block:"center"})},80))},children:"View receipt"}):s.jsx("span",{className:"policy-alert-toast-missing",children:"Receipt unavailable"})]}),s.jsxs("div",{className:"input-area",children:[s.jsxs("div",{className:`input-box ${le.length>0?"has-attachments":""}`,onDrop:El,onDragOver:I=>{I.preventDefault(),I.stopPropagation()},children:[s.jsxs("div",{className:"input-content",children:[le.length>0&&s.jsx("div",{className:"attachment-strip",children:le.map(I=>s.jsxs("div",{className:`attachment-preview ${I.error?"attachment-error":""}`,children:[I.isImage&&I.url?s.jsx("img",{src:I.url,alt:I.name,className:"attachment-thumb"}):s.jsx("div",{className:"attachment-file-icon",children:s.jsx($n,{size:16})}),s.jsx("span",{className:"attachment-name",title:I.name,children:I.name.length>20?I.name.slice(0,17)+"...":I.name}),I.uploading&&s.jsx("span",{className:"attachment-spinner"}),I.error&&s.jsx("span",{className:"attachment-error-text",children:I.error}),s.jsx("button",{className:"attachment-remove",onClick:()=>Tl(I.id),title:"Remove","aria-label":`Remove ${I.name}`,children:s.jsx(tt,{size:12})})]},I.id))}),s.jsx("textarea",{ref:Jt,className:"msg-input",value:pe,onChange:Vn,onKeyDown:mr,onPaste:dr,placeholder:"Type a message or paste an image... (Shift+Enter for new line)",rows:1,disabled:d||(O==null?void 0:O.init_state)==="initializing","aria-label":"Message input"})]}),s.jsxs("div",{className:"input-btns",children:[s.jsx("button",{className:"btn-icon-sm",onClick:()=>D(!0),title:"Upload document","aria-label":"Upload document",children:s.jsx(pl,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>C(!0),title:"Browse files","aria-label":"Browse files",children:s.jsx(_m,{size:15})}),d?s.jsx("button",{className:"stop-btn",onClick:wn,title:"Stop generating","aria-label":"Stop generating",children:s.jsx(vw,{size:14})}):s.jsx("button",{className:"send-btn",onClick:()=>bn(),disabled:!pe.trim()&&!le.some(I=>I.uploaded),title:"Send (Enter)","aria-label":"Send message",children:s.jsx(hw,{size:16})})]})]}),s.jsxs("div",{className:"input-footer",children:[t&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"create-agent-btn",onClick:t,title:"Build a custom agent","aria-label":"Build a custom agent",children:s.jsx(hl,{size:10})}),re.length>1&&s.jsx("span",{className:"input-footer-sep"})]}),re.length>1&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"agent-picker",ref:ve,children:[s.jsxs("button",{className:"agent-picker-btn",onClick:()=>!d&&de(I=>!I),title:"Switch agent","aria-label":"Switch agent",disabled:d,children:[s.jsx(du,{size:10}),s.jsx("span",{children:((hs=re.find(I=>I.id===be))==null?void 0:hs.name)||"Agent"}),s.jsx(ai,{size:10})]}),Q&&s.jsx("div",{className:"agent-picker-dropdown",children:re.map(I=>s.jsxs("button",{className:`agent-picker-option${I.id===be?" active":""}`,onClick:()=>qe(I.id),children:[s.jsx(du,{size:12}),s.jsx("span",{children:I.name})]},I.id))})]}),s.jsx("span",{className:"input-footer-sep"})]}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx(gy,{size:10}),s.jsx("span",{children:"100% local & private"})]}),s.jsx("span",{className:"input-footer-sep"}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Enter"}),s.jsx("span",{children:"send"})]}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Shift+Enter"}),s.jsx("span",{children:"new line"})]}),d&&s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Esc"}),s.jsx("span",{children:"stop"})]}),s.jsx("span",{className:"input-footer-sep"}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Ctrl+K"}),s.jsx("span",{children:"search"})]}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Ctrl+V"}),s.jsx("span",{children:"paste image"})]})]})]})]})}const $h="GAIA",na="Your private AI assistant, running 100% locally on AMD Ryzen AI",bE=65,jE=350;function qx(e,t){return t===","||t==="."?60+Math.random()*50:t===" "?15+Math.random()*25:Math.random()<.35?8+Math.random()*12:Math.random()<.06?45+Math.random()*35:18+Math.random()*22}const SE=["Scan my Downloads and tell me what I should clean up","Index a folder of documents so I can chat about them","What have I been working on lately? Show my recent files","What hardware is in my PC? Tell me about my CPU and GPU"];function NE({onNewTask:e,onSendPrompt:t,onCreateAgent:n}){const{systemStatus:r,agents:i,activeAgentId:l,setActiveAgentId:a}=we(),o=p.useMemo(()=>{var C;const D=i.find(M=>M.id===l);return(C=D==null?void 0:D.conversation_starters)!=null&&C.length?D.conversation_starters:SE},[i,l]),[c,u]=p.useState(""),[d,f]=p.useState(!1),[h,m]=p.useState(""),[g,v]=p.useState(!1),[w,x]=p.useState("title"),[k,j]=p.useState(!1),z=r!==null&&!r.initialized,A=(r==null?void 0:r.init_state)==="initializing",_=r!==null&&r.lemonade_running&&!r.model_loaded;return p.useEffect(()=>{let D=0;const C=setInterval(()=>{D++,D<=$h.length?u($h.slice(0,D)):(clearInterval(C),f(!0))},bE);return()=>clearInterval(C)},[]),p.useEffect(()=>{if(!d)return;let D=!1;const C=setTimeout(()=>{if(D)return;x("subtitle");let N=0;const U=()=>{if(!D)if(N++,N<=na.length){m(na.slice(0,N));const O=na[N-1],re=N>1?na[N-2]:"",ie=qx(O,re);M.current=setTimeout(U,ie)}else v(!0),x("done")};U()},jE),M={current:null};return()=>{D=!0,clearTimeout(C),M.current&&clearTimeout(M.current)}},[d]),p.useEffect(()=>{if(!g)return;const D=setTimeout(()=>j(!0),200);return()=>clearTimeout(D)},[g]),s.jsx("main",{className:"welcome",children:s.jsxs("div",{className:`welcome-inner ${k?"content-revealed":""}`,children:[s.jsxs("h1",{className:`welcome-title${d?" typing-done":""}`,children:[c.length>=4?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"gaia-glow",children:c.slice(0,4)}),s.jsx("span",{children:c.slice(4)})]}):c,w==="title"&&s.jsx("span",{className:`terminal-cursor${d?" blink":""}`})]}),s.jsx("p",{className:"welcome-sub",children:s.jsxs("span",{className:"typewriter-text",children:[h,(w==="subtitle"||w==="done")&&s.jsx("span",{className:`terminal-cursor terminal-cursor-sub${w==="done"?" blink":""}`})]})}),s.jsxs("span",{className:"welcome-version",children:["v","0.18.0"," ",s.jsx("span",{className:"beta-badge",children:"BETA"})]}),s.jsxs("div",{className:"features",children:[s.jsx(ra,{icon:s.jsx(gy,{size:22}),title:"Private",desc:"Data stays on your device",codeHint:"> encrypt --local",expandedDesc:"All processing happens on-device. No cloud, no tracking, complete data privacy."}),s.jsx(ra,{icon:s.jsx(Ws,{size:22}),title:"Fast",desc:"NPU acceleration",codeHint:"> npu.accelerate()",expandedDesc:"Hardware-accelerated with AMD Ryzen AI NPU for real-time local inference."}),s.jsx(ra,{icon:s.jsx($n,{size:22}),title:"Smart",desc:"Document Q&A",codeHint:'> rag.query("...")',expandedDesc:"RAG-powered document Q&A — index files and chat with their contents."}),s.jsx(ra,{icon:s.jsx(Kk,{size:22}),title:"Free",desc:"No subscriptions",codeHint:"> license: MIT",expandedDesc:"No API keys, no subscriptions, no hidden costs. Fully open-source."})]}),i.length>1&&s.jsx("div",{className:"agent-pills",children:i.map(D=>s.jsxs("button",{className:`agent-pill${D.id===l?" active":""}`,onClick:()=>a(D.id),title:D.description||D.name,children:[s.jsx(du,{size:14}),s.jsx("span",{children:D.name})]},D.id))}),z&&s.jsxs("div",{className:"welcome-setup-hint",children:[s.jsx(qa,{size:14}),s.jsxs("span",{children:[s.jsx("strong",{children:"First time?"})," Run ",s.jsx("code",{children:"gaia init --profile chat"})," in a terminal to install Lemonade Server and download the required AI model",r!=null&&r.default_model_size_gb?` (~${r.default_model_size_gb.toFixed(1)} GB).`:"."]})]}),!z&&_&&s.jsxs("div",{className:"welcome-setup-hint",children:[s.jsx(qa,{size:14}),s.jsxs("span",{children:["No model loaded. Run ",s.jsx("code",{children:"gaia init --profile chat"})," to download",r!=null&&r.default_model_size_gb?` (~${r.default_model_size_gb.toFixed(1)} GB).`:"."]})]}),s.jsxs("div",{className:"welcome-actions",children:[s.jsx("button",{className:"btn-primary start-btn",onClick:e,disabled:A,children:"Start a New Task"}),n&&s.jsxs("button",{className:"build-agent-btn",onClick:n,disabled:A,children:[s.jsx(hl,{size:14}),"Build a Custom Agent"]})]}),s.jsxs("div",{className:"suggestions",children:[s.jsx("span",{className:"suggestions-label",children:"Try asking:"}),s.jsx("div",{className:"suggestion-chips",children:o.map(D=>s.jsx("button",{className:"chip",onClick:()=>t(D),disabled:A,children:D},D))})]}),s.jsx("p",{className:"welcome-copyright",children:"© 2025–2026 Advanced Micro Devices, Inc. All rights reserved."})]})})}function ra({icon:e,title:t,desc:n,expandedDesc:r,codeHint:i}){const[l,a]=p.useState("idle"),[o,c]=p.useState(i),[u,d]=p.useState(""),f=p.useRef(null),h=()=>{a("erasing"),d("");let v=i.length;const w=()=>{if(v--,v>=0)c(i.slice(0,v)),f.current=setTimeout(w,15+Math.random()*20);else{a("typing"),c("");let x=0;const k=()=>{if(x++,x<=r.length){d(r.slice(0,x));const j=r[x-1],z=x>1?r[x-2]:"";f.current=setTimeout(k,qx(j,z))}else a("done")};k()}};w()},m=()=>{f.current&&clearTimeout(f.current),a("idle"),c(i),d("")};p.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const g=l!=="idle";return s.jsxs("div",{className:`feature-card ${g?"feature-hovered":""}`,onMouseEnter:h,onMouseLeave:m,children:[s.jsx("div",{className:"feature-icon",children:e}),s.jsx("h3",{children:t}),s.jsx("p",{children:n}),s.jsxs("div",{className:"feature-terminal",children:[l==="idle"&&s.jsx("span",{className:"feature-code-hint",children:i}),l==="erasing"&&s.jsxs("span",{className:"feature-inline",children:[s.jsx("span",{className:"feature-code-hint feature-code-erasing",children:o}),s.jsx("span",{className:"terminal-cursor terminal-cursor-sm"})]}),(l==="typing"||l==="done")&&s.jsxs("span",{className:"feature-inline",children:[s.jsx("span",{className:"feature-expanded-text",children:u}),s.jsx("span",{className:`terminal-cursor terminal-cursor-sm${l==="done"?" blink":""}`})]})]})]})}function CE(e){const t=Math.floor((Date.now()-e)/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return`${n}m ${r}s`}function _E(e){try{const t=new Date(e);if(isNaN(t.getTime()))return"";const r=new Date().getTime()-t.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),a=Math.floor(l/60),o=Math.floor(a/24);return i<60?"just now":l<60?`${l}m ago`:a<24?`${a}h ago`:o===1?"yesterday":o<7?`${o}d ago`:t.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return""}}function EE(e){try{const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit"})}catch{return""}}function TE(){const{documents:e,setDocuments:t,setShowDocLibrary:n,setShowFileBrowser:r,currentSessionId:i,sessions:l,updateSessionInList:a}=we(),o=l.find(T=>T.id===i)??null,[c,u]=p.useState(!1),[d,f]=p.useState(!1),[h,m]=p.useState(""),[g,v]=p.useState(""),[w,x]=p.useState(null),k=p.useRef(new Map),[,j]=p.useState(0);p.useEffect(()=>{E.doc.info("Loading document library...");const T=E.doc.time();ji().then(P=>{const b=P.documents||[];t(b),E.doc.timed(`Loaded ${b.length} document(s), ${P.total_chunks||0} chunks, ${P.total_size_bytes||0} bytes total`,T)}).catch(P=>{E.doc.error("Failed to load documents",P),t([])})},[t]);const z=e.some(T=>T.indexing_status==="indexing"||T.indexing_status==="pending");p.useEffect(()=>{if(!z)return;const T=we.getState().documents;for(const J of T)(J.indexing_status==="indexing"||J.indexing_status==="pending")&&!k.current.has(J.id)&&k.current.set(J.id,Date.now());let P=!1;const b=setInterval(async()=>{if(j(J=>J+1),!P){P=!0;try{const B=we.getState().documents.filter(S=>S.indexing_status==="indexing"||S.indexing_status==="pending");for(const S of B)try{const oe=await v0(S.id);if(oe.indexing_status!=="indexing"&&oe.indexing_status!=="pending"){k.current.delete(S.id);const pe=await ji();t(pe.documents||[]);break}}catch{}}finally{P=!1}}},2e3);return()=>clearInterval(b)},[z,t]),p.useEffect(()=>{const T=new Set(e.filter(P=>P.indexing_status==="indexing"||P.indexing_status==="pending").map(P=>P.id));for(const P of k.current.keys())T.has(P)||k.current.delete(P)},[e]),p.useEffect(()=>{const T=setInterval(async()=>{try{const b=(await ji()).documents||[],J=we.getState().documents;(b.length!==J.length||b.some((S,oe)=>{const pe=J.find(ae=>ae.id===S.id);return!pe||pe.indexing_status!==S.indexing_status||pe.indexed_at!==S.indexed_at||pe.chunk_count!==S.chunk_count}))&&(t(b),E.doc.debug("Document list refreshed (server-side changes detected)"))}catch{}},15e3);return()=>clearInterval(T)},[t]);const A=e.reduce((T,P)=>T+P.file_size,0),_=e.reduce((T,P)=>T+P.chunk_count,0),D=T=>{if(T<=0)return"0 B";const P=1024,b=["B","KB","MB","GB"],J=Math.min(Math.floor(Math.log(T)/Math.log(P)),b.length-1);return parseFloat((T/Math.pow(P,J)).toFixed(1))+" "+b[J]},C=p.useCallback(async(T,P)=>{var B;const b=T.includes(".")?"."+((B=T.split(".").pop())==null?void 0:B.toLowerCase()):"";if(b&&!eo(b)){const S=Ks(b),oe=S?S.message:`The file type "${b}" is not supported for indexing.`;E.doc.warn(`Unsupported file type: ${T} (${b})`),x({filename:T,error:oe});return}E.doc.info(`Indexing document: ${T}`);const J=E.doc.time();f(!0),m(`Indexing ${T}...`),x(null);try{const S=await P();if(E.doc.timed(`Indexed "${T}": ${(S==null?void 0:S.chunk_count)||"?"} chunks`,J),i&&(S!=null&&S.id))try{await Qa(i,S.id);const pe=we.getState().sessions.find(_e=>_e.id===i),ae=(pe==null?void 0:pe.document_ids)??[];ae.includes(S.id)||a(i,{document_ids:[...ae,S.id]}),E.doc.info(`Auto-attached "${T}" to session ${i}`)}catch(pe){E.doc.warn(`Could not attach document to session: ${pe}`)}const oe=await ji();t(oe.documents||[]),m("")}catch(S){E.doc.error(`Failed to index "${T}"`,S);const oe=S instanceof Error?S.message:"Upload failed";x({filename:T,error:oe}),m("")}finally{f(!1)}},[i,a,t]),M=p.useCallback(async(T,P)=>{await C(P,()=>Dy(T))},[C]),N=p.useCallback(async T=>{await C(T.name,()=>Ay(T))},[C]),U=p.useCallback(async T=>{T.preventDefault(),u(!1);const P=Array.from(T.dataTransfer.files);E.doc.info(`Dropped ${P.length} file(s) into Document Library`);for(const b of P)await N(b)},[N]),O=p.useCallback(async T=>{const P=e.find(b=>b.id===T);E.doc.info(`Deleting document: ${(P==null?void 0:P.filename)||T}`);try{await x0(T),k.current.delete(T),t(e.filter(b=>b.id!==T)),E.doc.info(`Deleted document: ${(P==null?void 0:P.filename)||T}`)}catch(b){E.doc.error(`Failed to delete document: ${(P==null?void 0:P.filename)||T}`,b)}},[e,t]),re=p.useCallback(async(T,P)=>{E.doc.info(`Opening folder for: ${T}`);try{await _d(T,!0)}catch(b){E.doc.error(`Failed to open folder for: ${P}`,b)}},[]),ie=p.useCallback(async T=>{const P=e.find(b=>b.id===T);E.doc.info(`Cancelling indexing for: ${(P==null?void 0:P.filename)||T}`);try{await k0(T),k.current.delete(T);const b=await ji();t(b.documents||[]),E.doc.info(`Cancelled indexing for: ${(P==null?void 0:P.filename)||T}`)}catch(b){E.doc.error(`Failed to cancel indexing: ${(P==null?void 0:P.filename)||T}`,b)}},[e,t]),X=p.useCallback(async T=>{if(!i)return;const P=e.find(b=>b.id===T);E.doc.info(`Attaching document to session: ${(P==null?void 0:P.filename)||T}`);try{await Qa(i,T);const b=we.getState().sessions.find(B=>B.id===i),J=(b==null?void 0:b.document_ids)??[];J.includes(T)||a(i,{document_ids:[...J,T]}),E.doc.info(`Attached "${(P==null?void 0:P.filename)||T}" to session ${i}`)}catch(b){E.doc.error(`Failed to attach document to session: ${(P==null?void 0:P.filename)||T}`,b)}},[i,e,a]),xe=p.useCallback(async T=>{T.preventDefault(),g.trim()&&(E.doc.info(`Indexing from path input: ${g.trim()}`),await M(g.trim(),g.trim().split(/[\\/]/).pop()||"file"),v(""))},[g,M]),ce=T=>{const P=T.indexing_status||"complete",b=k.current.get(T.id),J=T.indexed_at?_E(T.indexed_at):"",B=T.indexed_at?EE(T.indexed_at):"";switch(P){case"indexing":case"pending":return s.jsxs("div",{className:"doc-indexing-status",children:[s.jsxs("div",{className:"doc-indexing-bar",children:[s.jsx("div",{className:"doc-indexing-bar-track",children:s.jsx("div",{className:"doc-indexing-bar-fill"})}),s.jsxs("span",{className:"doc-indexing-label",children:[s.jsx(rw,{size:12,className:"doc-spin"}),"Indexing",b?` (${CE(b)})`:"..."]})]}),s.jsxs("button",{className:"btn-cancel",onClick:S=>{S.stopPropagation(),ie(T.id)},title:"Cancel indexing","aria-label":`Cancel indexing ${T.filename}`,children:[s.jsx(Tm,{size:14}),"Cancel"]})]});case"failed":return s.jsxs("span",{className:"doc-status-badge doc-status-failed",children:[s.jsx(kt,{size:12})," Failed"]});case"cancelled":return s.jsxs("span",{className:"doc-status-badge doc-status-cancelled",children:[s.jsx(Tm,{size:12})," Cancelled"]});case"missing":return s.jsxs("span",{className:"doc-status-badge doc-status-missing",children:[s.jsx(kt,{size:12})," File missing"]});default:return s.jsxs("span",{className:"doc-meta",children:[D(T.file_size)," · ",T.chunk_count," chunks",J&&s.jsxs("span",{className:"doc-timestamp",title:`Indexed: ${B}`,children:[s.jsx(Wa,{size:10}),J]})]})}};return s.jsx("div",{className:"modal-overlay",onClick:()=>n(!1),role:"dialog","aria-modal":"true","aria-label":"Document Library",children:s.jsxs("div",{className:"modal-panel doc-modal",onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:"Document Library"}),s.jsx("button",{className:"btn-icon",onClick:()=>n(!1),"aria-label":"Close document library",children:s.jsx(tt,{size:18})})]}),s.jsxs("div",{className:"modal-body",children:[s.jsx("div",{className:`drop-zone ${c?"drag-over":""} ${d?"uploading":""}`,onDragOver:T=>{T.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:U,children:d?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"upload-spinner"}),s.jsx("p",{children:h})]}):s.jsxs(s.Fragment,{children:[s.jsx(pl,{size:32,strokeWidth:1.5}),s.jsx("p",{children:"Drop files here to index"}),s.jsx("span",{className:"drop-hint",children:"PDF, TXT, MD, code files, and 50+ formats"})]})}),s.jsxs("form",{className:"path-input-form",onSubmit:xe,children:[s.jsx(Yn,{size:16,className:"path-icon"}),s.jsx("input",{type:"text",className:"path-input",value:g,onChange:T=>v(T.target.value),placeholder:"Or enter file path: C:\\docs\\manual.pdf","aria-label":"File path to index"}),s.jsx("button",{type:"submit",className:"btn-secondary",disabled:!g.trim()||d,children:"Index"}),s.jsxs("button",{type:"button",className:"btn-secondary",onClick:()=>{n(!1),r(!0)},title:"Browse files on this computer",children:[s.jsx(Fn,{size:14}),"Browse Files"]})]}),w&&s.jsx(Gx,{filename:w.filename,error:w.error,onDismiss:()=>x(null)}),e.length>0&&s.jsxs("div",{className:"doc-stats",children:[s.jsxs("span",{children:[e.length," document",e.length!==1?"s":""]}),s.jsx("span",{children:"·"}),s.jsxs("span",{children:[_," chunks"]}),s.jsx("span",{children:"·"}),s.jsx("span",{children:D(A)})]}),s.jsxs("div",{className:"doc-list",children:[e.length===0&&!d&&s.jsxs("div",{className:"empty-docs",children:[s.jsx($n,{size:32,strokeWidth:1}),s.jsx("p",{children:"No documents indexed yet"}),s.jsx("span",{children:"Drop files above or enter a file path"})]}),e.map(T=>{var P;return s.jsxs("div",{className:`doc-row ${T.indexing_status==="indexing"?"doc-row-indexing":""}`,children:[s.jsxs("div",{className:"doc-info",children:[s.jsx("span",{className:"doc-name",children:T.filename}),ce(T)]}),s.jsxs("div",{className:"doc-row-actions",children:[T.filepath&&s.jsx("button",{className:"btn-icon-sm doc-open-folder",onClick:()=>re(T.filepath,T.filename),title:`Open folder: ${T.filepath}`,"aria-label":`Open containing folder for ${T.filename}`,children:s.jsx(Yn,{size:14})}),i&&T.indexing_status==="complete"&&!((P=o==null?void 0:o.document_ids)!=null&&P.includes(T.id))&&s.jsx("button",{className:"btn-icon-sm doc-attach",onClick:()=>X(T.id),title:"Use in current session","aria-label":`Attach ${T.filename} to current session`,children:s.jsx(nw,{size:14})}),T.indexing_status!=="indexing"&&T.indexing_status!=="pending"&&s.jsx("button",{className:"btn-icon-sm doc-delete",onClick:()=>O(T.id),title:"Remove","aria-label":`Remove ${T.filename}`,children:s.jsx(ci,{size:14})})]})]},T.id)})]})]})]})})}function zE(e){if(e.type==="folder")return s.jsx(my,{size:16});const t=(e.extension||"").toLowerCase();return[".csv",".xlsx",".xls",".tsv"].includes(t)?s.jsx(ww,{size:16}):[".py",".js",".ts",".java",".c",".cpp",".go",".rs"].includes(t)?s.jsx(Qk,{size:16}):[".pdf",".doc",".docx",".txt",".md"].includes(t)?s.jsx($n,{size:16}):s.jsx(fy,{size:16})}function LE(e){if(e<=0)return"";const t=1024,n=["B","KB","MB","GB"],r=Math.min(Math.floor(Math.log(e)/Math.log(t)),n.length-1);return parseFloat((e/Math.pow(t,r)).toFixed(1))+" "+n[r]}function IE(e){if(!e)return"";const t=new Date(e),n=new Date,r=n.getTime()-t.getTime(),i=Math.floor(r/36e5);if(i<1)return"Just now";if(i<24)return`${i}h ago`;const l=Math.floor(i/24);return l<7?`${l}d ago`:t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0})}function DE(e){switch(e){case"home":return s.jsx(Jk,{size:14});case"desktop":return s.jsx(lw,{size:14});case"documents":return s.jsx($n,{size:14});case"download":return s.jsx(oi,{size:14});default:return s.jsx(my,{size:14})}}const AE=[{label:"All Files",value:""},{label:"Documents",value:"pdf,doc,docx,txt,md"},{label:"Spreadsheets",value:"csv,xlsx,xls,tsv"},{label:"Code",value:"py,js,ts,java,c,cpp,go,rs,rb,sh"},{label:"Data",value:"json,xml,yaml,yml,csv,tsv"}];async function Fh(e,t,n,r){var f;const i=[],l=[];for(const h of e){const m=h.includes(".")?"."+((f=h.split(".").pop())==null?void 0:f.toLowerCase()):"";m&&!eo(m)?l.push(h):i.push(h)}const a=[],o=[];let c=0,u="";const d=new Set(t.filter(h=>h.type==="folder").map(h=>h.path));for(const h of i)try{if(d.has(h)){const m=await j0(h),g=[];m.documents.forEach(v=>{v.id&&g.push(v.id)}),g.length>0&&(g.forEach(v=>a.push(v)),o.push(h))}else{const m=await Dy(h);m!=null&&m.id&&(a.push(m.id),o.push(h))}}catch(m){c++,u=m instanceof Error?m.message:"Unknown error"}if(n&&a.length>0){for(const v of a)try{await Qa(n,v)}catch(w){E.doc.warn(`Could not attach document to session: ${w}`)}const h=we.getState().sessions.find(v=>v.id===n),m=(h==null?void 0:h.document_ids)??[],g=a.filter(v=>!m.includes(v));g.length>0&&r(n,{document_ids:[...m,...g]})}return{docIds:a,supported:i,succeededFiles:o,unsupported:l,failed:c,lastError:u}}function PE(){const{setShowFileBrowser:e,currentSessionId:t,updateSessionInList:n,setPendingPrompt:r}=we(),[i,l]=p.useState(""),[a,o]=p.useState(null),[c,u]=p.useState([]),[d,f]=p.useState([]),[h,m]=p.useState(!1),[g,v]=p.useState(null),[w,x]=p.useState(""),[k,j]=p.useState(null),[z,A]=p.useState(!1),[_,D]=p.useState(""),[C,M]=p.useState(new Set),[N,U]=p.useState(null),[O,re]=p.useState(!1),[ie,X]=p.useState(new Set),[xe,ce]=p.useState(null),T=p.useRef(null),[P,b]=p.useState(null),J=p.useCallback(async L=>{m(!0),v(null),j(null),x("");try{const F=await b0(L);l(F.current_path),o(F.parent_path),u(F.entries),F.quick_links.length>0&&f(F.quick_links),E.ui.info(`Browsing: ${F.current_path} (${F.entries.length} items)`)}catch(F){const Y=F instanceof Error?F.message:"Failed to load directory";v(Y),E.ui.error("Browse failed",F)}finally{m(!1)}},[]);p.useEffect(()=>{J()},[J]),p.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const B=p.useCallback(async()=>{if(!w.trim()){j(null);return}A(!0),v(null);try{const L=await S0(w.trim(),_||void 0,30);j(L.results),E.ui.info(`Search "${w}": ${L.total} results`)}catch(L){const F=L instanceof Error?L.message:"Search failed";v(F),E.ui.error("Search failed",L)}finally{A(!1)}},[w,_]),S=L=>{L.key==="Enter"&&B()},oe=p.useCallback(L=>{L.type==="folder"&&(J(L.path),M(new Set),U(null))},[J]),pe=p.useCallback(async L=>{re(!0);try{const F=await N0(L);U(F)}catch(F){E.ui.error("Preview failed",F)}finally{re(!1)}},[]),ae=p.useCallback(async()=>{if(C.size===0)return;const L=Array.from(C);if(b(null),!L.some(Y=>{var he;const ue=Y.includes(".")?"."+((he=Y.split(".").pop())==null?void 0:he.toLowerCase()):"";return!ue||eo(ue)})){const Y=L[0],ue=Y.lastIndexOf("."),he=ue>0?Y.slice(ue).toLowerCase():"",H=Ks(he);b({filename:L.length===1?Y.split(/[\\/]/).pop()||Y:`${L.length} files`,error:H?H.message:`File type "${he}" is not supported for indexing.`});return}X(new Set(L)),ce(`Indexing ${L.length} file(s)...`);try{const Y=await Fh(L,c,t,n);if(Y.failed>0)ce(`Done: ${Y.docIds.length} indexed, ${Y.failed} failed`),b({filename:`${Y.failed} file(s)`,error:Y.lastError||"Indexing failed for some files"});else{const ue=Y.unsupported.length>0?` (${Y.unsupported.length} skipped — unsupported type)`:"";ce(`Successfully indexed ${Y.docIds.length} file(s)${ue}`)}T.current&&clearTimeout(T.current),T.current=setTimeout(()=>ce(null),5e3),M(new Set)}catch(Y){E.doc.error("Index selected failed",Y),b({filename:L.length===1?L[0].split(/[\\/]/).pop()||L[0]:`${L.length} files`,error:Y instanceof Error?Y.message:"An unexpected error occurred."})}finally{X(new Set)}},[C,t,n,c]),_e=p.useCallback(async()=>{if(C.size===0)return;const L=Array.from(C);b(null),X(new Set(L)),ce(`Indexing ${L.length} file(s) for analysis...`);try{const F=await Fh(L,c,t,n);if(F.supported.length===0){const he=L[0].lastIndexOf("."),H=he>0?L[0].slice(he).toLowerCase():"",le=Ks(H);b({filename:L.length===1?L[0].split(/[\\/]/).pop()||L[0]:`${L.length} files`,error:(le==null?void 0:le.message)??`File type "${H}" is not supported for indexing.`});return}if(F.docIds.length===0){b({filename:F.supported.length===1?F.supported[0].split(/[\\/]/).pop()||F.supported[0]:`${F.supported.length} files`,error:"Failed to index selected file(s). Please try again."});return}F.failed>0&&ce(`Warning: ${F.failed} file(s) failed to index and will be excluded.`);const Y=(F.succeededFiles.length>0?F.succeededFiles:F.supported).map(he=>he.split(/[\\/]/).pop()||he),ue=Y.length===1?`Please analyze this document for me: ${Y[0]}`:`Please analyze these documents for me:
540
+ If Lemonade Server is running but responses are slow, the model may need more resources.`+dt:ee=`Error: ${Ce}`+dt;const Ie={id:Date.now()+2,session_id:e,role:"assistant",content:ee,created_at:new Date().toISOString(),rag_sources:null};a(Ie),h(!1),g(),z()},onAgentCreated:()=>{Nd().then(V=>we.getState().setAgents(V.agents||[])).catch(()=>{})}},void 0,void 0,ie);Zt.current=St},[pe,le,d,e,B,a,l,h,or,g,u,w,x,k,j,z,ie,xe]);cs.current=bn,p.useEffect(()=>{const I=q=>{var ge;const Z=(ge=q.detail)==null?void 0:ge.text;typeof Z=="string"&&Z.trim()&&cs.current(Z)};return window.addEventListener("gaia:send-message",I),()=>window.removeEventListener("gaia:send-message",I)},[]),p.useEffect(()=>{!d&&Jt.current&&Jt.current.focus()},[d]);const fr=p.useCallback(async I=>{d||(E.chat.info(`Deleting message ${I} from session=${e}`),je(I),setTimeout(async()=>{o(I),je(null);try{await m0(e,I)}catch(q){E.chat.error(`Failed to delete message ${I}`,q),As(e).then(te=>{we.getState().currentSessionId===e&&l(te.messages||[])}).catch(()=>{})}},250))},[e,d,o,l]),jt=p.useCallback(async I=>{if(d||I.role!=="user")return;const q=I.content;E.chat.info(`Resending message ${I.id} from session=${e}`,{preview:q.slice(0,80)}),c(I.id);try{await h0(e,I.id)}catch(te){E.chat.error(`Failed to delete messages from ${I.id}`,te),As(e).then(Z=>{we.getState().currentSessionId===e&&l(Z.messages||[])}).catch(()=>{});return}bn(q)},[e,d,c,l,bn]),mr=I=>{I.key==="Enter"&&!I.shiftKey&&(I.preventDefault(),bn())},ds=()=>{Ge((B==null?void 0:B.title)||""),He(!0)},Dn=async()=>{nt.trim()&&nt!==(B==null?void 0:B.title)&&(await tc(e,{title:nt.trim()}),u(e,{title:nt.trim()})),He(!1)},Wn=p.useCallback(async()=>{if(e)try{const I=await d0(e);u(e,{private:I.private})}catch(I){E.ui.warn("Failed to toggle private mode",I)}},[e,u]),hr=async()=>{try{const I=await f0(e),q=new Blob([I.content],{type:"text/markdown"}),te=URL.createObjectURL(q),Z=document.createElement("a");Z.href=te;const ge=((B==null?void 0:B.title)||"chat").replace(/[/\\:*?"<>|]/g,"_").slice(0,100);Z.download=`${ge}.md`,Z.click(),URL.revokeObjectURL(te)}catch(I){E.chat.error("Export failed",I)}},zl=p.useCallback(async(I,q)=>{I.stopPropagation();const te=A.find(Z=>Z.id===q);E.doc.info(`Detaching document from session: ${(te==null?void 0:te.filename)||q}`);try{await w0(e,q);const Z=we.getState().sessions.find(Ee=>Ee.id===e),ge=((Z==null?void 0:Z.document_ids)??[]).filter(Ee=>Ee!==q);u(e,{document_ids:ge}),ge.length<=3&&$e(!1),E.doc.info(`Detached document from session: ${(te==null?void 0:te.filename)||q}`)}catch(Z){E.doc.error(`Failed to detach document: ${(te==null?void 0:te.filename)||q}`,Z)}},[A,e,u]),Ll=p.useCallback(async I=>{if(I.preventDefault(),I.stopPropagation(),F(!1),I.dataTransfer.files.length!==0)for(const q of Array.from(I.dataTransfer.files)){E.doc.info(`Dropped on chat view: ${q.name}`);try{const te=await Ay(q);if(e&&(te!=null&&te.id))try{await Qa(e,te.id);const Z=we.getState().sessions.find(Ee=>Ee.id===e),ge=(Z==null?void 0:Z.document_ids)??[];ge.includes(te.id)||u(e,{document_ids:[...ge,te.id]}),E.doc.info(`Auto-attached "${q.name}" to session ${e}`)}catch(Z){E.doc.warn(`Could not attach dropped document to session: ${Z}`)}}catch(te){E.doc.error(`Upload failed: ${q.name}`,te)}}},[e,u]),fs=I=>{I.preventDefault(),I.stopPropagation(),F(!0)},_o=I=>{I.preventDefault(),I.stopPropagation(),F(!1)},pi=I=>{ae(I),bn(I)},pr=!N&&i.length===0&&!d,ms=p.useMemo(()=>{const I=new Map;let q;for(const te of i)if(te.role==="user"&&te.created_at)q=new Date(te.created_at).getTime();else if(te.role==="assistant"&&te.created_at&&q!==void 0){const Z=new Date(te.created_at).getTime();Z>q&&I.set(te.id,Z-q),q=void 0}return I},[i]);return s.jsxs("main",{className:`task-view ${L?"drag-active":""}`,onDrop:Ll,onDragOver:fs,onDragLeave:_o,children:[os&&s.jsx("div",{className:"dashboard-overlay",children:s.jsx(gE,{sessionId:e,onClose:()=>$(!1)})}),s.jsxs("header",{className:"task-header",children:[s.jsx("div",{className:"task-header-left",children:_e?s.jsx("input",{className:"title-edit",value:nt,onChange:I=>Ge(I.target.value),onBlur:Dn,onKeyDown:I=>I.key==="Enter"&&Dn(),autoFocus:!0,"aria-label":"Edit task title"}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"task-title",children:(B==null?void 0:B.title)||"New Task"}),s.jsx("button",{className:"btn-icon-sm",onClick:ds,title:"Rename","aria-label":"Rename task",children:s.jsx(fw,{size:13})})]})}),s.jsxs("div",{className:"task-header-right",children:[s.jsxs("span",{className:`model-badge ${O!=null&&O.model_loaded?"":"no-model"}`,title:O!=null&&O.model_loaded&&(O!=null&&O.model_context_size)?`${O.model_loaded} · context window: ${O.model_context_size.toLocaleString()} tokens`:(O==null?void 0:O.model_loaded)||"No model loaded",children:[(O==null?void 0:O.model_loaded)||"No model loaded",(O==null?void 0:O.model_loaded)&&(O==null?void 0:O.model_context_size)!=null&&s.jsxs("span",{className:"model-ctx-size",children:[" · ",O.model_context_size%1024===0?`${O.model_context_size/1024}K`:O.model_context_size.toLocaleString()]})]}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>D(!0),title:"Documents","aria-label":"Attach documents",children:s.jsx(dw,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>C(!0),title:"Browse files","aria-label":"Browse files",children:s.jsx(_m,{size:15})}),s.jsx("button",{className:`btn-icon-sm${B!=null&&B.private?" active":""}`,onClick:Wn,title:B!=null&&B.private?"Private mode on — click to disable":"Enable private mode (nothing saved to memory)","aria-label":B!=null&&B.private?"Disable private mode":"Enable private mode","aria-pressed":!!(B!=null&&B.private),children:s.jsx(dy,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>M(!0),title:"Memory","aria-label":"Open memory dashboard",children:s.jsx(Jr,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:hr,title:"Export","aria-label":"Export task",children:s.jsx(oi,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>$(I=>!I),title:"Refresh dashboard","aria-label":"Refresh dashboard",children:s.jsx(Nm,{size:15})}),s.jsxs("button",{className:`notification-center-trigger ${b>0?"has-unread":""}`,onClick:()=>T(!ce),"aria-label":"Open notification center","aria-expanded":ce,title:"Notifications",children:[s.jsx(oy,{size:15}),b>0&&s.jsx("span",{className:"notification-center-trigger-badge",children:b>99?"99+":b})]})]})]}),oe.length>0&&(()=>{const I=[...oe].sort((Z,ge)=>{const Ee=Z.last_accessed_at||Z.indexed_at||"";return(ge.last_accessed_at||ge.indexed_at||"").localeCompare(Ee)}),q=Ae?I:I.slice(0,3),te=I.length-3;return s.jsxs("div",{className:`doc-context-bar${Ae?" doc-context-expanded":""}`,"aria-label":`${oe.length} indexed document${oe.length!==1?"s":""}`,children:[s.jsx(nr,{size:12,className:"doc-context-icon"}),s.jsxs("span",{className:"doc-context-label",onClick:()=>D(!0),title:"Click to manage documents",role:"button",tabIndex:0,children:[oe.length," indexed"]}),s.jsxs("div",{className:`doc-context-pills${Ae?" doc-context-pills-expanded":""}`,children:[q.map(Z=>s.jsxs("span",{className:"doc-pill",title:Z.filepath||Z.filename,children:[s.jsx($n,{size:9,className:"doc-pill-icon"}),s.jsx("span",{className:"doc-pill-name",children:Z.filename}),s.jsx("button",{className:"doc-pill-remove",onClick:ge=>zl(ge,Z.id),title:`Remove ${Z.filename} from this session`,"aria-label":`Remove ${Z.filename} from this session`,children:s.jsx(tt,{size:10})})]},Z.id)),!Ae&&te>0&&s.jsxs("button",{className:"doc-pill-more",onClick:Z=>{Z.stopPropagation(),$e(!0)},title:"Show all indexed files","aria-label":`Show ${te} more files`,children:["+",te," more"]}),Ae&&te>0&&s.jsx("button",{className:"doc-pill-collapse",onClick:Z=>{Z.stopPropagation(),$e(!1)},title:"Show fewer files","aria-label":"Collapse file list",children:"show less"})]})]})})(),s.jsxs("div",{className:"messages-scroll",ref:cn,onScroll:ur,children:[N&&s.jsx("div",{className:"skeleton-messages","aria-label":"Loading messages",children:[0,1,2].map(I=>s.jsxs("div",{className:"skeleton-msg",children:[s.jsxs("div",{className:"skeleton-header",children:[s.jsx("div",{className:"skeleton-avatar"}),s.jsx("div",{className:"skeleton-role"})]}),s.jsxs("div",{className:"skeleton-lines",children:[s.jsx("div",{className:"skeleton-line"}),s.jsx("div",{className:"skeleton-line"}),I!==2&&s.jsx("div",{className:"skeleton-line"})]})]},I))}),pr&&s.jsxs("div",{className:"empty-task",children:[s.jsx("div",{className:"empty-task-icon",children:s.jsx(fu,{size:36,strokeWidth:1.2})}),s.jsx("h4",{className:"empty-task-title",children:"What can I help you with?"}),s.jsx("p",{className:"empty-task-desc",children:"Ask about your documents, search files, or analyze data — powered by local AI."}),s.jsx("div",{className:"empty-task-suggestions",children:yE.map(I=>s.jsx("button",{className:"empty-task-chip",onClick:()=>pi(I),children:I},I))})]}),i.map((I,q)=>{const te=!d&&!Pt&&I.role==="assistant"&&i.slice(q+1).every(Ee=>Ee.role!=="assistant");if(Pt&&I.role==="assistant"&&q===i.length-1)return null;const ge=ms.get(I.id);return s.jsx("div",{className:ut===I.id?"msg-deleting":void 0,children:s.jsx(Mh,{message:I,showTerminalCursor:te,agentSteps:I.role==="assistant"?I.agentSteps:void 0,onDelete:d?void 0:fr,onResend:!d&&I.role==="user"?jt:void 0,latencyMs:ge,agentName:I.role==="assistant"?wt:void 0})},I.id)}),(d||Pt)&&s.jsx("div",{className:`streaming-bubble ${Pt?"stream-ending":"stream-active"}`,children:s.jsx(Mh,{message:{id:-1,session_id:e,role:"assistant",content:(d?f:rt.current)||"",created_at:"",rag_sources:null},isStreaming:d,showTerminalCursor:Pt,agentSteps:d?v:Mt.current,agentStepsActive:d&&v.some(I=>I.active),agentName:pt})}),s.jsx("div",{ref:xn})]}),Y&&s.jsx("button",{className:"scroll-bottom-btn",onClick:us,title:"Scroll to bottom","aria-label":"Scroll to bottom",children:s.jsx(Nm,{size:16})}),L&&s.jsxs("div",{className:"drag-overlay",children:[s.jsx(pl,{size:32,strokeWidth:1.5}),s.jsx("span",{children:"Drop files to index"})]}),Je&&s.jsxs("div",{className:"toast policy-alert-toast",role:"alert",children:[s.jsxs("span",{children:["Blocked: ",Je.tool," is restricted by policy."]}),Je.receiptId?s.jsx("button",{type:"button",className:"policy-alert-toast-link",onClick:()=>{const I=Je.receiptId;I&&(P("policy_alert"),T(!0),window.setTimeout(()=>{var q;(q=document.getElementById(kE(I)))==null||q.scrollIntoView({behavior:"smooth",block:"center"})},80))},children:"View receipt"}):s.jsx("span",{className:"policy-alert-toast-missing",children:"Receipt unavailable"})]}),s.jsxs("div",{className:"input-area",children:[s.jsxs("div",{className:`input-box ${le.length>0?"has-attachments":""}`,onDrop:El,onDragOver:I=>{I.preventDefault(),I.stopPropagation()},children:[s.jsxs("div",{className:"input-content",children:[le.length>0&&s.jsx("div",{className:"attachment-strip",children:le.map(I=>s.jsxs("div",{className:`attachment-preview ${I.error?"attachment-error":""}`,children:[I.isImage&&I.url?s.jsx("img",{src:I.url,alt:I.name,className:"attachment-thumb"}):s.jsx("div",{className:"attachment-file-icon",children:s.jsx($n,{size:16})}),s.jsx("span",{className:"attachment-name",title:I.name,children:I.name.length>20?I.name.slice(0,17)+"...":I.name}),I.uploading&&s.jsx("span",{className:"attachment-spinner"}),I.error&&s.jsx("span",{className:"attachment-error-text",children:I.error}),s.jsx("button",{className:"attachment-remove",onClick:()=>Tl(I.id),title:"Remove","aria-label":`Remove ${I.name}`,children:s.jsx(tt,{size:12})})]},I.id))}),s.jsx("textarea",{ref:Jt,className:"msg-input",value:pe,onChange:Vn,onKeyDown:mr,onPaste:dr,placeholder:"Type a message or paste an image... (Shift+Enter for new line)",rows:1,disabled:d||(O==null?void 0:O.init_state)==="initializing","aria-label":"Message input"})]}),s.jsxs("div",{className:"input-btns",children:[s.jsx("button",{className:"btn-icon-sm",onClick:()=>D(!0),title:"Upload document","aria-label":"Upload document",children:s.jsx(pl,{size:15})}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>C(!0),title:"Browse files","aria-label":"Browse files",children:s.jsx(_m,{size:15})}),d?s.jsx("button",{className:"stop-btn",onClick:wn,title:"Stop generating","aria-label":"Stop generating",children:s.jsx(vw,{size:14})}):s.jsx("button",{className:"send-btn",onClick:()=>bn(),disabled:!pe.trim()&&!le.some(I=>I.uploaded),title:"Send (Enter)","aria-label":"Send message",children:s.jsx(hw,{size:16})})]})]}),s.jsxs("div",{className:"input-footer",children:[t&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"create-agent-btn",onClick:t,title:"Build a custom agent","aria-label":"Build a custom agent",children:s.jsx(hl,{size:10})}),re.length>1&&s.jsx("span",{className:"input-footer-sep"})]}),re.length>1&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"agent-picker",ref:ve,children:[s.jsxs("button",{className:"agent-picker-btn",onClick:()=>!d&&de(I=>!I),title:"Switch agent","aria-label":"Switch agent",disabled:d,children:[s.jsx(du,{size:10}),s.jsx("span",{children:((hs=re.find(I=>I.id===be))==null?void 0:hs.name)||"Agent"}),s.jsx(ai,{size:10})]}),Q&&s.jsx("div",{className:"agent-picker-dropdown",children:re.map(I=>s.jsxs("button",{className:`agent-picker-option${I.id===be?" active":""}`,onClick:()=>qe(I.id),children:[s.jsx(du,{size:12}),s.jsx("span",{children:I.name})]},I.id))})]}),s.jsx("span",{className:"input-footer-sep"})]}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx(gy,{size:10}),s.jsx("span",{children:"100% local & private"})]}),s.jsx("span",{className:"input-footer-sep"}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Enter"}),s.jsx("span",{children:"send"})]}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Shift+Enter"}),s.jsx("span",{children:"new line"})]}),d&&s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Esc"}),s.jsx("span",{children:"stop"})]}),s.jsx("span",{className:"input-footer-sep"}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Ctrl+K"}),s.jsx("span",{children:"search"})]}),s.jsxs("span",{className:"input-footer-item",children:[s.jsx("kbd",{className:"kbd-hint",children:"Ctrl+V"}),s.jsx("span",{children:"paste image"})]})]})]})]})}const $h="GAIA",na="Your private AI assistant, running 100% locally on AMD Ryzen AI",bE=65,jE=350;function qx(e,t){return t===","||t==="."?60+Math.random()*50:t===" "?15+Math.random()*25:Math.random()<.35?8+Math.random()*12:Math.random()<.06?45+Math.random()*35:18+Math.random()*22}const SE=["Scan my Downloads and tell me what I should clean up","Index a folder of documents so I can chat about them","What have I been working on lately? Show my recent files","What hardware is in my PC? Tell me about my CPU and GPU"];function NE({onNewTask:e,onSendPrompt:t,onCreateAgent:n}){const{systemStatus:r,agents:i,activeAgentId:l,setActiveAgentId:a}=we(),o=p.useMemo(()=>{var C;const D=i.find(M=>M.id===l);return(C=D==null?void 0:D.conversation_starters)!=null&&C.length?D.conversation_starters:SE},[i,l]),[c,u]=p.useState(""),[d,f]=p.useState(!1),[h,m]=p.useState(""),[g,v]=p.useState(!1),[w,x]=p.useState("title"),[k,j]=p.useState(!1),z=r!==null&&!r.initialized,A=(r==null?void 0:r.init_state)==="initializing",_=r!==null&&r.lemonade_running&&!r.model_loaded;return p.useEffect(()=>{let D=0;const C=setInterval(()=>{D++,D<=$h.length?u($h.slice(0,D)):(clearInterval(C),f(!0))},bE);return()=>clearInterval(C)},[]),p.useEffect(()=>{if(!d)return;let D=!1;const C=setTimeout(()=>{if(D)return;x("subtitle");let N=0;const U=()=>{if(!D)if(N++,N<=na.length){m(na.slice(0,N));const O=na[N-1],re=N>1?na[N-2]:"",ie=qx(O,re);M.current=setTimeout(U,ie)}else v(!0),x("done")};U()},jE),M={current:null};return()=>{D=!0,clearTimeout(C),M.current&&clearTimeout(M.current)}},[d]),p.useEffect(()=>{if(!g)return;const D=setTimeout(()=>j(!0),200);return()=>clearTimeout(D)},[g]),s.jsx("main",{className:"welcome",children:s.jsxs("div",{className:`welcome-inner ${k?"content-revealed":""}`,children:[s.jsxs("h1",{className:`welcome-title${d?" typing-done":""}`,children:[c.length>=4?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"gaia-glow",children:c.slice(0,4)}),s.jsx("span",{children:c.slice(4)})]}):c,w==="title"&&s.jsx("span",{className:`terminal-cursor${d?" blink":""}`})]}),s.jsx("p",{className:"welcome-sub",children:s.jsxs("span",{className:"typewriter-text",children:[h,(w==="subtitle"||w==="done")&&s.jsx("span",{className:`terminal-cursor terminal-cursor-sub${w==="done"?" blink":""}`})]})}),s.jsxs("span",{className:"welcome-version",children:["v","0.18.1"," ",s.jsx("span",{className:"beta-badge",children:"BETA"})]}),s.jsxs("div",{className:"features",children:[s.jsx(ra,{icon:s.jsx(gy,{size:22}),title:"Private",desc:"Data stays on your device",codeHint:"> encrypt --local",expandedDesc:"All processing happens on-device. No cloud, no tracking, complete data privacy."}),s.jsx(ra,{icon:s.jsx(Ws,{size:22}),title:"Fast",desc:"NPU acceleration",codeHint:"> npu.accelerate()",expandedDesc:"Hardware-accelerated with AMD Ryzen AI NPU for real-time local inference."}),s.jsx(ra,{icon:s.jsx($n,{size:22}),title:"Smart",desc:"Document Q&A",codeHint:'> rag.query("...")',expandedDesc:"RAG-powered document Q&A — index files and chat with their contents."}),s.jsx(ra,{icon:s.jsx(Kk,{size:22}),title:"Free",desc:"No subscriptions",codeHint:"> license: MIT",expandedDesc:"No API keys, no subscriptions, no hidden costs. Fully open-source."})]}),i.length>1&&s.jsx("div",{className:"agent-pills",children:i.map(D=>s.jsxs("button",{className:`agent-pill${D.id===l?" active":""}`,onClick:()=>a(D.id),title:D.description||D.name,children:[s.jsx(du,{size:14}),s.jsx("span",{children:D.name})]},D.id))}),z&&s.jsxs("div",{className:"welcome-setup-hint",children:[s.jsx(qa,{size:14}),s.jsxs("span",{children:[s.jsx("strong",{children:"First time?"})," Run ",s.jsx("code",{children:"gaia init --profile chat"})," in a terminal to install Lemonade Server and download the required AI model",r!=null&&r.default_model_size_gb?` (~${r.default_model_size_gb.toFixed(1)} GB).`:"."]})]}),!z&&_&&s.jsxs("div",{className:"welcome-setup-hint",children:[s.jsx(qa,{size:14}),s.jsxs("span",{children:["No model loaded. Run ",s.jsx("code",{children:"gaia init --profile chat"})," to download",r!=null&&r.default_model_size_gb?` (~${r.default_model_size_gb.toFixed(1)} GB).`:"."]})]}),s.jsxs("div",{className:"welcome-actions",children:[s.jsx("button",{className:"btn-primary start-btn",onClick:e,disabled:A,children:"Start a New Task"}),n&&s.jsxs("button",{className:"build-agent-btn",onClick:n,disabled:A,children:[s.jsx(hl,{size:14}),"Build a Custom Agent"]})]}),s.jsxs("div",{className:"suggestions",children:[s.jsx("span",{className:"suggestions-label",children:"Try asking:"}),s.jsx("div",{className:"suggestion-chips",children:o.map(D=>s.jsx("button",{className:"chip",onClick:()=>t(D),disabled:A,children:D},D))})]}),s.jsx("p",{className:"welcome-copyright",children:"© 2025–2026 Advanced Micro Devices, Inc. All rights reserved."})]})})}function ra({icon:e,title:t,desc:n,expandedDesc:r,codeHint:i}){const[l,a]=p.useState("idle"),[o,c]=p.useState(i),[u,d]=p.useState(""),f=p.useRef(null),h=()=>{a("erasing"),d("");let v=i.length;const w=()=>{if(v--,v>=0)c(i.slice(0,v)),f.current=setTimeout(w,15+Math.random()*20);else{a("typing"),c("");let x=0;const k=()=>{if(x++,x<=r.length){d(r.slice(0,x));const j=r[x-1],z=x>1?r[x-2]:"";f.current=setTimeout(k,qx(j,z))}else a("done")};k()}};w()},m=()=>{f.current&&clearTimeout(f.current),a("idle"),c(i),d("")};p.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const g=l!=="idle";return s.jsxs("div",{className:`feature-card ${g?"feature-hovered":""}`,onMouseEnter:h,onMouseLeave:m,children:[s.jsx("div",{className:"feature-icon",children:e}),s.jsx("h3",{children:t}),s.jsx("p",{children:n}),s.jsxs("div",{className:"feature-terminal",children:[l==="idle"&&s.jsx("span",{className:"feature-code-hint",children:i}),l==="erasing"&&s.jsxs("span",{className:"feature-inline",children:[s.jsx("span",{className:"feature-code-hint feature-code-erasing",children:o}),s.jsx("span",{className:"terminal-cursor terminal-cursor-sm"})]}),(l==="typing"||l==="done")&&s.jsxs("span",{className:"feature-inline",children:[s.jsx("span",{className:"feature-expanded-text",children:u}),s.jsx("span",{className:`terminal-cursor terminal-cursor-sm${l==="done"?" blink":""}`})]})]})]})}function CE(e){const t=Math.floor((Date.now()-e)/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return`${n}m ${r}s`}function _E(e){try{const t=new Date(e);if(isNaN(t.getTime()))return"";const r=new Date().getTime()-t.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),a=Math.floor(l/60),o=Math.floor(a/24);return i<60?"just now":l<60?`${l}m ago`:a<24?`${a}h ago`:o===1?"yesterday":o<7?`${o}d ago`:t.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return""}}function EE(e){try{const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit"})}catch{return""}}function TE(){const{documents:e,setDocuments:t,setShowDocLibrary:n,setShowFileBrowser:r,currentSessionId:i,sessions:l,updateSessionInList:a}=we(),o=l.find(T=>T.id===i)??null,[c,u]=p.useState(!1),[d,f]=p.useState(!1),[h,m]=p.useState(""),[g,v]=p.useState(""),[w,x]=p.useState(null),k=p.useRef(new Map),[,j]=p.useState(0);p.useEffect(()=>{E.doc.info("Loading document library...");const T=E.doc.time();ji().then(P=>{const b=P.documents||[];t(b),E.doc.timed(`Loaded ${b.length} document(s), ${P.total_chunks||0} chunks, ${P.total_size_bytes||0} bytes total`,T)}).catch(P=>{E.doc.error("Failed to load documents",P),t([])})},[t]);const z=e.some(T=>T.indexing_status==="indexing"||T.indexing_status==="pending");p.useEffect(()=>{if(!z)return;const T=we.getState().documents;for(const J of T)(J.indexing_status==="indexing"||J.indexing_status==="pending")&&!k.current.has(J.id)&&k.current.set(J.id,Date.now());let P=!1;const b=setInterval(async()=>{if(j(J=>J+1),!P){P=!0;try{const B=we.getState().documents.filter(S=>S.indexing_status==="indexing"||S.indexing_status==="pending");for(const S of B)try{const oe=await v0(S.id);if(oe.indexing_status!=="indexing"&&oe.indexing_status!=="pending"){k.current.delete(S.id);const pe=await ji();t(pe.documents||[]);break}}catch{}}finally{P=!1}}},2e3);return()=>clearInterval(b)},[z,t]),p.useEffect(()=>{const T=new Set(e.filter(P=>P.indexing_status==="indexing"||P.indexing_status==="pending").map(P=>P.id));for(const P of k.current.keys())T.has(P)||k.current.delete(P)},[e]),p.useEffect(()=>{const T=setInterval(async()=>{try{const b=(await ji()).documents||[],J=we.getState().documents;(b.length!==J.length||b.some((S,oe)=>{const pe=J.find(ae=>ae.id===S.id);return!pe||pe.indexing_status!==S.indexing_status||pe.indexed_at!==S.indexed_at||pe.chunk_count!==S.chunk_count}))&&(t(b),E.doc.debug("Document list refreshed (server-side changes detected)"))}catch{}},15e3);return()=>clearInterval(T)},[t]);const A=e.reduce((T,P)=>T+P.file_size,0),_=e.reduce((T,P)=>T+P.chunk_count,0),D=T=>{if(T<=0)return"0 B";const P=1024,b=["B","KB","MB","GB"],J=Math.min(Math.floor(Math.log(T)/Math.log(P)),b.length-1);return parseFloat((T/Math.pow(P,J)).toFixed(1))+" "+b[J]},C=p.useCallback(async(T,P)=>{var B;const b=T.includes(".")?"."+((B=T.split(".").pop())==null?void 0:B.toLowerCase()):"";if(b&&!eo(b)){const S=Ks(b),oe=S?S.message:`The file type "${b}" is not supported for indexing.`;E.doc.warn(`Unsupported file type: ${T} (${b})`),x({filename:T,error:oe});return}E.doc.info(`Indexing document: ${T}`);const J=E.doc.time();f(!0),m(`Indexing ${T}...`),x(null);try{const S=await P();if(E.doc.timed(`Indexed "${T}": ${(S==null?void 0:S.chunk_count)||"?"} chunks`,J),i&&(S!=null&&S.id))try{await Qa(i,S.id);const pe=we.getState().sessions.find(_e=>_e.id===i),ae=(pe==null?void 0:pe.document_ids)??[];ae.includes(S.id)||a(i,{document_ids:[...ae,S.id]}),E.doc.info(`Auto-attached "${T}" to session ${i}`)}catch(pe){E.doc.warn(`Could not attach document to session: ${pe}`)}const oe=await ji();t(oe.documents||[]),m("")}catch(S){E.doc.error(`Failed to index "${T}"`,S);const oe=S instanceof Error?S.message:"Upload failed";x({filename:T,error:oe}),m("")}finally{f(!1)}},[i,a,t]),M=p.useCallback(async(T,P)=>{await C(P,()=>Dy(T))},[C]),N=p.useCallback(async T=>{await C(T.name,()=>Ay(T))},[C]),U=p.useCallback(async T=>{T.preventDefault(),u(!1);const P=Array.from(T.dataTransfer.files);E.doc.info(`Dropped ${P.length} file(s) into Document Library`);for(const b of P)await N(b)},[N]),O=p.useCallback(async T=>{const P=e.find(b=>b.id===T);E.doc.info(`Deleting document: ${(P==null?void 0:P.filename)||T}`);try{await x0(T),k.current.delete(T),t(e.filter(b=>b.id!==T)),E.doc.info(`Deleted document: ${(P==null?void 0:P.filename)||T}`)}catch(b){E.doc.error(`Failed to delete document: ${(P==null?void 0:P.filename)||T}`,b)}},[e,t]),re=p.useCallback(async(T,P)=>{E.doc.info(`Opening folder for: ${T}`);try{await _d(T,!0)}catch(b){E.doc.error(`Failed to open folder for: ${P}`,b)}},[]),ie=p.useCallback(async T=>{const P=e.find(b=>b.id===T);E.doc.info(`Cancelling indexing for: ${(P==null?void 0:P.filename)||T}`);try{await k0(T),k.current.delete(T);const b=await ji();t(b.documents||[]),E.doc.info(`Cancelled indexing for: ${(P==null?void 0:P.filename)||T}`)}catch(b){E.doc.error(`Failed to cancel indexing: ${(P==null?void 0:P.filename)||T}`,b)}},[e,t]),X=p.useCallback(async T=>{if(!i)return;const P=e.find(b=>b.id===T);E.doc.info(`Attaching document to session: ${(P==null?void 0:P.filename)||T}`);try{await Qa(i,T);const b=we.getState().sessions.find(B=>B.id===i),J=(b==null?void 0:b.document_ids)??[];J.includes(T)||a(i,{document_ids:[...J,T]}),E.doc.info(`Attached "${(P==null?void 0:P.filename)||T}" to session ${i}`)}catch(b){E.doc.error(`Failed to attach document to session: ${(P==null?void 0:P.filename)||T}`,b)}},[i,e,a]),xe=p.useCallback(async T=>{T.preventDefault(),g.trim()&&(E.doc.info(`Indexing from path input: ${g.trim()}`),await M(g.trim(),g.trim().split(/[\\/]/).pop()||"file"),v(""))},[g,M]),ce=T=>{const P=T.indexing_status||"complete",b=k.current.get(T.id),J=T.indexed_at?_E(T.indexed_at):"",B=T.indexed_at?EE(T.indexed_at):"";switch(P){case"indexing":case"pending":return s.jsxs("div",{className:"doc-indexing-status",children:[s.jsxs("div",{className:"doc-indexing-bar",children:[s.jsx("div",{className:"doc-indexing-bar-track",children:s.jsx("div",{className:"doc-indexing-bar-fill"})}),s.jsxs("span",{className:"doc-indexing-label",children:[s.jsx(rw,{size:12,className:"doc-spin"}),"Indexing",b?` (${CE(b)})`:"..."]})]}),s.jsxs("button",{className:"btn-cancel",onClick:S=>{S.stopPropagation(),ie(T.id)},title:"Cancel indexing","aria-label":`Cancel indexing ${T.filename}`,children:[s.jsx(Tm,{size:14}),"Cancel"]})]});case"failed":return s.jsxs("span",{className:"doc-status-badge doc-status-failed",children:[s.jsx(kt,{size:12})," Failed"]});case"cancelled":return s.jsxs("span",{className:"doc-status-badge doc-status-cancelled",children:[s.jsx(Tm,{size:12})," Cancelled"]});case"missing":return s.jsxs("span",{className:"doc-status-badge doc-status-missing",children:[s.jsx(kt,{size:12})," File missing"]});default:return s.jsxs("span",{className:"doc-meta",children:[D(T.file_size)," · ",T.chunk_count," chunks",J&&s.jsxs("span",{className:"doc-timestamp",title:`Indexed: ${B}`,children:[s.jsx(Wa,{size:10}),J]})]})}};return s.jsx("div",{className:"modal-overlay",onClick:()=>n(!1),role:"dialog","aria-modal":"true","aria-label":"Document Library",children:s.jsxs("div",{className:"modal-panel doc-modal",onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:"Document Library"}),s.jsx("button",{className:"btn-icon",onClick:()=>n(!1),"aria-label":"Close document library",children:s.jsx(tt,{size:18})})]}),s.jsxs("div",{className:"modal-body",children:[s.jsx("div",{className:`drop-zone ${c?"drag-over":""} ${d?"uploading":""}`,onDragOver:T=>{T.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:U,children:d?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"upload-spinner"}),s.jsx("p",{children:h})]}):s.jsxs(s.Fragment,{children:[s.jsx(pl,{size:32,strokeWidth:1.5}),s.jsx("p",{children:"Drop files here to index"}),s.jsx("span",{className:"drop-hint",children:"PDF, TXT, MD, code files, and 50+ formats"})]})}),s.jsxs("form",{className:"path-input-form",onSubmit:xe,children:[s.jsx(Yn,{size:16,className:"path-icon"}),s.jsx("input",{type:"text",className:"path-input",value:g,onChange:T=>v(T.target.value),placeholder:"Or enter file path: C:\\docs\\manual.pdf","aria-label":"File path to index"}),s.jsx("button",{type:"submit",className:"btn-secondary",disabled:!g.trim()||d,children:"Index"}),s.jsxs("button",{type:"button",className:"btn-secondary",onClick:()=>{n(!1),r(!0)},title:"Browse files on this computer",children:[s.jsx(Fn,{size:14}),"Browse Files"]})]}),w&&s.jsx(Gx,{filename:w.filename,error:w.error,onDismiss:()=>x(null)}),e.length>0&&s.jsxs("div",{className:"doc-stats",children:[s.jsxs("span",{children:[e.length," document",e.length!==1?"s":""]}),s.jsx("span",{children:"·"}),s.jsxs("span",{children:[_," chunks"]}),s.jsx("span",{children:"·"}),s.jsx("span",{children:D(A)})]}),s.jsxs("div",{className:"doc-list",children:[e.length===0&&!d&&s.jsxs("div",{className:"empty-docs",children:[s.jsx($n,{size:32,strokeWidth:1}),s.jsx("p",{children:"No documents indexed yet"}),s.jsx("span",{children:"Drop files above or enter a file path"})]}),e.map(T=>{var P;return s.jsxs("div",{className:`doc-row ${T.indexing_status==="indexing"?"doc-row-indexing":""}`,children:[s.jsxs("div",{className:"doc-info",children:[s.jsx("span",{className:"doc-name",children:T.filename}),ce(T)]}),s.jsxs("div",{className:"doc-row-actions",children:[T.filepath&&s.jsx("button",{className:"btn-icon-sm doc-open-folder",onClick:()=>re(T.filepath,T.filename),title:`Open folder: ${T.filepath}`,"aria-label":`Open containing folder for ${T.filename}`,children:s.jsx(Yn,{size:14})}),i&&T.indexing_status==="complete"&&!((P=o==null?void 0:o.document_ids)!=null&&P.includes(T.id))&&s.jsx("button",{className:"btn-icon-sm doc-attach",onClick:()=>X(T.id),title:"Use in current session","aria-label":`Attach ${T.filename} to current session`,children:s.jsx(nw,{size:14})}),T.indexing_status!=="indexing"&&T.indexing_status!=="pending"&&s.jsx("button",{className:"btn-icon-sm doc-delete",onClick:()=>O(T.id),title:"Remove","aria-label":`Remove ${T.filename}`,children:s.jsx(ci,{size:14})})]})]},T.id)})]})]})]})})}function zE(e){if(e.type==="folder")return s.jsx(my,{size:16});const t=(e.extension||"").toLowerCase();return[".csv",".xlsx",".xls",".tsv"].includes(t)?s.jsx(ww,{size:16}):[".py",".js",".ts",".java",".c",".cpp",".go",".rs"].includes(t)?s.jsx(Qk,{size:16}):[".pdf",".doc",".docx",".txt",".md"].includes(t)?s.jsx($n,{size:16}):s.jsx(fy,{size:16})}function LE(e){if(e<=0)return"";const t=1024,n=["B","KB","MB","GB"],r=Math.min(Math.floor(Math.log(e)/Math.log(t)),n.length-1);return parseFloat((e/Math.pow(t,r)).toFixed(1))+" "+n[r]}function IE(e){if(!e)return"";const t=new Date(e),n=new Date,r=n.getTime()-t.getTime(),i=Math.floor(r/36e5);if(i<1)return"Just now";if(i<24)return`${i}h ago`;const l=Math.floor(i/24);return l<7?`${l}d ago`:t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0})}function DE(e){switch(e){case"home":return s.jsx(Jk,{size:14});case"desktop":return s.jsx(lw,{size:14});case"documents":return s.jsx($n,{size:14});case"download":return s.jsx(oi,{size:14});default:return s.jsx(my,{size:14})}}const AE=[{label:"All Files",value:""},{label:"Documents",value:"pdf,doc,docx,txt,md"},{label:"Spreadsheets",value:"csv,xlsx,xls,tsv"},{label:"Code",value:"py,js,ts,java,c,cpp,go,rs,rb,sh"},{label:"Data",value:"json,xml,yaml,yml,csv,tsv"}];async function Fh(e,t,n,r){var f;const i=[],l=[];for(const h of e){const m=h.includes(".")?"."+((f=h.split(".").pop())==null?void 0:f.toLowerCase()):"";m&&!eo(m)?l.push(h):i.push(h)}const a=[],o=[];let c=0,u="";const d=new Set(t.filter(h=>h.type==="folder").map(h=>h.path));for(const h of i)try{if(d.has(h)){const m=await j0(h),g=[];m.documents.forEach(v=>{v.id&&g.push(v.id)}),g.length>0&&(g.forEach(v=>a.push(v)),o.push(h))}else{const m=await Dy(h);m!=null&&m.id&&(a.push(m.id),o.push(h))}}catch(m){c++,u=m instanceof Error?m.message:"Unknown error"}if(n&&a.length>0){for(const v of a)try{await Qa(n,v)}catch(w){E.doc.warn(`Could not attach document to session: ${w}`)}const h=we.getState().sessions.find(v=>v.id===n),m=(h==null?void 0:h.document_ids)??[],g=a.filter(v=>!m.includes(v));g.length>0&&r(n,{document_ids:[...m,...g]})}return{docIds:a,supported:i,succeededFiles:o,unsupported:l,failed:c,lastError:u}}function PE(){const{setShowFileBrowser:e,currentSessionId:t,updateSessionInList:n,setPendingPrompt:r}=we(),[i,l]=p.useState(""),[a,o]=p.useState(null),[c,u]=p.useState([]),[d,f]=p.useState([]),[h,m]=p.useState(!1),[g,v]=p.useState(null),[w,x]=p.useState(""),[k,j]=p.useState(null),[z,A]=p.useState(!1),[_,D]=p.useState(""),[C,M]=p.useState(new Set),[N,U]=p.useState(null),[O,re]=p.useState(!1),[ie,X]=p.useState(new Set),[xe,ce]=p.useState(null),T=p.useRef(null),[P,b]=p.useState(null),J=p.useCallback(async L=>{m(!0),v(null),j(null),x("");try{const F=await b0(L);l(F.current_path),o(F.parent_path),u(F.entries),F.quick_links.length>0&&f(F.quick_links),E.ui.info(`Browsing: ${F.current_path} (${F.entries.length} items)`)}catch(F){const Y=F instanceof Error?F.message:"Failed to load directory";v(Y),E.ui.error("Browse failed",F)}finally{m(!1)}},[]);p.useEffect(()=>{J()},[J]),p.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const B=p.useCallback(async()=>{if(!w.trim()){j(null);return}A(!0),v(null);try{const L=await S0(w.trim(),_||void 0,30);j(L.results),E.ui.info(`Search "${w}": ${L.total} results`)}catch(L){const F=L instanceof Error?L.message:"Search failed";v(F),E.ui.error("Search failed",L)}finally{A(!1)}},[w,_]),S=L=>{L.key==="Enter"&&B()},oe=p.useCallback(L=>{L.type==="folder"&&(J(L.path),M(new Set),U(null))},[J]),pe=p.useCallback(async L=>{re(!0);try{const F=await N0(L);U(F)}catch(F){E.ui.error("Preview failed",F)}finally{re(!1)}},[]),ae=p.useCallback(async()=>{if(C.size===0)return;const L=Array.from(C);if(b(null),!L.some(Y=>{var he;const ue=Y.includes(".")?"."+((he=Y.split(".").pop())==null?void 0:he.toLowerCase()):"";return!ue||eo(ue)})){const Y=L[0],ue=Y.lastIndexOf("."),he=ue>0?Y.slice(ue).toLowerCase():"",H=Ks(he);b({filename:L.length===1?Y.split(/[\\/]/).pop()||Y:`${L.length} files`,error:H?H.message:`File type "${he}" is not supported for indexing.`});return}X(new Set(L)),ce(`Indexing ${L.length} file(s)...`);try{const Y=await Fh(L,c,t,n);if(Y.failed>0)ce(`Done: ${Y.docIds.length} indexed, ${Y.failed} failed`),b({filename:`${Y.failed} file(s)`,error:Y.lastError||"Indexing failed for some files"});else{const ue=Y.unsupported.length>0?` (${Y.unsupported.length} skipped — unsupported type)`:"";ce(`Successfully indexed ${Y.docIds.length} file(s)${ue}`)}T.current&&clearTimeout(T.current),T.current=setTimeout(()=>ce(null),5e3),M(new Set)}catch(Y){E.doc.error("Index selected failed",Y),b({filename:L.length===1?L[0].split(/[\\/]/).pop()||L[0]:`${L.length} files`,error:Y instanceof Error?Y.message:"An unexpected error occurred."})}finally{X(new Set)}},[C,t,n,c]),_e=p.useCallback(async()=>{if(C.size===0)return;const L=Array.from(C);b(null),X(new Set(L)),ce(`Indexing ${L.length} file(s) for analysis...`);try{const F=await Fh(L,c,t,n);if(F.supported.length===0){const he=L[0].lastIndexOf("."),H=he>0?L[0].slice(he).toLowerCase():"",le=Ks(H);b({filename:L.length===1?L[0].split(/[\\/]/).pop()||L[0]:`${L.length} files`,error:(le==null?void 0:le.message)??`File type "${H}" is not supported for indexing.`});return}if(F.docIds.length===0){b({filename:F.supported.length===1?F.supported[0].split(/[\\/]/).pop()||F.supported[0]:`${F.supported.length} files`,error:"Failed to index selected file(s). Please try again."});return}F.failed>0&&ce(`Warning: ${F.failed} file(s) failed to index and will be excluded.`);const Y=(F.succeededFiles.length>0?F.succeededFiles:F.supported).map(he=>he.split(/[\\/]/).pop()||he),ue=Y.length===1?`Please analyze this document for me: ${Y[0]}`:`Please analyze these documents for me:
541
541
  ${Y.map(he=>`- ${he}`).join(`
542
542
  `)}`;r(ue),e(!1),M(new Set)}catch(F){E.doc.error("Ask Agent failed",F),b({filename:L.length===1?L[0].split(/[\\/]/).pop()||L[0]:`${L.length} files`,error:F instanceof Error?F.message:"An unexpected error occurred."})}finally{X(new Set),ce(null)}},[C,t,n,c,r,e]),He=i?i.replace(/\\/g,"/").split("/").filter(Boolean):[],nt=He.map((L,F)=>({label:L,path:He.slice(0,F+1).join("/")+(F===0&&L.includes(":")?"/":"")})),Ge=k?k.map(L=>({name:L.name,path:L.path,type:"file",size:L.size,extension:L.extension||"",modified:L.modified||""})):c;return s.jsx("div",{className:"modal-overlay",onClick:()=>e(!1),role:"dialog","aria-modal":"true","aria-label":"File Browser",children:s.jsxs("div",{className:`modal-panel file-browser-modal ${N?"has-preview":""}`,onClick:L=>L.stopPropagation(),children:[s.jsxs("div",{className:"modal-header",children:[s.jsxs("h3",{children:[s.jsx(Yn,{size:18})," File Browser"]}),s.jsx("button",{className:"btn-icon",onClick:()=>e(!1),"aria-label":"Close",children:s.jsx(tt,{size:18})})]}),s.jsxs("div",{className:"file-browser-body",children:[s.jsx("div",{className:"fb-quick-links",children:d.map(L=>s.jsxs("button",{className:"fb-quick-link",onClick:()=>J(L.path),title:L.path,children:[DE(L.icon),s.jsx("span",{children:L.name})]},L.path))}),s.jsxs("div",{className:"fb-search-bar",children:[s.jsxs("div",{className:"fb-search-input-wrap",children:[s.jsx(Fn,{size:14,className:"fb-search-icon"}),s.jsx("input",{type:"text",className:"fb-search-input",placeholder:"Search files on your PC...",value:w,onChange:L=>x(L.target.value),onKeyDown:S,"aria-label":"Search files"}),w&&s.jsx("button",{className:"fb-search-clear",onClick:()=>{x(""),j(null)},"aria-label":"Clear search",children:s.jsx(tt,{size:12})})]}),s.jsx("select",{className:"fb-type-filter",value:_,onChange:L=>D(L.target.value),"aria-label":"File type filter",children:AE.map(L=>s.jsx("option",{value:L.value,children:L.label},L.value))}),s.jsx("button",{className:"fb-search-btn",onClick:B,disabled:!w.trim()||z,children:z?"Searching...":"Search"})]}),!k&&s.jsxs("div",{className:"fb-breadcrumb",children:[s.jsx("button",{className:"fb-crumb",onClick:()=>J("/"),children:s.jsx(Xk,{size:12})}),nt.map((L,F)=>s.jsxs("span",{className:"fb-crumb-item",children:[s.jsx(ss,{size:12,className:"fb-crumb-sep"}),s.jsx("button",{className:"fb-crumb",onClick:()=>J(L.path),children:L.label})]},F)),a&&s.jsx("button",{className:"fb-up-btn",onClick:()=>J(a),title:"Go up",children:s.jsx(Hk,{size:14})})]}),k&&s.jsxs("div",{className:"fb-search-header",children:[s.jsxs("span",{children:["Found ",k.length,' result(s) for "',w,'"']}),s.jsx("button",{className:"fb-back-btn",onClick:()=>{j(null),x("")},children:"Back to browsing"})]}),g&&s.jsx("div",{className:"fb-error",children:g}),s.jsxs("div",{className:"fb-content",children:[s.jsxs("div",{className:"fb-file-list",children:[h&&s.jsx("div",{className:"fb-loading",children:"Loading..."}),!h&&Ge.length===0&&s.jsx("div",{className:"fb-empty",children:k?"No files found":"This folder is empty"}),!h&&Ge.map(L=>{var he;const F=L.extension||(L.name.includes(".")?"."+((he=L.name.split(".").pop())==null?void 0:he.toLowerCase()):""),Y=L.type==="file"&&F&&!eo(F),ue=Y?Ks(F):null;return s.jsxs("div",{className:`fb-entry ${L.type} ${C.has(L.path)?"selected":""} ${Y?"unsupported":""}`,onClick:()=>L.type==="folder"?oe(L):pe(L.path),onDoubleClick:()=>L.type==="folder"?oe(L):void 0,title:Y?`${(ue==null?void 0:ue.label)||"This"} file type cannot be indexed`:L.path,children:[s.jsx("input",{type:"checkbox",className:"fb-entry-checkbox",checked:C.has(L.path),onChange:()=>{M(H=>{const le=new Set(H);return le.has(L.path)?le.delete(L.path):le.add(L.path),le})},onClick:H=>H.stopPropagation(),"aria-label":`Select ${L.name}`}),s.jsx("span",{className:"fb-entry-icon",children:zE(L)}),s.jsx("span",{className:"fb-entry-name",title:L.path,children:L.name}),Y&&s.jsx("span",{className:"fb-unsupported-badge",children:"Not indexable"}),s.jsx("span",{className:"fb-entry-size",children:L.type==="file"?LE(L.size):""}),s.jsx("span",{className:"fb-entry-date",children:IE(L.modified)})]},L.path)})]}),N&&s.jsxs("div",{className:"fb-preview",children:[s.jsxs("div",{className:"fb-preview-header",children:[s.jsx("span",{className:"fb-preview-name",children:N.name}),s.jsx("button",{className:"btn-icon-sm",onClick:()=>U(null),"aria-label":"Close preview",children:s.jsx(tt,{size:14})})]}),s.jsxs("div",{className:"fb-preview-meta",children:[s.jsx("span",{children:N.size_display}),N.total_lines&&s.jsxs("span",{children:[N.total_lines," lines"]}),N.columns&&s.jsxs("span",{children:[N.columns.length," columns"]}),N.row_count!==null&&s.jsxs("span",{children:[N.row_count," rows"]})]}),N.columns&&s.jsxs("div",{className:"fb-preview-columns",children:[s.jsx("strong",{children:"Columns:"})," ",N.columns.join(", ")]}),O?s.jsx("div",{className:"fb-preview-loading",children:"Loading preview..."}):N.is_text&&N.preview_lines.length>0?s.jsx("pre",{className:"fb-preview-content",children:N.preview_lines.slice(0,30).join(`
543
543
  `)}):s.jsx("div",{className:"fb-preview-binary",children:"Binary file - no preview available"})]})]}),P&&s.jsx(Gx,{filename:P.filename,error:P.error,onDismiss:()=>b(null)}),s.jsxs("div",{className:"fb-actions",children:[s.jsx("div",{className:"fb-selection-info",children:C.size>0?`${C.size} item(s) selected`:"Select files to index or analyze"}),xe&&s.jsx("span",{className:"fb-index-status",children:xe}),s.jsxs("div",{className:"fb-action-btns",children:[s.jsxs("button",{className:"fb-action-btn secondary",onClick:ae,disabled:C.size===0||ie.size>0,title:"Index selected files for RAG search",children:[s.jsx(pl,{size:14}),"Index Selected"]}),s.jsxs("button",{className:"fb-action-btn primary",onClick:_e,disabled:C.size===0||ie.size>0,title:"Index and send selected files to the chat agent for analysis",children:[s.jsx(Jr,{size:14}),"Ask Agent"]})]})]})]})]})})}const qd="/api";async function De(e,t,n){const r=`${qd}${t}`,i={};e!=="GET"&&(i["X-Gaia-UI"]="1"),n!==void 0&&(i["Content-Type"]="application/json");const l={method:e,headers:Object.keys(i).length>0?i:void 0,body:n!==void 0?JSON.stringify(n):void 0},a=await fetch(r,l);if(!a.ok){const c=await a.text().catch(()=>"");let u=c;try{u=JSON.parse(c).detail||c}catch{}throw new Error(u||`Memory API error (HTTP ${a.status})`)}if((a.headers.get("content-type")||"").includes("application/json"))return a.json()}function Qx(e){const t=[];for(const[n,r]of Object.entries(e))if(!(r==null||r===""))if(Array.isArray(r))for(const i of r)t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);else t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`);return t.length?`?${t.join("&")}`:""}function ME(){return De("GET","/memory/stats")}function RE(e=30){return De("GET",`/memory/activity?days=${e}`)}function $E(e={}){return De("GET",`/memory/knowledge${Qx(e)}`)}function FE(e){return De("POST","/memory/knowledge",e)}function Oh(e,t){return De("PUT",`/memory/knowledge/${encodeURIComponent(e)}`,t)}function OE(e){return De("DELETE",`/memory/knowledge/${encodeURIComponent(e)}`)}function UE(){return De("GET","/memory/entities")}function BE(){return De("GET","/memory/tools")}function HE(e=20){return De("GET",`/memory/conversations?limit=${e}`)}function VE(e,t=20){return De("GET",`/memory/conversations/search?query=${encodeURIComponent(e)}&limit=${t}`)}function WE(e){return De("GET",`/memory/conversations/${encodeURIComponent(e)}`)}function GE(e=7){return De("GET",`/memory/upcoming?days=${e}`)}function qE(){return De("GET","/memory/embedding-coverage")}function QE(){return De("POST","/memory/consolidate")}function KE(){return De("POST","/memory/rebuild-embeddings")}function YE(){return De("POST","/memory/reconcile")}function XE(){return De("POST","/memory/rebuild-fts")}function JE(){return De("POST","/memory/refresh-system-context")}function ZE(){return new EventSource(`${qd}/memory/stream-discovery`)}function eT(e){return new EventSource(`${qd}/memory/stream-inference?include_browser=${e}`)}function tT(e){return De("POST","/memory/commit-discovery",{items:e})}function nT(e){return De("POST","/memory/commit-inference",{insights:e})}function rT(){return De("GET","/memory/settings")}function vi(e){return De("PUT","/memory/settings",e)}function iT(){return De("DELETE","/memory/all")}function sT(){return De("POST","/memory/reinitialize")}function lT(){return De("GET","/goals/stats")}function aT(e={}){return De("GET",`/goals${Qx(e)}`)}function oT(e){return De("POST","/goals",e)}function cT(e){return De("PUT",`/goals/${encodeURIComponent(e)}/approve`)}function uT(e){return De("PUT",`/goals/${encodeURIComponent(e)}/reject`)}function dT(e){return De("PUT",`/goals/${encodeURIComponent(e)}/cancel`)}function fT(e){return De("DELETE",`/goals/${encodeURIComponent(e)}`)}function Uh(e){if(!e)return"—";try{const t=new Date(e);if(isNaN(t.getTime()))return"—";const n={month:"short",day:"numeric"};return t.getFullYear()!==new Date().getFullYear()&&(n.year="numeric"),t.toLocaleDateString(void 0,n)}catch{return"—"}}function Nn(e){if(!e)return"";try{const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return""}}function jr(e){if(!e)return"—";try{const t=new Date(e);if(isNaN(t.getTime()))return"—";const n=Date.now(),r=t.getTime()-n,i=Math.abs(r),l=Math.floor(i/1e3),a=Math.floor(i/6e4),o=Math.floor(i/36e5),c=Math.floor(i/864e5);return r<0?l<5?"just now":l<60?`${l}s ago`:o===0?`${a}m ago`:c===0?`${o}h ago`:c===1?"yesterday":c<30?`${c}d ago`:Nn(e):l<5?"now":l<60?`in ${l}s`:o===0?`in ${a}m`:c===0?`in ${o}h`:c===1?"tomorrow":c<30?`in ${c}d`:Nn(e)}catch{return"—"}}function mT(e){if(e<=0)return"0 B";const t=1024,n=["B","KB","MB","GB"],r=Math.min(Math.floor(Math.log(e)/Math.log(t)),n.length-1);return parseFloat((e/Math.pow(t,r)).toFixed(1))+" "+n[r]}function hT(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}function Bh(e){try{return new Date(e).getTime()<Date.now()}catch{return!1}}function pT(e){return e>=.7?"high":e>=.4?"medium":"low"}function Hh(e){return e>=.9?"high":e>=.7?"medium":"low"}function gT(e,t){const n=Uh(e),r=Uh(t);return n==="—"&&r==="—"?"":n===r?n:`${n} – ${r}`}function yT(e){if(e.length===0)return 0;const t=new Date().toISOString().slice(0,10),n=e.find(r=>r.date===t);return n?n.knowledge_added:0}const Vh=["fact","preference","error","skill","note","reminder"],xT={work:"blue",technical:"purple",personal:"green",general:"gray"};function vT(){var Zd,ef,tf,nf,rf,sf,lf,af,of,cf,uf,df,ff,mf,hf,pf;const{setShowMemoryDashboard:e}=we(),[t,n]=p.useState(null),[r,i]=p.useState([]),[l,a]=p.useState(null),[o,c]=p.useState([]),[u,d]=p.useState([]),[f,h]=p.useState([]),[m,g]=p.useState(null),[v,w]=p.useState([]),[x,k]=p.useState(!0),[j,z]=p.useState(null),[A,_]=p.useState(null),[D,C]=p.useState(!1),[M,N]=p.useState(null),[U,O]=p.useState([]),re=p.useRef(0),[ie,X]=p.useState([]),[xe,ce]=p.useState(""),[T,P]=p.useState(""),[b,J]=p.useState(""),[B,S]=p.useState("updated_at"),[oe,pe]=p.useState("desc"),[ae,_e]=p.useState(0),[He,nt]=p.useState(!1),Ge=15,[L,F]=p.useState(""),[Y,ue]=p.useState(null),he=p.useRef(null),[H,le]=p.useState(null),[Pe,Ae]=p.useState(!1),[$e,ut]=p.useState(null),[je,Je]=p.useState({content:"",category:"fact",domain:"",context:"global",entity:"",sensitive:!1,due_at:""}),[Vr,os]=p.useState(new Set),[$,Q]=p.useState(!1),[de,ve]=p.useState(!1),[be,wt]=p.useState(!1),[pt,qe]=p.useState(!1),[Pt,Xt]=p.useState(!1),[rt,Mt]=p.useState(!1),[bt,xn]=p.useState(null),[cn,Jt]=p.useState("dashboard"),[Zt,sr]=p.useState([]),[vn,cs]=p.useState(null),[kn,gt]=p.useState(!1),[Hn,lr]=p.useState(null),[_l,ar]=p.useState(!1),[or,cr]=p.useState({title:"",description:"",priority:"medium"}),[st,ur]=p.useState("idle"),[us,wn]=p.useState([]),[Vn,dr]=p.useState([]),[El,Tl]=p.useState(null),bn=p.useRef(null),fr=p.useRef(null),[jt,mr]=p.useState("idle"),[ds,Dn]=p.useState([]),[Wn,hr]=p.useState([]),[zl,Ll]=p.useState(null),[fs,_o]=p.useState(!1),pi=p.useRef(null),pr=p.useRef(null),[ms,Il]=p.useState(30),[gi,hs]=p.useState(!1),[I,q]=p.useState(!1),[te,Z]=p.useState(!1),[ge,Ee]=p.useState(!1),[yt,gr]=p.useState(!1),[lt,Et]=p.useState(!1),St=p.useRef(null),V=p.useRef(null),ee=p.useCallback((y,R="info")=>{const se=++re.current;O(me=>[...me,{id:se,text:y,type:R}]),setTimeout(()=>{O(me=>me.filter(Fe=>Fe.id!==se))},4e3)},[]);p.useEffect(()=>{if(!D)return;const y=R=>{V.current&&!V.current.contains(R.target)&&C(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[D]),p.useEffect(()=>{const y=R=>{R.key==="Escape"&&(bt?xn(null):Pt?Xt(!1):rt?Mt(!1):H?le(null):D?C(!1):Pe||$e?(Ae(!1),ut(null)):M?N(null):e(!1))};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[H,D,Pe,$e,M,e,bt,Pt,rt]);const Ce=p.useCallback(async()=>{try{const y=await ME();n(y)}catch(y){E.system.warn("Failed to load memory stats",y)}},[]),dt=p.useCallback(async()=>{try{const y=await RE(ms);i(y)}catch(y){E.system.warn("Failed to load memory activity",y)}},[ms]),Ie=p.useCallback(async()=>{try{const y=await $E({category:ie.length>0?ie:void 0,context:xe||void 0,entity:T||void 0,search:b||void 0,sort_by:B,order:oe,offset:ae,limit:Ge,include_sensitive:!0,include_superseded:He});a(y)}catch(y){E.system.warn("Failed to load knowledge",y)}},[ie,xe,T,b,B,oe,ae,He]),ze=p.useCallback(async()=>{try{const y=await BE();c(y)}catch(y){E.system.warn("Failed to load tool summary",y)}},[]),Me=p.useCallback(async()=>{try{const y=await HE(20);d(y)}catch(y){E.system.warn("Failed to load conversations",y)}},[]),Ht=p.useCallback(async()=>{try{const y=await GE(7);h(y)}catch(y){E.system.warn("Failed to load upcoming items",y)}},[]),Ze=p.useCallback(async()=>{try{const y=await qE();g(y)}catch(y){E.system.warn("Failed to load embedding coverage",y)}},[]),ps=p.useCallback(async()=>{try{const y=await UE();w(y||[])}catch(y){E.system.warn("Failed to load entities",y)}},[]),Kd=p.useCallback(async()=>{try{const y=await rT();ve(y.mcp_memory_enabled),Q(y.memory_enabled),wt(y.system_discovery_consent)}catch(y){E.system.warn("Failed to load memory settings",y)}},[]),yr=p.useCallback(async()=>{gt(!0);try{const[y,R]=await Promise.all([aT(),lT()]);sr(y.goals),cs(R)}catch(y){E.system.warn("Failed to load goals",y)}finally{gt(!1)}},[]),Rt=p.useCallback(async()=>{k(!0),z(null);try{await Promise.all([Ce(),dt(),Ie(),ze(),Me(),Ht(),Ze(),ps(),Kd(),yr()])}catch(y){z("Failed to load memory data. Is the backend running?"),E.system.error("Memory dashboard load failed",y)}finally{k(!1)}},[Ce,dt,Ie,ze,Me,Ht,Ze,ps,Kd,yr]);p.useEffect(()=>{Rt()},[Rt]),p.useEffect(()=>{Ie()},[Ie]);const Yd=p.useRef(!0);p.useEffect(()=>{if(Yd.current){Yd.current=!1;return}dt()},[dt]);const Yx=p.useCallback(y=>{J(y),Et(!0),St.current&&clearTimeout(St.current),St.current=setTimeout(()=>{_e(0),Et(!1)},300)},[]),Xx=p.useCallback(async()=>{if(je.content.trim())try{await FE({content:je.content,category:je.category,domain:je.domain||void 0,context:je.context,entity:je.entity||void 0,sensitive:je.sensitive,due_at:je.due_at||void 0}),Ae(!1),Je({content:"",category:"fact",domain:"",context:"global",entity:"",sensitive:!1,due_at:""}),Ie(),Ce(),Ze(),E.ui.info("Created new knowledge entry"),ee("Memory created successfully","success")}catch(y){E.system.error("Failed to create knowledge",y),ee("Failed to create memory","error")}},[je,Ie,Ce,Ze,ee]),Jx=p.useCallback(async()=>{if(!(!$e||!je.content.trim()))try{await Oh($e,{content:je.content,category:je.category,domain:je.domain||void 0,context:je.context,entity:je.entity||void 0,sensitive:je.sensitive,due_at:je.due_at||void 0}),ut(null),Je({content:"",category:"fact",domain:"",context:"global",entity:"",sensitive:!1,due_at:""}),Ie(),E.ui.info(`Updated knowledge ${$e}`),ee("Memory updated","success")}catch(y){E.system.error("Failed to update knowledge",y),ee("Failed to update memory","error")}},[$e,je,Ie,ee]),Zx=p.useCallback(async y=>{try{await OE(y),Ie(),Ce(),Ze(),E.ui.info(`Deleted knowledge ${y}`),ee("Memory deleted","info")}catch(R){E.system.error("Failed to delete knowledge",R),ee("Failed to delete memory","error")}},[Ie,Ce,Ze,ee]),ev=p.useCallback(async y=>{try{await Oh(y.id,{sensitive:!y.sensitive}),Ie(),E.ui.info(`Toggled sensitive for ${y.id}: ${!y.sensitive}`),ee(y.sensitive?"Unmarked as sensitive":"Marked as sensitive","info")}catch(R){E.system.error("Failed to toggle sensitive",R),ee("Failed to toggle sensitive flag","error")}},[Ie,ee]),tv=p.useCallback(y=>{ut(y.id),Ae(!1),Je({content:y.content,category:y.category,domain:y.domain||"",context:y.context,entity:y.entity||"",sensitive:y.sensitive,due_at:y.due_at||""})},[]),nv=p.useCallback(y=>{navigator.clipboard.writeText(y).catch(()=>{}),E.ui.info(`Copied knowledge ID: ${y}`),ee("ID copied to clipboard","info")},[ee]),rv=p.useCallback(y=>{if(F(y),he.current&&clearTimeout(he.current),!y.trim()){ue(null);return}he.current=setTimeout(async()=>{try{const R=await VE(y.trim(),20);ue(R)}catch(R){E.system.warn("Conversation search failed",R)}},300)},[]),Xd=p.useCallback(async y=>{try{const R=await WE(y);le({sessionId:y,turns:R})}catch(R){E.system.error("Failed to load conversation detail",R)}},[]),iv=p.useCallback(y=>{X(R=>R.includes(y)?R.filter(se=>se!==y):[...R,y]),_e(0)},[]),gs=p.useCallback(y=>{B===y?pe(R=>R==="desc"?"asc":"desc"):(S(y),pe("desc")),_e(0)},[B]),sv=p.useCallback(async()=>{hs(!0),C(!1);try{const y=await QE();await Rt(),ee(`Consolidated ${y.consolidated??0} sessions, extracted ${y.extracted_items??0} items`,"success")}catch(y){E.system.error("Failed to consolidate sessions",y),ee("Failed to consolidate sessions","error")}finally{hs(!1)}},[Rt,ee]),lv=p.useCallback(async()=>{q(!0),C(!1);try{const y=await KE();await Ze(),ee(`Backfilled ${y.backfilled??0} embeddings${y.total_without?` (${y.total_without} were missing)`:""}`,"success")}catch(y){E.system.error("Failed to rebuild embeddings",y),ee("Failed to rebuild embeddings","error")}finally{q(!1)}},[Ze,ee]),av=p.useCallback(async()=>{Z(!0),C(!1);try{const y=await YE();await Rt(),ee(`Checked ${y.pairs_checked??0} pairs: ${y.reinforced??0} reinforced, ${y.contradicted??0} contradicted`,"success")}catch(y){E.system.error("Failed to reconcile memory",y),ee("Failed to reconcile memory","error")}finally{Z(!1)}},[Rt,ee]),ov=p.useCallback(async()=>{Ee(!0),C(!1);try{await XE(),await Rt(),ee("FTS indexes rebuilt successfully","success")}catch(y){E.system.error("Failed to rebuild FTS index",y),ee("Failed to rebuild FTS indexes","error")}finally{Ee(!1)}},[Rt,ee]),cv=p.useCallback(async()=>{gr(!0),C(!1);try{const y=await JE();await Rt(),y.skipped?ee("System context collection is disabled — enable it in settings","error"):ee(`System context refreshed: ${y.stored} facts updated`,"success")}catch(y){E.system.error("Failed to refresh system context",y),ee("Failed to refresh system context","error")}finally{gr(!1)}},[Rt,ee]),Jd=gi||I||te||ge||yt,uv=p.useCallback(()=>{ur("running"),wn([]),dr([]),Tl(null);const y=ZE();fr.current=y,y.onmessage=R=>{try{const se=JSON.parse(R.data);if(se.type==="log")wn(me=>[...me,{text:se.message,kind:"log"}]);else if(se.type==="finding"){const me=se.item;wn(Fe=>[...Fe,{text:` Found: ${me.content}`,kind:"finding"}]),dr(Fe=>[...Fe,{...me,_checked:!0}])}else se.type==="error"?wn(me=>[...me,{text:` Error: ${se.message}`,kind:"error"}]):se.type==="done"&&(y.close(),fr.current=null,wn(me=>[...me,{text:`Done. ${se.total??0} items discovered.`,kind:"log"}]),ur("review"))}catch{wn(se=>[...se,{text:"Failed to parse event data.",kind:"error"}])}},y.onerror=()=>{y.close(),fr.current=null,wn(R=>[...R,{text:"Connection error. Is the GAIA server running?",kind:"error"}]),dr(R=>(ur(R.length>0?"review":"idle"),R))}},[]),dv=p.useCallback(async()=>{const y=Vn.filter(R=>R._checked);if(y.length!==0){ur("saving");try{const R=y.map(({_checked:me,...Fe})=>Fe),se=await tT(R);Tl(se.stored),ur("done"),ee(`Saved ${se.stored} items to memory`,"success")}catch(R){E.system.error("Failed to commit discovery items",R),ee("Failed to save discovery items","error"),ur("review")}}},[Vn,ee]),fv=p.useCallback(()=>{mr("running"),Dn([]),hr([]),Ll(null);const y=eT(fs);pr.current=y,y.onmessage=R=>{try{const se=JSON.parse(R.data);if(se.type==="log")Dn(me=>[...me,{text:se.message,kind:"log"}]);else if(se.type==="insight"){const me=se.item;Dn(Fe=>[...Fe,{text:` Insight: ${me.content}`,kind:"finding"}]),hr(Fe=>[...Fe,{...me,_checked:!0}])}else se.type==="error"?Dn(me=>[...me,{text:` Error: ${se.message}`,kind:"error"}]):se.type==="done"&&(y.close(),pr.current=null,Dn(me=>[...me,{text:`Done. ${se.total??0} insights generated.`,kind:"log"}]),mr("review"))}catch{Dn(se=>[...se,{text:"Failed to parse event data.",kind:"error"}])}},y.onerror=()=>{y.close(),pr.current=null,Dn(R=>[...R,{text:"Connection error. Is Lemonade Server running?",kind:"error"}]),hr(R=>(mr(R.length>0?"review":"idle"),R))}},[fs]),mv=p.useCallback(async()=>{const y=Wn.filter(R=>R._checked);if(y.length!==0){mr("saving");try{const R=y.map(({_checked:me,...Fe})=>Fe),se=await nT(R);Ll(se.stored),mr("done"),ee(`Saved ${se.stored} insights to memory`,"success")}catch(R){E.system.error("Failed to commit inference insights",R),ee("Failed to save inference insights","error"),mr("review")}}},[Wn,ee]);p.useEffect(()=>{bn.current&&(bn.current.scrollTop=bn.current.scrollHeight)},[us]),p.useEffect(()=>{pi.current&&(pi.current.scrollTop=pi.current.scrollHeight)},[ds]),p.useEffect(()=>()=>{fr.current&&(fr.current.close(),fr.current=null),pr.current&&(pr.current.close(),pr.current=null)},[]);const ys=y=>B!==y?null:s.jsx("span",{className:"mem-sort-arrow",children:oe==="desc"?"↓":"↑"}),Dl=Math.max(1,...r.map(y=>y.conversations+y.tool_calls+y.knowledge_added+y.errors)),hv=(Zd=t==null?void 0:t.knowledge)!=null&&Zd.by_context?Object.keys(t.knowledge.by_context):[];return s.jsxs("div",{className:"memory-dashboard-page",children:[s.jsxs("div",{className:"memory-dashboard-header",children:[s.jsxs("div",{className:"memory-dashboard-header-left",children:[s.jsx("button",{className:"btn-icon settings-back-btn",onClick:()=>e(!1),"aria-label":"Back",children:s.jsx(ay,{size:18})}),s.jsxs("h3",{children:["Memory Dashboard ",s.jsx("span",{style:{fontSize:11,fontWeight:600,color:"#f59e0b",background:"rgba(245,158,11,0.15)",padding:"2px 8px",borderRadius:4,marginLeft:8,verticalAlign:"middle",letterSpacing:"0.5px"},children:"BETA"})]})]}),s.jsxs("div",{className:"memory-dashboard-header-actions",children:[m&&m.total_items>0&&s.jsxs("div",{className:"mem-embedding-coverage",title:`${m.with_embedding} of ${m.total_items} entries embedded`,children:[s.jsx("div",{className:"mem-embedding-bar",children:s.jsx("div",{className:"mem-embedding-fill",style:{width:`${Math.round(m.coverage_pct)}%`}})}),s.jsxs("span",{className:"mem-embedding-label",children:[Math.round(m.coverage_pct),"% embedded"]})]}),s.jsxs("div",{className:"mem-maintenance-wrap",ref:V,children:[s.jsxs("button",{className:`btn-icon ${Jd?"mem-spinning":""}`,onClick:()=>C(y=>!y),title:"Maintenance actions","aria-label":"Maintenance actions","aria-expanded":D,children:[Jd?s.jsx("div",{className:"mem-spinner-sm"}):s.jsx(bi,{size:16}),s.jsx(ai,{size:10,style:{marginLeft:2}})]}),D&&s.jsxs("div",{className:"mem-maintenance-menu",role:"menu",children:[s.jsxs("button",{className:"mem-maintenance-item",onClick:sv,disabled:gi,role:"menuitem",children:[s.jsx(Em,{size:14}),gi?"Consolidating...":"Consolidate Sessions"]}),s.jsxs("button",{className:"mem-maintenance-item",onClick:lv,disabled:I,role:"menuitem",children:[s.jsx(Ws,{size:14}),I?"Rebuilding...":"Rebuild Embeddings"]}),s.jsxs("button",{className:"mem-maintenance-item",onClick:av,disabled:te,role:"menuitem",children:[s.jsx(wi,{size:14}),te?"Reconciling...":"Reconcile Memory"]}),s.jsx("div",{className:"mem-maintenance-divider"}),s.jsxs("button",{className:"mem-maintenance-item",onClick:cv,disabled:yt,role:"menuitem",children:[s.jsx(Vs,{size:14}),yt?"Refreshing...":"Refresh System Context"]}),s.jsx("div",{className:"mem-maintenance-divider"}),s.jsxs("button",{className:"mem-maintenance-item",onClick:ov,disabled:ge,role:"menuitem",children:[s.jsx(Fn,{size:14}),ge?"Rebuilding...":"Rebuild FTS Indexes"]})]})]}),s.jsx("button",{className:"btn-icon",onClick:Rt,title:"Refresh","aria-label":"Refresh dashboard",children:s.jsx(Vs,{size:16})})]})]}),s.jsxs("div",{className:"mem-tab-bar",role:"tablist",children:[s.jsxs("button",{className:`mem-tab-btn${cn==="dashboard"?" mem-tab-active":""}`,onClick:()=>Jt("dashboard"),role:"tab","aria-selected":cn==="dashboard",children:[s.jsx(Jr,{size:14})," Dashboard"]}),s.jsxs("button",{className:`mem-tab-btn${cn==="goals"?" mem-tab-active":""}`,onClick:()=>{Jt("goals"),yr()},role:"tab","aria-selected":cn==="goals",children:[s.jsx(zm,{size:14})," Goals",vn&&(vn.goals.pending_approval??0)>0&&s.jsx("span",{className:"mem-tab-badge",children:vn.goals.pending_approval})]}),s.jsxs("button",{className:`mem-tab-btn${cn==="profile"?" mem-tab-active":""}`,onClick:()=>Jt("profile"),role:"tab","aria-selected":cn==="profile",children:[s.jsx(bw,{size:14})," Profile"]})]}),s.jsxs("div",{className:"memory-dashboard-body",children:[cn==="dashboard"&&s.jsx(s.Fragment,{children:x&&!t?s.jsxs("div",{className:"mem-loading",children:[s.jsx("div",{className:"mem-spinner"}),"Loading memory data..."]}):j?s.jsxs("div",{className:"mem-empty",children:[s.jsx("div",{className:"mem-empty-icon",children:s.jsx(pn,{size:32})}),s.jsx("p",{children:j}),s.jsxs("button",{className:"btn-secondary",onClick:Rt,style:{marginTop:12},children:[s.jsx(Vs,{size:14})," Retry"]})]}):s.jsxs(s.Fragment,{children:[!$&&s.jsxs("div",{className:"mem-empty-state",style:{margin:"40px 0"},children:[s.jsx("div",{className:"mem-empty-icon",style:{opacity:.5},children:s.jsx(Cs,{size:32})}),s.jsx("p",{style:{color:"#888",fontSize:14},children:"Memory is disabled. Enable it in Settings below to start storing knowledge, conversations, and preferences."})]}),$&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mem-stat-cards",children:[s.jsxs("div",{className:"mem-stat-card","data-accent":"purple",children:[s.jsx("div",{className:"mem-stat-value",children:((ef=t==null?void 0:t.knowledge)==null?void 0:ef.total)??0}),s.jsx("div",{className:"mem-stat-label",children:"Stored"}),s.jsx("div",{className:"mem-stat-sub",children:(()=>{var R;const y=yT(r);return y>0?`+${y} today`:(R=t==null?void 0:t.knowledge)!=null&&R.by_category?Object.entries(t.knowledge.by_category).slice(0,3).map(([se,me])=>`${me} ${se}s`).join(", "):"No entries"})()})]}),s.jsxs("div",{className:"mem-stat-card","data-accent":"gold",children:[s.jsx("div",{className:"mem-stat-value",children:((tf=t==null?void 0:t.knowledge)==null?void 0:tf.total_retrievals)??0}),s.jsx("div",{className:"mem-stat-label",children:"Retrieved"}),s.jsx("div",{className:"mem-stat-sub",children:(nf=t==null?void 0:t.knowledge)!=null&&nf.total&&((rf=t==null?void 0:t.knowledge)!=null&&rf.total_retrievals)?`avg ${(t.knowledge.total_retrievals/t.knowledge.total).toFixed(1)}x per memory`:"No recalls yet"})]}),s.jsxs("div",{className:"mem-stat-card","data-accent":"blue",children:[s.jsx("div",{className:"mem-stat-value",children:((sf=t==null?void 0:t.conversations)==null?void 0:sf.total_sessions)??0}),s.jsx("div",{className:"mem-stat-label",children:"Sessions"}),s.jsx("div",{className:"mem-stat-sub",children:gT(((lf=t==null?void 0:t.conversations)==null?void 0:lf.first_session)??null,((af=t==null?void 0:t.conversations)==null?void 0:af.last_session)??null)||`${((of=t==null?void 0:t.conversations)==null?void 0:of.total_turns)??0} total turns`})]}),s.jsxs("div",{className:"mem-stat-card","data-accent":"green",children:[s.jsx("div",{className:"mem-stat-value",children:((cf=t==null?void 0:t.tools)==null?void 0:cf.total_calls)??0}),s.jsx("div",{className:"mem-stat-label",children:"Tool Calls"}),s.jsxs("div",{className:"mem-stat-sub",children:[((uf=t==null?void 0:t.tools)==null?void 0:uf.unique_tools)??0," tools"]})]}),s.jsxs("div",{className:"mem-stat-card","data-accent":"red",children:[s.jsx("div",{className:"mem-stat-value",children:((df=t==null?void 0:t.tools)==null?void 0:df.overall_success_rate)!=null?`${Math.round(t.tools.overall_success_rate*100)}%`:"—"}),s.jsx("div",{className:"mem-stat-label",children:"Success Rate"}),s.jsxs("div",{className:"mem-stat-sub",children:[((ff=t==null?void 0:t.tools)==null?void 0:ff.total_errors)??0," errors"]})]})]}),s.jsxs("div",{className:"mem-section",children:[s.jsxs("div",{className:"mem-section-title mem-section-title-row",children:[s.jsxs("span",{className:"mem-section-title-left",children:[s.jsx(Lm,{size:14})," Activity"]}),s.jsx("div",{className:"mem-range-tabs",role:"group","aria-label":"Activity range",children:[1,7,30].map(y=>s.jsx("button",{className:`mem-range-tab${ms===y?" active":""}`,onClick:()=>Il(y),children:y===1?"1D":y===7?"7D":"30D"},y))})]}),r.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mem-activity-chart",children:r.map((y,R)=>{const se=y.conversations+y.tool_calls+y.knowledge_added+y.errors,me=R===0||R===r.length-1||R%7===0,Fe=new Date(y.date+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"});return s.jsxs("div",{className:"mem-activity-bar-group",onMouseEnter:()=>_(R),onMouseLeave:()=>_(null),children:[y.errors>0&&s.jsx("div",{className:"mem-activity-bar errors",style:{height:`${y.errors/Dl*100}%`}}),y.knowledge_added>0&&s.jsx("div",{className:"mem-activity-bar knowledge",style:{height:`${y.knowledge_added/Dl*100}%`}}),y.tool_calls>0&&s.jsx("div",{className:"mem-activity-bar tool_calls",style:{height:`${y.tool_calls/Dl*100}%`}}),y.conversations>0&&s.jsx("div",{className:"mem-activity-bar conversations",style:{height:`${y.conversations/Dl*100}%`}}),me&&s.jsx("span",{className:"mem-activity-date-label",children:Fe}),A===R&&se>0&&s.jsxs("div",{className:"mem-activity-tooltip",children:[s.jsx("strong",{children:Fe}),s.jsx("br",{}),y.conversations>0&&s.jsxs(s.Fragment,{children:[y.conversations," conversations",s.jsx("br",{})]}),y.tool_calls>0&&s.jsxs(s.Fragment,{children:[y.tool_calls," tool calls",s.jsx("br",{})]}),y.knowledge_added>0&&s.jsxs(s.Fragment,{children:[y.knowledge_added," learned",s.jsx("br",{})]}),y.errors>0&&s.jsxs(s.Fragment,{children:[y.errors," errors"]})]})]},y.date)})}),s.jsxs("div",{className:"mem-activity-legend",children:[s.jsxs("span",{className:"mem-activity-legend-item",children:[s.jsx("span",{className:"mem-activity-legend-dot conversations"})," Conversations"]}),s.jsxs("span",{className:"mem-activity-legend-item",children:[s.jsx("span",{className:"mem-activity-legend-dot tool_calls"})," Tool Calls"]}),s.jsxs("span",{className:"mem-activity-legend-item",children:[s.jsx("span",{className:"mem-activity-legend-dot knowledge"})," Knowledge"]}),s.jsxs("span",{className:"mem-activity-legend-item",children:[s.jsx("span",{className:"mem-activity-legend-dot errors"})," Errors"]})]})]}):s.jsxs("div",{className:"mem-empty",children:[s.jsx("div",{className:"mem-empty-icon",children:s.jsx(Lm,{size:28})}),s.jsx("p",{children:"No activity data yet"})]})]}),s.jsxs("div",{className:"mem-section",children:[s.jsxs("div",{className:"mem-section-title mem-section-title-row",children:[s.jsxs("span",{className:"mem-section-title-left",children:[s.jsx(Jr,{size:14})," Knowledge Browser",l&&l.total>0&&s.jsx("span",{className:"mem-section-count",children:l.total})]}),!Pe&&!$e&&s.jsxs("button",{className:"mem-section-add-btn",onClick:()=>Ae(!0),title:"Add a memory entry",children:[s.jsx(hl,{size:13})," Add"]})]}),s.jsxs("div",{className:"mem-filters",children:[s.jsxs("div",{className:"mem-category-pills",role:"group","aria-label":"Filter by category",children:[Vh.map(y=>s.jsx("button",{className:`mem-category-pill ${y}${ie.includes(y)?" active":""}`,onClick:()=>iv(y),"aria-pressed":ie.includes(y),children:y},y)),ie.length>0&&s.jsx("button",{className:"mem-category-pill clear",onClick:()=>{X([]),_e(0)},"aria-label":"Clear category filters",children:"✕ Clear"})]}),s.jsxs("select",{className:"mem-filter-select",value:xe,onChange:y=>{ce(y.target.value),_e(0)},"aria-label":"Filter by context",children:[s.jsx("option",{value:"",children:"All Contexts"}),hv.map(y=>s.jsx("option",{value:y,children:y},y))]}),s.jsxs("select",{className:"mem-filter-select",value:T,onChange:y=>{P(y.target.value),_e(0)},"aria-label":"Filter by entity",children:[s.jsx("option",{value:"",children:"All Entities"}),v.map(y=>s.jsxs("option",{value:y.entity,children:[y.entity," (",y.count,")"]},y.entity))]}),s.jsxs("div",{className:"mem-filter-search-wrap",children:[lt?s.jsx("div",{className:"mem-spinner-sm search-icon",style:{width:12,height:12,borderWidth:1.5}}):s.jsx(Fn,{size:13,className:"search-icon"}),s.jsx("input",{className:"mem-filter-search",type:"text",placeholder:"Search memories...",value:b,onChange:y=>Yx(y.target.value),"aria-label":"Search memories"})]}),s.jsxs("label",{className:"mem-filter-toggle",title:"Show entries that have been superseded by newer versions",children:[s.jsx("input",{type:"checkbox",checked:He,onChange:y=>nt(y.target.checked)}),s.jsx("span",{children:"Superseded"})]})]}),(Pe||$e)&&s.jsxs("div",{className:"mem-inline-form",children:[s.jsxs("div",{className:"mem-inline-form-row",children:[s.jsx("label",{children:"Content"}),s.jsx("textarea",{value:je.content,onChange:y=>Je(R=>({...R,content:y.target.value})),placeholder:"What should the agent remember?"})]}),s.jsxs("div",{className:"mem-inline-form-row",children:[s.jsx("label",{children:"Category"}),s.jsx("select",{value:je.category,onChange:y=>Je(R=>({...R,category:y.target.value})),children:Vh.map(y=>s.jsx("option",{value:y,children:y.charAt(0).toUpperCase()+y.slice(1)},y))})]}),s.jsxs("div",{className:"mem-inline-form-row",children:[s.jsx("label",{children:"Context"}),s.jsx("input",{type:"text",value:je.context,onChange:y=>Je(R=>({...R,context:y.target.value})),placeholder:"global"})]}),s.jsxs("div",{className:"mem-inline-form-row",children:[s.jsx("label",{children:"Domain"}),s.jsx("input",{type:"text",value:je.domain,onChange:y=>Je(R=>({...R,domain:y.target.value})),placeholder:"e.g., python, frontend"})]}),s.jsxs("div",{className:"mem-inline-form-row",children:[s.jsx("label",{children:"Entity"}),s.jsx("input",{type:"text",value:je.entity,onChange:y=>Je(R=>({...R,entity:y.target.value})),placeholder:"e.g., person:sarah_chen"})]}),s.jsxs("div",{className:"mem-inline-form-row",children:[s.jsx("label",{children:"Due At"}),s.jsx("input",{type:"text",value:je.due_at,onChange:y=>Je(R=>({...R,due_at:y.target.value})),placeholder:"ISO 8601 (e.g., 2026-03-25T09:00:00-07:00)"})]}),s.jsxs("div",{className:"mem-inline-form-row",children:[s.jsx("label",{children:"Sensitive"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12},children:[s.jsx("input",{type:"checkbox",checked:je.sensitive,onChange:y=>Je(R=>({...R,sensitive:y.target.checked}))}),"Mark as sensitive (excluded from system prompt)"]})]}),s.jsxs("div",{className:"mem-inline-form-actions",children:[s.jsx("button",{className:"btn-secondary",onClick:()=>{Ae(!1),ut(null)},children:"Cancel"}),s.jsx("button",{className:"btn-primary",onClick:$e?Jx:Xx,style:{padding:"8px 20px",fontSize:13},children:$e?"Update":"Save"})]})]}),l&&l.items.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{className:"mem-knowledge-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsxs("th",{onClick:()=>gs("category"),className:B==="category"?"sorted":"",children:["Category",ys("category")]}),s.jsx("th",{children:"Content"}),s.jsxs("th",{onClick:()=>gs("context"),className:B==="context"?"sorted":"",children:["Context",ys("context")]}),s.jsx("th",{children:"Entity"}),s.jsxs("th",{onClick:()=>gs("confidence"),className:B==="confidence"?"sorted":"",children:["Confidence",ys("confidence")]}),s.jsx("th",{children:"Source"}),s.jsxs("th",{onClick:()=>gs("updated_at"),className:B==="updated_at"?"sorted":"",children:["Updated",ys("updated_at")]}),s.jsxs("th",{onClick:()=>gs("created_at"),className:B==="created_at"?"sorted":"",children:["Created",ys("created_at")]}),s.jsx("th",{children:"Due"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:l.items.map(y=>{const R=M===y.id,se=y.has_embedding;return s.jsxs(Gi.Fragment,{children:[s.jsxs("tr",{className:`${y.superseded_by?"mem-superseded-row":""} ${R?"mem-expanded-row":""}`,onClick:()=>N(R?null:y.id),onKeyDown:me=>{(me.key==="Enter"||me.key===" ")&&(me.preventDefault(),N(R?null:y.id))},tabIndex:0,role:"row","aria-expanded":R,style:{cursor:"pointer"},children:[s.jsx("td",{children:s.jsx("span",{className:`mem-cat-badge ${y.category}`,children:y.category})}),s.jsx("td",{children:s.jsxs("div",{className:"mem-content-cell",title:y.content,children:[se!==void 0&&s.jsx("span",{className:`mem-embed-dot ${se?"embedded":"missing"}`,title:se?"Embedded":"Embedding missing",children:s.jsx(Gk,{size:6,fill:"currentColor"})}),y.sensitive&&s.jsx("span",{className:"mem-sensitive-badge",title:"Sensitive",children:s.jsx(Cs,{size:11})}),s.jsx("span",{className:y.sensitive&&!Vr.has(y.id)?"mem-sensitive-blur":y.superseded_by?"mem-superseded-text":"",onClick:me=>{y.sensitive&&(me.stopPropagation(),os(Fe=>{const xr=new Set(Fe);return xr.has(y.id)?xr.delete(y.id):xr.add(y.id),xr}))},children:y.content})]})}),s.jsx("td",{children:s.jsx("span",{className:"mem-date-cell",children:y.context})}),s.jsx("td",{children:y.entity?s.jsx("span",{className:"mem-entity-link",onClick:me=>{me.stopPropagation(),P(y.entity),_e(0)},title:`Filter by ${y.entity}`,children:y.entity}):s.jsx("span",{className:"mem-date-cell",children:"—"})}),s.jsx("td",{children:s.jsxs("div",{className:"mem-confidence",children:[s.jsx("div",{className:"mem-confidence-bar",children:s.jsx("div",{className:`mem-confidence-fill ${pT(y.confidence)}`,style:{width:`${y.confidence*100}%`}})}),y.confidence.toFixed(2)]})}),s.jsx("td",{children:s.jsx("span",{className:"mem-date-cell",children:y.source||"—"})}),s.jsx("td",{children:s.jsx("span",{className:"mem-date-cell",title:Nn(y.updated_at),children:jr(y.updated_at)})}),s.jsx("td",{children:s.jsx("span",{className:"mem-date-cell",title:Nn(y.created_at),children:jr(y.created_at)})}),s.jsx("td",{children:y.due_at?s.jsx("span",{className:`mem-due-badge ${Bh(y.due_at)?"overdue":"upcoming"}`,title:Nn(y.due_at),children:jr(y.due_at)}):s.jsx("span",{className:"mem-due-badge none",children:"—"})}),s.jsx("td",{children:s.jsxs("div",{className:"mem-row-actions",onClick:me=>me.stopPropagation(),children:[s.jsx("button",{className:"mem-row-action-btn",onClick:()=>tv(y),title:"Edit",children:s.jsx(mw,{size:13})}),s.jsx("button",{className:"mem-row-action-btn",onClick:()=>ev(y),title:y.sensitive?"Unmark sensitive":"Mark sensitive",children:y.sensitive?s.jsx(gw,{size:13}):s.jsx(Cs,{size:13})}),s.jsx("button",{className:"mem-row-action-btn",onClick:()=>nv(y.id),title:"Copy ID",children:s.jsx(jl,{size:13})}),s.jsx("button",{className:"mem-row-action-btn delete",onClick:()=>Zx(y.id),title:"Delete",children:s.jsx(ci,{size:13})})]})})]}),R&&s.jsx("tr",{className:"mem-detail-row",children:s.jsx("td",{colSpan:10,children:s.jsxs("div",{className:"mem-detail-panel",children:[s.jsxs("div",{className:"mem-detail-grid",children:[s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"ID"}),s.jsx("span",{className:"mem-detail-value",children:y.id})]}),s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Domain"}),s.jsx("span",{className:"mem-detail-value",children:y.domain||"—"})]}),s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Source"}),s.jsx("span",{className:"mem-detail-value",children:y.source||"—"})]}),s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Use Count"}),s.jsx("span",{className:"mem-detail-value",children:y.use_count??0})]}),s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Created"}),s.jsx("span",{className:"mem-detail-value",children:Nn(y.created_at)})]}),s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Updated"}),s.jsx("span",{className:"mem-detail-value",children:Nn(y.updated_at)})]}),s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Last Used"}),s.jsx("span",{className:"mem-detail-value",children:Nn(y.last_used)})]}),s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Reminded At"}),s.jsx("span",{className:"mem-detail-value",children:Nn(y.reminded_at)})]}),y.superseded_by&&s.jsxs("div",{className:"mem-detail-field",children:[s.jsx("span",{className:"mem-detail-label",children:"Superseded By"}),s.jsx("span",{className:"mem-detail-value mem-detail-chain",children:y.superseded_by})]}),y.metadata&&s.jsxs("div",{className:"mem-detail-field mem-detail-full",children:[s.jsx("span",{className:"mem-detail-label",children:"Metadata"}),s.jsx("span",{className:"mem-detail-value",children:typeof y.metadata=="object"?JSON.stringify(y.metadata,null,2):y.metadata})]})]}),s.jsxs("div",{className:"mem-detail-content-full",children:[s.jsx("span",{className:"mem-detail-label",children:"Full Content"}),s.jsx("div",{className:"mem-detail-content-text",children:y.content})]})]})})})]},y.id)})})]})}),s.jsxs("div",{className:"mem-pagination",children:[s.jsxs("span",{children:[ae+1,"–",Math.min(ae+Ge,l.total)," of ",l.total]}),s.jsxs("div",{className:"mem-pagination-btns",children:[s.jsx("button",{className:"mem-page-btn",disabled:ae===0,onClick:()=>_e(Math.max(0,ae-Ge)),children:s.jsx(Wk,{size:14})}),s.jsx("button",{className:"mem-page-btn",disabled:ae+Ge>=l.total,onClick:()=>_e(ae+Ge),children:s.jsx(ss,{size:14})})]})]})]}):s.jsxs("div",{className:"mem-empty",children:[s.jsx("div",{className:"mem-empty-icon",children:s.jsx(Jr,{size:28})}),s.jsx("p",{children:b||ie.length>0||xe||T?"No matching memories":"No memories stored yet"})]})]}),s.jsxs("div",{className:"mem-two-col",children:[s.jsxs("div",{className:"mem-section",children:[s.jsxs("div",{className:"mem-section-title",children:[s.jsx(mu,{size:14})," Tool Performance"]}),o.length>0?s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{className:"mem-tool-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Tool"}),s.jsx("th",{children:"Calls"}),s.jsx("th",{children:"Success"}),s.jsx("th",{children:"Avg Time"}),s.jsx("th",{children:"Last Used"}),s.jsx("th",{children:"Last Error"})]})}),s.jsx("tbody",{children:o.map(y=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("span",{className:"mem-tool-name",children:y.tool_name})}),s.jsx("td",{children:y.total_calls}),s.jsx("td",{children:s.jsxs("div",{className:"mem-confidence",children:[s.jsx("div",{className:"mem-confidence-bar",style:{width:40},children:s.jsx("div",{className:`mem-confidence-fill ${Hh(y.success_rate)}`,style:{width:`${y.success_rate*100}%`}})}),s.jsxs("span",{className:`mem-success-rate ${Hh(y.success_rate)}`,children:[Math.round(y.success_rate*100),"%"]})]})}),s.jsx("td",{children:hT(y.avg_duration_ms)}),s.jsx("td",{children:s.jsx("span",{className:"mem-date-cell",title:Nn(y.last_used),children:jr(y.last_used)})}),s.jsx("td",{children:s.jsx("span",{className:"mem-tool-error",title:y.last_error||"",children:y.last_error||"—"})})]},y.tool_name))})]})}):s.jsxs("div",{className:"mem-empty",children:[s.jsx("div",{className:"mem-empty-icon",children:s.jsx(mu,{size:28})}),s.jsx("p",{children:"No tool calls recorded yet"})]})]}),s.jsxs("div",{className:"mem-section",children:[s.jsxs("div",{className:"mem-section-title",children:[s.jsx(Wa,{size:14})," Upcoming & Overdue"]}),f.length>0?s.jsx("div",{className:"mem-temporal-list",children:f.map(y=>{const R=Bh(y.due_at);return s.jsxs("div",{className:`mem-temporal-item ${R?"overdue":"upcoming"}`,children:[s.jsx("span",{className:"mem-temporal-icon",children:R?s.jsx(pn,{size:16}):s.jsx(Wa,{size:16})}),s.jsxs("div",{className:"mem-temporal-content",children:[s.jsx("div",{className:"mem-temporal-text",children:y.content}),s.jsxs("div",{className:"mem-temporal-date",children:[R?"OVERDUE":"Due",": ",jr(y.due_at),y.context!=="global"&&` · ${y.context}`]})]})]},y.id)})}):s.jsxs("div",{className:"mem-empty",children:[s.jsx("div",{className:"mem-empty-icon",children:s.jsx(wi,{size:28})}),s.jsx("p",{children:"Nothing upcoming or overdue"})]})]})]}),s.jsxs("div",{className:"mem-section",children:[s.jsxs("div",{className:"mem-section-title",children:[s.jsx(fu,{size:14})," Conversation History"]}),s.jsxs("div",{className:"mem-conv-search",children:[s.jsx(Fn,{size:13,className:"search-icon"}),s.jsx("input",{type:"text",placeholder:"Search conversations...",value:L,onChange:y=>rv(y.target.value),"aria-label":"Search conversations"}),L&&s.jsx("button",{className:"mem-search-clear",onClick:()=>{F(""),ue(null)},"aria-label":"Clear search",children:s.jsx(tt,{size:12})})]}),Y!==null?Y.length>0?s.jsx("div",{className:"mem-conv-list",children:Y.map(y=>s.jsxs("div",{className:"mem-conv-item",onClick:()=>Xd(y.session_id),children:[s.jsxs("div",{className:"mem-conv-info",children:[s.jsxs("div",{className:"mem-conv-session-id",children:[s.jsx("span",{className:`mem-conv-turn-role ${y.role}`,children:y.role})," ",y.session_id.slice(0,8),"..."]}),s.jsx("div",{className:"mem-conv-preview",children:y.content})]}),s.jsx("div",{className:"mem-conv-meta",children:s.jsx("span",{children:jr(y.timestamp)})})]},y.id))}):s.jsx("div",{className:"mem-empty",children:s.jsxs("p",{children:["No conversations match “",L,"”"]})}):u.length>0?s.jsx("div",{className:"mem-conv-list",children:u.map(y=>s.jsxs("div",{className:"mem-conv-item",onClick:()=>Xd(y.session_id),children:[s.jsxs("div",{className:"mem-conv-info",children:[s.jsxs("div",{className:"mem-conv-session-id",children:[y.session_id.slice(0,8),"...",y.consolidated&&s.jsx("span",{className:"mem-consolidated-badge",title:"Consolidated",children:s.jsx(Em,{size:11})})]}),y.first_message&&s.jsx("div",{className:"mem-conv-preview",children:y.first_message})]}),s.jsxs("div",{className:"mem-conv-meta",children:[s.jsxs("span",{children:[y.turn_count," turns"]}),s.jsx("span",{children:jr(y.last_activity)})]})]},y.session_id))}):s.jsxs("div",{className:"mem-empty",children:[s.jsx("div",{className:"mem-empty-icon",children:s.jsx(fu,{size:28})}),s.jsx("p",{children:"No conversation history in memory"})]})]}),H&&s.jsxs("div",{className:"mem-conv-detail-overlay",children:[s.jsxs("div",{className:"mem-conv-detail-header",children:[s.jsxs("h4",{children:["Session: ",H.sessionId.slice(0,12),"..."]}),s.jsx("button",{className:"btn-icon",onClick:()=>le(null),children:s.jsx(tt,{size:16})})]}),s.jsxs("div",{className:"mem-conv-detail-body",children:[H.turns.map(y=>s.jsxs("div",{className:"mem-conv-turn",children:[s.jsxs("div",{className:"mem-conv-turn-header",children:[s.jsx("div",{className:`mem-conv-turn-role ${y.role}`,children:y.role}),s.jsx("span",{className:"mem-conv-turn-time",title:Nn(y.timestamp),children:jr(y.timestamp)})]}),s.jsx("div",{className:"mem-conv-turn-content",children:y.content})]},y.id)),H.turns.length===0&&s.jsx("div",{className:"mem-empty",children:"No turns found"})]})]})]}),s.jsxs("div",{className:"mem-section",children:[s.jsxs("div",{className:"mem-section-title",children:[s.jsx(Cs,{size:14})," Settings ",s.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#f59e0b",background:"rgba(245,158,11,0.15)",padding:"1px 6px",borderRadius:4,marginLeft:6,verticalAlign:"middle",letterSpacing:"0.5px"},children:"BETA"})]}),s.jsxs("div",{className:"mem-setting-row",children:[s.jsxs("div",{className:"mem-setting-info",children:[s.jsx("span",{className:"mem-setting-label",children:"Memory enabled"}),s.jsx("span",{className:"mem-setting-desc",children:"When disabled, no knowledge or conversation data is stored during any session (global incognito)."})]}),s.jsx("button",{className:`mem-toggle${$?" mem-toggle-on":""}`,disabled:pt,onClick:async()=>{if(!$){xn("memory");return}qe(!0);try{const y=await vi({memory_enabled:!1});Q(y.memory_enabled)}catch(y){E.system.warn("Failed to disable memory",y)}finally{qe(!1)}},"aria-pressed":$,"aria-label":`Memory is ${$?"enabled":"disabled"}`,children:$?"On":"Off"})]}),bt&&(()=>{const R={memory:{title:"Enable Agent Memory?",description:"Agent memory is a work-in-progress. By enabling it:",bullets:[["Conversations and facts are stored ","locally on this machine"],["Stored data ","may be lost"," during updates"],["You can disable it at any time from this settings panel"]],buttonLabel:"Enable Memory",onConfirm:async()=>{const se=await vi({memory_enabled:!0});Q(se.memory_enabled),ee("Memory enabled","info")}},mcp:{title:"Enable MCP Memory Access?",description:"This exposes memory data to external MCP clients:",bullets:[["MCP clients can ","read your stored memories"," (read-only)"],["Requires an ","MCP server restart"," to take effect"],["Intended for debugging and troubleshooting only"]],buttonLabel:"Enable MCP Access",onConfirm:async()=>{const se=await vi({mcp_memory_enabled:!0});ve(se.mcp_memory_enabled),ee("MCP memory access enabled","info")}},discovery:{title:"Enable System Discovery?",description:"This scans your system to personalize responses:",bullets:[["Collects ","hardware, software, and environment"," information"],["Scans files, git repos, browser history, and SSH config"],["All data stays ","local on this machine"]],buttonLabel:"Enable Discovery",onConfirm:async()=>{var me;const se=await vi({system_discovery_consent:!0});if(wt(se.system_discovery_consent),se.system_context_error)ee(`System discovery enabled but scan failed: ${se.system_context_error}`,"error");else{const Fe=((me=se.system_context_refresh)==null?void 0:me.stored)??0;ee(`System discovery enabled — ${Fe} system facts collected`,"info")}Rt()}}}[bt];return s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.6)",zIndex:9998,backdropFilter:"blur(4px)"},onClick:()=>xn(null)}),s.jsxs("div",{style:{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:9999,background:"#1a1a2e",border:"1px solid #333",borderRadius:12,padding:"28px 32px",maxWidth:420,width:"90vw",boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:16},children:[s.jsx("span",{style:{fontSize:11,fontWeight:700,color:"#f59e0b",background:"rgba(245,158,11,0.15)",padding:"3px 10px",borderRadius:4,letterSpacing:"0.5px"},children:"BETA"}),s.jsx("span",{style:{fontSize:16,fontWeight:600,color:"#e0e0e0"},children:R.title})]}),s.jsx("p",{style:{fontSize:13,lineHeight:1.6,color:"#999",margin:"0 0 8px"},children:R.description}),s.jsx("ul",{style:{fontSize:13,lineHeight:1.7,color:"#999",margin:"0 0 24px",paddingLeft:20},children:R.bullets.map((se,me)=>s.jsx("li",{children:se.map((Fe,xr)=>xr%2===1?s.jsx("strong",{style:{color:"#ccc"},children:Fe},xr):s.jsx("span",{children:Fe},xr))},me))}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:10},children:[s.jsx("button",{className:"btn-secondary",onClick:()=>xn(null),style:{padding:"8px 20px",fontSize:13,borderRadius:6},children:"Cancel"}),s.jsx("button",{disabled:pt,onClick:async()=>{qe(!0);try{await R.onConfirm()}catch(se){E.system.warn("Failed to update setting",se),ee("Failed to update setting. Please try again.","error")}finally{qe(!1),xn(null)}},style:{padding:"8px 24px",fontSize:13,fontWeight:600,borderRadius:6,border:"none",cursor:"pointer",background:"linear-gradient(135deg, #f59e0b, #d97706)",color:"#000"},children:R.buttonLabel})]})]})]})})(),s.jsxs("div",{className:"mem-setting-row",children:[s.jsxs("div",{className:"mem-setting-info",children:[s.jsx("span",{className:"mem-setting-label",children:"MCP memory access"}),s.jsx("span",{className:"mem-setting-desc",children:"Expose read-only memory tools to MCP clients (for debug/troubleshooting). Requires MCP server restart."})]}),s.jsx("button",{className:`mem-toggle${de?" mem-toggle-on":""}`,disabled:pt,onClick:async()=>{if(!de){xn("mcp");return}qe(!0);try{const y=await vi({mcp_memory_enabled:!1});ve(y.mcp_memory_enabled)}catch(y){E.system.warn("Failed to update memory settings",y)}finally{qe(!1)}},"aria-label":"Toggle MCP memory access","aria-pressed":de,children:de?"On":"Off"})]}),s.jsxs("div",{className:"mem-setting-row",children:[s.jsxs("div",{className:"mem-setting-info",children:[s.jsx("span",{className:"mem-setting-label",children:"System discovery"}),s.jsx("span",{className:"mem-setting-desc",children:"Allow GAIA to scan your system for hardware, software, and environment information to personalize responses."})]}),s.jsx("button",{className:`mem-toggle${be?" mem-toggle-on":""}`,disabled:pt,onClick:async()=>{if(!be){xn("discovery");return}qe(!0);try{const y=await vi({system_discovery_consent:!1});wt(y.system_discovery_consent)}catch(y){E.system.warn("Failed to update system discovery setting",y)}finally{qe(!1)}},"aria-label":"Toggle system discovery","aria-pressed":be,children:be?"On":"Off"})]}),s.jsxs("div",{className:"mem-setting-row mem-setting-row-danger",children:[s.jsxs("div",{className:"mem-setting-info",children:[s.jsx("span",{className:"mem-setting-label",children:"Re-initialize memory"}),s.jsx("span",{className:"mem-setting-desc",children:"Wipe all memories, conversations, and tool logs, then re-collect system information. This cannot be undone."})]}),rt?s.jsxs("div",{className:"mem-delete-confirm",children:[s.jsx("span",{className:"mem-delete-confirm-label",children:"Are you sure?"}),s.jsx("button",{className:"mem-btn-danger",disabled:pt,onClick:async()=>{qe(!0);try{const y=await sT();ee(`Re-initialized: cleared ${y.cleared.knowledge} entries, restored ${y.system_context.stored} system facts`,"info"),Rt()}catch(y){E.system.warn("Failed to reinitialize memory",y),ee("Failed to re-initialize memory","error")}finally{qe(!1),Mt(!1)}},children:"Yes, re-initialize"}),s.jsx("button",{className:"btn-secondary",onClick:()=>Mt(!1),style:{padding:"6px 14px",fontSize:12},children:"Cancel"})]}):s.jsx("button",{className:"mem-btn-danger",disabled:pt,onClick:()=>Mt(!0),children:"Re-initialize"})]}),s.jsxs("div",{className:"mem-setting-row mem-setting-row-danger",children:[s.jsxs("div",{className:"mem-setting-info",children:[s.jsx("span",{className:"mem-setting-label",children:"Delete all memories"}),s.jsx("span",{className:"mem-setting-desc",children:"Permanently wipe all knowledge entries, conversation history, and tool logs. This cannot be undone."})]}),Pt?s.jsxs("div",{className:"mem-delete-confirm",children:[s.jsx("span",{className:"mem-delete-confirm-label",children:"Are you sure?"}),s.jsx("button",{className:"mem-btn-danger",disabled:pt,onClick:async()=>{qe(!0);try{const y=await iT();ee(`Deleted ${y.knowledge} knowledge entries, ${y.conversations} conversations`,"info"),Rt()}catch(y){E.system.warn("Failed to clear memory",y),ee("Failed to clear memory","error")}finally{qe(!1),Xt(!1)}},children:"Yes, delete all"}),s.jsx("button",{className:"btn-secondary",onClick:()=>Xt(!1),style:{padding:"6px 14px",fontSize:12},children:"Cancel"})]}):s.jsx("button",{className:"mem-btn-danger",disabled:pt,onClick:()=>Xt(!0),children:"Delete All"})]})]}),t&&s.jsxs("div",{className:"mem-db-footer",children:[s.jsxs("span",{children:["Database: ",mT(t.db_size_bytes),((mf=t.knowledge)==null?void 0:mf.avg_confidence)!=null&&` · Avg confidence: ${t.knowledge.avg_confidence.toFixed(2)}`]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[((hf=t.knowledge)==null?void 0:hf.entity_count)!=null&&t.knowledge.entity_count>0&&s.jsxs("span",{children:[t.knowledge.entity_count," entities"]}),((pf=t.knowledge)==null?void 0:pf.sensitive_count)!=null&&t.knowledge.sensitive_count>0&&s.jsxs("span",{children:[s.jsx(Cs,{size:10})," ",t.knowledge.sensitive_count," sensitive"]})]})]})]})}),cn==="profile"&&s.jsxs("div",{className:"mem-profile-grid",children:[s.jsxs("div",{className:"mem-profile-card",children:[s.jsxs("div",{className:"mem-profile-card-title",children:[s.jsx(uy,{size:16})," System Discovery"]}),s.jsx("p",{className:"mem-profile-desc",children:"Scan your system to discover apps, projects, and usage patterns."}),s.jsx("button",{className:"btn-primary mem-profile-run-btn",disabled:st==="running"||st==="saving",onClick:uv,children:st==="running"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mem-spinner-sm"})," Running..."]}):"Run Discovery"}),us.length>0&&s.jsx("div",{className:"mem-log",ref:bn,children:us.map((y,R)=>s.jsx("div",{className:`mem-log-line ${y.kind}`,children:y.text},R))}),(st==="review"||st==="saving"||st==="done")&&Vn.length>0&&s.jsxs("div",{className:"mem-review-section",children:[s.jsx("div",{className:"mem-review-header",children:"Review & Save"}),s.jsx("div",{className:"mem-review-list",children:Vn.map((y,R)=>s.jsxs("label",{className:"mem-review-item",children:[s.jsx("input",{type:"checkbox",checked:y._checked,disabled:st==="saving"||st==="done",onChange:()=>{dr(se=>se.map((me,Fe)=>Fe===R?{...me,_checked:!me._checked}:me))}}),s.jsx("span",{className:"mem-review-content",children:y.content}),s.jsx("span",{className:"mem-source-badge",children:y._source_name||y.category}),s.jsxs("span",{className:"mem-conf-badge",children:[Math.round(y.confidence*100),"%"]})]},R))}),s.jsxs("div",{className:"mem-review-actions",children:[s.jsx("button",{className:"btn-primary",disabled:st==="saving"||st==="done"||Vn.filter(y=>y._checked).length===0,onClick:dv,children:st==="saving"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mem-spinner-sm"})," Saving..."]}):`Save Selected (${Vn.filter(y=>y._checked).length})`}),s.jsxs("span",{className:"mem-review-select-links",children:[s.jsx("a",{onClick:()=>dr(y=>y.map(R=>({...R,_checked:!0}))),children:"Select All"})," / ",s.jsx("a",{onClick:()=>dr(y=>y.map(R=>({...R,_checked:!1}))),children:"None"})]})]})]}),st==="done"&&El!==null&&s.jsxs("div",{className:"mem-profile-success",children:[s.jsx(wi,{size:14})," Saved ",El," items to memory"]}),st==="review"&&Vn.length===0&&s.jsx("div",{className:"mem-profile-empty",children:"No items discovered."})]}),s.jsxs("div",{className:"mem-profile-card",children:[s.jsxs("div",{className:"mem-profile-card-title",children:[s.jsx(yw,{size:16})," AI Profile Inference"]}),s.jsx("p",{className:"mem-profile-desc",children:"Use the local LLM to generate profile insights from your data."}),s.jsx("p",{className:"mem-profile-note",children:"Requires Lemonade Server running."}),s.jsxs("label",{className:"mem-profile-checkbox",children:[s.jsx("input",{type:"checkbox",checked:fs,onChange:y=>_o(y.target.checked),disabled:jt==="running"||jt==="saving"}),"Include browser history"]}),s.jsx("button",{className:"btn-primary mem-profile-run-btn",disabled:jt==="running"||jt==="saving",onClick:fv,children:jt==="running"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mem-spinner-sm"})," Running..."]}):"Run Inference"}),ds.length>0&&s.jsx("div",{className:"mem-log",ref:pi,children:ds.map((y,R)=>s.jsx("div",{className:`mem-log-line ${y.kind}`,children:y.text},R))}),(jt==="review"||jt==="saving"||jt==="done")&&Wn.length>0&&s.jsxs("div",{className:"mem-review-section",children:[s.jsx("div",{className:"mem-review-header",children:"Review & Save"}),s.jsx("div",{className:"mem-review-list",children:Wn.map((y,R)=>s.jsxs("label",{className:"mem-review-item",children:[s.jsx("input",{type:"checkbox",checked:y._checked,disabled:jt==="saving"||jt==="done",onChange:()=>{hr(se=>se.map((me,Fe)=>Fe===R?{...me,_checked:!me._checked}:me))}}),s.jsx("span",{className:"mem-review-content",children:y.content}),s.jsx("span",{className:`mem-domain-badge ${xT[y.domain]||"gray"}`,children:y.domain}),s.jsxs("span",{className:"mem-conf-badge",children:[Math.round(y.confidence*100),"%"]})]},R))}),s.jsxs("div",{className:"mem-review-actions",children:[s.jsx("button",{className:"btn-primary",disabled:jt==="saving"||jt==="done"||Wn.filter(y=>y._checked).length===0,onClick:mv,children:jt==="saving"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mem-spinner-sm"})," Saving..."]}):`Save Selected (${Wn.filter(y=>y._checked).length})`}),s.jsxs("span",{className:"mem-review-select-links",children:[s.jsx("a",{onClick:()=>hr(y=>y.map(R=>({...R,_checked:!0}))),children:"Select All"})," / ",s.jsx("a",{onClick:()=>hr(y=>y.map(R=>({...R,_checked:!1}))),children:"None"})]})]})]}),jt==="done"&&zl!==null&&s.jsxs("div",{className:"mem-profile-success",children:[s.jsx(wi,{size:14})," Saved ",zl," insights to memory"]}),jt==="review"&&Wn.length===0&&s.jsx("div",{className:"mem-profile-empty",children:"No insights generated."})]})]}),cn==="goals"&&s.jsxs("div",{className:"mem-goals-tab",children:[s.jsx("div",{className:"mem-goals-stats-row",children:["queued","in_progress","completed","failed"].map(y=>s.jsxs("div",{className:`mem-goals-stat-pill mem-goal-status-${y.replace("_","-")}`,children:[s.jsx("span",{className:"mem-goals-stat-n",children:(vn==null?void 0:vn.goals[y])??0}),s.jsx("span",{className:"mem-goals-stat-label",children:y.replace("_"," ")})]},y))}),Zt.filter(y=>y.status==="pending_approval").length>0&&s.jsxs("div",{className:"mem-goals-approval-banner",children:[s.jsxs("div",{className:"mem-goals-approval-title",children:[s.jsx(Ws,{size:14})," Agent suggested ",Zt.filter(y=>y.status==="pending_approval").length," goal(s) — review before execution"]}),Zt.filter(y=>y.status==="pending_approval").map(y=>s.jsxs("div",{className:"mem-goals-approval-item",children:[s.jsxs("div",{className:"mem-goals-approval-text",children:[s.jsx("strong",{children:y.title}),s.jsx("span",{children:y.description})]}),s.jsxs("div",{className:"mem-goals-approval-actions",children:[s.jsx("button",{className:"btn-danger-sm",onClick:async()=>{await uT(y.id),yr()},children:"Reject"}),s.jsx("button",{className:"btn-secondary",onClick:async()=>{await cT(y.id),yr()},children:"Accept"})]})]},y.id))]}),s.jsx("div",{className:"mem-goals-toolbar",children:s.jsxs("button",{className:"btn-primary",onClick:()=>ar(y=>!y),children:[s.jsx(hl,{size:14})," New Goal"]})}),_l&&s.jsxs("div",{className:"mem-goals-add-form",children:[s.jsx("input",{className:"mem-input",placeholder:"Goal title",value:or.title,onChange:y=>cr(R=>({...R,title:y.target.value}))}),s.jsx("textarea",{className:"mem-input",placeholder:"Description — what should the agent work toward?",rows:2,value:or.description,onChange:y=>cr(R=>({...R,description:y.target.value}))}),s.jsxs("div",{className:"mem-goals-form-row",children:[s.jsxs("select",{className:"mem-select",value:or.priority,onChange:y=>cr(R=>({...R,priority:y.target.value})),children:[s.jsx("option",{value:"low",children:"Low priority"}),s.jsx("option",{value:"medium",children:"Medium priority"}),s.jsx("option",{value:"high",children:"High priority"})]}),s.jsx("button",{className:"btn-primary",onClick:async()=>{or.title.trim()&&(await oT(or),cr({title:"",description:"",priority:"medium"}),ar(!1),yr())},children:"Create"}),s.jsx("button",{className:"btn-secondary",onClick:()=>ar(!1),children:"Cancel"})]})]}),kn?s.jsxs("div",{className:"mem-loading",children:[s.jsx("div",{className:"mem-spinner"})," Loading goals..."]}):Zt.filter(y=>y.status!=="pending_approval"&&y.status!=="rejected").length===0?s.jsxs("div",{className:"mem-empty",children:[s.jsx("div",{className:"mem-empty-icon",children:s.jsx(zm,{size:32})}),s.jsx("p",{children:"No goals yet. Create one or let the agent suggest goals in autonomous mode."})]}):s.jsx("div",{className:"mem-goals-list",children:Zt.filter(y=>y.status!=="pending_approval"&&y.status!=="rejected").map(y=>s.jsxs("div",{className:`mem-goal-card mem-goal-status-${y.status.replace("_","-")}`,children:[s.jsxs("div",{className:"mem-goal-header",onClick:()=>lr(R=>R===y.id?null:y.id),children:[s.jsxs("div",{className:"mem-goal-header-left",children:[s.jsx("span",{className:`mem-goal-status-dot status-${y.status.replace("_","-")}`}),s.jsx("span",{className:"mem-goal-title",children:y.title}),s.jsx("span",{className:`mem-goal-priority mem-priority-${y.priority}`,children:y.priority}),y.source!=="user"&&s.jsxs("span",{className:"mem-goal-source-badge",children:[s.jsx(Ws,{size:10})," ",y.source.replace("_"," ")]})]}),s.jsxs("div",{className:"mem-goal-header-right",children:[s.jsxs("span",{className:"mem-goal-task-count",children:[s.jsx(py,{size:12}),y.tasks.filter(R=>R.status==="completed").length,"/",y.tasks.length]}),y.status==="queued"&&s.jsx("button",{className:"mem-goal-action-btn mem-goal-cancel-btn",onClick:async R=>{R.stopPropagation(),await dT(y.id),yr()},children:"Cancel"}),s.jsx("button",{className:"mem-goal-action-btn mem-goal-delete-btn",onClick:async R=>{R.stopPropagation(),confirm(`Delete goal "${y.title}"?`)&&(await fT(y.id),yr())},children:s.jsx(ci,{size:12})}),s.jsx(ai,{size:14,className:Hn===y.id?"mem-chevron-open":""})]})]}),Hn===y.id&&s.jsxs("div",{className:"mem-goal-body",children:[y.description&&s.jsx("p",{className:"mem-goal-desc",children:y.description}),y.progress_notes&&s.jsx("p",{className:"mem-goal-progress",children:y.progress_notes}),y.tasks.length>0?s.jsx("div",{className:"mem-task-list",children:y.tasks.map(R=>s.jsxs("div",{className:`mem-task-row mem-task-status-${R.status}`,children:[s.jsx("span",{className:`mem-task-dot status-${R.status}`}),s.jsx("span",{className:"mem-task-desc",children:R.description}),s.jsx("span",{className:"mem-task-status-label",children:R.status}),R.result&&s.jsx("span",{className:"mem-task-result",children:R.result})]},R.id))}):s.jsx("p",{className:"mem-goal-no-tasks",children:"No tasks yet — the agent will break this down when it starts."})]})]},y.id))})]})]}),U.length>0&&s.jsx("div",{className:"mem-toast-container","aria-live":"polite",children:U.map(y=>s.jsxs("div",{className:`mem-toast mem-toast-${y.type}`,role:"status",children:[y.type==="success"&&s.jsx(wi,{size:14}),y.type==="error"&&s.jsx(pn,{size:14}),y.type==="info"&&s.jsx(Jr,{size:14}),s.jsx("span",{children:y.text})]},y.id))})]})}const Ys=32768,Qd="Qwen3.5-35B-A3B-GGUF",kT=3e5,wT=18e5,bT=1e4;function Kx(e,t){const[n,r]=p.useState(!1),[i,l]=p.useState(!1),a=p.useRef(null),o=p.useRef(null),c=p.useRef(null),u=p.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null),o.current&&(clearTimeout(o.current),o.current=null),c.current&&(clearInterval(c.current),c.current=null)},[]);p.useEffect(()=>u,[u]);const d=p.useCallback((g,v)=>{c.current&&clearInterval(c.current),c.current=setInterval(async()=>{var w,x;try{const k=await Sd();v==="load"?((w=k.model_loaded)==null?void 0:w.toLowerCase())===g.toLowerCase()&&(r(!1),a.current&&(clearTimeout(a.current),a.current=null),c.current&&(clearInterval(c.current),c.current=null)):(k.model_downloaded===!0||((x=k.model_loaded)==null?void 0:x.toLowerCase())===g.toLowerCase())&&(l(!1),o.current&&(clearTimeout(o.current),o.current=null),c.current&&(clearInterval(c.current),c.current=null))}catch{}},bT)},[]),f=e??Qd,h=p.useCallback(async(g,v)=>{const w=g??f,x=v??Ys;r(!0);try{await r0(w,x),E.system.info(`Load model triggered: ${w} (ctx=${x})`),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>r(!1),kT),d(w,"load")}catch(k){E.system.error("Failed to trigger model load",k),r(!1)}},[f,t,d]),m=p.useCallback(async(g=!1,v)=>{const w=v??f;l(!0);try{await i0(w,g),E.system.info(`Download model triggered: ${w} (force=${g})`),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>l(!1),wT),d(w,"download")}catch(x){E.system.error("Failed to trigger model download",x),l(!1)}},[f,d]);return{isLoadingModel:n,isDownloadingModel:i,loadModel:h,downloadModel:m}}const Wh=jd();function jT(){const{agents:e,setAgents:t}=we(),[n,r]=p.useState({kind:"idle"}),i=p.useRef(null),l=p.useRef(null),a=p.useRef(null);p.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]),p.useEffect(()=>{var g;n.kind==="error"&&((g=a.current)==null||g.scrollIntoView({behavior:"smooth",block:"nearest"}))},[n]);const o=p.useCallback((g,v=5e3)=>{r(g),l.current&&clearTimeout(l.current),(g.kind==="success"||g.kind==="error")&&(l.current=setTimeout(()=>r({kind:"idle"}),v))},[]),c=p.useCallback(async()=>{try{const g=await Nd();t(g.agents||[])}catch(g){E.api.warn("Failed to refresh agents after import",g)}},[t]),u=e.filter(g=>g.source!=="builtin"),d=p.useCallback(async()=>{if(window.confirm(`Exported bundle contains your agent source files as-is. Any API keys, tokens, or credentials in agent.py will be included in the bundle. Review before sharing.
@@ -546,5 +546,5 @@ Continue?`)){o({kind:"working",message:"Exporting…"});try{const v=await fetch(
546
546
 
547
547
  `+x+`
548
548
 
549
- Import?`)){o({kind:"working",message:"Uploading…"});try{const z=new FormData;z.append("bundle",v,v.name);const A=await fetch(`${Wh}/agents/import`,{method:"POST",headers:{"X-Gaia-UI":"1"},body:z});if(!A.ok){const N=await A.text().catch(()=>"");let U=N;try{U=JSON.parse(N).detail||N}catch{}throw new Error(U||`Import failed (HTTP ${A.status})`)}const _=await A.json(),D=_.imported||[],C=_.overwritten||[];await c();let M;if(D.length===0?M="No agents imported":(M=`Installed ${D.length} agent(s): ${D.join(", ")}`,C.length>0&&(M+=` (replaced: ${C.join(", ")})`)),_.requires_restart&&(M+=" — restart required for replaced agents to take full effect"),_.errors&&_.errors.length>0){const N=_.errors.map(U=>`${U.id}: ${U.error}`).join("; ");o({kind:"error",message:`${M}. Errors: ${N}`})}else o({kind:"success",message:M})}catch(z){console.error("Agent import failed:",z);const A=z instanceof Error?z.message:String(z);E.api.error("Agent import failed",z),o({kind:"error",message:`Import failed: ${A}`})}}},[o,c]),m=n.kind==="working";return s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Custom Agents"}),u.length===0?s.jsx("p",{className:"danger-warning",style:{marginBottom:12},children:"No custom agents installed yet. Import a bundle below to add one."}):s.jsx("div",{className:"status-grid",style:{marginBottom:12},children:u.map(g=>s.jsxs("div",{className:"status-row",children:[s.jsx("span",{className:"status-label",children:g.name}),s.jsxs("div",{className:"status-value-wrap",children:[s.jsx("span",{className:"status-value ok",children:g.id}),g.source&&g.source!=="builtin"&&s.jsx("span",{className:"status-hint",children:s.jsx("code",{children:g.source})})]})]},g.id))}),s.jsxs("div",{className:"setting-actions",style:{display:"flex",gap:8,flexWrap:"wrap"},children:[s.jsx("button",{className:"btn-model-save",onClick:d,disabled:m||u.length===0,title:u.length===0?"No custom agents to export":void 0,children:m&&n.message.startsWith("Export")?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Exporting…"]}):s.jsxs(s.Fragment,{children:[s.jsx(oi,{size:13,style:{verticalAlign:-2,marginRight:6}}),"Export All"]})}),s.jsx("button",{className:"btn-model-save",onClick:f,disabled:m,children:m&&n.message.startsWith("Upload")?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Uploading…"]}):s.jsxs(s.Fragment,{children:[s.jsx(pl,{size:13,style:{verticalAlign:-2,marginRight:6}}),"Import"]})}),s.jsx("input",{ref:i,type:"file",accept:".zip,application/zip",style:{display:"none"},onChange:h})]}),n.kind!=="idle"&&s.jsxs("div",{ref:a,className:"danger-warning",style:{marginTop:12,display:"flex",alignItems:"center",gap:8,color:n.kind==="error"?"var(--accent-gold)":"var(--text-secondary)"},role:"status",children:[n.kind==="working"&&s.jsx(mt,{size:14,className:"btn-spinner"}),n.kind==="success"&&s.jsx(nr,{size:14}),n.kind==="error"&&s.jsx(kt,{size:14}),s.jsx("span",{children:n.message})]})]})}async function ST(e){const t=await e.arrayBuffer(),n=new DataView(t),r=new Uint8Array(t),i=Math.min(t.byteLength,65557),l=t.byteLength-i;let a=-1;for(let d=t.byteLength-22;d>=l;d--)if(n.getUint32(d,!0)===101010256){a=d;break}if(a<0)return null;const o=n.getUint16(a+10,!0);let u=n.getUint32(a+16,!0);for(let d=0;d<o;d++){if(u+46>t.byteLength||n.getUint32(u,!0)!==33639248)return null;const f=n.getUint16(u+10,!0),h=n.getUint32(u+20,!0),m=n.getUint16(u+28,!0),g=n.getUint16(u+30,!0),v=n.getUint16(u+32,!0),w=n.getUint32(u+42,!0);if(new TextDecoder("utf-8").decode(r.subarray(u+46,u+46+m))==="bundle.json"){if(w+30>t.byteLength||n.getUint32(w,!0)!==67324752)return null;const k=n.getUint16(w+26,!0),j=n.getUint16(w+28,!0),z=w+30+k+j,A=z+h;if(A>t.byteLength)return null;const _=r.subarray(z,A);let D;if(f===0)D=new TextDecoder("utf-8").decode(_);else if(f===8){const N=new DecompressionStream("deflate-raw"),U=new Blob([_]).stream().pipeThrough(N),O=await new Response(U).arrayBuffer();D=new TextDecoder("utf-8").decode(O)}else return null;const C=JSON.parse(D),M=C==null?void 0:C.agent_ids;return Array.isArray(M)&&M.every(N=>typeof N=="string")?M:null}u+=46+m+g+v}return null}const Gh=E.api;function NT(e){switch(e){case"connector.configured":return"configured";case"connector.disconnected":return"disconnected";case"connection.revoked":return"disconnected";case"connector.oauth.completed":return"oauth_completed";case"connection.connected":return"oauth_completed";case"connector.oauth.error":return"oauth_error";case"connector.tested":return"tested";case"connector.enabled":return"enabled";case"connector.disabled":return"disabled";case"connector.grant.changed":return"grant_changed";default:return null}}function CT(e){const t=p.useRef(e);p.useEffect(()=>{t.current=e},[e]),p.useEffect(()=>{const n=`${jd()}/connectors/events`;let r=null,i=1e3,l=null,a=!1;const o=()=>{a||(r=new EventSource(n),r.onopen=()=>{i=1e3},r.onmessage=c=>{try{const u=JSON.parse(c.data),d=NT(u.type);if(d===null){Gh.debug("connectors-sse: ignoring event",u.type);return}const f=u.payload??{},h=f.connector_id??f.provider??null;t.current({connectorId:h,reason:d,payload:f})}catch(u){Gh.warn("connectors-sse: malformed event",u)}},r.onerror=()=>{r==null||r.close(),r=null,!a&&(l=setTimeout(o,i),i=Math.min(i*2,3e4))})};return o(),()=>{a=!0,l&&clearTimeout(l),r==null||r.close()}},[])}function _T(e){return e.type==="mcp_server"&&e.configured}function ET({connector:e,onChanged:t}){const[n,r]=p.useState(!1),[i,l]=p.useState(!1),[a,o]=p.useState(null),[c,u]=p.useState(null),d=p.useRef(null),f=p.useRef(null);if(p.useEffect(()=>{if(!n)return;const v=w=>{const x=w.target;d.current&&!d.current.contains(x)&&f.current&&!f.current.contains(x)&&r(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[n]),p.useEffect(()=>{if(!n)return;const v=w=>{w.key==="Escape"&&r(!1)};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[n]),p.useEffect(()=>{if(!n)return;const v=()=>{if(!d.current)return;const w=d.current.getBoundingClientRect();u({top:w.bottom+4,right:window.innerWidth-w.right})};return window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)}},[n]),!_T(e))return null;const h=v=>{v.stopPropagation(),v.preventDefault()},m=v=>{if(h(v),!n&&d.current){const w=d.current.getBoundingClientRect();u({top:w.bottom+4,right:window.innerWidth-w.right})}r(w=>!w)},g=async v=>{l(!0),o(null);try{await v(),r(!1),t()}catch(w){o(w instanceof Error?w.message:String(w))}finally{l(!1)}};return s.jsxs("div",{className:"connector-tile-menu",onClick:h,onKeyDown:h,children:[s.jsx("button",{ref:d,type:"button",className:"connector-tile-menu-trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":"Connector actions",onClick:m,disabled:i,children:s.jsx(ow,{size:14})}),n&&c&&s.jsxs("div",{ref:f,role:"menu",className:"connector-tile-menu-popup",style:{position:"fixed",top:c.top,right:c.right},children:[e.enabled?s.jsx("button",{role:"menuitem",type:"button",className:"connector-tile-menu-item",onClick:()=>void g(()=>Ty(e.id)),disabled:i,children:"Disable"}):s.jsx("button",{role:"menuitem",type:"button",className:"connector-tile-menu-item",onClick:()=>void g(()=>Ey(e.id)),disabled:i,children:"Enable"}),s.jsx("div",{className:"connector-tile-menu-divider"}),s.jsx("button",{role:"menuitem",type:"button",className:"connector-tile-menu-item connector-tile-menu-item--danger",onClick:()=>void g(()=>Cd(e.id)),disabled:i,children:"Disconnect"}),a&&s.jsx("div",{className:"connector-tile-menu-error",children:a})]})]})}const TT={"https://www.googleapis.com/auth/gmail.readonly":"Read emails","https://www.googleapis.com/auth/gmail.modify":"Organize emails (archive, label, trash)","https://www.googleapis.com/auth/gmail.send":"Send emails on your behalf","https://www.googleapis.com/auth/gmail.compose":"Compose emails","https://www.googleapis.com/auth/calendar.readonly":"View calendar events","https://www.googleapis.com/auth/calendar.events":"Create & respond to calendar events","https://www.googleapis.com/auth/drive.readonly":"Read Google Drive files","https://www.googleapis.com/auth/drive.file":"Manage Drive files created by this app","https://www.googleapis.com/auth/spreadsheets.readonly":"Read Google Sheets","https://www.googleapis.com/auth/spreadsheets":"Edit Google Sheets",openid:"Identify you",email:"See your email address",profile:"See your basic profile info"};function zT(e){return TT[e]??e.split(/[/.:]/).pop()??e}function LT(){const[e,t]=p.useState([]),[n,r]=p.useState([]),[i,l]=p.useState(!0),[a,o]=p.useState(null),[c,u]=p.useState(null),d=p.useCallback(async()=>{try{const[{connectors:m},{agent_mcps:g}]=await Promise.all([s0(),l0()]);t(m),r(g),o(null)}catch(m){o(m instanceof Error?m.message:String(m))}finally{l(!1)}},[]);p.useEffect(()=>{d()},[d]);const f=m=>u(g=>g===m?null:m),h=p.useCallback(async m=>{try{const g=await Ny(m);t(v=>v.map(w=>w.id===m?g:w))}catch{d()}},[d]);return CT(p.useCallback(m=>{m.connectorId?h(m.connectorId):d()},[h,d])),s.jsxs("section",{className:"settings-section connectors-section",children:[s.jsx("h4",{children:"Connectors"}),s.jsx("p",{className:"settings-help",children:"Connect external accounts and MCP servers so agents can use them on your behalf. Each agent must be granted scopes individually."}),a&&s.jsxs("div",{className:"error-banner",children:[s.jsx(kt,{size:14}),s.jsx("span",{children:a})]}),i?s.jsx("div",{className:"connectors-loading",children:s.jsx(mt,{size:16,className:"spin"})}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"connectors-list",children:e.map(m=>s.jsx(IT,{connector:m,expanded:c===m.id,onToggle:()=>f(m.id),onChanged:()=>void h(m.id)},m.id))}),n.length>0&&s.jsx(MT,{servers:n,expanded:c,onToggle:f})]})]})}function IT({connector:e,expanded:t,onToggle:n,onChanged:r}){const i=()=>e.configured?e.type==="mcp_server"&&e.enabled===!1?s.jsx("span",{className:"connector-status disabled",children:"Disabled"}):s.jsxs("span",{className:"connector-status ok",children:[s.jsx(nr,{size:12}),e.account_id??"Configured"]}):s.jsx("span",{className:"connector-status idle",children:"Not configured"});return s.jsxs("div",{className:`connector-tile${t?" connector-tile--open":""}`,children:[s.jsxs("button",{className:"connector-tile-header",onClick:n,"aria-expanded":t,children:[s.jsx("span",{className:"connector-tile-name",children:e.display_name}),s.jsx("span",{className:"connector-tile-type",children:e.type==="oauth_pkce"?"OAuth":"MCP"}),i(),s.jsx(ET,{connector:e,onChanged:r}),s.jsx("span",{className:"connector-tile-chevron",children:t?s.jsx(cy,{size:14}):s.jsx(ai,{size:14})})]}),t&&s.jsxs("div",{className:"connector-detail",children:[e.type==="oauth_pkce"?s.jsx(DT,{connector:e,onChanged:r}):s.jsx(AT,{connector:e,onChanged:r}),e.configured&&s.jsx($T,{connectorId:e.id})]})]})}function DT({connector:e,onChanged:t}){const[n,r]=p.useState(!1),[i,l]=p.useState(null),[a,o]=p.useState({});p.useEffect(()=>{const g=()=>{t()};return window.addEventListener("focus",g),()=>window.removeEventListener("focus",g)},[t]);const c=g=>{var w;const v=window;(w=v.gaia)!=null&&w.openExternal?v.gaia.openExternal(g):window.open(g,"_blank","noopener")},u=async()=>{var g;r(!0),l(null);try{const v=await Cy(e.id,(g=e.available_scopes)!=null&&g.length?e.available_scopes:e.default_scopes);c(v.authorization_url)}catch(v){l(v instanceof Error?v.message:String(v))}finally{r(!1)}},d=async()=>{r(!0),l(null);try{await Cd(e.id),t()}catch(g){l(g instanceof Error?g.message:String(g))}finally{r(!1)}},f=async()=>{var v;const g=(e.oauth_setup_fields??[]).filter(w=>{var x;return w.required!==!1&&!((x=a[w.key])!=null&&x.trim())}).map(w=>w.label);if(g.length){l(`Required: ${g.join(", ")}`);return}r(!0),l(null);try{const w=(v=e.available_scopes)!=null&&v.length?e.available_scopes:e.default_scopes,x=await _y(e.id,{...a,scopes:w}),k=typeof x.authorization_url=="string"?x.authorization_url:null;k&&c(k),t()}catch(w){l(w instanceof Error?w.message:String(w))}finally{r(!1)}},h=e.oauth_setup_fields??[],m=e.configurable===!1&&!e.configured&&h.length>0;return s.jsxs("div",{className:"configure-body",children:[e.description&&s.jsx("p",{className:"connector-desc",children:e.description}),m&&s.jsxs("div",{className:"oauth-setup-form",children:[s.jsx("p",{className:"connector-desc",children:"First-time setup — provide your OAuth client credentials below. They’re stored encrypted in your OS keyring and reused for future connections."}),h.map(g=>s.jsxs("label",{className:"oauth-setup-field",children:[s.jsx("span",{className:"oauth-setup-label",children:g.label}),s.jsx("input",{type:g.kind==="secret"?"password":"text",className:"oauth-setup-input",placeholder:g.placeholder,value:a[g.key]??"",onChange:v=>o(w=>({...w,[g.key]:v.target.value})),autoComplete:"off",spellCheck:!1}),g.help_md&&s.jsx("span",{className:"oauth-setup-help",children:g.help_md})]},g.key))]}),i&&s.jsxs("div",{className:"configure-error",children:[s.jsx(kt,{size:12})," ",i]}),s.jsxs("div",{className:"configure-actions",children:[e.configured?s.jsx("button",{className:"btn-secondary",disabled:n,onClick:()=>void d(),children:n?s.jsx(mt,{size:12,className:"spin"}):"Disconnect"}):m?s.jsx("button",{className:"btn-primary",disabled:n,onClick:()=>void f(),children:n?s.jsx(mt,{size:12,className:"spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Vi,{size:12})," Save & Connect"]})}):e.configurable===!1?s.jsx("span",{className:"connector-setup-required",title:e.config_error??void 0,children:"Setup required"}):s.jsx("button",{className:"btn-primary",disabled:n,onClick:()=>void u(),children:n?s.jsx(mt,{size:12,className:"spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Vi,{size:12})," Connect"]})}),(e.docs_url||e.product_url)&&s.jsxs("a",{href:e.docs_url||e.product_url||"#",target:"_blank",rel:"noopener noreferrer",className:"connector-product-link",children:["Learn more ",s.jsx(Vi,{size:11})]})]})]})}function AT({connector:e,onChanged:t}){const[n,r]=p.useState(()=>Object.fromEntries(e.mcp_env_keys.map(m=>[m,""]))),[i,l]=p.useState(!1),[a,o]=p.useState(!1),[c,u]=p.useState(null);p.useEffect(()=>{r(Object.fromEntries(e.mcp_env_keys.map(m=>[m,""])))},[e.mcp_env_keys.join(",")]);const d=async()=>{const m=Object.fromEntries(Object.entries(n).filter(([,g])=>g.trim()!==""));if(Object.keys(m).length!==0){l(!0),u(null),o(!1);try{await _y(e.id,m),o(!0),t(),setTimeout(()=>o(!1),2200)}catch(g){u(g instanceof Error?g.message:String(g))}finally{l(!1)}}},f=async()=>{l(!0),u(null);try{await Cd(e.id),r(Object.fromEntries(e.mcp_env_keys.map(m=>[m,""]))),t()}catch(m){u(m instanceof Error?m.message:String(m))}finally{l(!1)}},h=async()=>{l(!0),u(null);try{e.enabled?await Ty(e.id):await Ey(e.id),t()}catch(m){u(m instanceof Error?m.message:String(m))}finally{l(!1)}};return s.jsxs("div",{className:"configure-body",children:[e.description&&s.jsx("p",{className:"connector-desc",children:e.description}),c&&s.jsxs("div",{className:"configure-error",children:[s.jsx(kt,{size:12})," ",c]}),e.configured&&s.jsxs("div",{className:"connector-toggle-row",children:[s.jsx("span",{className:"connector-toggle-label",children:"Active"}),s.jsxs("span",{className:"toggle-switch",children:[s.jsx("input",{type:"checkbox",checked:e.enabled!==!1,onChange:()=>void h(),disabled:i,"aria-label":e.enabled?"Disable this MCP server":"Enable this MCP server"}),s.jsx("span",{className:"toggle-track"})]})]}),e.configured&&e.enabled===!1&&s.jsx("p",{className:"connector-toggle-help",children:"Credentials and per-agent grants are preserved. Re-enable to make this server's tools available again."}),e.mcp_env_keys.map(m=>s.jsxs("div",{className:"mcp-key-row",children:[s.jsx("label",{className:"mcp-key-label",children:m}),s.jsx("input",{type:"password",className:"mcp-key-input",placeholder:e.configured?"••••••••":"Enter value",value:n[m]??"",onChange:g=>r(v=>({...v,[m]:g.target.value})),spellCheck:!1,autoComplete:"off"})]},m)),s.jsxs("div",{className:"configure-actions",children:[s.jsx("button",{className:`btn-model-save${a?" saved":""}`,disabled:i||Object.values(n).every(m=>m.trim()===""),onClick:()=>void d(),children:i?s.jsx(mt,{size:12,className:"spin"}):a?s.jsxs(s.Fragment,{children:[s.jsx(nr,{size:12})," Saved"]}):"Save"}),e.configured&&s.jsx("button",{className:"btn-secondary",disabled:i,onClick:()=>void f(),children:"Disconnect"}),e.product_url&&s.jsxs("a",{href:e.product_url,target:"_blank",rel:"noopener noreferrer",className:"connector-product-link",children:["Docs ",s.jsx(Vi,{size:11})]})]})]})}function PT({agent:e,connectorId:t,grantedScopes:n,onChanged:r}){var m;const i=(m=e.required_connections)==null?void 0:m.find(g=>g.connector_id===t),l=e.namespaced_agent_id;if(!i||!l)return null;const[a,o]=p.useState(()=>new Set(n)),[c,u]=p.useState(null),[d,f]=p.useState(null);p.useEffect(()=>{o(new Set(n))},[n.join(",")]);const h=async g=>{if(c!==null)return;const v=new Set(a);v.has(g)?v.delete(g):v.add(g),o(v),u(g),f(null);try{v.size===0?await c0(t,l):await o0(t,l,[...v]),r()}catch(w){o(new Set(n)),f(w instanceof Error?w.message:String(w))}finally{u(null)}};return s.jsxs("div",{className:"grant-agent-card",children:[s.jsx("div",{className:"grant-agent-card-name",children:e.name}),s.jsx("div",{className:"grant-scope-list",children:i.scopes.map(g=>s.jsxs("label",{className:"grant-scope-item",children:[s.jsx("span",{className:"grant-scope-label",children:zT(g)}),s.jsxs("span",{className:"toggle-switch",children:[s.jsx("input",{type:"checkbox",checked:a.has(g),onChange:()=>void h(g),disabled:c!==null}),s.jsx("span",{className:"toggle-track"})]})]},g))}),d&&s.jsxs("div",{className:"grant-scope-warning grant-scope-warning--error",children:[s.jsx(kt,{size:11})," ",d]})]})}function MT({servers:e,expanded:t,onToggle:n}){return s.jsxs("div",{className:"agent-mcps-section",children:[s.jsx("div",{className:"agent-mcps-section-header",children:"Custom agent servers"}),s.jsx("div",{className:"connectors-list",children:e.map(r=>{const i=`${r.agent_id}::${r.server_name}`;return s.jsx(RT,{server:r,expanded:t===i,onToggle:()=>n(i)},i)})})]})}function RT({server:e,expanded:t,onToggle:n}){const r=[e.command,...e.args].join(" ");return s.jsxs("div",{className:`agent-mcp-tile${t?" agent-mcp-tile--open":""}`,children:[s.jsxs("button",{type:"button",className:"agent-mcp-tile-header",onClick:n,"aria-expanded":t,children:[s.jsx("span",{className:"agent-mcp-server-name",children:e.server_name}),s.jsxs("span",{className:"agent-mcp-agent-label",children:["via ",e.agent_name]}),e.disabled?s.jsx("span",{className:"agent-mcp-status disabled",children:"Disabled"}):s.jsxs("span",{className:"agent-mcp-status enabled",children:[s.jsx(nr,{size:11})," Active"]}),s.jsx("span",{className:"agent-mcp-readonly-badge",children:"read-only"}),s.jsx("span",{className:"agent-mcp-chevron",children:t?s.jsx(cy,{size:14}):s.jsx(ai,{size:14})})]}),t&&s.jsxs("div",{className:"agent-mcp-detail",children:[r&&s.jsx("div",{className:"agent-mcp-command-row",children:r}),s.jsx("div",{className:"agent-mcp-config-path",children:e.config_path}),s.jsxs("div",{className:"agent-mcp-config-hint",children:["Edit the agent's ",s.jsx("code",{children:"mcp_servers.json"})," to change this server."]})]})]})}function $T({connectorId:e}){const{agents:t}=we(),[n,r]=p.useState({}),[i,l]=p.useState(!0),a=p.useCallback(async()=>{try{const{grants:c}=await a0(e);r(c)}catch{r({})}finally{l(!1)}},[e]);if(p.useEffect(()=>{a()},[a]),i)return null;const o=t.filter(c=>{var u;return c.namespaced_agent_id&&((u=c.required_connections)==null?void 0:u.some(d=>d.connector_id===e))});return s.jsxs("div",{className:"connection-grants",children:[s.jsx("div",{className:"grants-header",children:"Per-agent grants"}),o.length===0?s.jsx("div",{className:"grants-empty",children:"No agents require access to this connector."}):o.map(c=>s.jsx(PT,{agent:c,connectorId:e,grantedScopes:n[c.namespaced_agent_id]??[],onChanged:()=>void a()},c.namespaced_agent_id))]})}function FT(){const{setShowSettings:e,sessions:t,removeSession:n,agents:r}=we(),[i,l]=p.useState(null),[a,o]=p.useState(!0),[c,u]=p.useState([]),[d,f]=p.useState(""),[h,m]=p.useState(""),[g,v]=p.useState(!1),[w,x]=p.useState(!1),[k,j]=p.useState(null),[z,A]=p.useState(!1),_=p.useRef(null);p.useEffect(()=>{E.system.info("Checking system status...");const L=E.system.time();Sd().then(F=>{l(F),E.system.timed("System status received",L,{lemonade:F.lemonade_running?"running":"stopped",model:F.model_loaded||"none",embedding:F.embedding_model_loaded?"yes":"no",disk:`${F.disk_space_gb}GB free`,memory:F.memory_available_gb!=null?`${F.memory_available_gb}GB available`:"unknown"}),F.lemonade_running||E.system.warn("Lemonade Server is NOT running.")}).catch(F=>{E.system.error("Failed to get system status",F),l(null)}).finally(()=>o(!1)),E0().then(F=>u(F.servers)).catch(()=>{}),t0().then(F=>{const Y=F.custom_model??"";f(Y),m(Y)}).catch(F=>{E.system.error("Failed to load settings",F)}).finally(()=>v(!0))},[]),p.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const D=p.useCallback(async()=>{const L=d.trim(),F=L.length>0?L:"";x(!0),j(null),A(!1);try{E.system.info("Saving custom_model override",{custom_model:F});const ue=(await n0({custom_model:F})).custom_model??"";f(ue),m(ue),A(!0),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>A(!1),2200)}catch(Y){const ue=Y instanceof Error?Y.message:String(Y);E.system.error("Failed to save custom_model",Y),j(ue)}finally{x(!1)}},[d]),C=d.trim()!==h.trim(),M=(i==null?void 0:i.default_model_name)??Qd,{isLoadingModel:N,isDownloadingModel:U,loadModel:O,downloadModel:re}=Kx(M),ie=[{label:"4K",value:4096},{label:"8K",value:8192},{label:"16K",value:16384},{label:"32K",value:32768}],X=(i==null?void 0:i.model_context_size)??null,[xe,ce]=p.useState("");p.useEffect(()=>{X!=null&&ce(String(X))},[X]);const T=(()=>{const L=parseInt(xe,10);return Number.isFinite(L)&&L>0?L:null})(),P=T!=null&&T!==X,b=(i==null?void 0:i.model_loaded)??M,J=p.useCallback(async()=>{T&&(E.system.info(`Reloading ${b} with ctx_size=${T}`),await O(b,T))},[T,b,O]),[B,S]=p.useState(!1),oe=p.useRef(null);p.useEffect(()=>()=>{oe.current&&clearTimeout(oe.current)},[]);const pe=p.useCallback(async()=>{if(!B){S(!0),oe.current&&clearTimeout(oe.current),oe.current=setTimeout(()=>S(!1),4e3);return}S(!1),oe.current&&clearTimeout(oe.current),E.system.warn(`Clearing ALL data: ${t.length} session(s)`);const L=E.system.time();let F=0;for(const Y of t)try{await zy(Y.id),n(Y.id),F++}catch(ue){E.system.error(`Failed to delete session ${Y.id}`,ue)}E.system.timed(`Cleared ${F}/${t.length} session(s)`,L),e(!1)},[B,t,n,e]),ae="0.18.0",_e=!!(i!=null&&i.lemonade_running&&i.model_loaded&&i.expected_model_loaded===!1),He=!!(i!=null&&i.lemonade_running&&i.model_loaded&&i.context_size_sufficient===!1),nt=!!(i!=null&&i.lemonade_running&&!i.model_loaded&&i.model_downloaded===!1),Ge=_e||He;return s.jsxs("div",{className:"settings-page",children:[s.jsxs("div",{className:"settings-page-header",children:[s.jsx("button",{className:"btn-icon settings-back-btn",onClick:()=>e(!1),"aria-label":"Back",children:s.jsx(ay,{size:18})}),s.jsx("h3",{children:"Settings"})]}),s.jsxs("div",{className:"settings-page-body",children:[s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"System Status"}),a?s.jsx("p",{className:"loading-text",children:"Checking system..."}):i?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"status-grid",children:[s.jsx(Sn,{label:"Lemonade Server",value:i.lemonade_running?`Running${i.lemonade_version?` v${i.lemonade_version}`:""}`:"Not Running",ok:i.lemonade_running,hint:i.lemonade_running?void 0:i.initialized?"Run: lemonade-server serve":"Run: gaia init --profile chat"}),s.jsx(Sn,{label:"Model",value:i.model_loaded||"None loaded",ok:!!i.model_loaded&&i.expected_model_loaded!==!1,hint:i.model_loaded?i.expected_model_loaded===!1?`Expected: ${M}`:void 0:"Run: gaia init --profile chat"}),i.model_size_gb!=null&&s.jsx(Sn,{label:"Model Size",value:`${i.model_size_gb} GB`,ok:!0}),i.model_device&&s.jsx(Sn,{label:"Device",value:i.model_device.toUpperCase(),ok:i.model_device!=="cpu"}),i.model_context_size!=null&&s.jsx(Sn,{label:"Context Window",value:`${(i.model_context_size/1024).toFixed(0)}K tokens`,ok:i.context_size_sufficient}),i.model_labels&&i.model_labels.length>0&&s.jsx(Sn,{label:"Capabilities",value:i.model_labels.join(", "),ok:!0}),s.jsx(Sn,{label:"Embedding Model",value:i.embedding_model_loaded?"Available":"Not loaded",ok:i.embedding_model_loaded}),i.gpu_name&&s.jsx(Sn,{label:"GPU",value:`${i.gpu_name}${i.gpu_vram_gb?` (${i.gpu_vram_gb} GB)`:""}`,ok:!0}),s.jsx(Sn,{label:"Disk Space",value:`${i.disk_space_gb} GB free`,ok:i.disk_space_gb>5,hint:!i.model_loaded&&i.disk_space_gb<30?`Models require ~25 GB — only ${i.disk_space_gb} GB available`:void 0}),s.jsx(Sn,{label:"Memory",value:i.memory_available_gb!=null?`${i.memory_available_gb} GB available`:"unknown",ok:i.memory_available_gb!=null&&i.memory_available_gb>2}),i.processor_name&&s.jsx(Sn,{label:"Processor",value:i.processor_name,ok:i.device_supported!==!1})]}),nt&&s.jsxs("div",{className:"model-action-row model-action-row--download",children:[s.jsxs("div",{className:"model-action-info",children:[s.jsx("span",{className:"model-action-label",children:"Model not downloaded."}),s.jsxs("span",{className:"model-action-desc",children:[s.jsx("strong",{children:M})," is required for GAIA Chat (~25 GB)."]})]}),s.jsx("button",{className:"btn-model-action btn-model-action--download",onClick:()=>re(!1),disabled:U,children:U?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Downloading…"]}):"Download"})]}),Ge&&s.jsxs("div",{className:"model-action-row model-action-row--load",children:[s.jsxs("div",{className:"model-action-info",children:[s.jsx("span",{className:"model-action-label",children:_e?"Wrong model loaded.":"Context window too small."}),s.jsxs("span",{className:"model-action-desc",children:["Load ",s.jsx("strong",{children:M})," with ",(Ys/1024).toFixed(0),"K token context."]})]}),s.jsx("button",{className:"btn-model-action btn-model-action--load",onClick:()=>O(),disabled:N,children:N?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Loading…"]}):"Load Model"})]}),i.lemonade_running&&s.jsxs("div",{className:"force-redownload-row",children:[s.jsx("span",{className:"force-redownload-label",children:"If the model file is corrupted:"}),s.jsx("button",{className:"btn-force-redownload",onClick:()=>re(!0),disabled:U,children:U?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:12,className:"btn-spinner"})," Downloading…"]}):"Force Re-download"})]})]}):s.jsxs("div",{className:"status-error",children:[s.jsx("p",{children:"Could not connect to server"}),s.jsx("code",{children:"gaia chat --ui"})]})]}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Active Model"}),s.jsx("p",{className:"model-override-desc",children:"Override the model used by the active agent. Leave empty to use the current agent’s preferred model."}),s.jsxs("div",{className:"model-input-row",children:[s.jsx("input",{type:"text",className:`model-input${h?" has-override":""}`,placeholder:"Use agent default",value:d,onChange:L=>{f(L.target.value),j(null),A(!1)},onKeyDown:L=>{L.key==="Enter"&&!w&&C&&g&&(L.preventDefault(),D())},disabled:!g||w,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off","aria-label":"Custom model override"}),s.jsx("div",{className:"model-btn-group",children:s.jsx("button",{className:`btn-model-save${z?" saved":""}`,onClick:()=>{D()},disabled:!g||w||!C&&!z,"aria-label":"Save custom model",children:w?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Saving…"]}):z?s.jsxs(s.Fragment,{children:[s.jsx(nr,{size:13})," Saved"]}):"Save"})})]}),s.jsxs("p",{className:"model-status-hint",children:["Accepts a Lemonade model ID (e.g. ",s.jsx("code",{children:"Qwen3-4B-Instruct-2507-GGUF"}),")"," ","or a HuggingFace ID (e.g. ",s.jsx("code",{children:"unsloth/Qwen3-4B-GGUF"}),")."]}),k&&s.jsxs("div",{className:"model-warning",role:"alert",children:[s.jsx(kt,{size:14}),s.jsxs("div",{className:"model-warning-content",children:[s.jsx("strong",{children:"Could not save"}),s.jsx("p",{children:k})]})]})]}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Context Size"}),s.jsx("p",{className:"model-override-desc",children:"Reload the active model with a different context window. Larger contexts use more memory and slow inference; going past the model’s training length may degrade quality."}),s.jsx("div",{className:"ctx-preset-row",children:ie.map(L=>{const F=T===L.value;return s.jsx("button",{className:`btn-ctx-preset${F?" active":""}`,onClick:()=>ce(String(L.value)),disabled:N,type:"button",children:L.label},L.value)})}),s.jsxs("div",{className:"model-input-row",children:[s.jsx("input",{type:"number",className:"model-input",placeholder:X!=null?String(X):"4096",value:xe,min:512,step:1024,onChange:L=>ce(L.target.value),disabled:N,"aria-label":"Context size in tokens"}),s.jsx("div",{className:"model-btn-group",children:s.jsx("button",{className:"btn-model-save",onClick:()=>{J()},disabled:N||!P||!(i!=null&&i.lemonade_running),"aria-label":"Reload model with new context size",children:N?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Reloading…"]}):"Apply"})})]}),s.jsxs("p",{className:"model-status-hint",children:["Current: ",s.jsx("code",{children:X!=null?`${X.toLocaleString()} tokens`:"unknown"}),(i==null?void 0:i.model_loaded)&&s.jsxs(s.Fragment,{children:[" on ",s.jsx("code",{children:i.model_loaded})]}),"."]})]}),i&&i.memory_available_gb!=null&&(()=>{const L=i.memory_available_gb,F=r.filter(Y=>Y.min_memory_gb!=null&&Y.min_memory_gb>L);return F.length===0?null:s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Memory Warnings"}),s.jsx("div",{className:"status-grid",children:F.map(Y=>s.jsxs("div",{className:"status-row status-row--has-hint",children:[s.jsx("span",{className:"status-label",children:Y.name}),s.jsxs("div",{className:"status-value-wrap",children:[s.jsxs("span",{className:"status-value warn memory-warning-value",children:[s.jsx(kt,{size:12}),"Needs ~",Y.min_memory_gb," GB free"]}),s.jsxs("span",{className:"status-hint",children:["Only ",i.memory_available_gb," GB available — model load may fail or swap heavily."]})]})]},Y.id))})]})})(),c.length>0&&s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"MCP Servers"}),s.jsx("div",{className:"status-grid",children:c.map(L=>s.jsxs("div",{className:"status-row",children:[s.jsx("span",{className:"status-label",children:L.name}),s.jsx("div",{className:"status-value-wrap",children:L.connected?s.jsxs("span",{className:"status-value ok mcp-status-connected",children:[s.jsx(nr,{size:12}),L.tool_count," tool",L.tool_count!==1?"s":""]}):s.jsxs("span",{className:"status-value warn mcp-status-failed",title:L.error??void 0,children:[s.jsx(kt,{size:12}),"Failed"]})})]},L.name))})]}),s.jsx(jT,{}),s.jsx(LT,{}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"About"}),s.jsxs("div",{className:"about-info",children:[s.jsxs("p",{children:["GAIA v",ae," ",s.jsx("span",{className:"beta-badge",children:"BETA"})]}),s.jsx("p",{className:"about-sub",children:"Privacy-first AI chat for AMD Ryzen AI PCs."})]})]}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Privacy & Data"}),s.jsxs("div",{className:"setting-row",children:[s.jsx("span",{children:"Data location"}),s.jsx("code",{className:"setting-path",children:"~/.gaia/chat/"})]}),s.jsx("div",{className:"danger-divider"}),s.jsxs("div",{className:"setting-actions",children:[s.jsx("p",{className:"danger-warning",children:"This will permanently delete all sessions, messages, and documents."}),s.jsx("button",{className:"btn-danger",onClick:pe,children:B?"Click again to confirm":"Clear All Data"})]})]})]})]})}function Sn({label:e,value:t,ok:n,hint:r}){return s.jsxs("div",{className:`status-row${r?" status-row--has-hint":""}`,children:[s.jsx("span",{className:"status-label",children:e}),s.jsxs("div",{className:"status-value-wrap",children:[s.jsx("span",{className:`status-value ${n?"ok":"warn"}`,children:t}),r&&s.jsx("span",{className:"status-hint",children:s.jsx("code",{children:r})})]})]})}const OT="modulepreload",UT=function(e,t){return new URL(e,t).href},qh={},BT=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){const a=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),c=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(u=>{if(u=UT(u,r),u in qh)return;qh[u]=!0;const d=u.endsWith(".css"),f=d?'[rel="stylesheet"]':"";if(!!r)for(let g=a.length-1;g>=0;g--){const v=a[g];if(v.href===u&&(!d||v.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${u}"]${f}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":OT,d||(m.as="script"),m.crossOrigin="",m.href=u,c&&m.setAttribute("nonce",c),document.head.appendChild(m),d)return new Promise((g,v)=>{m.addEventListener("load",g),m.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${u}`)))})}))}function l(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&l(o.reason);return t().catch(l)})};let yc=null;function HT({isOpen:e,onClose:t,onStop:n,error:r}){const[i,l]=p.useState(null),[a,o]=p.useState(!1),c=p.useRef(null),u=p.useCallback(async()=>{try{const m=await Py();return l(m),m}catch(m){return E.system.error("Failed to fetch tunnel status",m),null}},[]);p.useEffect(()=>{if(!e||r)return;u();const m=setInterval(async()=>{const g=await u();g!=null&&g.active&&(g!=null&&g.url)&&clearInterval(m)},2e3);return()=>clearInterval(m)},[e,r,u]),p.useEffect(()=>{if(!(i!=null&&i.active)||!i.url||!i.token||!c.current)return;const m=`${i.url}/?token=${i.token}`;E.system.info(`Generating QR code for: ${m}`),(async()=>{if(!yc)try{const w=await BT(()=>import("./browser-CTB2jwNe.js").then(x=>x.b),[],import.meta.url);yc=w.default||w}catch{E.system.error("QR code library not available - install with: npm install qrcode");return}const v=document.documentElement.getAttribute("data-theme")==="dark";try{await yc.toCanvas(c.current,m,{width:200,margin:2,color:{dark:v?"#e6edf3":"#111827",light:v?"#0d0d0d":"#ffffff"}})}catch(w){E.system.error("QR code generation failed",w)}})()},[i==null?void 0:i.active,i==null?void 0:i.url,i==null?void 0:i.token]);const d=p.useRef(null),f=p.useCallback(()=>{if(!(i!=null&&i.url)||!(i!=null&&i.token))return;const m=`${i.url}/?token=${i.token}`;navigator.clipboard.writeText(m).then(()=>{o(!0),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>o(!1),2e3)})},[i]);if(p.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]),!e)return null;const h=i!=null&&i.active&&(i!=null&&i.url)&&(i!=null&&i.token)?`${i.url}/?token=${i.token}`:"";return s.jsx("div",{className:"modal-overlay",onClick:t,role:"dialog","aria-modal":"true","aria-label":"Mobile Access",children:s.jsxs("div",{className:"modal-panel mobile-modal",onClick:m=>m.stopPropagation(),children:[s.jsxs("div",{className:"modal-header",children:[s.jsxs("h3",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx(yy,{size:18}),"Mobile Access"]}),s.jsx("button",{className:"btn-icon",onClick:t,"aria-label":"Close",children:s.jsx(tt,{size:18})})]}),s.jsxs("div",{className:"modal-body mobile-modal-body",children:[s.jsxs("div",{className:"tunnel-status",children:[s.jsx("span",{className:`status-dot ${i!=null&&i.active?"active":r?"error":"starting"}`}),s.jsx("span",{children:i!=null&&i.active?"Tunnel active":r?"Connection failed":"Starting tunnel..."}),!(i!=null&&i.active)&&!r&&s.jsx("span",{className:"tunnel-spinner"})]}),r&&s.jsx("div",{className:"tunnel-error",children:r}),s.jsx("div",{className:"qr-code-area",children:i!=null&&i.active?s.jsx("canvas",{ref:c}):r?s.jsx("div",{className:"qr-placeholder error",children:"Failed to connect"}):s.jsxs("div",{className:"qr-placeholder",children:[s.jsx("div",{className:"placeholder-spinner"}),s.jsx("span",{children:"Connecting..."})]})}),(i==null?void 0:i.active)&&h&&s.jsxs("div",{className:"tunnel-url-area",children:[s.jsx("label",{children:"Mobile URL"}),s.jsxs("div",{className:"tunnel-url-row",children:[s.jsx("input",{type:"text",readOnly:!0,value:h}),s.jsxs("button",{className:`copy-url-btn ${a?"copied":""}`,onClick:f,title:"Copy URL",children:[a?s.jsx(li,{size:13}):s.jsx(jl,{size:13}),a?"Copied":"Copy"]})]})]}),(i==null?void 0:i.active)&&(i==null?void 0:i.publicIp)&&(i==null?void 0:i.url)&&!i.url.includes("ngrok-free.app")&&s.jsxs("div",{className:"tunnel-password-hint",children:[s.jsx("label",{children:"Tunnel Password"}),s.jsx("div",{className:"tunnel-password-value",children:i.publicIp}),s.jsx("span",{className:"tunnel-password-note",children:"Enter this when the tunnel page asks for a password"})]}),s.jsx("div",{className:"mobile-instructions",children:s.jsxs("ol",{children:[s.jsx("li",{children:"Scan the QR code with your phone's camera"}),(i==null?void 0:i.url)&&!i.url.includes("ngrok-free.app")&&s.jsx("li",{children:"Enter the tunnel password shown above when prompted"}),s.jsx("li",{children:"Chat with GAIA from your mobile device"}),s.jsx("li",{children:"Your data stays secure via encrypted tunnel"})]})}),s.jsxs("div",{className:"mobile-access-actions",children:[(i==null?void 0:i.active)&&n&&s.jsx("button",{className:"btn-danger",onClick:n,title:"Close the tunnel and revoke the mobile URL",children:"Stop Tunnel"}),s.jsx("button",{className:"btn-secondary",onClick:t,children:"Close"})]})]})]})})}function VT({onRetry:e}){var j;const{backendConnected:t,systemStatus:n,currentSessionId:r,messages:i}=we(),[l,a]=p.useState(!1),o=!!r&&i.length>0,c=(n==null?void 0:n.default_model_name)??Qd,{isLoadingModel:u,isDownloadingModel:d,loadModel:f,downloadModel:h}=Kx(c),m=p.useRef(n==null?void 0:n.lemonade_running),g=p.useRef(n==null?void 0:n.model_downloaded),v=p.useRef(n==null?void 0:n.context_size_sufficient),w=p.useRef(n==null?void 0:n.expected_model_loaded);p.useEffect(()=>{if(o)return;const z=n==null?void 0:n.lemonade_running,A=n==null?void 0:n.model_downloaded,_=n==null?void 0:n.context_size_sufficient,D=n==null?void 0:n.expected_model_loaded;let C=!1;m.current!==z&&(m.current=z,z===!1&&(C=!0)),g.current!==A&&(g.current=A,A===!1&&(C=!0)),v.current!==_&&(v.current=_,_===!1&&(C=!0)),w.current!==D&&(w.current=D,D===!1&&(C=!0)),C&&a(!1)},[n,o]);const x=(n==null?void 0:n.download_progress)??null;if(d||(x==null?void 0:x.state)==="downloading"||(x==null?void 0:x.state)==="starting"||(x==null?void 0:x.state)==="error"){const z=n!=null&&n.default_model_size_gb?`~${n.default_model_size_gb.toFixed(1)} GB`:"large download",A=(x==null?void 0:x.state)==="error";return s.jsxs("div",{className:`connection-banner ${A?"connection-banner--error":"connection-banner--warning"}`,role:A?"alert":"status",children:[s.jsx("div",{className:"connection-banner__icon",children:A?s.jsx(pn,{size:16}):s.jsx(oi,{size:16})}),s.jsx("div",{className:"connection-banner__text",children:A?s.jsxs(s.Fragment,{children:["Download of ",s.jsx("strong",{children:c})," failed."," ",(x==null?void 0:x.message)&&s.jsx("span",{className:"connection-banner__hint",children:x.message})]}):s.jsxs(s.Fragment,{children:["Downloading ",s.jsx("strong",{children:c})," (",z,").",(x==null?void 0:x.state)==="downloading"&&x.file&&s.jsxs(s.Fragment,{children:[" ",s.jsxs("span",{className:"connection-banner__hint",children:["File ",x.file_index," / ",x.total_files,": ",s.jsx("code",{children:x.file})]})]})]})}),A?s.jsx("button",{className:"connection-banner__retry",onClick:()=>h(!1),children:"Retry"}):s.jsx("span",{className:"connection-banner__loading connection-banner__progress",children:x&&x.state==="downloading"&&x.total_bytes>0?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"connection-banner__progress-bar",role:"progressbar","aria-valuenow":x.percent,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Download progress",children:s.jsx("span",{className:"connection-banner__progress-fill",style:{width:`${x.percent}%`}})}),s.jsxs("span",{className:"connection-banner__progress-label",children:[x.percent,"% ·"," ",(x.downloaded_bytes/1e9).toFixed(2)," /"," ",(x.total_bytes/1e9).toFixed(2)," GB"]})]}):s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"connection-banner__spinner"}),(x==null?void 0:x.state)==="starting"?"Starting download…":"Downloading…"]})}),A&&s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}if((n==null?void 0:n.init_state)==="initializing"){const z=(j=n.init_tasks)==null?void 0:j.find(_=>_.status==="running"),A=(z==null?void 0:z.name)||"Preparing AI system";return s.jsxs("div",{className:"connection-banner connection-banner--init",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(mt,{size:16,className:"connection-banner__spinner"})}),s.jsxs("div",{className:"connection-banner__text",children:[A,s.jsxs("span",{className:"thinking-dots",children:[s.jsx("span",{children:"."}),s.jsx("span",{children:"."}),s.jsx("span",{children:"."})]})]})]})}if(l||o)return null;if(!t)return s.jsxs("div",{className:"connection-banner connection-banner--error",role:"alert",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(jw,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["Cannot connect to GAIA server."," ",s.jsxs("span",{className:"connection-banner__hint",children:["Start it with: ",s.jsx("code",{children:"gaia chat --ui"})]})]}),e&&s.jsx("button",{className:"connection-banner__retry",onClick:e,children:"Retry"})]});if(n&&!n.lemonade_running)return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(pn,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["LLM server is not responding — it may be busy or not running."," ",s.jsxs("span",{className:"connection-banner__hint",children:["If not started, run: ",s.jsx("code",{children:"lemonade-server serve"})]})]}),e&&s.jsx("button",{className:"connection-banner__retry",onClick:e,children:"Check again"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]});if(n&&n.lemonade_running&&!n.model_loaded&&n.model_downloaded===!1){const z=n.default_model_size_gb?`~${n.default_model_size_gb.toFixed(1)} GB`:"large download";return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(oi,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["Required model ",s.jsx("strong",{children:c})," is not downloaded (",z,")."]}),s.jsx("button",{className:"connection-banner__retry",onClick:()=>h(!1),children:"Download"}),e&&s.jsx("button",{className:"connection-banner__retry connection-banner__retry--secondary",onClick:e,children:"Recheck"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}if(n&&n.lemonade_running&&n.model_loaded&&n.expected_model_loaded===!1&&!n.embedding_model_loaded){const z=n.model_loaded,A=n.context_size_sufficient===!1;return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(uy,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["Wrong model loaded: ",s.jsx("strong",{children:z}),"."," ","GAIA Chat requires ",s.jsx("strong",{children:c}),".",A&&s.jsxs(s.Fragment,{children:[" ","Context window is also too small."]})]}),u?s.jsxs("span",{className:"connection-banner__loading",children:[s.jsx(mt,{size:13,className:"connection-banner__spinner"}),"Loading…"]}):s.jsx("button",{className:"connection-banner__retry",onClick:()=>f(),children:"Load Now"}),e&&!u&&s.jsx("button",{className:"connection-banner__retry connection-banner__retry--secondary",onClick:e,children:"Recheck"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}if(n&&n.lemonade_running&&n.model_loaded&&n.context_size_sufficient===!1){const z=n.model_context_size??0,A=n.lemonade_url??"http://localhost:13305";return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(tw,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["LLM context window is too small (",z.toLocaleString()," tokens;"," ",Ys.toLocaleString()," required)."," ",s.jsxs("span",{className:"connection-banner__hint",children:["In"," ",s.jsx("a",{className:"connection-banner__link",href:A,target:"_blank",rel:"noreferrer",children:"Lemonade"}),", set ctx‑size to ",Ys.toLocaleString(),", or restart with:"," ",s.jsxs("code",{children:["lemonade-server serve --ctx-size ",Ys]})]})]}),e&&s.jsx("button",{className:"connection-banner__retry",onClick:e,children:"Check again"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}return null}const WT={status:"idle",version:null,progress:0,releaseNotes:null,error:null};function GT(){const[e,t]=p.useState(WT);return p.useEffect(()=>{const n=window.gaiaUpdater;if(!n)return;let r=!0;n.getStatus().then(l=>{r&&l&&t(l)}).catch(()=>{});const i=n.onStatusChange(l=>{r&&l&&t(l)});return()=>{r=!1;try{i()}catch{}}},[]),e}function qT(){const e=GT(),[t,n]=p.useState(!1),r=p.useCallback(()=>{const i=window.gaiaUpdater;i==null||i.check().catch(()=>{})},[]);if(t||e.status==="idle"||e.status==="checking"||e.status==="disabled")return null;if(e.status==="downloading"){const i=Math.max(0,Math.min(100,e.progress));return s.jsxs("div",{className:"update-chip update-chip--downloading",role:"status","aria-live":"polite",title:`Downloading update${e.version?` ${e.version}`:""}…`,children:[s.jsx(oi,{size:13,className:"update-chip__icon"}),s.jsxs("span",{className:"update-chip__label",children:["Downloading update… ",i,"%"]})]})}return e.status==="available"?s.jsxs("div",{className:"update-chip update-chip--available",role:"status",title:e.releaseNotes||"A new version is available.",children:[s.jsx(oi,{size:13,className:"update-chip__icon"}),s.jsxs("span",{className:"update-chip__label",children:["Update available",e.version?`: ${e.version}`:""]}),s.jsx("button",{type:"button",className:"update-chip__dismiss",onClick:()=>n(!0),"aria-label":"Dismiss update notification",children:s.jsx(tt,{size:11})})]}):e.status==="downloaded"?s.jsxs("div",{className:"update-chip update-chip--ready",role:"status","aria-live":"polite",children:[s.jsx(Vs,{size:13,className:"update-chip__icon"}),s.jsx("button",{type:"button",className:"update-chip__action",onClick:r,title:"Click to restart and apply the update",children:"Update ready — restart to apply"})]}):e.status==="error"?s.jsxs("div",{className:"update-chip update-chip--error",role:"status",title:e.error||"Update check failed.",children:[s.jsx(pn,{size:13,className:"update-chip__icon"}),s.jsx("span",{className:"update-chip__label",children:"Update check failed"}),s.jsx("button",{type:"button",className:"update-chip__dismiss",onClick:()=>n(!0),"aria-label":"Dismiss update error",children:s.jsx(tt,{size:11})})]}):null}function QT(){const e=ot(mE),t=ot(n=>n.respondToPermission);return e?s.jsx("div",{className:"permission-overlay",role:"dialog","aria-modal":"true","aria-label":"Permission Request",children:s.jsx(KT,{notification:e,onRespond:t},e.id)}):null}function KT({notification:e,onRespond:t}){const n=e.timeoutSeconds!=null&&e.timeoutSeconds>0,[r,i]=p.useState(n?e.timeoutSeconds:null),l=p.useRef(null),[a,o]=p.useState(!1),[c,u]=p.useState(!1),d=p.useRef(!1),f=p.useRef(t);f.current=t,p.useEffect(()=>{if(n)return l.current=setInterval(()=>{i(w=>w===null||w<=1?(l.current&&clearInterval(l.current),0):w-1)},1e3),()=>{l.current&&clearInterval(l.current)}},[n]),p.useEffect(()=>{if(r===0){if(d.current)return;d.current=!0,o(!0),f.current(e.id,"deny",!1)}},[r,e.id]);const h=p.useCallback(async()=>{if(!d.current){d.current=!0,o(!0),l.current&&clearInterval(l.current);try{await t(e.id,"allow",c)}finally{d.current=!1,o(!1)}}},[e.id,t,c]),m=p.useCallback(async()=>{if(!d.current){d.current=!0,o(!0),l.current&&clearInterval(l.current);try{await t(e.id,"deny",!1)}finally{d.current=!1,o(!1)}}},[e.id,t]);p.useEffect(()=>{const w=x=>{x.key==="Enter"&&!x.shiftKey?(x.preventDefault(),h()):x.key==="Escape"&&(x.preventDefault(),m())};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[h,m]);const g=e.toolArgs,v=g&&Object.keys(g).length>0;return s.jsxs("div",{className:"permission-prompt",children:[s.jsxs("div",{className:"permission-header",children:[s.jsx("div",{className:"permission-header-icon",children:s.jsx(Ga,{size:24})}),s.jsxs("div",{className:"permission-header-text",children:[s.jsx("h2",{className:"permission-title",children:"Permission Request"}),s.jsx("span",{className:"permission-agent",children:e.agentName})]}),r!==null&&r>0&&s.jsxs("div",{className:"permission-countdown",title:"Auto-deny on timeout",children:[s.jsx(Wa,{size:14}),s.jsxs("span",{children:[r,"s"]})]})]}),s.jsxs("div",{className:"permission-body",children:[s.jsx("p",{className:"permission-message",children:e.message}),e.tool&&s.jsxs("div",{className:"permission-tool-info",children:[s.jsxs("div",{className:"permission-tool-header",children:[s.jsx(pn,{size:14}),s.jsx("span",{children:"Tool Invocation"})]}),s.jsx("div",{className:"permission-tool-name",children:s.jsx("code",{children:e.tool})}),v&&s.jsx("div",{className:"permission-tool-args",children:s.jsx("pre",{children:JSON.stringify(g,null,2)})})]}),e.priority==="critical"&&s.jsxs("div",{className:"permission-critical-banner",children:[s.jsx(pn,{size:14}),s.jsx("span",{children:"This is a critical-tier operation"})]}),s.jsxs("label",{className:"permission-remember",children:[s.jsx("input",{type:"checkbox",checked:c,onChange:w=>u(w.target.checked),disabled:a}),s.jsx("span",{children:"Always allow this tool"})]})]}),s.jsxs("div",{className:"permission-actions",children:[s.jsxs("button",{className:"permission-btn permission-btn-deny",onClick:m,disabled:a,title:"Deny (Esc)",children:[s.jsx(tt,{size:16}),"Deny"]}),s.jsxs("button",{className:"permission-btn permission-btn-allow",onClick:h,disabled:a,title:"Allow (Enter)",children:[s.jsx(li,{size:16}),"Allow"]})]}),s.jsxs("div",{className:"permission-hints",children:[s.jsxs("span",{children:[s.jsx("kbd",{children:"Enter"})," Allow"]}),s.jsxs("span",{children:[s.jsx("kbd",{children:"Esc"})," Deny"]})]})]})}const YT={permission_request:{icon:s.jsx(Ga,{size:16}),colorClass:"notif-type-permission",label:"Permission"},policy_alert:{icon:s.jsx(Ga,{size:16}),colorClass:"notif-type-policy",label:"Policy"},security_alert:{icon:s.jsx(pn,{size:16}),colorClass:"notif-type-security",label:"Security"},status_change:{icon:s.jsx(wi,{size:16}),colorClass:"notif-type-status",label:"Status"},info:{icon:s.jsx(ew,{size:16}),colorClass:"notif-type-info",label:"Info"},error:{icon:s.jsx(kt,{size:16}),colorClass:"notif-type-error",label:"Error"}};function XT(e){const n=Date.now()-e,r=Math.floor(n/1e3);if(r<60)return"just now";const i=Math.floor(r/60);if(i<60)return`${i}m ago`;const l=Math.floor(i/60);if(l<24)return`${l}h ago`;const a=Math.floor(l/24);return a<7?`${a}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function JT({onClose:e}){const t=ot(fE),n=ot(Hx),r=ot(w=>w.markRead),i=ot(w=>w.markAllRead),l=ot(w=>w.clearAll),a=ot(w=>w.dismiss),o=ot(w=>w.addNotification),c=ot(w=>w.respondToPermission),u=ot(w=>w.typeFilter),d=ot(w=>w.setTypeFilter),f=p.useRef(!1);p.useEffect(()=>{var x;const w=window.gaiaAPI;!((x=w==null?void 0:w.notification)!=null&&x.onNotification)||f.current||(f.current=!0,w.notification.onNotification(k=>{o(k)}))},[o]);const h=p.useCallback(w=>{r(w)},[r]),m=p.useCallback(w=>{c(w.id,"allow",!1)},[c]),g=p.useCallback(w=>{c(w.id,"deny",!1)},[c]);p.useEffect(()=>{const w=x=>{x.key==="Escape"&&!x.defaultPrevented&&e()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[e]);const v=[{key:null,label:"All"},{key:"permission_request",label:"Permissions"},{key:"policy_alert",label:"Policy"},{key:"error",label:"Errors"},{key:"security_alert",label:"Security"},{key:"status_change",label:"Status"},{key:"info",label:"Info"}];return s.jsxs("div",{className:"notification-center",role:"dialog","aria-label":"Notification Center",children:[s.jsxs("div",{className:"notification-center-header",children:[s.jsxs("div",{className:"notification-center-title-row",children:[s.jsx("h2",{className:"notification-center-title",children:"Notifications"}),n>0&&s.jsx("span",{className:"notification-center-badge",children:n})]}),s.jsx("button",{className:"btn-icon notification-center-close",onClick:e,"aria-label":"Close notification center",children:s.jsx(tt,{size:18})})]}),s.jsx("div",{className:"notification-filter-bar",role:"tablist","aria-label":"Filter notifications",children:v.map(w=>s.jsx("button",{role:"tab","aria-selected":u===w.key,className:`notification-filter-tab ${u===w.key?"active":""}`,onClick:()=>d(w.key),children:w.label},w.key??"all"))}),s.jsx("div",{className:"notification-list",children:t.length===0?s.jsxs("div",{className:"notification-empty",children:[s.jsx(oy,{size:40,strokeWidth:1.2}),s.jsx("span",{children:"No notifications"})]}):t.map(w=>{const x=YT[w.type];return s.jsxs("div",{className:`notification-item ${w.read?"":"unread"} ${x.colorClass}`,id:w.type==="policy_alert"&&w.receiptId?`policy-receipt-${encodeURIComponent(w.receiptId)}`:void 0,onClick:()=>h(w.id),role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&h(w.id)},children:[!w.read&&s.jsx("span",{className:"notification-unread-dot"}),s.jsx("span",{className:"notification-icon",children:x.icon}),s.jsxs("div",{className:"notification-content",children:[s.jsxs("div",{className:"notification-content-header",children:[s.jsx("span",{className:"notification-agent",children:w.agentName}),s.jsx("span",{className:"notification-time",children:XT(w.timestamp)})]}),w.title&&s.jsx("span",{className:"notification-title",children:w.title}),s.jsx("span",{className:"notification-message",children:w.message}),w.type==="permission_request"&&w.tool&&s.jsxs("span",{className:"notification-tool",children:["Tool: ",s.jsx("code",{children:w.tool})]}),w.type==="policy_alert"&&s.jsxs("div",{className:"notification-policy-details",children:[w.tool&&s.jsxs("span",{className:"notification-tool",children:["Tool: ",s.jsx("code",{children:w.tool})]}),w.reason&&s.jsxs("span",{className:"notification-policy-reason",children:["Reason: ",w.reason]}),w.ruleIds&&w.ruleIds.length>0&&s.jsxs("span",{className:"notification-tool",children:["Rules: ",s.jsx("code",{children:w.ruleIds.join(", ")})]}),w.policyVersion&&s.jsxs("span",{className:"notification-tool",children:["Policy: ",s.jsx("code",{children:w.policyVersion})]}),s.jsxs("span",{className:"notification-tool",children:["Receipt:"," ",w.receiptId?s.jsx("code",{children:w.receiptId}):s.jsx("em",{children:"Receipt unavailable"})]})]}),w.type==="permission_request"&&!w.response&&s.jsxs("div",{className:"notification-actions",children:[s.jsxs("button",{className:"notification-action-btn notification-action-allow",onClick:k=>{k.stopPropagation(),m(w)},children:[s.jsx(li,{size:14}),"Approve"]}),s.jsxs("button",{className:"notification-action-btn notification-action-deny",onClick:k=>{k.stopPropagation(),g(w)},children:[s.jsx(tt,{size:14}),"Deny"]})]}),w.type==="permission_request"&&w.response&&s.jsx("span",{className:`notification-response-badge ${w.response==="allow"?"response-allow":"response-deny"}`,children:w.response==="allow"?"Approved":"Denied"})]}),s.jsx("button",{className:"notification-dismiss",onClick:k=>{k.stopPropagation(),a(w.id)},"aria-label":"Dismiss notification",children:s.jsx(tt,{size:14})})]},w.id)})}),t.length>0&&s.jsxs("div",{className:"notification-center-footer",children:[s.jsxs("button",{className:"notification-footer-btn",onClick:i,disabled:n===0,children:[s.jsx(li,{size:14}),"Mark All Read"]}),s.jsxs("button",{className:"notification-footer-btn notification-footer-clear",onClick:l,children:[s.jsx(ci,{size:14}),"Clear"]})]})]})}function ia({show:e,children:t,duration:n=250}){const[r,i]=p.useState(!1),[l,a]=p.useState("idle");return p.useEffect(()=>{if(e)i(!0),requestAnimationFrame(()=>a("entering"));else if(r){a("exiting");const o=setTimeout(()=>{i(!1),a("idle")},n);return()=>clearTimeout(o)}},[e,r,n]),r?s.jsx("div",{className:`animated-presence ${l}`,"data-duration":n,children:t}):null}function ZT(){const{currentSessionId:e,setSessions:t,setCurrentSession:n,addSession:r,removeSession:i,updateSessionInList:l,setMessages:a,showDocLibrary:o,showFileBrowser:c,showSettings:u,showMemoryDashboard:d,sidebarOpen:f,toggleSidebar:h,setSidebarOpen:m,systemStatus:g,setSystemStatus:v,setBackendConnected:w,setAgents:x}=we(),k=ot(H=>H.showPanel),j=ot(H=>H.setShowPanel),z=p.useRef(""),A=p.useCallback(async()=>{try{const le=(await Nd()).agents||[],Pe=le.map(Ae=>Ae.id).sort().join(",");Pe!==z.current&&(z.current=Pe,x(le))}catch{}},[x]);p.useEffect(()=>{A();const H=setInterval(A,3e4);return()=>clearInterval(H)},[A]);const[_,D]=p.useState(!1),[C,M]=p.useState(!1),[N,U]=p.useState(!1),[O,re]=p.useState(null),ie=p.useRef(null),X=p.useRef(0),xe=3,ce=p.useCallback(async()=>{try{const H=await Sd();if(w(!0),H.lemonade_running)X.current=0,v(H);else if(X.current+=1,E.system.warn(`Lemonade health check failed (${X.current}/${xe})`),X.current>=xe)v(H);else{const le=we.getState().systemStatus;le&&le.lemonade_running?v({...le,disk_space_gb:H.disk_space_gb,memory_available_gb:H.memory_available_gb}):v(H)}E.system.info("System status:",{lemonade:H.lemonade_running,model:H.model_loaded,failCount:X.current})}catch(H){E.system.warn("System status check failed",H),w(!1),v(null)}},[v,w]),T=p.useRef(3e3);p.useEffect(()=>(ce(),T.current=3e3,ie.current=setInterval(ce,3e3),()=>{ie.current&&clearInterval(ie.current)}),[ce]),p.useEffect(()=>{const H=g==null?void 0:g.init_state;if(!H||H==="initializing")return;const le=15e3;le!==T.current&&(T.current=le,ie.current&&clearInterval(ie.current),ie.current=setInterval(ce,le))},[g==null?void 0:g.init_state,ce]);const P=p.useRef(null),b=p.useRef("");p.useEffect(()=>{e0("0.18.0"),E.system.info("App mounting, loading sessions...");const H=E.system.time(),le=Ae=>Ae.map($e=>`${$e.id}|${$e.updated_at}|${$e.title}`).join(`
549
+ Import?`)){o({kind:"working",message:"Uploading…"});try{const z=new FormData;z.append("bundle",v,v.name);const A=await fetch(`${Wh}/agents/import`,{method:"POST",headers:{"X-Gaia-UI":"1"},body:z});if(!A.ok){const N=await A.text().catch(()=>"");let U=N;try{U=JSON.parse(N).detail||N}catch{}throw new Error(U||`Import failed (HTTP ${A.status})`)}const _=await A.json(),D=_.imported||[],C=_.overwritten||[];await c();let M;if(D.length===0?M="No agents imported":(M=`Installed ${D.length} agent(s): ${D.join(", ")}`,C.length>0&&(M+=` (replaced: ${C.join(", ")})`)),_.requires_restart&&(M+=" — restart required for replaced agents to take full effect"),_.errors&&_.errors.length>0){const N=_.errors.map(U=>`${U.id}: ${U.error}`).join("; ");o({kind:"error",message:`${M}. Errors: ${N}`})}else o({kind:"success",message:M})}catch(z){console.error("Agent import failed:",z);const A=z instanceof Error?z.message:String(z);E.api.error("Agent import failed",z),o({kind:"error",message:`Import failed: ${A}`})}}},[o,c]),m=n.kind==="working";return s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Custom Agents"}),u.length===0?s.jsx("p",{className:"danger-warning",style:{marginBottom:12},children:"No custom agents installed yet. Import a bundle below to add one."}):s.jsx("div",{className:"status-grid",style:{marginBottom:12},children:u.map(g=>s.jsxs("div",{className:"status-row",children:[s.jsx("span",{className:"status-label",children:g.name}),s.jsxs("div",{className:"status-value-wrap",children:[s.jsx("span",{className:"status-value ok",children:g.id}),g.source&&g.source!=="builtin"&&s.jsx("span",{className:"status-hint",children:s.jsx("code",{children:g.source})})]})]},g.id))}),s.jsxs("div",{className:"setting-actions",style:{display:"flex",gap:8,flexWrap:"wrap"},children:[s.jsx("button",{className:"btn-model-save",onClick:d,disabled:m||u.length===0,title:u.length===0?"No custom agents to export":void 0,children:m&&n.message.startsWith("Export")?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Exporting…"]}):s.jsxs(s.Fragment,{children:[s.jsx(oi,{size:13,style:{verticalAlign:-2,marginRight:6}}),"Export All"]})}),s.jsx("button",{className:"btn-model-save",onClick:f,disabled:m,children:m&&n.message.startsWith("Upload")?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Uploading…"]}):s.jsxs(s.Fragment,{children:[s.jsx(pl,{size:13,style:{verticalAlign:-2,marginRight:6}}),"Import"]})}),s.jsx("input",{ref:i,type:"file",accept:".zip,application/zip",style:{display:"none"},onChange:h})]}),n.kind!=="idle"&&s.jsxs("div",{ref:a,className:"danger-warning",style:{marginTop:12,display:"flex",alignItems:"center",gap:8,color:n.kind==="error"?"var(--accent-gold)":"var(--text-secondary)"},role:"status",children:[n.kind==="working"&&s.jsx(mt,{size:14,className:"btn-spinner"}),n.kind==="success"&&s.jsx(nr,{size:14}),n.kind==="error"&&s.jsx(kt,{size:14}),s.jsx("span",{children:n.message})]})]})}async function ST(e){const t=await e.arrayBuffer(),n=new DataView(t),r=new Uint8Array(t),i=Math.min(t.byteLength,65557),l=t.byteLength-i;let a=-1;for(let d=t.byteLength-22;d>=l;d--)if(n.getUint32(d,!0)===101010256){a=d;break}if(a<0)return null;const o=n.getUint16(a+10,!0);let u=n.getUint32(a+16,!0);for(let d=0;d<o;d++){if(u+46>t.byteLength||n.getUint32(u,!0)!==33639248)return null;const f=n.getUint16(u+10,!0),h=n.getUint32(u+20,!0),m=n.getUint16(u+28,!0),g=n.getUint16(u+30,!0),v=n.getUint16(u+32,!0),w=n.getUint32(u+42,!0);if(new TextDecoder("utf-8").decode(r.subarray(u+46,u+46+m))==="bundle.json"){if(w+30>t.byteLength||n.getUint32(w,!0)!==67324752)return null;const k=n.getUint16(w+26,!0),j=n.getUint16(w+28,!0),z=w+30+k+j,A=z+h;if(A>t.byteLength)return null;const _=r.subarray(z,A);let D;if(f===0)D=new TextDecoder("utf-8").decode(_);else if(f===8){const N=new DecompressionStream("deflate-raw"),U=new Blob([_]).stream().pipeThrough(N),O=await new Response(U).arrayBuffer();D=new TextDecoder("utf-8").decode(O)}else return null;const C=JSON.parse(D),M=C==null?void 0:C.agent_ids;return Array.isArray(M)&&M.every(N=>typeof N=="string")?M:null}u+=46+m+g+v}return null}const Gh=E.api;function NT(e){switch(e){case"connector.configured":return"configured";case"connector.disconnected":return"disconnected";case"connection.revoked":return"disconnected";case"connector.oauth.completed":return"oauth_completed";case"connection.connected":return"oauth_completed";case"connector.oauth.error":return"oauth_error";case"connector.tested":return"tested";case"connector.enabled":return"enabled";case"connector.disabled":return"disabled";case"connector.grant.changed":return"grant_changed";default:return null}}function CT(e){const t=p.useRef(e);p.useEffect(()=>{t.current=e},[e]),p.useEffect(()=>{const n=`${jd()}/connectors/events`;let r=null,i=1e3,l=null,a=!1;const o=()=>{a||(r=new EventSource(n),r.onopen=()=>{i=1e3},r.onmessage=c=>{try{const u=JSON.parse(c.data),d=NT(u.type);if(d===null){Gh.debug("connectors-sse: ignoring event",u.type);return}const f=u.payload??{},h=f.connector_id??f.provider??null;t.current({connectorId:h,reason:d,payload:f})}catch(u){Gh.warn("connectors-sse: malformed event",u)}},r.onerror=()=>{r==null||r.close(),r=null,!a&&(l=setTimeout(o,i),i=Math.min(i*2,3e4))})};return o(),()=>{a=!0,l&&clearTimeout(l),r==null||r.close()}},[])}function _T(e){return e.type==="mcp_server"&&e.configured}function ET({connector:e,onChanged:t}){const[n,r]=p.useState(!1),[i,l]=p.useState(!1),[a,o]=p.useState(null),[c,u]=p.useState(null),d=p.useRef(null),f=p.useRef(null);if(p.useEffect(()=>{if(!n)return;const v=w=>{const x=w.target;d.current&&!d.current.contains(x)&&f.current&&!f.current.contains(x)&&r(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[n]),p.useEffect(()=>{if(!n)return;const v=w=>{w.key==="Escape"&&r(!1)};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[n]),p.useEffect(()=>{if(!n)return;const v=()=>{if(!d.current)return;const w=d.current.getBoundingClientRect();u({top:w.bottom+4,right:window.innerWidth-w.right})};return window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)}},[n]),!_T(e))return null;const h=v=>{v.stopPropagation(),v.preventDefault()},m=v=>{if(h(v),!n&&d.current){const w=d.current.getBoundingClientRect();u({top:w.bottom+4,right:window.innerWidth-w.right})}r(w=>!w)},g=async v=>{l(!0),o(null);try{await v(),r(!1),t()}catch(w){o(w instanceof Error?w.message:String(w))}finally{l(!1)}};return s.jsxs("div",{className:"connector-tile-menu",onClick:h,onKeyDown:h,children:[s.jsx("button",{ref:d,type:"button",className:"connector-tile-menu-trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":"Connector actions",onClick:m,disabled:i,children:s.jsx(ow,{size:14})}),n&&c&&s.jsxs("div",{ref:f,role:"menu",className:"connector-tile-menu-popup",style:{position:"fixed",top:c.top,right:c.right},children:[e.enabled?s.jsx("button",{role:"menuitem",type:"button",className:"connector-tile-menu-item",onClick:()=>void g(()=>Ty(e.id)),disabled:i,children:"Disable"}):s.jsx("button",{role:"menuitem",type:"button",className:"connector-tile-menu-item",onClick:()=>void g(()=>Ey(e.id)),disabled:i,children:"Enable"}),s.jsx("div",{className:"connector-tile-menu-divider"}),s.jsx("button",{role:"menuitem",type:"button",className:"connector-tile-menu-item connector-tile-menu-item--danger",onClick:()=>void g(()=>Cd(e.id)),disabled:i,children:"Disconnect"}),a&&s.jsx("div",{className:"connector-tile-menu-error",children:a})]})]})}const TT={"https://www.googleapis.com/auth/gmail.readonly":"Read emails","https://www.googleapis.com/auth/gmail.modify":"Organize emails (archive, label, trash)","https://www.googleapis.com/auth/gmail.send":"Send emails on your behalf","https://www.googleapis.com/auth/gmail.compose":"Compose emails","https://www.googleapis.com/auth/calendar.readonly":"View calendar events","https://www.googleapis.com/auth/calendar.events":"Create & respond to calendar events","https://www.googleapis.com/auth/drive.readonly":"Read Google Drive files","https://www.googleapis.com/auth/drive.file":"Manage Drive files created by this app","https://www.googleapis.com/auth/spreadsheets.readonly":"Read Google Sheets","https://www.googleapis.com/auth/spreadsheets":"Edit Google Sheets",openid:"Identify you",email:"See your email address",profile:"See your basic profile info"};function zT(e){return TT[e]??e.split(/[/.:]/).pop()??e}function LT(){const[e,t]=p.useState([]),[n,r]=p.useState([]),[i,l]=p.useState(!0),[a,o]=p.useState(null),[c,u]=p.useState(null),d=p.useCallback(async()=>{try{const[{connectors:m},{agent_mcps:g}]=await Promise.all([s0(),l0()]);t(m),r(g),o(null)}catch(m){o(m instanceof Error?m.message:String(m))}finally{l(!1)}},[]);p.useEffect(()=>{d()},[d]);const f=m=>u(g=>g===m?null:m),h=p.useCallback(async m=>{try{const g=await Ny(m);t(v=>v.map(w=>w.id===m?g:w))}catch{d()}},[d]);return CT(p.useCallback(m=>{m.connectorId?h(m.connectorId):d()},[h,d])),s.jsxs("section",{className:"settings-section connectors-section",children:[s.jsx("h4",{children:"Connectors"}),s.jsx("p",{className:"settings-help",children:"Connect external accounts and MCP servers so agents can use them on your behalf. Each agent must be granted scopes individually."}),a&&s.jsxs("div",{className:"error-banner",children:[s.jsx(kt,{size:14}),s.jsx("span",{children:a})]}),i?s.jsx("div",{className:"connectors-loading",children:s.jsx(mt,{size:16,className:"spin"})}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"connectors-list",children:e.map(m=>s.jsx(IT,{connector:m,expanded:c===m.id,onToggle:()=>f(m.id),onChanged:()=>void h(m.id)},m.id))}),n.length>0&&s.jsx(MT,{servers:n,expanded:c,onToggle:f})]})]})}function IT({connector:e,expanded:t,onToggle:n,onChanged:r}){const i=()=>e.configured?e.type==="mcp_server"&&e.enabled===!1?s.jsx("span",{className:"connector-status disabled",children:"Disabled"}):s.jsxs("span",{className:"connector-status ok",children:[s.jsx(nr,{size:12}),e.account_id??"Configured"]}):s.jsx("span",{className:"connector-status idle",children:"Not configured"});return s.jsxs("div",{className:`connector-tile${t?" connector-tile--open":""}`,children:[s.jsxs("button",{className:"connector-tile-header",onClick:n,"aria-expanded":t,children:[s.jsx("span",{className:"connector-tile-name",children:e.display_name}),s.jsx("span",{className:"connector-tile-type",children:e.type==="oauth_pkce"?"OAuth":"MCP"}),i(),s.jsx(ET,{connector:e,onChanged:r}),s.jsx("span",{className:"connector-tile-chevron",children:t?s.jsx(cy,{size:14}):s.jsx(ai,{size:14})})]}),t&&s.jsxs("div",{className:"connector-detail",children:[e.type==="oauth_pkce"?s.jsx(DT,{connector:e,onChanged:r}):s.jsx(AT,{connector:e,onChanged:r}),e.configured&&s.jsx($T,{connectorId:e.id})]})]})}function DT({connector:e,onChanged:t}){const[n,r]=p.useState(!1),[i,l]=p.useState(null),[a,o]=p.useState({});p.useEffect(()=>{const g=()=>{t()};return window.addEventListener("focus",g),()=>window.removeEventListener("focus",g)},[t]);const c=g=>{var w;const v=window;(w=v.gaia)!=null&&w.openExternal?v.gaia.openExternal(g):window.open(g,"_blank","noopener")},u=async()=>{var g;r(!0),l(null);try{const v=await Cy(e.id,(g=e.available_scopes)!=null&&g.length?e.available_scopes:e.default_scopes);c(v.authorization_url)}catch(v){l(v instanceof Error?v.message:String(v))}finally{r(!1)}},d=async()=>{r(!0),l(null);try{await Cd(e.id),t()}catch(g){l(g instanceof Error?g.message:String(g))}finally{r(!1)}},f=async()=>{var v;const g=(e.oauth_setup_fields??[]).filter(w=>{var x;return w.required!==!1&&!((x=a[w.key])!=null&&x.trim())}).map(w=>w.label);if(g.length){l(`Required: ${g.join(", ")}`);return}r(!0),l(null);try{const w=(v=e.available_scopes)!=null&&v.length?e.available_scopes:e.default_scopes,x=await _y(e.id,{...a,scopes:w}),k=typeof x.authorization_url=="string"?x.authorization_url:null;k&&c(k),t()}catch(w){l(w instanceof Error?w.message:String(w))}finally{r(!1)}},h=e.oauth_setup_fields??[],m=e.configurable===!1&&!e.configured&&h.length>0;return s.jsxs("div",{className:"configure-body",children:[e.description&&s.jsx("p",{className:"connector-desc",children:e.description}),m&&s.jsxs("div",{className:"oauth-setup-form",children:[s.jsx("p",{className:"connector-desc",children:"First-time setup — provide your OAuth client credentials below. They’re stored encrypted in your OS keyring and reused for future connections."}),h.map(g=>s.jsxs("label",{className:"oauth-setup-field",children:[s.jsx("span",{className:"oauth-setup-label",children:g.label}),s.jsx("input",{type:g.kind==="secret"?"password":"text",className:"oauth-setup-input",placeholder:g.placeholder,value:a[g.key]??"",onChange:v=>o(w=>({...w,[g.key]:v.target.value})),autoComplete:"off",spellCheck:!1}),g.help_md&&s.jsx("span",{className:"oauth-setup-help",children:g.help_md})]},g.key))]}),i&&s.jsxs("div",{className:"configure-error",children:[s.jsx(kt,{size:12})," ",i]}),s.jsxs("div",{className:"configure-actions",children:[e.configured?s.jsx("button",{className:"btn-secondary",disabled:n,onClick:()=>void d(),children:n?s.jsx(mt,{size:12,className:"spin"}):"Disconnect"}):m?s.jsx("button",{className:"btn-primary",disabled:n,onClick:()=>void f(),children:n?s.jsx(mt,{size:12,className:"spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Vi,{size:12})," Save & Connect"]})}):e.configurable===!1?s.jsx("span",{className:"connector-setup-required",title:e.config_error??void 0,children:"Setup required"}):s.jsx("button",{className:"btn-primary",disabled:n,onClick:()=>void u(),children:n?s.jsx(mt,{size:12,className:"spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Vi,{size:12})," Connect"]})}),(e.docs_url||e.product_url)&&s.jsxs("a",{href:e.docs_url||e.product_url||"#",target:"_blank",rel:"noopener noreferrer",className:"connector-product-link",children:["Learn more ",s.jsx(Vi,{size:11})]})]})]})}function AT({connector:e,onChanged:t}){const[n,r]=p.useState(()=>Object.fromEntries(e.mcp_env_keys.map(m=>[m,""]))),[i,l]=p.useState(!1),[a,o]=p.useState(!1),[c,u]=p.useState(null);p.useEffect(()=>{r(Object.fromEntries(e.mcp_env_keys.map(m=>[m,""])))},[e.mcp_env_keys.join(",")]);const d=async()=>{const m=Object.fromEntries(Object.entries(n).filter(([,g])=>g.trim()!==""));if(Object.keys(m).length!==0){l(!0),u(null),o(!1);try{await _y(e.id,m),o(!0),t(),setTimeout(()=>o(!1),2200)}catch(g){u(g instanceof Error?g.message:String(g))}finally{l(!1)}}},f=async()=>{l(!0),u(null);try{await Cd(e.id),r(Object.fromEntries(e.mcp_env_keys.map(m=>[m,""]))),t()}catch(m){u(m instanceof Error?m.message:String(m))}finally{l(!1)}},h=async()=>{l(!0),u(null);try{e.enabled?await Ty(e.id):await Ey(e.id),t()}catch(m){u(m instanceof Error?m.message:String(m))}finally{l(!1)}};return s.jsxs("div",{className:"configure-body",children:[e.description&&s.jsx("p",{className:"connector-desc",children:e.description}),c&&s.jsxs("div",{className:"configure-error",children:[s.jsx(kt,{size:12})," ",c]}),e.configured&&s.jsxs("div",{className:"connector-toggle-row",children:[s.jsx("span",{className:"connector-toggle-label",children:"Active"}),s.jsxs("span",{className:"toggle-switch",children:[s.jsx("input",{type:"checkbox",checked:e.enabled!==!1,onChange:()=>void h(),disabled:i,"aria-label":e.enabled?"Disable this MCP server":"Enable this MCP server"}),s.jsx("span",{className:"toggle-track"})]})]}),e.configured&&e.enabled===!1&&s.jsx("p",{className:"connector-toggle-help",children:"Credentials and per-agent grants are preserved. Re-enable to make this server's tools available again."}),e.mcp_env_keys.map(m=>s.jsxs("div",{className:"mcp-key-row",children:[s.jsx("label",{className:"mcp-key-label",children:m}),s.jsx("input",{type:"password",className:"mcp-key-input",placeholder:e.configured?"••••••••":"Enter value",value:n[m]??"",onChange:g=>r(v=>({...v,[m]:g.target.value})),spellCheck:!1,autoComplete:"off"})]},m)),s.jsxs("div",{className:"configure-actions",children:[s.jsx("button",{className:`btn-model-save${a?" saved":""}`,disabled:i||Object.values(n).every(m=>m.trim()===""),onClick:()=>void d(),children:i?s.jsx(mt,{size:12,className:"spin"}):a?s.jsxs(s.Fragment,{children:[s.jsx(nr,{size:12})," Saved"]}):"Save"}),e.configured&&s.jsx("button",{className:"btn-secondary",disabled:i,onClick:()=>void f(),children:"Disconnect"}),e.product_url&&s.jsxs("a",{href:e.product_url,target:"_blank",rel:"noopener noreferrer",className:"connector-product-link",children:["Docs ",s.jsx(Vi,{size:11})]})]})]})}function PT({agent:e,connectorId:t,grantedScopes:n,onChanged:r}){var m;const i=(m=e.required_connections)==null?void 0:m.find(g=>g.connector_id===t),l=e.namespaced_agent_id;if(!i||!l)return null;const[a,o]=p.useState(()=>new Set(n)),[c,u]=p.useState(null),[d,f]=p.useState(null);p.useEffect(()=>{o(new Set(n))},[n.join(",")]);const h=async g=>{if(c!==null)return;const v=new Set(a);v.has(g)?v.delete(g):v.add(g),o(v),u(g),f(null);try{v.size===0?await c0(t,l):await o0(t,l,[...v]),r()}catch(w){o(new Set(n)),f(w instanceof Error?w.message:String(w))}finally{u(null)}};return s.jsxs("div",{className:"grant-agent-card",children:[s.jsx("div",{className:"grant-agent-card-name",children:e.name}),s.jsx("div",{className:"grant-scope-list",children:i.scopes.map(g=>s.jsxs("label",{className:"grant-scope-item",children:[s.jsx("span",{className:"grant-scope-label",children:zT(g)}),s.jsxs("span",{className:"toggle-switch",children:[s.jsx("input",{type:"checkbox",checked:a.has(g),onChange:()=>void h(g),disabled:c!==null}),s.jsx("span",{className:"toggle-track"})]})]},g))}),d&&s.jsxs("div",{className:"grant-scope-warning grant-scope-warning--error",children:[s.jsx(kt,{size:11})," ",d]})]})}function MT({servers:e,expanded:t,onToggle:n}){return s.jsxs("div",{className:"agent-mcps-section",children:[s.jsx("div",{className:"agent-mcps-section-header",children:"Custom agent servers"}),s.jsx("div",{className:"connectors-list",children:e.map(r=>{const i=`${r.agent_id}::${r.server_name}`;return s.jsx(RT,{server:r,expanded:t===i,onToggle:()=>n(i)},i)})})]})}function RT({server:e,expanded:t,onToggle:n}){const r=[e.command,...e.args].join(" ");return s.jsxs("div",{className:`agent-mcp-tile${t?" agent-mcp-tile--open":""}`,children:[s.jsxs("button",{type:"button",className:"agent-mcp-tile-header",onClick:n,"aria-expanded":t,children:[s.jsx("span",{className:"agent-mcp-server-name",children:e.server_name}),s.jsxs("span",{className:"agent-mcp-agent-label",children:["via ",e.agent_name]}),e.disabled?s.jsx("span",{className:"agent-mcp-status disabled",children:"Disabled"}):s.jsxs("span",{className:"agent-mcp-status enabled",children:[s.jsx(nr,{size:11})," Active"]}),s.jsx("span",{className:"agent-mcp-readonly-badge",children:"read-only"}),s.jsx("span",{className:"agent-mcp-chevron",children:t?s.jsx(cy,{size:14}):s.jsx(ai,{size:14})})]}),t&&s.jsxs("div",{className:"agent-mcp-detail",children:[r&&s.jsx("div",{className:"agent-mcp-command-row",children:r}),s.jsx("div",{className:"agent-mcp-config-path",children:e.config_path}),s.jsxs("div",{className:"agent-mcp-config-hint",children:["Edit the agent's ",s.jsx("code",{children:"mcp_servers.json"})," to change this server."]})]})]})}function $T({connectorId:e}){const{agents:t}=we(),[n,r]=p.useState({}),[i,l]=p.useState(!0),a=p.useCallback(async()=>{try{const{grants:c}=await a0(e);r(c)}catch{r({})}finally{l(!1)}},[e]);if(p.useEffect(()=>{a()},[a]),i)return null;const o=t.filter(c=>{var u;return c.namespaced_agent_id&&((u=c.required_connections)==null?void 0:u.some(d=>d.connector_id===e))});return s.jsxs("div",{className:"connection-grants",children:[s.jsx("div",{className:"grants-header",children:"Per-agent grants"}),o.length===0?s.jsx("div",{className:"grants-empty",children:"No agents require access to this connector."}):o.map(c=>s.jsx(PT,{agent:c,connectorId:e,grantedScopes:n[c.namespaced_agent_id]??[],onChanged:()=>void a()},c.namespaced_agent_id))]})}function FT(){const{setShowSettings:e,sessions:t,removeSession:n,agents:r}=we(),[i,l]=p.useState(null),[a,o]=p.useState(!0),[c,u]=p.useState([]),[d,f]=p.useState(""),[h,m]=p.useState(""),[g,v]=p.useState(!1),[w,x]=p.useState(!1),[k,j]=p.useState(null),[z,A]=p.useState(!1),_=p.useRef(null);p.useEffect(()=>{E.system.info("Checking system status...");const L=E.system.time();Sd().then(F=>{l(F),E.system.timed("System status received",L,{lemonade:F.lemonade_running?"running":"stopped",model:F.model_loaded||"none",embedding:F.embedding_model_loaded?"yes":"no",disk:`${F.disk_space_gb}GB free`,memory:F.memory_available_gb!=null?`${F.memory_available_gb}GB available`:"unknown"}),F.lemonade_running||E.system.warn("Lemonade Server is NOT running.")}).catch(F=>{E.system.error("Failed to get system status",F),l(null)}).finally(()=>o(!1)),E0().then(F=>u(F.servers)).catch(()=>{}),t0().then(F=>{const Y=F.custom_model??"";f(Y),m(Y)}).catch(F=>{E.system.error("Failed to load settings",F)}).finally(()=>v(!0))},[]),p.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const D=p.useCallback(async()=>{const L=d.trim(),F=L.length>0?L:"";x(!0),j(null),A(!1);try{E.system.info("Saving custom_model override",{custom_model:F});const ue=(await n0({custom_model:F})).custom_model??"";f(ue),m(ue),A(!0),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>A(!1),2200)}catch(Y){const ue=Y instanceof Error?Y.message:String(Y);E.system.error("Failed to save custom_model",Y),j(ue)}finally{x(!1)}},[d]),C=d.trim()!==h.trim(),M=(i==null?void 0:i.default_model_name)??Qd,{isLoadingModel:N,isDownloadingModel:U,loadModel:O,downloadModel:re}=Kx(M),ie=[{label:"4K",value:4096},{label:"8K",value:8192},{label:"16K",value:16384},{label:"32K",value:32768}],X=(i==null?void 0:i.model_context_size)??null,[xe,ce]=p.useState("");p.useEffect(()=>{X!=null&&ce(String(X))},[X]);const T=(()=>{const L=parseInt(xe,10);return Number.isFinite(L)&&L>0?L:null})(),P=T!=null&&T!==X,b=(i==null?void 0:i.model_loaded)??M,J=p.useCallback(async()=>{T&&(E.system.info(`Reloading ${b} with ctx_size=${T}`),await O(b,T))},[T,b,O]),[B,S]=p.useState(!1),oe=p.useRef(null);p.useEffect(()=>()=>{oe.current&&clearTimeout(oe.current)},[]);const pe=p.useCallback(async()=>{if(!B){S(!0),oe.current&&clearTimeout(oe.current),oe.current=setTimeout(()=>S(!1),4e3);return}S(!1),oe.current&&clearTimeout(oe.current),E.system.warn(`Clearing ALL data: ${t.length} session(s)`);const L=E.system.time();let F=0;for(const Y of t)try{await zy(Y.id),n(Y.id),F++}catch(ue){E.system.error(`Failed to delete session ${Y.id}`,ue)}E.system.timed(`Cleared ${F}/${t.length} session(s)`,L),e(!1)},[B,t,n,e]),ae="0.18.1",_e=!!(i!=null&&i.lemonade_running&&i.model_loaded&&i.expected_model_loaded===!1),He=!!(i!=null&&i.lemonade_running&&i.model_loaded&&i.context_size_sufficient===!1),nt=!!(i!=null&&i.lemonade_running&&!i.model_loaded&&i.model_downloaded===!1),Ge=_e||He;return s.jsxs("div",{className:"settings-page",children:[s.jsxs("div",{className:"settings-page-header",children:[s.jsx("button",{className:"btn-icon settings-back-btn",onClick:()=>e(!1),"aria-label":"Back",children:s.jsx(ay,{size:18})}),s.jsx("h3",{children:"Settings"})]}),s.jsxs("div",{className:"settings-page-body",children:[s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"System Status"}),a?s.jsx("p",{className:"loading-text",children:"Checking system..."}):i?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"status-grid",children:[s.jsx(Sn,{label:"Lemonade Server",value:i.lemonade_running?`Running${i.lemonade_version?` v${i.lemonade_version}`:""}`:"Not Running",ok:i.lemonade_running,hint:i.lemonade_running?void 0:i.initialized?"Run: lemonade-server serve":"Run: gaia init --profile chat"}),s.jsx(Sn,{label:"Model",value:i.model_loaded||"None loaded",ok:!!i.model_loaded&&i.expected_model_loaded!==!1,hint:i.model_loaded?i.expected_model_loaded===!1?`Expected: ${M}`:void 0:"Run: gaia init --profile chat"}),i.model_size_gb!=null&&s.jsx(Sn,{label:"Model Size",value:`${i.model_size_gb} GB`,ok:!0}),i.model_device&&s.jsx(Sn,{label:"Device",value:i.model_device.toUpperCase(),ok:i.model_device!=="cpu"}),i.model_context_size!=null&&s.jsx(Sn,{label:"Context Window",value:`${(i.model_context_size/1024).toFixed(0)}K tokens`,ok:i.context_size_sufficient}),i.model_labels&&i.model_labels.length>0&&s.jsx(Sn,{label:"Capabilities",value:i.model_labels.join(", "),ok:!0}),s.jsx(Sn,{label:"Embedding Model",value:i.embedding_model_loaded?"Available":"Not loaded",ok:i.embedding_model_loaded}),i.gpu_name&&s.jsx(Sn,{label:"GPU",value:`${i.gpu_name}${i.gpu_vram_gb?` (${i.gpu_vram_gb} GB)`:""}`,ok:!0}),s.jsx(Sn,{label:"Disk Space",value:`${i.disk_space_gb} GB free`,ok:i.disk_space_gb>5,hint:!i.model_loaded&&i.disk_space_gb<30?`Models require ~25 GB — only ${i.disk_space_gb} GB available`:void 0}),s.jsx(Sn,{label:"Memory",value:i.memory_available_gb!=null?`${i.memory_available_gb} GB available`:"unknown",ok:i.memory_available_gb!=null&&i.memory_available_gb>2}),i.processor_name&&s.jsx(Sn,{label:"Processor",value:i.processor_name,ok:i.device_supported!==!1})]}),nt&&s.jsxs("div",{className:"model-action-row model-action-row--download",children:[s.jsxs("div",{className:"model-action-info",children:[s.jsx("span",{className:"model-action-label",children:"Model not downloaded."}),s.jsxs("span",{className:"model-action-desc",children:[s.jsx("strong",{children:M})," is required for GAIA Chat (~25 GB)."]})]}),s.jsx("button",{className:"btn-model-action btn-model-action--download",onClick:()=>re(!1),disabled:U,children:U?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Downloading…"]}):"Download"})]}),Ge&&s.jsxs("div",{className:"model-action-row model-action-row--load",children:[s.jsxs("div",{className:"model-action-info",children:[s.jsx("span",{className:"model-action-label",children:_e?"Wrong model loaded.":"Context window too small."}),s.jsxs("span",{className:"model-action-desc",children:["Load ",s.jsx("strong",{children:M})," with ",(Ys/1024).toFixed(0),"K token context."]})]}),s.jsx("button",{className:"btn-model-action btn-model-action--load",onClick:()=>O(),disabled:N,children:N?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Loading…"]}):"Load Model"})]}),i.lemonade_running&&s.jsxs("div",{className:"force-redownload-row",children:[s.jsx("span",{className:"force-redownload-label",children:"If the model file is corrupted:"}),s.jsx("button",{className:"btn-force-redownload",onClick:()=>re(!0),disabled:U,children:U?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:12,className:"btn-spinner"})," Downloading…"]}):"Force Re-download"})]})]}):s.jsxs("div",{className:"status-error",children:[s.jsx("p",{children:"Could not connect to server"}),s.jsx("code",{children:"gaia chat --ui"})]})]}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Active Model"}),s.jsx("p",{className:"model-override-desc",children:"Override the model used by the active agent. Leave empty to use the current agent’s preferred model."}),s.jsxs("div",{className:"model-input-row",children:[s.jsx("input",{type:"text",className:`model-input${h?" has-override":""}`,placeholder:"Use agent default",value:d,onChange:L=>{f(L.target.value),j(null),A(!1)},onKeyDown:L=>{L.key==="Enter"&&!w&&C&&g&&(L.preventDefault(),D())},disabled:!g||w,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off","aria-label":"Custom model override"}),s.jsx("div",{className:"model-btn-group",children:s.jsx("button",{className:`btn-model-save${z?" saved":""}`,onClick:()=>{D()},disabled:!g||w||!C&&!z,"aria-label":"Save custom model",children:w?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Saving…"]}):z?s.jsxs(s.Fragment,{children:[s.jsx(nr,{size:13})," Saved"]}):"Save"})})]}),s.jsxs("p",{className:"model-status-hint",children:["Accepts a Lemonade model ID (e.g. ",s.jsx("code",{children:"Qwen3-4B-Instruct-2507-GGUF"}),")"," ","or a HuggingFace ID (e.g. ",s.jsx("code",{children:"unsloth/Qwen3-4B-GGUF"}),")."]}),k&&s.jsxs("div",{className:"model-warning",role:"alert",children:[s.jsx(kt,{size:14}),s.jsxs("div",{className:"model-warning-content",children:[s.jsx("strong",{children:"Could not save"}),s.jsx("p",{children:k})]})]})]}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Context Size"}),s.jsx("p",{className:"model-override-desc",children:"Reload the active model with a different context window. Larger contexts use more memory and slow inference; going past the model’s training length may degrade quality."}),s.jsx("div",{className:"ctx-preset-row",children:ie.map(L=>{const F=T===L.value;return s.jsx("button",{className:`btn-ctx-preset${F?" active":""}`,onClick:()=>ce(String(L.value)),disabled:N,type:"button",children:L.label},L.value)})}),s.jsxs("div",{className:"model-input-row",children:[s.jsx("input",{type:"number",className:"model-input",placeholder:X!=null?String(X):"4096",value:xe,min:512,step:1024,onChange:L=>ce(L.target.value),disabled:N,"aria-label":"Context size in tokens"}),s.jsx("div",{className:"model-btn-group",children:s.jsx("button",{className:"btn-model-save",onClick:()=>{J()},disabled:N||!P||!(i!=null&&i.lemonade_running),"aria-label":"Reload model with new context size",children:N?s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"btn-spinner"})," Reloading…"]}):"Apply"})})]}),s.jsxs("p",{className:"model-status-hint",children:["Current: ",s.jsx("code",{children:X!=null?`${X.toLocaleString()} tokens`:"unknown"}),(i==null?void 0:i.model_loaded)&&s.jsxs(s.Fragment,{children:[" on ",s.jsx("code",{children:i.model_loaded})]}),"."]})]}),i&&i.memory_available_gb!=null&&(()=>{const L=i.memory_available_gb,F=r.filter(Y=>Y.min_memory_gb!=null&&Y.min_memory_gb>L);return F.length===0?null:s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Memory Warnings"}),s.jsx("div",{className:"status-grid",children:F.map(Y=>s.jsxs("div",{className:"status-row status-row--has-hint",children:[s.jsx("span",{className:"status-label",children:Y.name}),s.jsxs("div",{className:"status-value-wrap",children:[s.jsxs("span",{className:"status-value warn memory-warning-value",children:[s.jsx(kt,{size:12}),"Needs ~",Y.min_memory_gb," GB free"]}),s.jsxs("span",{className:"status-hint",children:["Only ",i.memory_available_gb," GB available — model load may fail or swap heavily."]})]})]},Y.id))})]})})(),c.length>0&&s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"MCP Servers"}),s.jsx("div",{className:"status-grid",children:c.map(L=>s.jsxs("div",{className:"status-row",children:[s.jsx("span",{className:"status-label",children:L.name}),s.jsx("div",{className:"status-value-wrap",children:L.connected?s.jsxs("span",{className:"status-value ok mcp-status-connected",children:[s.jsx(nr,{size:12}),L.tool_count," tool",L.tool_count!==1?"s":""]}):s.jsxs("span",{className:"status-value warn mcp-status-failed",title:L.error??void 0,children:[s.jsx(kt,{size:12}),"Failed"]})})]},L.name))})]}),s.jsx(jT,{}),s.jsx(LT,{}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"About"}),s.jsxs("div",{className:"about-info",children:[s.jsxs("p",{children:["GAIA v",ae," ",s.jsx("span",{className:"beta-badge",children:"BETA"})]}),s.jsx("p",{className:"about-sub",children:"Privacy-first AI chat for AMD Ryzen AI PCs."})]})]}),s.jsxs("section",{className:"settings-section",children:[s.jsx("h4",{children:"Privacy & Data"}),s.jsxs("div",{className:"setting-row",children:[s.jsx("span",{children:"Data location"}),s.jsx("code",{className:"setting-path",children:"~/.gaia/chat/"})]}),s.jsx("div",{className:"danger-divider"}),s.jsxs("div",{className:"setting-actions",children:[s.jsx("p",{className:"danger-warning",children:"This will permanently delete all sessions, messages, and documents."}),s.jsx("button",{className:"btn-danger",onClick:pe,children:B?"Click again to confirm":"Clear All Data"})]})]})]})]})}function Sn({label:e,value:t,ok:n,hint:r}){return s.jsxs("div",{className:`status-row${r?" status-row--has-hint":""}`,children:[s.jsx("span",{className:"status-label",children:e}),s.jsxs("div",{className:"status-value-wrap",children:[s.jsx("span",{className:`status-value ${n?"ok":"warn"}`,children:t}),r&&s.jsx("span",{className:"status-hint",children:s.jsx("code",{children:r})})]})]})}const OT="modulepreload",UT=function(e,t){return new URL(e,t).href},qh={},BT=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){const a=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),c=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(u=>{if(u=UT(u,r),u in qh)return;qh[u]=!0;const d=u.endsWith(".css"),f=d?'[rel="stylesheet"]':"";if(!!r)for(let g=a.length-1;g>=0;g--){const v=a[g];if(v.href===u&&(!d||v.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${u}"]${f}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":OT,d||(m.as="script"),m.crossOrigin="",m.href=u,c&&m.setAttribute("nonce",c),document.head.appendChild(m),d)return new Promise((g,v)=>{m.addEventListener("load",g),m.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${u}`)))})}))}function l(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&l(o.reason);return t().catch(l)})};let yc=null;function HT({isOpen:e,onClose:t,onStop:n,error:r}){const[i,l]=p.useState(null),[a,o]=p.useState(!1),c=p.useRef(null),u=p.useCallback(async()=>{try{const m=await Py();return l(m),m}catch(m){return E.system.error("Failed to fetch tunnel status",m),null}},[]);p.useEffect(()=>{if(!e||r)return;u();const m=setInterval(async()=>{const g=await u();g!=null&&g.active&&(g!=null&&g.url)&&clearInterval(m)},2e3);return()=>clearInterval(m)},[e,r,u]),p.useEffect(()=>{if(!(i!=null&&i.active)||!i.url||!i.token||!c.current)return;const m=`${i.url}/?token=${i.token}`;E.system.info(`Generating QR code for: ${m}`),(async()=>{if(!yc)try{const w=await BT(()=>import("./browser-CTB2jwNe.js").then(x=>x.b),[],import.meta.url);yc=w.default||w}catch{E.system.error("QR code library not available - install with: npm install qrcode");return}const v=document.documentElement.getAttribute("data-theme")==="dark";try{await yc.toCanvas(c.current,m,{width:200,margin:2,color:{dark:v?"#e6edf3":"#111827",light:v?"#0d0d0d":"#ffffff"}})}catch(w){E.system.error("QR code generation failed",w)}})()},[i==null?void 0:i.active,i==null?void 0:i.url,i==null?void 0:i.token]);const d=p.useRef(null),f=p.useCallback(()=>{if(!(i!=null&&i.url)||!(i!=null&&i.token))return;const m=`${i.url}/?token=${i.token}`;navigator.clipboard.writeText(m).then(()=>{o(!0),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>o(!1),2e3)})},[i]);if(p.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]),!e)return null;const h=i!=null&&i.active&&(i!=null&&i.url)&&(i!=null&&i.token)?`${i.url}/?token=${i.token}`:"";return s.jsx("div",{className:"modal-overlay",onClick:t,role:"dialog","aria-modal":"true","aria-label":"Mobile Access",children:s.jsxs("div",{className:"modal-panel mobile-modal",onClick:m=>m.stopPropagation(),children:[s.jsxs("div",{className:"modal-header",children:[s.jsxs("h3",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx(yy,{size:18}),"Mobile Access"]}),s.jsx("button",{className:"btn-icon",onClick:t,"aria-label":"Close",children:s.jsx(tt,{size:18})})]}),s.jsxs("div",{className:"modal-body mobile-modal-body",children:[s.jsxs("div",{className:"tunnel-status",children:[s.jsx("span",{className:`status-dot ${i!=null&&i.active?"active":r?"error":"starting"}`}),s.jsx("span",{children:i!=null&&i.active?"Tunnel active":r?"Connection failed":"Starting tunnel..."}),!(i!=null&&i.active)&&!r&&s.jsx("span",{className:"tunnel-spinner"})]}),r&&s.jsx("div",{className:"tunnel-error",children:r}),s.jsx("div",{className:"qr-code-area",children:i!=null&&i.active?s.jsx("canvas",{ref:c}):r?s.jsx("div",{className:"qr-placeholder error",children:"Failed to connect"}):s.jsxs("div",{className:"qr-placeholder",children:[s.jsx("div",{className:"placeholder-spinner"}),s.jsx("span",{children:"Connecting..."})]})}),(i==null?void 0:i.active)&&h&&s.jsxs("div",{className:"tunnel-url-area",children:[s.jsx("label",{children:"Mobile URL"}),s.jsxs("div",{className:"tunnel-url-row",children:[s.jsx("input",{type:"text",readOnly:!0,value:h}),s.jsxs("button",{className:`copy-url-btn ${a?"copied":""}`,onClick:f,title:"Copy URL",children:[a?s.jsx(li,{size:13}):s.jsx(jl,{size:13}),a?"Copied":"Copy"]})]})]}),(i==null?void 0:i.active)&&(i==null?void 0:i.publicIp)&&(i==null?void 0:i.url)&&!i.url.includes("ngrok-free.app")&&s.jsxs("div",{className:"tunnel-password-hint",children:[s.jsx("label",{children:"Tunnel Password"}),s.jsx("div",{className:"tunnel-password-value",children:i.publicIp}),s.jsx("span",{className:"tunnel-password-note",children:"Enter this when the tunnel page asks for a password"})]}),s.jsx("div",{className:"mobile-instructions",children:s.jsxs("ol",{children:[s.jsx("li",{children:"Scan the QR code with your phone's camera"}),(i==null?void 0:i.url)&&!i.url.includes("ngrok-free.app")&&s.jsx("li",{children:"Enter the tunnel password shown above when prompted"}),s.jsx("li",{children:"Chat with GAIA from your mobile device"}),s.jsx("li",{children:"Your data stays secure via encrypted tunnel"})]})}),s.jsxs("div",{className:"mobile-access-actions",children:[(i==null?void 0:i.active)&&n&&s.jsx("button",{className:"btn-danger",onClick:n,title:"Close the tunnel and revoke the mobile URL",children:"Stop Tunnel"}),s.jsx("button",{className:"btn-secondary",onClick:t,children:"Close"})]})]})]})})}function VT({onRetry:e}){var j;const{backendConnected:t,systemStatus:n,currentSessionId:r,messages:i}=we(),[l,a]=p.useState(!1),o=!!r&&i.length>0,c=(n==null?void 0:n.default_model_name)??Qd,{isLoadingModel:u,isDownloadingModel:d,loadModel:f,downloadModel:h}=Kx(c),m=p.useRef(n==null?void 0:n.lemonade_running),g=p.useRef(n==null?void 0:n.model_downloaded),v=p.useRef(n==null?void 0:n.context_size_sufficient),w=p.useRef(n==null?void 0:n.expected_model_loaded);p.useEffect(()=>{if(o)return;const z=n==null?void 0:n.lemonade_running,A=n==null?void 0:n.model_downloaded,_=n==null?void 0:n.context_size_sufficient,D=n==null?void 0:n.expected_model_loaded;let C=!1;m.current!==z&&(m.current=z,z===!1&&(C=!0)),g.current!==A&&(g.current=A,A===!1&&(C=!0)),v.current!==_&&(v.current=_,_===!1&&(C=!0)),w.current!==D&&(w.current=D,D===!1&&(C=!0)),C&&a(!1)},[n,o]);const x=(n==null?void 0:n.download_progress)??null;if(d||(x==null?void 0:x.state)==="downloading"||(x==null?void 0:x.state)==="starting"||(x==null?void 0:x.state)==="error"){const z=n!=null&&n.default_model_size_gb?`~${n.default_model_size_gb.toFixed(1)} GB`:"large download",A=(x==null?void 0:x.state)==="error";return s.jsxs("div",{className:`connection-banner ${A?"connection-banner--error":"connection-banner--warning"}`,role:A?"alert":"status",children:[s.jsx("div",{className:"connection-banner__icon",children:A?s.jsx(pn,{size:16}):s.jsx(oi,{size:16})}),s.jsx("div",{className:"connection-banner__text",children:A?s.jsxs(s.Fragment,{children:["Download of ",s.jsx("strong",{children:c})," failed."," ",(x==null?void 0:x.message)&&s.jsx("span",{className:"connection-banner__hint",children:x.message})]}):s.jsxs(s.Fragment,{children:["Downloading ",s.jsx("strong",{children:c})," (",z,").",(x==null?void 0:x.state)==="downloading"&&x.file&&s.jsxs(s.Fragment,{children:[" ",s.jsxs("span",{className:"connection-banner__hint",children:["File ",x.file_index," / ",x.total_files,": ",s.jsx("code",{children:x.file})]})]})]})}),A?s.jsx("button",{className:"connection-banner__retry",onClick:()=>h(!1),children:"Retry"}):s.jsx("span",{className:"connection-banner__loading connection-banner__progress",children:x&&x.state==="downloading"&&x.total_bytes>0?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"connection-banner__progress-bar",role:"progressbar","aria-valuenow":x.percent,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Download progress",children:s.jsx("span",{className:"connection-banner__progress-fill",style:{width:`${x.percent}%`}})}),s.jsxs("span",{className:"connection-banner__progress-label",children:[x.percent,"% ·"," ",(x.downloaded_bytes/1e9).toFixed(2)," /"," ",(x.total_bytes/1e9).toFixed(2)," GB"]})]}):s.jsxs(s.Fragment,{children:[s.jsx(mt,{size:13,className:"connection-banner__spinner"}),(x==null?void 0:x.state)==="starting"?"Starting download…":"Downloading…"]})}),A&&s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}if((n==null?void 0:n.init_state)==="initializing"){const z=(j=n.init_tasks)==null?void 0:j.find(_=>_.status==="running"),A=(z==null?void 0:z.name)||"Preparing AI system";return s.jsxs("div",{className:"connection-banner connection-banner--init",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(mt,{size:16,className:"connection-banner__spinner"})}),s.jsxs("div",{className:"connection-banner__text",children:[A,s.jsxs("span",{className:"thinking-dots",children:[s.jsx("span",{children:"."}),s.jsx("span",{children:"."}),s.jsx("span",{children:"."})]})]})]})}if(l||o)return null;if(!t)return s.jsxs("div",{className:"connection-banner connection-banner--error",role:"alert",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(jw,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["Cannot connect to GAIA server."," ",s.jsxs("span",{className:"connection-banner__hint",children:["Start it with: ",s.jsx("code",{children:"gaia chat --ui"})]})]}),e&&s.jsx("button",{className:"connection-banner__retry",onClick:e,children:"Retry"})]});if(n&&!n.lemonade_running)return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(pn,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["LLM server is not responding — it may be busy or not running."," ",s.jsxs("span",{className:"connection-banner__hint",children:["If not started, run: ",s.jsx("code",{children:"lemonade-server serve"})]})]}),e&&s.jsx("button",{className:"connection-banner__retry",onClick:e,children:"Check again"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]});if(n&&n.lemonade_running&&!n.model_loaded&&n.model_downloaded===!1){const z=n.default_model_size_gb?`~${n.default_model_size_gb.toFixed(1)} GB`:"large download";return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(oi,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["Required model ",s.jsx("strong",{children:c})," is not downloaded (",z,")."]}),s.jsx("button",{className:"connection-banner__retry",onClick:()=>h(!1),children:"Download"}),e&&s.jsx("button",{className:"connection-banner__retry connection-banner__retry--secondary",onClick:e,children:"Recheck"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}if(n&&n.lemonade_running&&n.model_loaded&&n.expected_model_loaded===!1&&!n.embedding_model_loaded){const z=n.model_loaded,A=n.context_size_sufficient===!1;return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(uy,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["Wrong model loaded: ",s.jsx("strong",{children:z}),"."," ","GAIA Chat requires ",s.jsx("strong",{children:c}),".",A&&s.jsxs(s.Fragment,{children:[" ","Context window is also too small."]})]}),u?s.jsxs("span",{className:"connection-banner__loading",children:[s.jsx(mt,{size:13,className:"connection-banner__spinner"}),"Loading…"]}):s.jsx("button",{className:"connection-banner__retry",onClick:()=>f(),children:"Load Now"}),e&&!u&&s.jsx("button",{className:"connection-banner__retry connection-banner__retry--secondary",onClick:e,children:"Recheck"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}if(n&&n.lemonade_running&&n.model_loaded&&n.context_size_sufficient===!1){const z=n.model_context_size??0,A=n.lemonade_url??"http://localhost:13305";return s.jsxs("div",{className:"connection-banner connection-banner--warning",role:"status",children:[s.jsx("div",{className:"connection-banner__icon",children:s.jsx(tw,{size:16})}),s.jsxs("div",{className:"connection-banner__text",children:["LLM context window is too small (",z.toLocaleString()," tokens;"," ",Ys.toLocaleString()," required)."," ",s.jsxs("span",{className:"connection-banner__hint",children:["In"," ",s.jsx("a",{className:"connection-banner__link",href:A,target:"_blank",rel:"noreferrer",children:"Lemonade"}),", set ctx‑size to ",Ys.toLocaleString(),", or restart with:"," ",s.jsxs("code",{children:["lemonade-server serve --ctx-size ",Ys]})]})]}),e&&s.jsx("button",{className:"connection-banner__retry",onClick:e,children:"Check again"}),s.jsx("button",{className:"connection-banner__dismiss",onClick:()=>a(!0),"aria-label":"Dismiss",children:s.jsx(tt,{size:14})})]})}return null}const WT={status:"idle",version:null,progress:0,releaseNotes:null,error:null};function GT(){const[e,t]=p.useState(WT);return p.useEffect(()=>{const n=window.gaiaUpdater;if(!n)return;let r=!0;n.getStatus().then(l=>{r&&l&&t(l)}).catch(()=>{});const i=n.onStatusChange(l=>{r&&l&&t(l)});return()=>{r=!1;try{i()}catch{}}},[]),e}function qT(){const e=GT(),[t,n]=p.useState(!1),r=p.useCallback(()=>{const i=window.gaiaUpdater;i==null||i.check().catch(()=>{})},[]);if(t||e.status==="idle"||e.status==="checking"||e.status==="disabled")return null;if(e.status==="downloading"){const i=Math.max(0,Math.min(100,e.progress));return s.jsxs("div",{className:"update-chip update-chip--downloading",role:"status","aria-live":"polite",title:`Downloading update${e.version?` ${e.version}`:""}…`,children:[s.jsx(oi,{size:13,className:"update-chip__icon"}),s.jsxs("span",{className:"update-chip__label",children:["Downloading update… ",i,"%"]})]})}return e.status==="available"?s.jsxs("div",{className:"update-chip update-chip--available",role:"status",title:e.releaseNotes||"A new version is available.",children:[s.jsx(oi,{size:13,className:"update-chip__icon"}),s.jsxs("span",{className:"update-chip__label",children:["Update available",e.version?`: ${e.version}`:""]}),s.jsx("button",{type:"button",className:"update-chip__dismiss",onClick:()=>n(!0),"aria-label":"Dismiss update notification",children:s.jsx(tt,{size:11})})]}):e.status==="downloaded"?s.jsxs("div",{className:"update-chip update-chip--ready",role:"status","aria-live":"polite",children:[s.jsx(Vs,{size:13,className:"update-chip__icon"}),s.jsx("button",{type:"button",className:"update-chip__action",onClick:r,title:"Click to restart and apply the update",children:"Update ready — restart to apply"})]}):e.status==="error"?s.jsxs("div",{className:"update-chip update-chip--error",role:"status",title:e.error||"Update check failed.",children:[s.jsx(pn,{size:13,className:"update-chip__icon"}),s.jsx("span",{className:"update-chip__label",children:"Update check failed"}),s.jsx("button",{type:"button",className:"update-chip__dismiss",onClick:()=>n(!0),"aria-label":"Dismiss update error",children:s.jsx(tt,{size:11})})]}):null}function QT(){const e=ot(mE),t=ot(n=>n.respondToPermission);return e?s.jsx("div",{className:"permission-overlay",role:"dialog","aria-modal":"true","aria-label":"Permission Request",children:s.jsx(KT,{notification:e,onRespond:t},e.id)}):null}function KT({notification:e,onRespond:t}){const n=e.timeoutSeconds!=null&&e.timeoutSeconds>0,[r,i]=p.useState(n?e.timeoutSeconds:null),l=p.useRef(null),[a,o]=p.useState(!1),[c,u]=p.useState(!1),d=p.useRef(!1),f=p.useRef(t);f.current=t,p.useEffect(()=>{if(n)return l.current=setInterval(()=>{i(w=>w===null||w<=1?(l.current&&clearInterval(l.current),0):w-1)},1e3),()=>{l.current&&clearInterval(l.current)}},[n]),p.useEffect(()=>{if(r===0){if(d.current)return;d.current=!0,o(!0),f.current(e.id,"deny",!1)}},[r,e.id]);const h=p.useCallback(async()=>{if(!d.current){d.current=!0,o(!0),l.current&&clearInterval(l.current);try{await t(e.id,"allow",c)}finally{d.current=!1,o(!1)}}},[e.id,t,c]),m=p.useCallback(async()=>{if(!d.current){d.current=!0,o(!0),l.current&&clearInterval(l.current);try{await t(e.id,"deny",!1)}finally{d.current=!1,o(!1)}}},[e.id,t]);p.useEffect(()=>{const w=x=>{x.key==="Enter"&&!x.shiftKey?(x.preventDefault(),h()):x.key==="Escape"&&(x.preventDefault(),m())};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[h,m]);const g=e.toolArgs,v=g&&Object.keys(g).length>0;return s.jsxs("div",{className:"permission-prompt",children:[s.jsxs("div",{className:"permission-header",children:[s.jsx("div",{className:"permission-header-icon",children:s.jsx(Ga,{size:24})}),s.jsxs("div",{className:"permission-header-text",children:[s.jsx("h2",{className:"permission-title",children:"Permission Request"}),s.jsx("span",{className:"permission-agent",children:e.agentName})]}),r!==null&&r>0&&s.jsxs("div",{className:"permission-countdown",title:"Auto-deny on timeout",children:[s.jsx(Wa,{size:14}),s.jsxs("span",{children:[r,"s"]})]})]}),s.jsxs("div",{className:"permission-body",children:[s.jsx("p",{className:"permission-message",children:e.message}),e.tool&&s.jsxs("div",{className:"permission-tool-info",children:[s.jsxs("div",{className:"permission-tool-header",children:[s.jsx(pn,{size:14}),s.jsx("span",{children:"Tool Invocation"})]}),s.jsx("div",{className:"permission-tool-name",children:s.jsx("code",{children:e.tool})}),v&&s.jsx("div",{className:"permission-tool-args",children:s.jsx("pre",{children:JSON.stringify(g,null,2)})})]}),e.priority==="critical"&&s.jsxs("div",{className:"permission-critical-banner",children:[s.jsx(pn,{size:14}),s.jsx("span",{children:"This is a critical-tier operation"})]}),s.jsxs("label",{className:"permission-remember",children:[s.jsx("input",{type:"checkbox",checked:c,onChange:w=>u(w.target.checked),disabled:a}),s.jsx("span",{children:"Always allow this tool"})]})]}),s.jsxs("div",{className:"permission-actions",children:[s.jsxs("button",{className:"permission-btn permission-btn-deny",onClick:m,disabled:a,title:"Deny (Esc)",children:[s.jsx(tt,{size:16}),"Deny"]}),s.jsxs("button",{className:"permission-btn permission-btn-allow",onClick:h,disabled:a,title:"Allow (Enter)",children:[s.jsx(li,{size:16}),"Allow"]})]}),s.jsxs("div",{className:"permission-hints",children:[s.jsxs("span",{children:[s.jsx("kbd",{children:"Enter"})," Allow"]}),s.jsxs("span",{children:[s.jsx("kbd",{children:"Esc"})," Deny"]})]})]})}const YT={permission_request:{icon:s.jsx(Ga,{size:16}),colorClass:"notif-type-permission",label:"Permission"},policy_alert:{icon:s.jsx(Ga,{size:16}),colorClass:"notif-type-policy",label:"Policy"},security_alert:{icon:s.jsx(pn,{size:16}),colorClass:"notif-type-security",label:"Security"},status_change:{icon:s.jsx(wi,{size:16}),colorClass:"notif-type-status",label:"Status"},info:{icon:s.jsx(ew,{size:16}),colorClass:"notif-type-info",label:"Info"},error:{icon:s.jsx(kt,{size:16}),colorClass:"notif-type-error",label:"Error"}};function XT(e){const n=Date.now()-e,r=Math.floor(n/1e3);if(r<60)return"just now";const i=Math.floor(r/60);if(i<60)return`${i}m ago`;const l=Math.floor(i/60);if(l<24)return`${l}h ago`;const a=Math.floor(l/24);return a<7?`${a}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function JT({onClose:e}){const t=ot(fE),n=ot(Hx),r=ot(w=>w.markRead),i=ot(w=>w.markAllRead),l=ot(w=>w.clearAll),a=ot(w=>w.dismiss),o=ot(w=>w.addNotification),c=ot(w=>w.respondToPermission),u=ot(w=>w.typeFilter),d=ot(w=>w.setTypeFilter),f=p.useRef(!1);p.useEffect(()=>{var x;const w=window.gaiaAPI;!((x=w==null?void 0:w.notification)!=null&&x.onNotification)||f.current||(f.current=!0,w.notification.onNotification(k=>{o(k)}))},[o]);const h=p.useCallback(w=>{r(w)},[r]),m=p.useCallback(w=>{c(w.id,"allow",!1)},[c]),g=p.useCallback(w=>{c(w.id,"deny",!1)},[c]);p.useEffect(()=>{const w=x=>{x.key==="Escape"&&!x.defaultPrevented&&e()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[e]);const v=[{key:null,label:"All"},{key:"permission_request",label:"Permissions"},{key:"policy_alert",label:"Policy"},{key:"error",label:"Errors"},{key:"security_alert",label:"Security"},{key:"status_change",label:"Status"},{key:"info",label:"Info"}];return s.jsxs("div",{className:"notification-center",role:"dialog","aria-label":"Notification Center",children:[s.jsxs("div",{className:"notification-center-header",children:[s.jsxs("div",{className:"notification-center-title-row",children:[s.jsx("h2",{className:"notification-center-title",children:"Notifications"}),n>0&&s.jsx("span",{className:"notification-center-badge",children:n})]}),s.jsx("button",{className:"btn-icon notification-center-close",onClick:e,"aria-label":"Close notification center",children:s.jsx(tt,{size:18})})]}),s.jsx("div",{className:"notification-filter-bar",role:"tablist","aria-label":"Filter notifications",children:v.map(w=>s.jsx("button",{role:"tab","aria-selected":u===w.key,className:`notification-filter-tab ${u===w.key?"active":""}`,onClick:()=>d(w.key),children:w.label},w.key??"all"))}),s.jsx("div",{className:"notification-list",children:t.length===0?s.jsxs("div",{className:"notification-empty",children:[s.jsx(oy,{size:40,strokeWidth:1.2}),s.jsx("span",{children:"No notifications"})]}):t.map(w=>{const x=YT[w.type];return s.jsxs("div",{className:`notification-item ${w.read?"":"unread"} ${x.colorClass}`,id:w.type==="policy_alert"&&w.receiptId?`policy-receipt-${encodeURIComponent(w.receiptId)}`:void 0,onClick:()=>h(w.id),role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&h(w.id)},children:[!w.read&&s.jsx("span",{className:"notification-unread-dot"}),s.jsx("span",{className:"notification-icon",children:x.icon}),s.jsxs("div",{className:"notification-content",children:[s.jsxs("div",{className:"notification-content-header",children:[s.jsx("span",{className:"notification-agent",children:w.agentName}),s.jsx("span",{className:"notification-time",children:XT(w.timestamp)})]}),w.title&&s.jsx("span",{className:"notification-title",children:w.title}),s.jsx("span",{className:"notification-message",children:w.message}),w.type==="permission_request"&&w.tool&&s.jsxs("span",{className:"notification-tool",children:["Tool: ",s.jsx("code",{children:w.tool})]}),w.type==="policy_alert"&&s.jsxs("div",{className:"notification-policy-details",children:[w.tool&&s.jsxs("span",{className:"notification-tool",children:["Tool: ",s.jsx("code",{children:w.tool})]}),w.reason&&s.jsxs("span",{className:"notification-policy-reason",children:["Reason: ",w.reason]}),w.ruleIds&&w.ruleIds.length>0&&s.jsxs("span",{className:"notification-tool",children:["Rules: ",s.jsx("code",{children:w.ruleIds.join(", ")})]}),w.policyVersion&&s.jsxs("span",{className:"notification-tool",children:["Policy: ",s.jsx("code",{children:w.policyVersion})]}),s.jsxs("span",{className:"notification-tool",children:["Receipt:"," ",w.receiptId?s.jsx("code",{children:w.receiptId}):s.jsx("em",{children:"Receipt unavailable"})]})]}),w.type==="permission_request"&&!w.response&&s.jsxs("div",{className:"notification-actions",children:[s.jsxs("button",{className:"notification-action-btn notification-action-allow",onClick:k=>{k.stopPropagation(),m(w)},children:[s.jsx(li,{size:14}),"Approve"]}),s.jsxs("button",{className:"notification-action-btn notification-action-deny",onClick:k=>{k.stopPropagation(),g(w)},children:[s.jsx(tt,{size:14}),"Deny"]})]}),w.type==="permission_request"&&w.response&&s.jsx("span",{className:`notification-response-badge ${w.response==="allow"?"response-allow":"response-deny"}`,children:w.response==="allow"?"Approved":"Denied"})]}),s.jsx("button",{className:"notification-dismiss",onClick:k=>{k.stopPropagation(),a(w.id)},"aria-label":"Dismiss notification",children:s.jsx(tt,{size:14})})]},w.id)})}),t.length>0&&s.jsxs("div",{className:"notification-center-footer",children:[s.jsxs("button",{className:"notification-footer-btn",onClick:i,disabled:n===0,children:[s.jsx(li,{size:14}),"Mark All Read"]}),s.jsxs("button",{className:"notification-footer-btn notification-footer-clear",onClick:l,children:[s.jsx(ci,{size:14}),"Clear"]})]})]})}function ia({show:e,children:t,duration:n=250}){const[r,i]=p.useState(!1),[l,a]=p.useState("idle");return p.useEffect(()=>{if(e)i(!0),requestAnimationFrame(()=>a("entering"));else if(r){a("exiting");const o=setTimeout(()=>{i(!1),a("idle")},n);return()=>clearTimeout(o)}},[e,r,n]),r?s.jsx("div",{className:`animated-presence ${l}`,"data-duration":n,children:t}):null}function ZT(){const{currentSessionId:e,setSessions:t,setCurrentSession:n,addSession:r,removeSession:i,updateSessionInList:l,setMessages:a,showDocLibrary:o,showFileBrowser:c,showSettings:u,showMemoryDashboard:d,sidebarOpen:f,toggleSidebar:h,setSidebarOpen:m,systemStatus:g,setSystemStatus:v,setBackendConnected:w,setAgents:x}=we(),k=ot(H=>H.showPanel),j=ot(H=>H.setShowPanel),z=p.useRef(""),A=p.useCallback(async()=>{try{const le=(await Nd()).agents||[],Pe=le.map(Ae=>Ae.id).sort().join(",");Pe!==z.current&&(z.current=Pe,x(le))}catch{}},[x]);p.useEffect(()=>{A();const H=setInterval(A,3e4);return()=>clearInterval(H)},[A]);const[_,D]=p.useState(!1),[C,M]=p.useState(!1),[N,U]=p.useState(!1),[O,re]=p.useState(null),ie=p.useRef(null),X=p.useRef(0),xe=3,ce=p.useCallback(async()=>{try{const H=await Sd();if(w(!0),H.lemonade_running)X.current=0,v(H);else if(X.current+=1,E.system.warn(`Lemonade health check failed (${X.current}/${xe})`),X.current>=xe)v(H);else{const le=we.getState().systemStatus;le&&le.lemonade_running?v({...le,disk_space_gb:H.disk_space_gb,memory_available_gb:H.memory_available_gb}):v(H)}E.system.info("System status:",{lemonade:H.lemonade_running,model:H.model_loaded,failCount:X.current})}catch(H){E.system.warn("System status check failed",H),w(!1),v(null)}},[v,w]),T=p.useRef(3e3);p.useEffect(()=>(ce(),T.current=3e3,ie.current=setInterval(ce,3e3),()=>{ie.current&&clearInterval(ie.current)}),[ce]),p.useEffect(()=>{const H=g==null?void 0:g.init_state;if(!H||H==="initializing")return;const le=15e3;le!==T.current&&(T.current=le,ie.current&&clearInterval(ie.current),ie.current=setInterval(ce,le))},[g==null?void 0:g.init_state,ce]);const P=p.useRef(null),b=p.useRef("");p.useEffect(()=>{e0("0.18.1"),E.system.info("App mounting, loading sessions...");const H=E.system.time(),le=Ae=>Ae.map($e=>`${$e.id}|${$e.updated_at}|${$e.title}`).join(`
550
550
  `),Pe=(Ae=!1)=>{u0().then($e=>{const ut=$e.sessions||[];if(Ae){t(ut),w(!0),b.current=le(ut),E.system.timed(`Loaded ${ut.length} session(s)`,H);return}const je=we.getState().sessions;if(ut.length===0&&je.length>0){E.system.warn(`Session poll returned 0 sessions but sidebar has ${je.length} — skipping update to prevent data loss`);return}const Je=le(ut);Je!==b.current&&(E.system.info(`Session list changed (${je.length} → ${ut.length} sessions)`),t(ut),b.current=Je)}).catch($e=>{Ae&&(E.system.error("Failed to load sessions from backend",$e),E.system.warn("Is the Python backend running? Start it with: gaia chat --ui"))})};return Pe(!0),P.current=setInterval(()=>Pe(!1),5e3),()=>{P.current&&clearInterval(P.current)}},[t,r,i,l,w]),p.useEffect(()=>{if(e)return;const le=new URLSearchParams(window.location.search).get("session"),Pe=window.location.hash.replace(/^#/,""),Ae=le||Pe;if(!Ae)return;E.nav.info(`URL session parameter: ${Ae}`);const $e=setTimeout(()=>{const{sessions:ut}=we.getState();let je=ut.some(Je=>Je.id===Ae)?Ae:T0(ut,Ae);je?(n(je),a([])):E.nav.warn(`Session ${Ae} not found in loaded sessions`)},500);return()=>clearTimeout($e)},[e,n,a]),p.useEffect(()=>{if(e){const H=Ri(e);window.location.hash!==`#${H}`&&window.history.replaceState(null,"",`#${H}`)}else window.location.hash&&window.history.replaceState(null,"",window.location.pathname+window.location.search)},[e]),p.useEffect(()=>{Py().then(H=>{M(H.active===!0)}).catch(()=>{})},[]),p.useEffect(()=>{const H=()=>{window.innerWidth>768&&m(!0)};return window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[m]);const[J,B]=p.useState(null),S=p.useCallback(async()=>{E.chat.info("Creating new task session..."),B(null);try{const{activeAgentId:H}=we.getState(),le=await hu({title:"New Task",agent_type:H});E.chat.info(`Session created: id=${le.id}, title="${le.title}"`),r(le),n(le.id),a([]),window.innerWidth<=768&&m(!1)}catch(H){E.chat.error("Failed to create session",H),ce(),B("Failed to create task. Is the server running?"),setTimeout(()=>B(null),6e3)}},[r,n,a,m,ce]),oe=p.useCallback(async H=>{we.getState().setActiveAgentId(H),await S()},[S]),{setPendingPrompt:pe}=we(),ae=p.useCallback(async H=>{E.chat.info(`New task with prompt: "${H.slice(0,60)}..."`),pe(H),await S()},[S,pe]),_e=p.useCallback(async()=>{E.chat.info("Creating builder agent session..."),B(null);try{pe("Hi, I'd like to create a new custom agent.");const H=await hu({title:"New Agent",agent_type:"builder"});E.chat.info(`Builder session created: id=${H.id}`),r(H),n(H.id),a([]),window.innerWidth<=768&&m(!1)}catch(H){pe(null),E.chat.error("Failed to create builder session",H),ce(),B("Failed to create task. Is the server running?"),setTimeout(()=>B(null),6e3)}},[r,n,a,m,ce,pe]),He=p.useCallback(async()=>{if(C){E.system.info("Reopening mobile access modal (tunnel already running)"),re(null),D(!0);return}E.system.info("Starting mobile access tunnel..."),D(!0),U(!0),re(null);try{const H=await C0();H.error?(E.system.error("Tunnel failed to start:",H.error),M(!1),re(H.error)):(M(!0),E.system.info("Tunnel started successfully"))}catch(H){E.system.error("Tunnel start error:",H),M(!1),re(H instanceof Error?H.message:"Failed to connect")}finally{U(!1)}},[C]),nt=p.useCallback(async()=>{E.system.info("Stopping mobile access tunnel...");try{await _0()}catch(H){E.system.warn("stopTunnel call failed (continuing)",H)}M(!1),re(null),D(!1)},[]);p.useEffect(()=>{const{sessions:H,setActiveAgentId:le}=we.getState(),Pe=H.find(Ae=>Ae.id===e);Pe!=null&&Pe.agent_type&&le(Pe.agent_type)},[e]),p.useEffect(()=>{e?E.nav.info(`Viewing session: ${e}`):E.nav.info("Viewing welcome screen (no session selected)")},[e]),p.useEffect(()=>{o&&E.ui.info("Document Library opened")},[o]),p.useEffect(()=>{u&&E.ui.info("Settings page opened")},[u]);const[Ge,L]=p.useState(typeof window<"u"&&window.innerWidth<=768);p.useEffect(()=>{const H=()=>L(window.innerWidth<=768);return window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]);const[F,Y]=p.useState(!1),[ue,he]=p.useState(null);return p.useEffect(()=>{if(e!==ue){Y(!0);const H=setTimeout(()=>{he(e),requestAnimationFrame(()=>{requestAnimationFrame(()=>{Y(!1)})})},220);return()=>clearTimeout(H)}},[e,ue]),s.jsxs("div",{className:"app",children:[s.jsx("button",{className:"sidebar-toggle",onClick:h,"aria-label":f?"Close sidebar":"Open sidebar",children:s.jsx(sw,{size:18})}),s.jsx("div",{className:`sidebar-overlay ${f?"visible":""}`,onClick:()=>m(!1),"aria-hidden":"true"}),s.jsx(L0,{onNewTask:S,tunnelActive:C,tunnelLoading:N,onMobileToggle:He}),s.jsx("div",{className:"main-content",children:u?s.jsx(FT,{}):d?s.jsx(vT,{}):s.jsxs(s.Fragment,{children:[s.jsx(VT,{onRetry:ce}),s.jsx("div",{className:`view-container ${F?"view-transitioning":""}`,children:ue?s.jsx(wE,{sessionId:ue,onCreateAgent:_e,onAgentChange:oe},ue):s.jsx(NE,{onNewTask:S,onSendPrompt:ae,onCreateAgent:_e})})]})}),s.jsx(ia,{show:o,children:s.jsx(TE,{})}),s.jsx(ia,{show:c,children:s.jsx(PE,{})}),s.jsx(ia,{show:k,children:s.jsx("div",{className:"notification-center-popover",children:s.jsx(JT,{onClose:()=>j(!1)})})}),!Ge&&s.jsx(ia,{show:_,children:s.jsx(HT,{isOpen:_,onClose:()=>D(!1),onStop:nt,error:O})}),s.jsx(QT,{}),s.jsx(qT,{}),J&&s.jsx("div",{className:"toast",role:"alert",children:J})]})}const ez=localStorage.getItem("gaia-chat-theme");ez!=="light"&&document.documentElement.setAttribute("data-theme","dark");xc.createRoot(document.getElementById("root")).render(s.jsx(Gi.StrictMode,{children:s.jsx(ZT,{})}));