@nxuss/lemma 0.7.5 → 0.7.7

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.
@@ -405,7 +405,7 @@ to {
405
405
  * This source code is licensed under the MIT license found in the
406
406
  * LICENSE file in the root directory of this source tree.
407
407
  */var Zc=j,CT=$T;function NT(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var MT=typeof Object.is=="function"?Object.is:NT,IT=CT.useSyncExternalStore,DT=Zc.useRef,RT=Zc.useEffect,LT=Zc.useMemo,BT=Zc.useDebugValue;z_.useSyncExternalStoreWithSelector=function(e,t,r,n,i){var o=DT(null);if(o.current===null){var a={hasValue:!1,value:null};o.current=a}else a=o.current;o=LT(function(){function l(h){if(!u){if(u=!0,f=h,h=n(h),i!==void 0&&a.hasValue){var p=a.value;if(i(p,h))return c=p}return c=h}if(p=c,MT(f,h))return p;var m=n(h);return i!==void 0&&i(p,m)?(f=h,p):(f=h,c=m)}var u=!1,f,c,d=r===void 0?null:r;return[function(){return l(t())},d===null?void 0:function(){return l(d())}]},[t,r,n,i]);var s=IT(e,o[0],o[1]);return RT(function(){a.hasValue=!0,a.value=s},[s]),BT(s),s};B_.exports=z_;var zT=B_.exports;const FT=me(zT),W_={},{useDebugValue:UT}=k,{useSyncExternalStoreWithSelector:WT}=FT;let s0=!1;const HT=e=>e;function VT(e,t=HT,r){(W_?"production":void 0)!=="production"&&r&&!s0&&(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"),s0=!0);const n=WT(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return UT(n),n}const qT=e=>{(W_?"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"?wT(e):e,r=(n,i)=>VT(t,n,i);return Object.assign(r,t),r},KT=e=>qT;var H_=Symbol.for("immer-nothing"),l0=Symbol.for("immer-draftable"),Nt=Symbol.for("immer-state");function cr(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var rs=Object.getPrototypeOf;function co(e){return!!e&&!!e[Nt]}function ci(e){var t;return e?V_(e)||Array.isArray(e)||!!e[l0]||!!((t=e.constructor)!=null&&t[l0])||Gs(e)||ef(e):!1}var GT=Object.prototype.constructor.toString(),u0=new WeakMap;function V_(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if(typeof r!="function")return!1;let n=u0.get(r);return n===void 0&&(n=Function.toString.call(r),u0.set(r,n)),n===GT}function Tu(e,t,r=!0){Jc(e)===0?(r?Reflect.ownKeys(e):Object.keys(e)).forEach(i=>{t(i,e[i],e)}):e.forEach((n,i)=>t(i,n,e))}function Jc(e){const t=e[Nt];return t?t.type_:Array.isArray(e)?1:Gs(e)?2:ef(e)?3:0}function Qp(e,t){return Jc(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function q_(e,t,r){const n=Jc(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function XT(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Gs(e){return e instanceof Map}function ef(e){return e instanceof Set}function Wn(e){return e.copy_||e.base_}function Zp(e,t){if(Gs(e))return new Map(e);if(ef(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=V_(e);if(t===!0||t==="class_only"&&!r){const n=Object.getOwnPropertyDescriptors(e);delete n[Nt];let i=Reflect.ownKeys(n);for(let o=0;o<i.length;o++){const a=i[o],s=n[a];s.writable===!1&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(n[a]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[a]})}return Object.create(rs(e),n)}else{const n=rs(e);if(n!==null&&r)return{...e};const i=Object.create(n);return Object.assign(i,e)}}function Cy(e,t=!1){return tf(e)||co(e)||!ci(e)||(Jc(e)>1&&Object.defineProperties(e,{set:Pl,add:Pl,clear:Pl,delete:Pl}),Object.freeze(e),t&&Object.values(e).forEach(r=>Cy(r,!0))),e}function YT(){cr(2)}var Pl={value:YT};function tf(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var QT={};function fi(e){const t=QT[e];return t||cr(0,e),t}var ns;function K_(){return ns}function ZT(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function c0(e,t){t&&(fi("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Jp(e){eh(e),e.drafts_.forEach(JT),e.drafts_=null}function eh(e){e===ns&&(ns=e.parent_)}function f0(e){return ns=ZT(ns,e)}function JT(e){const t=e[Nt];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function d0(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return e!==void 0&&e!==r?(r[Nt].modified_&&(Jp(t),cr(4)),ci(e)&&(e=$u(t,e),t.parent_||Cu(t,e)),t.patches_&&fi("Patches").generateReplacementPatches_(r[Nt].base_,e,t.patches_,t.inversePatches_)):e=$u(t,r,[]),Jp(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==H_?e:void 0}function $u(e,t,r){if(tf(t))return t;const n=e.immer_.shouldUseStrictIteration(),i=t[Nt];if(!i)return Tu(t,(o,a)=>p0(e,i,t,o,a,r),n),t;if(i.scope_!==e)return t;if(!i.modified_)return Cu(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const o=i.copy_;let a=o,s=!1;i.type_===3&&(a=new Set(o),o.clear(),s=!0),Tu(a,(l,u)=>p0(e,i,o,l,u,r,s),n),Cu(e,o,!1),r&&e.patches_&&fi("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function p0(e,t,r,n,i,o,a){if(i==null||typeof i!="object"&&!a)return;const s=tf(i);if(!(s&&!a)){if(co(i)){const l=o&&t&&t.type_!==3&&!Qp(t.assigned_,n)?o.concat(n):void 0,u=$u(e,i,l);if(q_(r,n,u),co(u))e.canAutoFreeze_=!1;else return}else a&&r.add(i);if(ci(i)&&!s){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[n]===i&&s)return;$u(e,i),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&(Gs(r)?r.has(n):Object.prototype.propertyIsEnumerable.call(r,n))&&Cu(e,i)}}}function Cu(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Cy(t,r)}function e$(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:K_(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=n,o=Ny;r&&(i=[n],o=is);const{revoke:a,proxy:s}=Proxy.revocable(i,o);return n.draft_=s,n.revoke_=a,s}var Ny={get(e,t){if(t===Nt)return e;const r=Wn(e);if(!Qp(r,t))return t$(e,r,t);const n=r[t];return e.finalized_||!ci(n)?n:n===wd(e.base_,t)?(Sd(e),e.copy_[t]=rh(n,e)):n},has(e,t){return t in Wn(e)},ownKeys(e){return Reflect.ownKeys(Wn(e))},set(e,t,r){const n=G_(Wn(e),t);if(n!=null&&n.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const i=wd(Wn(e),t),o=i==null?void 0:i[Nt];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(XT(r,i)&&(r!==void 0||Qp(e.base_,t)))return!0;Sd(e),th(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return wd(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Sd(e),th(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const r=Wn(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){cr(11)},getPrototypeOf(e){return rs(e.base_)},setPrototypeOf(){cr(12)}},is={};Tu(Ny,(e,t)=>{is[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});is.deleteProperty=function(e,t){return is.set.call(this,e,t,void 0)};is.set=function(e,t,r){return Ny.set.call(this,e[0],t,r,e[0])};function wd(e,t){const r=e[Nt];return(r?Wn(r):e)[t]}function t$(e,t,r){var i;const n=G_(t,r);return n?"value"in n?n.value:(i=n.get)==null?void 0:i.call(e.draft_):void 0}function G_(e,t){if(!(t in e))return;let r=rs(e);for(;r;){const n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=rs(r)}}function th(e){e.modified_||(e.modified_=!0,e.parent_&&th(e.parent_))}function Sd(e){e.copy_||(e.copy_=Zp(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var r$=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){const o=r;r=t;const a=this;return function(l=o,...u){return a.produce(l,f=>r.call(this,f,...u))}}typeof r!="function"&&cr(6),n!==void 0&&typeof n!="function"&&cr(7);let i;if(ci(t)){const o=f0(this),a=rh(t,void 0);let s=!0;try{i=r(a),s=!1}finally{s?Jp(o):eh(o)}return c0(o,n),d0(i,o)}else if(!t||typeof t!="object"){if(i=r(t),i===void 0&&(i=t),i===H_&&(i=void 0),this.autoFreeze_&&Cy(i,!0),n){const o=[],a=[];fi("Patches").generateReplacementPatches_(t,i,o,a),n(o,a)}return i}else cr(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(a,...s)=>this.produceWithPatches(a,l=>t(l,...s));let n,i;return[this.produce(t,r,(a,s)=>{n=a,i=s}),n,i]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof(e==null?void 0:e.useStrictIteration)=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){ci(e)||cr(8),co(e)&&(e=n$(e));const t=f0(this),r=rh(e,void 0);return r[Nt].isManual_=!0,eh(t),r}finishDraft(e,t){const r=e&&e[Nt];(!r||!r.isManual_)&&cr(9);const{scope_:n}=r;return c0(n,t),d0(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const i=t[r];if(i.path.length===0&&i.op==="replace"){e=i.value;break}}r>-1&&(t=t.slice(r+1));const n=fi("Patches").applyPatches_;return co(e)?n(e,t):this.produce(e,i=>n(i,t))}};function rh(e,t){const r=Gs(e)?fi("MapSet").proxyMap_(e,t):ef(e)?fi("MapSet").proxySet_(e,t):e$(e,t);return(t?t.scope_:K_()).drafts_.push(r),r}function n$(e){return co(e)||cr(10,e),X_(e)}function X_(e){if(!ci(e)||tf(e))return e;const t=e[Nt];let r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Zp(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=Zp(e,!0);return Tu(r,(i,o)=>{q_(r,i,X_(o))},n),t&&(t.finalized_=!1),r}var i$=new r$,o$=i$.produce;const a$=e=>(t,r,n)=>(n.setState=(i,o,...a)=>{const s=typeof i=="function"?o$(i):i;return t(s,o,...a)},e(n.setState,r,n)),s$=a$,l$=()=>{if(typeof window>"u")return 5;try{const e=window.localStorage.getItem("dashboardSettings");if(!e)return 5;const t=JSON.parse(e),r=Number(t.refreshIntervalSeconds??t.refreshInterval??5);return Number.isFinite(r)?Math.min(30,Math.max(2,r)):5}catch{return 5}},h0={metrics:null,isLoadingMetrics:!1,metricsError:null,agents:[],selectedAgentId:null,isLoadingAgents:!1,events:[],eventFilter:"all",eventPage:1,eventPageSize:50,totalEvents:0,topQueries:[],isLoadingCacheStats:!1,isConnected:!1,connectionStatus:"idle",isPaused:!1,selectedEventId:null,debuggerState:null,showDebugger:!1,activeSidePanel:"agents",refreshIntervalSeconds:l$(),searchQuery:"",searchResults:[],isSearching:!1,savingsBreakdown:null},re=KT()(s$(e=>({...h0,setMetrics:t=>{e(r=>{r.metrics=t,r.isLoadingMetrics=!1,r.metricsError=null})},setMetricsLoading:t=>{e(r=>{r.isLoadingMetrics=t})},setMetricsError:t=>{e(r=>{r.metricsError=t})},setAgents:t=>{e(r=>{r.agents=t,r.isLoadingAgents=!1})},setSelectedAgent:t=>{e(r=>{r.selectedAgentId=t})},addAgent:t=>{e(r=>{r.agents.find(i=>i.id===t.id)||r.agents.push(t)})},removeAgent:t=>{e(r=>{r.agents=r.agents.filter(n=>n.id!==t),r.selectedAgentId===t&&(r.selectedAgentId=null)})},setEvents:t=>{e(r=>{r.events=t})},addEvent:t=>{e(r=>{r.events.unshift(t),r.events.length>1e3&&r.events.pop()})},setEventFilter:t=>{e(r=>{r.eventFilter=t==="all"?"all":t,r.eventPage=1})},setEventPage:t=>{e(r=>{r.eventPage=t})},setTotalEvents:t=>{e(r=>{r.totalEvents=t})},setTopQueries:t=>{e(r=>{r.topQueries=t,r.isLoadingCacheStats=!1})},setConnected:t=>{e(r=>{r.isConnected=t})},setConnectionStatus:t=>{e(r=>{r.connectionStatus=t})},setPaused:t=>{e(r=>{r.isPaused=t})},setSelectedEvent:t=>{e(r=>{r.selectedEventId=t})},setDebuggerState:t=>{e(r=>{r.debuggerState=t})},setShowDebugger:t=>{e(r=>{r.showDebugger=t})},setActiveSidePanel:t=>{e(r=>{r.activeSidePanel=t})},setRefreshIntervalSeconds:t=>{e(r=>{r.refreshIntervalSeconds=Math.min(30,Math.max(2,t))})},setSearchQuery:t=>{e(r=>{r.searchQuery=t})},setSearchResults:t=>{e(r=>{r.searchResults=t,r.isSearching=!1})},setIsSearching:t=>{e(r=>{r.isSearching=t})},setSavingsBreakdown:t=>{e(r=>{r.savingsBreakdown=t})},reset:()=>{e(()=>h0)}}))),Er=Object.create(null);Er.open="0";Er.close="1";Er.ping="2";Er.pong="3";Er.message="4";Er.upgrade="5";Er.noop="6";const tu=Object.create(null);Object.keys(Er).forEach(e=>{tu[Er[e]]=e});const nh={type:"error",data:"parser error"},Y_=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Q_=typeof ArrayBuffer=="function",Z_=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,My=({type:e,data:t},r,n)=>Y_&&t instanceof Blob?r?n(t):m0(t,n):Q_&&(t instanceof ArrayBuffer||Z_(t))?r?n(t):m0(new Blob([t]),n):n(Er[e]+(t||"")),m0=(e,t)=>{const r=new FileReader;return r.onload=function(){const n=r.result.split(",")[1];t("b"+(n||""))},r.readAsDataURL(e)};function y0(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let _d;function u$(e,t){if(Y_&&e.data instanceof Blob)return e.data.arrayBuffer().then(y0).then(t);if(Q_&&(e.data instanceof ArrayBuffer||Z_(e.data)))return t(y0(e.data));My(e,!1,r=>{_d||(_d=new TextEncoder),t(_d.encode(r))})}const v0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wa=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<v0.length;e++)wa[v0.charCodeAt(e)]=e;const c$=e=>{let t=e.length*.75,r=e.length,n,i=0,o,a,s,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),f=new Uint8Array(u);for(n=0;n<r;n+=4)o=wa[e.charCodeAt(n)],a=wa[e.charCodeAt(n+1)],s=wa[e.charCodeAt(n+2)],l=wa[e.charCodeAt(n+3)],f[i++]=o<<2|a>>4,f[i++]=(a&15)<<4|s>>2,f[i++]=(s&3)<<6|l&63;return u},f$=typeof ArrayBuffer=="function",Iy=(e,t)=>{if(typeof e!="string")return{type:"message",data:J_(e,t)};const r=e.charAt(0);return r==="b"?{type:"message",data:d$(e.substring(1),t)}:tu[r]?e.length>1?{type:tu[r],data:e.substring(1)}:{type:tu[r]}:nh},d$=(e,t)=>{if(f$){const r=c$(e);return J_(r,t)}else return{base64:!0,data:e}},J_=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},eO="",p$=(e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach((o,a)=>{My(o,!1,s=>{n[a]=s,++i===r&&t(n.join(eO))})})},h$=(e,t)=>{const r=e.split(eO),n=[];for(let i=0;i<r.length;i++){const o=Iy(r[i],t);if(n.push(o),o.type==="error")break}return n};function m$(){return new TransformStream({transform(e,t){u$(e,r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const o=new DataView(i.buffer);o.setUint8(0,126),o.setUint16(1,n)}else{i=new Uint8Array(9);const o=new DataView(i.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(n))}e.data&&typeof e.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(r)})}})}let Od;function Al(e){return e.reduce((t,r)=>t+r.length,0)}function kl(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function y$(e,t){Od||(Od=new TextDecoder);const r=[];let n=0,i=-1,o=!1;return new TransformStream({transform(a,s){for(r.push(a);;){if(n===0){if(Al(r)<1)break;const l=kl(r,1);o=(l[0]&128)===128,i=l[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(Al(r)<2)break;const l=kl(r,2);i=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(Al(r)<8)break;const l=kl(r,8),u=new DataView(l.buffer,l.byteOffset,l.length),f=u.getUint32(0);if(f>Math.pow(2,21)-1){s.enqueue(nh);break}i=f*Math.pow(2,32)+u.getUint32(4),n=3}else{if(Al(r)<i)break;const l=kl(r,i);s.enqueue(Iy(o?l:Od.decode(l),t)),n=0}if(i===0||i>e){s.enqueue(nh);break}}}})}const tO=4;function Le(e){if(e)return v$(e)}function v$(e){for(var t in Le.prototype)e[t]=Le.prototype[t];return e}Le.prototype.on=Le.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Le.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};Le.prototype.off=Le.prototype.removeListener=Le.prototype.removeAllListeners=Le.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks["$"+e];if(!r)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var n,i=0;i<r.length;i++)if(n=r[i],n===t||n.fn===t){r.splice(i,1);break}return r.length===0&&delete this._callbacks["$"+e],this};Le.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){r=r.slice(0);for(var n=0,i=r.length;n<i;++n)r[n].apply(this,t)}return this};Le.prototype.emitReserved=Le.prototype.emit;Le.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};Le.prototype.hasListeners=function(e){return!!this.listeners(e).length};const rf=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,r)=>r(t,0),Wt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),g$="arraybuffer";function rO(e,...t){return t.reduce((r,n)=>(e.hasOwnProperty(n)&&(r[n]=e[n]),r),{})}const b$=Wt.setTimeout,x$=Wt.clearTimeout;function nf(e,t){t.useNativeTimers?(e.setTimeoutFn=b$.bind(Wt),e.clearTimeoutFn=x$.bind(Wt)):(e.setTimeoutFn=Wt.setTimeout.bind(Wt),e.clearTimeoutFn=Wt.clearTimeout.bind(Wt))}const w$=1.33;function S$(e){return typeof e=="string"?_$(e):Math.ceil((e.byteLength||e.size)*w$)}function _$(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}function nO(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function O$(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function P$(e){let t={},r=e.split("&");for(let n=0,i=r.length;n<i;n++){let o=r[n].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}class A$ extends Error{constructor(t,r,n){super(t),this.description=r,this.context=n,this.type="TransportError"}}class Dy extends Le{constructor(t){super(),this.writable=!1,nf(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,n){return super.emitReserved("error",new A$(t,r,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const r=Iy(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const r=O$(t);return r.length?"?"+r:""}}class k$ extends Dy{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const r=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||r()})),this.writable||(n++,this.once("drain",function(){--n||r()}))}else r()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const r=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};h$(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,p$(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=nO()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}}let iO=!1;try{iO=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const E$=iO;function j$(){}class T$ extends k${constructor(t){if(super(t),typeof location<"u"){const r=location.protocol==="https:";let n=location.port;n||(n=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,r){const n=this.request({method:"POST",data:t});n.on("success",r),n.on("error",(i,o)=>{this.onError("xhr post error",i,o)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,n)=>{this.onError("xhr poll error",r,n)}),this.pollXhr=t}}class Pr extends Le{constructor(t,r,n){super(),this.createRequest=t,nf(this,n),this._opts=n,this._method=n.method||"GET",this._uri=r,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const r=rO(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(r);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=j$,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",g0);else if(typeof addEventListener=="function"){const e="onpagehide"in Wt?"pagehide":"unload";addEventListener(e,g0,!1)}}function g0(){for(let e in Pr.requests)Pr.requests.hasOwnProperty(e)&&Pr.requests[e].abort()}const $$=function(){const e=oO({xdomain:!1});return e&&e.responseType!==null}();class C$ extends T${constructor(t){super(t);const r=t&&t.forceBase64;this.supportsBinary=$$&&!r}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Pr(oO,this.uri(),t)}}function oO(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||E$))return new XMLHttpRequest}catch{}if(!t)try{return new Wt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const aO=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class N$ extends Dy{get name(){return"websocket"}doOpen(){const t=this.uri(),r=this.opts.protocols,n=aO?{}:rO(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){const n=t[r],i=r===t.length-1;My(n,this.supportsBinary,o=>{try{this.doWrite(n,o)}catch{}i&&rf(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=nO()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}}const Pd=Wt.WebSocket||Wt.MozWebSocket;class M$ extends N${createSocket(t,r,n){return aO?new Pd(t,r,n):r?new Pd(t,r):new Pd(t)}doWrite(t,r){this.ws.send(r)}}class I$ extends Dy{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const r=y$(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(r).getReader(),i=m$();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const o=()=>{n.read().then(({done:s,value:l})=>{s||(this.onPacket(l),o())}).catch(s=>{})};o();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){const n=t[r],i=r===t.length-1;this._writer.write(n).then(()=>{i&&rf(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const D$={websocket:M$,webtransport:I$,polling:C$},R$=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,L$=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ih(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");r!=-1&&n!=-1&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=R$.exec(e||""),o={},a=14;for(;a--;)o[L$[a]]=i[a]||"";return r!=-1&&n!=-1&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=B$(o,o.path),o.queryKey=z$(o,o.query),o}function B$(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function z$(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,o){i&&(r[i]=o)}),r}const oh=typeof addEventListener=="function"&&typeof removeEventListener=="function",ru=[];oh&&addEventListener("offline",()=>{ru.forEach(e=>e())},!1);class On extends Le{constructor(t,r){if(super(),this.binaryType=g$,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){const n=ih(t);r.hostname=n.host,r.secure=n.protocol==="https"||n.protocol==="wss",r.port=n.port,n.query&&(r.query=n.query)}else r.host&&(r.hostname=ih(r.host).host);nf(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=P$(this.opts.query)),oh&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ru.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const r=Object.assign({},this.opts.query);r.EIO=tO,r.transport=t,this.id&&(r.sid=this.id);const n=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&On.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){this.readyState="open",On.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(r+=S$(i)),n>0&&r>this._maxPayload)return this.writeBuffer.slice(0,n);r+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,rf(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,n){return this._sendPacket("message",t,r,n),this}send(t,r,n){return this._sendPacket("message",t,r,n),this}_sendPacket(t,r,n,i){if(typeof r=="function"&&(i=r,r=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const o={type:t,data:r,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},n=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(On.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),oh&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=ru.indexOf(this._offlineEventListener);n!==-1&&ru.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}}On.protocol=tO;class F$ extends On{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let r=this.createTransport(t),n=!1;On.priorWebsocketSuccess=!1;const i=()=>{n||(r.send([{type:"ping",data:"probe"}]),r.once("packet",c=>{if(!n)if(c.type==="pong"&&c.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;On.priorWebsocketSuccess=r.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(f(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{const d=new Error("probe error");d.transport=r.name,this.emitReserved("upgradeError",d)}}))};function o(){n||(n=!0,f(),r.close(),r=null)}const a=c=>{const d=new Error("probe error: "+c);d.transport=r.name,o(),this.emitReserved("upgradeError",d)};function s(){a("transport closed")}function l(){a("socket closed")}function u(c){r&&c.name!==r.name&&o()}const f=()=>{r.removeListener("open",i),r.removeListener("error",a),r.removeListener("close",s),this.off("close",l),this.off("upgrading",u)};r.once("open",i),r.once("error",a),r.once("close",s),this.once("close",l),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const r=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&r.push(t[n]);return r}}let U$=class extends F${constructor(t,r={}){const n=typeof t=="object"?t:r;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>D$[i]).filter(i=>!!i)),super(t,n)}};function W$(e,t="",r){let n=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),n=ih(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const o=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+o+":"+n.port+t,n.href=n.protocol+"://"+o+(r&&r.port===n.port?"":":"+n.port),n}const H$=typeof ArrayBuffer=="function",V$=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,sO=Object.prototype.toString,q$=typeof Blob=="function"||typeof Blob<"u"&&sO.call(Blob)==="[object BlobConstructor]",K$=typeof File=="function"||typeof File<"u"&&sO.call(File)==="[object FileConstructor]";function Ry(e){return H$&&(e instanceof ArrayBuffer||V$(e))||q$&&e instanceof Blob||K$&&e instanceof File}function nu(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(nu(e[r]))return!0;return!1}if(Ry(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return nu(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&nu(e[r]))return!0;return!1}function G$(e){const t=[],r=e.data,n=e;return n.data=ah(r,t),n.attachments=t.length,{packet:n,buffers:t}}function ah(e,t){if(!e)return e;if(Ry(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}else if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=ah(e[n],t);return r}else if(typeof e=="object"&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=ah(e[n],t));return r}return e}function X$(e,t){return e.data=sh(e.data,t),delete e.attachments,e}function sh(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=sh(e[r],t);else if(typeof e=="object")for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=sh(e[r],t));return e}const Y$=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ne;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(ne||(ne={}));class Q${constructor(t){this.replacer=t}encode(t){return(t.type===ne.EVENT||t.type===ne.ACK)&&nu(t)?this.encodeAsBinary({type:t.type===ne.EVENT?ne.BINARY_EVENT:ne.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===ne.BINARY_EVENT||t.type===ne.BINARY_ACK)&&(r+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(r+=t.nsp+","),t.id!=null&&(r+=t.id),t.data!=null&&(r+=JSON.stringify(t.data,this.replacer)),r}encodeAsBinary(t){const r=G$(t),n=this.encodeAsString(r.packet),i=r.buffers;return i.unshift(n),i}}class Ly extends Le{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);const n=r.type===ne.BINARY_EVENT;n||r.type===ne.BINARY_ACK?(r.type=n?ne.EVENT:ne.ACK,this.reconstructor=new Z$(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(Ry(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0;const n={type:Number(t.charAt(0))};if(ne[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===ne.BINARY_EVENT||n.type===ne.BINARY_ACK){const o=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);const a=t.substring(o,r);if(a!=Number(a)||t.charAt(r)!=="-")throw new Error("Illegal attachments");const s=Number(a);if(!J$(s)||s<0)throw new Error("Illegal attachments");if(s>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=s}if(t.charAt(r+1)==="/"){const o=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););n.nsp=t.substring(o,r)}else n.nsp="/";const i=t.charAt(r+1);if(i!==""&&Number(i)==i){const o=r+1;for(;++r;){const a=t.charAt(r);if(a==null||Number(a)!=a){--r;break}if(r===t.length)break}n.id=Number(t.substring(o,r+1))}if(t.charAt(++r)){const o=this.tryParse(t.substr(r));if(Ly.isPayloadValid(n.type,o))n.data=o;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case ne.CONNECT:return b0(r);case ne.DISCONNECT:return r===void 0;case ne.CONNECT_ERROR:return typeof r=="string"||b0(r);case ne.EVENT:case ne.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&Y$.indexOf(r[0])===-1);case ne.ACK:case ne.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Z${constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const r=X$(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const J$=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function b0(e){return Object.prototype.toString.call(e)==="[object Object]"}const eC=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ly,Encoder:Q$,get PacketType(){return ne}},Symbol.toStringTag,{value:"Module"}));function ir(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const tC=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class lO extends Le{constructor(t,r,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[ir(t,"open",this.onopen.bind(this)),ir(t,"packet",this.onpacket.bind(this)),ir(t,"error",this.onerror.bind(this)),ir(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var n,i,o;if(tC.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;const a={type:ne.EVENT,data:r};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){const f=this.ids++,c=r.pop();this._registerAckCallback(f,c),a.id=f}const s=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,l=this.connected&&!(!((o=this.io.engine)===null||o===void 0)&&o._hasPingExpired());return this.flags.volatile&&!s||(l?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,r){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[t]=r;return}const o=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let s=0;s<this.sendBuffer.length;s++)this.sendBuffer[s].id===t&&this.sendBuffer.splice(s,1);r.call(this,new Error("operation has timed out"))},i),a=(...s)=>{this.io.clearTimeoutFn(o),r.apply(this,s)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...r){return new Promise((n,i)=>{const o=(a,s)=>a?i(a):n(s);o.withError=!0,r.push(o),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((i,...o)=>(this._queue[0],i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),r&&r(i)):(this._queue.shift(),r&&r(null,...o)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const r=this._queue[0];r.pending&&!t||(r.pending=!0,r.tryCount++,this.flags=r.flags,this.emit.apply(this,r.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:ne.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ne.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ne.EVENT:case ne.BINARY_EVENT:this.onevent(t);break;case ne.ACK:case ne.BINARY_ACK:this.onack(t);break;case ne.DISCONNECT:this.ondisconnect();break;case ne.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const r=t.data||[];t.id!=null&&r.push(this.ack(t.id)),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const r=this._anyListeners.slice();for(const n of r)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const r=this;let n=!1;return function(...i){n||(n=!0,r.packet({type:ne.ACK,id:t,data:i}))}}onack(t){const r=this.acks[t.id];typeof r=="function"&&(delete this.acks[t.id],r.withError&&t.data.unshift(null),r.apply(this,t.data))}onconnect(t,r){this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ne.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const r=this._anyListeners;for(let n=0;n<r.length;n++)if(t===r[n])return r.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const r=this._anyOutgoingListeners;for(let n=0;n<r.length;n++)if(t===r[n])return r.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const r=this._anyOutgoingListeners.slice();for(const n of r)n.apply(this,t.data)}}}function Ro(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ro.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};Ro.prototype.reset=function(){this.attempts=0};Ro.prototype.setMin=function(e){this.ms=e};Ro.prototype.setMax=function(e){this.max=e};Ro.prototype.setJitter=function(e){this.jitter=e};class lh extends Le{constructor(t,r){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,nf(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((n=r.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new Ro({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;const i=r.parser||eC;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new U$(this.uri,this.opts);const r=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=ir(r,"open",function(){n.onopen(),t&&t()}),o=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),t?t(s):this.maybeReconnectOnOpen()},a=ir(r,"error",o);if(this._timeout!==!1){const s=this._timeout,l=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),r.close()},s);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(ir(t,"ping",this.onping.bind(this)),ir(t,"data",this.ondata.bind(this)),ir(t,"error",this.onerror.bind(this)),ir(t,"close",this.onclose.bind(this)),ir(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){rf(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,r){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new lO(this,t,r),this.nsps[t]=n),n}_destroy(t){const r=Object.keys(this.nsps);for(const n of r)if(this.nsps[n].active)return;this._close()}_packet(t){const r=this.encoder.encode(t);for(let n=0;n<r.length;n++)this.engine.write(r[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const r=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):t.onreconnect()}))},r);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const oa={};function iu(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const r=W$(e,t.path||"/socket.io"),n=r.source,i=r.id,o=r.path,a=oa[i]&&o in oa[i].nsps,s=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let l;return s?l=new lh(n,t):(oa[i]||(oa[i]=new lh(n,t)),l=oa[i]),r.query&&!t.query&&(t.query=r.queryKey),l.socket(r.path,t)}Object.assign(iu,{Manager:lh,Socket:lO,io:iu,connect:iu});const rC=()=>typeof window<"u"?["8082","5173","3000"].includes(window.location.port)?{apiUrl:"http://localhost:8081",wsUrl:"http://localhost:8081"}:{apiUrl:window.location.origin,wsUrl:window.location.origin}:{apiUrl:"http://localhost:8081",wsUrl:"http://localhost:8081"},uO=rC(),gr=uO.apiUrl,nC=uO.wsUrl,iC=e=>({"agent:joined":"agent_join","agent:left":"agent_leave","agent:error":"error","cache:hit":"cache_hit","cache:miss":"cache_miss","debugger:paused":"debugger_paused","debugger:resumed":"debugger_resumed"})[e]||e.replace(/:/g,"_"),Pi=e=>({...e,type:iC(e.type)});function of(e={}){const t=re(),r=e.enableSocket??!1,n=j.useRef(null);j.useEffect(()=>{if(r){t.setConnectionStatus("connecting");try{n.current=iu(nC,{reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:5}),t.setConnected(!0),t.setConnectionStatus("connected"),n.current.on("connect",()=>{var p;console.log("✓ Connected to Dashboard API via WebSocket"),t.setConnected(!0),t.setConnectionStatus("connected"),(p=n.current)==null||p.emit("subscribe:metrics")}),n.current.on("connect_error",()=>{t.setConnected(!0),t.setConnectionStatus("connected")}),n.current.on("metrics:update",p=>{t.setMetrics({totalRequests:p.totalRequests,cacheHits:p.cacheHits,cacheMisses:p.cacheMisses,hitRate:parseFloat(p.hitRate),averageLatency:p.averageLatency,tokensSaved:p.tokensSaved,costSaved:p.costSaved,activeAgents:p.activeAgents||0,totalAgents:p.totalAgents||0,uptime:p.uptime||0,timestamp:p.timestamp,tier:p.tier||"free"})}),n.current.on("agent:joined",p=>{console.log("Agent joined:",p),p.capabilities&&t.addAgent({id:p.agentId,name:p.agentName,status:"active",capabilities:p.capabilities,tasksCompleted:0,lastSeen:new Date().toISOString(),errorCount:0,cacheHitRate:0}),t.addEvent(Pi(p))}),n.current.on("agent:left",p=>{console.log("Agent left:",p),t.removeAgent(p.agentId),t.addEvent(Pi(p))}),n.current.on("agent:error",p=>{console.log("Agent error:",p),t.addEvent(Pi(p)),ve.error(`Agent ${p.agentId} error: ${p.errorMessage}`)}),n.current.on("cache:hit",p=>{t.addEvent(Pi(p))}),n.current.on("cache:miss",p=>{t.addEvent(Pi(p))}),n.current.on("debugger:paused",()=>{t.setPaused(!0)}),n.current.on("debugger:resumed",()=>{t.setPaused(!1)}),n.current.on("disconnect",()=>{console.log("✗ Disconnected from Dashboard API"),t.setConnected(!1),t.setConnectionStatus("disconnected")}),n.current.on("error",p=>{console.error("WebSocket error:",p),ve.error("WebSocket connection error")})}catch(p){console.error("Failed to initialize WebSocket:",p),t.setConnectionStatus("disconnected")}return()=>{n.current&&n.current.disconnect()}}},[r]);const i=j.useCallback(async()=>{try{t.setMetricsLoading(!0);const p=await fetch(`${gr}/api/metrics`);if(!p.ok)throw new Error("Failed to fetch metrics");const m=await p.json();t.setConnectionStatus("connected"),t.setConnected(!0),t.setMetrics({totalRequests:m.totalRequests,cacheHits:m.cacheHits,cacheMisses:m.cacheMisses,hitRate:parseFloat(m.hitRate),averageLatency:m.averageLatency,tokensSaved:m.tokensSaved,costSaved:m.costSaved,activeAgents:m.activeAgents,totalAgents:m.totalAgents,uptime:m.uptime||0,timestamp:m.timestamp,tier:m.tier||"free"})}catch(p){console.error("Error fetching metrics:",p),t.setMetricsError(p.message)}},[]),o=j.useCallback(async()=>{try{const p=await fetch(`${gr}/api/agents`);if(!p.ok)throw new Error("Failed to fetch agents");const m=await p.json();t.setAgents(m.agents)}catch(p){console.error("Error fetching agents:",p),ve.error("Failed to fetch agents")}},[]),a=j.useCallback(async(p=1,m=50)=>{try{const x=await fetch(`${gr}/api/events?page=${p}&limit=${m}`);if(!x.ok)throw new Error("Failed to fetch events");const g=await x.json();t.setEvents((g.events||[]).map(Pi)),t.setTotalEvents(g.pagination.total)}catch(x){console.error("Error fetching events:",x),ve.error("Failed to fetch events")}},[]),s=j.useCallback(async()=>{try{const p=await fetch(`${gr}/api/cache-stats`);if(!p.ok)throw new Error("Failed to fetch cache stats");const m=await p.json();t.setTopQueries(m.topQueries)}catch(p){console.error("Error fetching cache stats:",p),ve.error("Failed to fetch cache stats")}},[]),l=j.useCallback(async()=>{try{const p=await fetch(`${gr}/api/savings-breakdown`);if(!p.ok)return;const m=await p.json();t.setSavingsBreakdown(m)}catch{}},[]),u=j.useCallback(async()=>{try{const p=await fetch(`${gr}/api/cache/clear`,{method:"POST"});if(!p.ok)throw new Error("Failed to clear cache");const m=await p.json();ve.success(`Cleared ${m.clearedEntries} cache entries`),i()}catch(p){console.error("Error clearing cache:",p),ve.error("Failed to clear cache")}},[]),f=j.useCallback(async()=>{try{if(!(await fetch(`${gr}/api/debugger/pause`,{method:"POST"})).ok)throw new Error("Failed to pause");t.setPaused(!0),ve.success("Paused agent processing")}catch(p){console.error("Error pausing:",p),ve.error("Failed to pause")}},[]),c=j.useCallback(async()=>{try{if(!(await fetch(`${gr}/api/debugger/resume`,{method:"POST"})).ok)throw new Error("Failed to resume");t.setPaused(!1),ve.success("Resumed agent processing")}catch(p){console.error("Error resuming:",p),ve.error("Failed to resume")}},[]),d=j.useCallback(async p=>{try{const m=await fetch(`${gr}/api/debugger/rewind`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventId:p})});if(!m.ok)throw new Error("Failed to rewind");const x=await m.json();t.setDebuggerState(x.state),ve.success("Rewound to selected event")}catch(m){console.error("Error rewinding:",m),ve.error("Failed to rewind")}},[]),h=j.useCallback(async p=>{if(!p.trim()){t.setSearchResults([]);return}try{t.setIsSearching(!0);const m=await fetch(`${gr}/api/search?q=${encodeURIComponent(p)}`);if(!m.ok)throw new Error("Search failed");const x=await m.json();t.setSearchResults(x.results||[])}catch(m){console.error("Error during search:",m),ve.error("Search failed: "+m.message),t.setIsSearching(!1)}},[]);return{fetchMetrics:i,fetchAgents:o,fetchEvents:a,fetchCacheStats:s,fetchSavingsBreakdown:l,clearCache:u,pauseDebugger:f,resumeDebugger:c,rewindToEvent:d,fetchSearch:h}}const oC=({isOpen:e,onClose:t})=>{const r=re(d=>d.metrics),n=re(d=>d.refreshIntervalSeconds),i=re(d=>d.setRefreshIntervalSeconds),[o,a]=j.useState(n),s=re(d=>d.events),l=re(d=>d.setEvents);j.useEffect(()=>{e&&a(n)},[e,n]);const u=()=>{i(o),localStorage.setItem("dashboardSettings",JSON.stringify({refreshIntervalSeconds:o})),ve.success("Settings saved!"),t()},f=()=>{if(!r){ve.error("No metrics to export");return}const d=[["Metric","Value"],["Total Requests",r.totalRequests||0],["Cache Hits",r.cacheHits||0],["Cache Misses",r.cacheMisses||0],["Hit Rate (%)",((r.hitRate||0)*100).toFixed(2)],["Avg Latency (ms)",r.averageLatency||0],["Tokens Saved",r.tokensSaved||0],["Cost Saved ($)",(r.costSaved||0).toFixed(2)],["Active Agents",r.activeAgents||0],["Total Agents",r.totalAgents||0],["Uptime (ms)",r.uptime||0]].map(x=>x.join(",")).join(`
408
- `),h=new Blob([d],{type:"text/csv"}),p=window.URL.createObjectURL(h),m=document.createElement("a");m.href=p,m.download=`lemma-metrics-${new Date().toISOString().split("T")[0]}.csv`,document.body.appendChild(m),m.click(),window.URL.revokeObjectURL(p),document.body.removeChild(m),ve.success("Metrics exported!")},c=()=>{l([]),ve.success("Event log cleared")};return e?v.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:v.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-md w-full mx-4",children:[v.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[v.jsx("h2",{className:"text-lg font-bold text-gray-900",children:"⚙️ Settings"}),v.jsx("button",{onClick:t,className:"p-1 hover:bg-gray-100 rounded transition",children:v.jsx(R_,{size:20,className:"text-gray-600"})})]}),v.jsxs("div",{className:"p-6 space-y-6",children:[v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm font-semibold text-gray-900 mb-3",children:"📊 Dashboard Refresh Interval"}),v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsx("input",{type:"range",min:"2",max:"30",value:o,onChange:d=>a(Number(d.target.value)),className:"flex-1"}),v.jsxs("span",{className:"text-sm font-semibold text-gray-600 w-16 text-right",children:[o,"s"]})]}),v.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"How often to fetch updated metrics from the server"})]}),v.jsx("hr",{className:"border-gray-200"}),v.jsxs("button",{onClick:f,className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-50 hover:bg-blue-100 text-blue-600 rounded-lg font-medium transition",children:[v.jsx(iT,{size:16}),"📥 Export Metrics as CSV"]}),v.jsxs("button",{onClick:c,className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-red-50 hover:bg-red-100 text-red-600 rounded-lg font-medium transition",children:[v.jsx(gT,{size:16}),"🗑️ Clear Event Log (",s.length," events)"]}),v.jsx("hr",{className:"border-gray-200"}),v.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[v.jsx("h3",{className:"text-xs font-semibold text-gray-600 uppercase mb-2",children:"API Status"}),v.jsxs("div",{className:"space-y-1 text-xs text-gray-600",children:[v.jsxs("div",{children:["API: ",v.jsx("span",{className:"text-green-600 font-semibold",children:"http://localhost:3001"})]}),v.jsxs("div",{children:["WS: ",v.jsx("span",{className:"text-green-600 font-semibold",children:"ws://localhost:3001"})]}),v.jsxs("div",{children:["Dashboard: ",v.jsx("span",{className:"text-green-600 font-semibold",children:"localhost:5173"})]})]})]})]}),v.jsxs("div",{className:"px-6 py-4 border-t border-gray-200 flex gap-3",children:[v.jsx("button",{onClick:t,className:"flex-1 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-900 rounded font-medium transition",children:"Cancel"}),v.jsx("button",{onClick:u,className:"flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded font-medium transition",children:"Save Settings"})]})]})}):null},aC={idle:{label:"Standby",description:"Waiting to connect",dot:"bg-gray-400",badge:"bg-gray-100/20 border-gray-400/30 text-gray-200",pulse:!1},connecting:{label:"Connecting",description:"Establishing connection…",dot:"bg-amber-400",badge:"bg-amber-400/20 border-amber-300/40 text-amber-200",pulse:!0},connected:{label:"Live",description:"System is running",dot:"bg-emerald-400",badge:"bg-emerald-400/20 border-emerald-300/40 text-emerald-200",pulse:!0},disconnected:{label:"Offline",description:"Connection lost",dot:"bg-red-400",badge:"bg-red-400/20 border-red-400/40 text-red-200",pulse:!1}},sC={active:{label:"MCP: Active",dot:"bg-cyan-500",pulse:!0,badge:"bg-cyan-500/20 border-cyan-400/40 text-cyan-200"},idle:{label:"MCP: Idle",dot:"bg-gray-500",pulse:!1,badge:"bg-gray-500/20 border-gray-400/40 text-gray-300"},offline:{label:"MCP: Offline",dot:"bg-red-500",pulse:!1,badge:"bg-red-500/20 border-red-400/40 text-red-300"}},lC=()=>{const[e,t]=j.useState(!1),[r,n]=j.useState("offline"),i=re(u=>u.connectionStatus),o=re(u=>u.metrics),{clearCache:a}=of({enableSocket:!1});j.useEffect(()=>{const u=async()=>{try{const d=await(await fetch("/api/mcp-status")).json();n(d.status||"offline")}catch{n("offline")}};u();const f=setInterval(u,5e3);return()=>clearInterval(f)},[]);const s=aC[i],l=sC[r];return v.jsxs(v.Fragment,{children:[v.jsx("header",{className:"bg-slate-900/60 backdrop-blur-xl px-6 py-3 border-b border-white/5 relative overflow-hidden flex-shrink-0",children:v.jsxs("div",{className:"flex items-center justify-between relative",children:[v.jsxs("div",{className:"flex items-center gap-4",children:[v.jsx("div",{className:"w-9 h-9 bg-indigo-600/20 backdrop-blur rounded-lg flex items-center justify-center border border-indigo-500/30",children:v.jsx(M_,{className:"w-5 h-5 text-indigo-400"})}),v.jsxs("div",{children:[v.jsxs("h1",{className:"text-lg font-black text-white tracking-tight leading-none uppercase italic",children:["Lemma ",v.jsx("span",{className:"text-indigo-500 font-bold not-italic text-sm ml-1",children:"v0.7.5"})]}),v.jsx("p",{className:"text-[10px] text-slate-500 mt-1 font-bold uppercase tracking-widest",children:"Semantic Cache & AI Orchestrator"})]}),v.jsx("div",{className:"hidden sm:block h-6 w-px bg-white/5 mx-2"}),v.jsxs("div",{className:`hidden sm:flex items-center gap-2 px-3 py-1 rounded-full border ${s.badge} backdrop-blur-sm`,children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${s.dot} ${s.pulse?"animate-pulse":""}`}),v.jsx("span",{className:"text-[10px] font-black tracking-widest uppercase",children:s.label})]}),v.jsxs("div",{className:`hidden sm:flex items-center gap-2 px-3 py-1 rounded-full border ${l.badge} backdrop-blur-sm`,children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${l.dot} ${l.pulse?"animate-pulse":""}`}),v.jsx("span",{className:"text-[10px] font-black tracking-widest uppercase",children:l.label})]}),v.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[v.jsx("button",{onClick:()=>re.getState().setActiveSidePanel("agents"),className:`px-4 py-1.5 text-[10px] font-black uppercase tracking-widest rounded-md transition-all ${re(u=>u.activeSidePanel==="agents")?"bg-indigo-500/20 text-indigo-400 border border-indigo-500/30":"text-slate-500 hover:text-slate-300"}`,children:"The Hub"}),v.jsx("button",{onClick:()=>re.getState().setActiveSidePanel("tools"),className:`px-4 py-1.5 text-[10px] font-black uppercase tracking-widest rounded-md transition-all ${re(u=>u.activeSidePanel==="tools")?"bg-purple-500/20 text-purple-400 border border-purple-500/30":"text-slate-500 hover:text-slate-300"}`,children:"The Tools"}),v.jsx("button",{onClick:()=>re.getState().setActiveSidePanel("brain"),className:`px-4 py-1.5 text-[10px] font-black uppercase tracking-widest rounded-md transition-all ${re(u=>u.activeSidePanel==="brain")?"bg-indigo-500/20 text-indigo-400 border border-indigo-500/30":"text-slate-500 hover:text-slate-300"}`,children:"The Brain"})]})]}),v.jsxs("div",{className:"flex items-center gap-3",children:[(o==null?void 0:o.tier)==="pro"?v.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full border border-violet-500/30 bg-violet-500/10",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-violet-400 animate-pulse"}),v.jsx("span",{className:"text-[10px] font-black uppercase tracking-widest text-violet-300",children:"PRO"})]}):o?v.jsxs("a",{href:"https://lemma.nxus.studio/upgrade",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-1.5 text-[10px] font-black uppercase tracking-widest text-amber-300 bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 rounded-full transition-all duration-200 animate-pulse-neon",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"}),"Upgrade to Pro · $12/mo"]}):null,v.jsxs("button",{onClick:()=>a(),className:"hidden sm:inline-flex items-center gap-2 px-3 py-1.5 text-[10px] font-black uppercase tracking-widest text-slate-400 bg-white/5 hover:bg-white/10 border border-white/5 rounded-md transition-all duration-200",children:[v.jsx(fT,{className:"w-3 h-3"}),"Flush Cache"]}),v.jsx("button",{onClick:()=>t(!0),className:"p-2 text-slate-400 bg-white/5 hover:bg-white/10 border border-white/5 rounded-md transition-all duration-200",children:v.jsx(hT,{className:"w-4 h-4"})})]})]})}),v.jsx(oC,{isOpen:e,onClose:()=>t(!1)})]})},aa=({title:e,subtitle:t,value:r,icon:n,unit:i,color:o,loading:a,tooltip:s})=>{const l={blue:"from-blue-500/20 to-blue-600/5 border-blue-500/30 hover:border-blue-400 hover:shadow-[0_0_15px_rgba(59,130,246,0.3)]",green:"from-emerald-500/20 to-emerald-600/5 border-emerald-500/30 hover:border-emerald-400 hover:shadow-[0_0_15px_rgba(16,185,129,0.3)]",purple:"from-violet-500/20 to-violet-600/5 border-violet-500/30 hover:border-violet-400 hover:shadow-[0_0_15px_rgba(139,92,246,0.3)]",orange:"from-amber-500/20 to-amber-600/5 border-amber-500/30 hover:border-amber-400 hover:shadow-[0_0_15px_rgba(245,158,11,0.3)]"},u={blue:"from-blue-500 to-blue-600",green:"from-emerald-500 to-emerald-600",purple:"from-violet-500 to-violet-600",orange:"from-amber-500 to-amber-600"},f={blue:"text-blue-400",green:"text-emerald-400",purple:"text-violet-400",orange:"text-amber-400"};return v.jsx("div",{className:`bg-slate-900/40 ${l[o]} border rounded-2xl p-4 backdrop-blur-md transition-all duration-300 group relative overflow-hidden`,title:s,children:v.jsxs("div",{className:"flex items-center justify-between relative gap-3",children:[v.jsxs("div",{className:"flex-1 min-w-0",children:[v.jsx("p",{className:"text-[10px] font-bold text-slate-500 uppercase tracking-widest truncate",children:e}),a?v.jsx("div",{className:"mt-1.5 space-y-1.5",children:v.jsx("div",{className:"h-6 w-16 bg-white/5 rounded animate-pulse"})}):v.jsxs(v.Fragment,{children:[v.jsxs("p",{className:`text-2xl font-black ${f[o]} mt-1 leading-none tracking-tight`,children:[r,i&&v.jsx("span",{className:"text-xs font-semibold text-slate-500 ml-1",children:i})]}),v.jsx("p",{className:"text-[10px] text-slate-500 mt-1 leading-tight truncate uppercase font-medium",children:t})]})]}),v.jsx("div",{className:`bg-gradient-to-br ${u[o]} p-2 rounded-lg shadow-lg flex-shrink-0 opacity-80 group-hover:opacity-100 transition-opacity`,children:v.jsx("div",{className:"text-white",children:n})})]})})},uC=()=>{const e=re(l=>l.metrics),t=re(l=>l.isLoadingMetrics),[r,n]=j.useState(0);if(j.useEffect(()=>{n(0);const l=setInterval(()=>n(u=>u+1),1e3);return()=>clearInterval(l)},[e]),!e)return v.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(l=>v.jsx(aa,{title:"Syncing...",subtitle:"Secure bridge active",value:"-",icon:v.jsx(L_,{className:"w-4 h-4"}),color:"blue",loading:!0},l))});const i=e.hitRate*100,o=!e.secretsMasked||e.secretsMasked===0,a=e.tokensSaved>=1e3?`${(e.tokensSaved/1e3).toFixed(1)}k`:e.tokensSaved.toLocaleString(),s=e.averageLatency>0?(2500/e.averageLatency).toFixed(0):"80";return v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[v.jsx(aa,{title:"Privacy Shield",subtitle:o?"Zero leaks detected":"Secrets masked locally",value:o?"SECURE":e.secretsMasked??0,icon:v.jsx(mT,{className:"w-4 h-4"}),color:o?"green":"blue",loading:t,tooltip:"Lemma Privacy Firewall intercepts PII and secrets before they reach the cloud."}),v.jsx(aa,{title:"Budget Saved",subtitle:`Total Saved (All-Time) ~${a}`,value:e.costSaved<1?`$${e.costSaved.toFixed(4)}`:`$${e.costSaved.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`,icon:v.jsx(nT,{className:"w-4 h-4"}),color:"green",loading:t,tooltip:"Every time a cached response is reused, the system avoids paying the AI provider."}),v.jsx(aa,{title:"Global Hit Rate",subtitle:"Semantic memory efficiency",value:`${i.toFixed(1)}`,unit:"%",icon:v.jsx(yT,{className:"w-4 h-4"}),color:"orange",loading:t,tooltip:"When an AI agent asks the same question again, the system returns the cached answer instantly."}),v.jsx(aa,{title:"Response Time",subtitle:`vs. 2.5s direct LLM (${s}x speed)`,value:e.averageLatency.toFixed(0),unit:"ms",icon:v.jsx(oT,{className:"w-4 h-4"}),color:"blue",loading:t,tooltip:"How quickly the system responds. Lower is faster. Cached hits respond in <10ms."})]}),v.jsx("p",{className:"text-right text-xs text-gray-400 mt-1 pr-0.5",children:t?"Updating…":`Updated ${r===0?"just now":`${r}s ago`}`})]})},x0={active:{label:"Active",description:"Currently working",dot:"bg-emerald-500",badge:"bg-emerald-50 text-emerald-700 border-emerald-200",icon:v.jsx(o0,{className:"w-3.5 h-3.5"}),ring:"ring-emerald-200"},online:{label:"Active",description:"Currently working",dot:"bg-emerald-500",badge:"bg-emerald-50 text-emerald-700 border-emerald-200",icon:v.jsx(o0,{className:"w-3.5 h-3.5"}),ring:"ring-emerald-200"},idle:{label:"Idle",description:"Waiting for tasks",dot:"bg-amber-400",badge:"bg-amber-400/10 text-amber-400 border-amber-400/20",icon:v.jsx(I_,{className:"w-3.5 h-3.5"}),ring:"ring-amber-200"},error:{label:"Error",description:"Needs attention",dot:"bg-red-500",badge:"bg-red-500/10 text-red-400 border-red-500/20",icon:v.jsx(bT,{className:"w-3.5 h-3.5"}),ring:"ring-red-200"}},cC={llm:"Language AI",cache:"Caching",search:"Search",embedding:"Embeddings",tools:"Tools",memory:"Memory",vision:"Vision",audio:"Audio"},fC=e=>cC[e.toLowerCase()]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),dC=e=>e.substring(0,8).toUpperCase(),pC=()=>{const e=re(a=>a.agents),t=re(a=>a.selectedAgentId),r=re(a=>a.setSelectedAgent),n=e.filter(a=>a.status==="active").length,i=e.filter(a=>a.status==="idle").length,o=e.filter(a=>a.status==="error").length;return e.length===0?v.jsxs("div",{className:"flex flex-col items-center justify-center h-full bg-transparent px-6 text-center",children:[v.jsx("div",{className:"w-16 h-16 bg-white/5 rounded-2xl flex items-center justify-center mb-4 border border-white/5",children:v.jsx(i0,{className:"w-8 h-8 text-slate-600"})}),v.jsx("p",{className:"text-white font-bold text-base",children:"No agents connected"}),v.jsx("p",{className:"text-slate-500 text-sm mt-2 leading-relaxed max-w-[180px]",children:"Start an AI agent to see it appear here and begin processing requests."})]}):v.jsxs("div",{className:"h-full flex flex-col bg-transparent",children:[v.jsxs("div",{className:"px-5 py-4 border-b border-white/5 bg-white/5 sticky top-0 z-10",children:[v.jsx("div",{className:"flex items-center justify-between mb-3",children:v.jsxs("div",{children:[v.jsxs("h2",{className:"text-sm font-bold text-white flex items-center gap-2",children:[v.jsx(i0,{className:"w-4 h-4 text-indigo-400"}),"AI Agents"]}),v.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[e.length," connected right now"]})]})}),v.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[n>0&&v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-widest px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),n," Working"]}),i>0&&v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-widest px-2.5 py-1 rounded-full bg-amber-500/10 text-amber-400 border border-amber-500/20",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"}),i," Idle"]}),o>0&&v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-widest px-2.5 py-1 rounded-full bg-red-500/10 text-red-400 border border-red-500/20",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-red-500"}),o," Error"]})]})]}),v.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-2",children:e.map(a=>{const s=x0[a.status]||x0.idle,l=t===a.id,u=a.cacheHitRate,c=typeof u=="number"&&!isNaN(u)&&a.tasksCompleted>0?(u*100).toFixed(0):null;return v.jsxs("div",{onClick:()=>r(a.id),className:`p-4 rounded-xl border transition-all duration-200 cursor-pointer select-none ${l?"bg-indigo-600/10 border-indigo-500/40 shadow-[0_0_20px_rgba(79,70,229,0.15)]":"bg-white/5 border-white/5 hover:border-white/10 hover:bg-white/[0.08]"}`,children:[v.jsxs("div",{className:"flex items-start justify-between gap-2",children:[v.jsxs("div",{className:"flex items-start gap-2.5 min-w-0",children:[v.jsx("div",{className:`w-8 h-8 rounded-lg bg-gradient-to-br from-indigo-400 to-purple-500 flex items-center justify-center flex-shrink-0 text-white text-xs font-black ring-2 ${l?"ring-indigo-300":s.ring}`,children:a.name.charAt(0).toUpperCase()}),v.jsxs("div",{className:"min-w-0",children:[v.jsx("p",{className:"text-sm font-bold text-white truncate leading-tight",children:a.name}),v.jsxs("p",{className:"text-[10px] text-slate-500 font-mono truncate mt-0.5",children:["#",dC(a.id)]})]})]}),v.jsxs("span",{className:`inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-tighter px-2 py-0.5 rounded-full border flex-shrink-0 ${s.badge}`,children:[s.icon,s.label]})]}),v.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[v.jsxs("div",{className:"flex-1 bg-black/20 rounded-lg px-3 py-1.5 text-center border border-white/5",children:[v.jsx("p",{className:"text-sm font-black text-white",children:a.tasksCompleted}),v.jsx("p",{className:"text-[10px] text-slate-500 uppercase font-bold tracking-tighter",children:"Tasks done"})]}),v.jsxs("div",{className:"flex-1 bg-black/20 rounded-lg px-3 py-1.5 text-center border border-white/5",children:[v.jsx("p",{className:`text-sm font-black ${c===null?"text-slate-500":parseInt(c)>=50?"text-emerald-400":"text-amber-400"}`,children:c===null?"—":`${c}%`}),v.jsx("p",{className:"text-[10px] text-slate-500 uppercase font-bold tracking-tighter",children:"Agent Hit Rate"})]})]}),a.errorCount>0&&v.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 text-red-600 bg-red-50 px-3 py-1.5 rounded-lg border border-red-100",children:[v.jsx(Jj,{className:"w-3.5 h-3.5 flex-shrink-0"}),v.jsxs("span",{className:"text-xs font-semibold",children:[a.errorCount," error",a.errorCount!==1?"s":""," — needs review"]})]}),a.capabilities.length>0&&v.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-2.5",children:[a.capabilities.slice(0,3).map(d=>v.jsx("span",{className:"text-[10px] font-black uppercase tracking-tighter bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 px-2 py-0.5 rounded-full",children:fC(d)},d)),a.capabilities.length>3&&v.jsxs("span",{className:"text-xs text-gray-400 font-medium self-center",children:["+",a.capabilities.length-3," more"]})]})]},a.id)})}),v.jsx("div",{className:"px-4 py-3 border-t border-white/5 bg-black/10",children:v.jsx("p",{className:"text-[10px] text-slate-600 text-center font-bold uppercase tracking-widest",children:"Tap an agent to focus its activity"})})]})};function cO(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=cO(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function le(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=cO(e))&&(n&&(n+=" "),n+=t);return n}var hC=Array.isArray,Ot=hC,mC=typeof al=="object"&&al&&al.Object===Object&&al,fO=mC,yC=fO,vC=typeof self=="object"&&self&&self.Object===Object&&self,gC=yC||vC||Function("return this")(),Tr=gC,bC=Tr,xC=bC.Symbol,Xs=xC,w0=Xs,dO=Object.prototype,wC=dO.hasOwnProperty,SC=dO.toString,sa=w0?w0.toStringTag:void 0;function _C(e){var t=wC.call(e,sa),r=e[sa];try{e[sa]=void 0;var n=!0}catch{}var i=SC.call(e);return n&&(t?e[sa]=r:delete e[sa]),i}var OC=_C,PC=Object.prototype,AC=PC.toString;function kC(e){return AC.call(e)}var EC=kC,S0=Xs,jC=OC,TC=EC,$C="[object Null]",CC="[object Undefined]",_0=S0?S0.toStringTag:void 0;function NC(e){return e==null?e===void 0?CC:$C:_0&&_0 in Object(e)?jC(e):TC(e)}var en=NC;function MC(e){return e!=null&&typeof e=="object"}var tn=MC,IC=en,DC=tn,RC="[object Symbol]";function LC(e){return typeof e=="symbol"||DC(e)&&IC(e)==RC}var Lo=LC,BC=Ot,zC=Lo,FC=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,UC=/^\w*$/;function WC(e,t){if(BC(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||zC(e)?!0:UC.test(e)||!FC.test(e)||t!=null&&e in Object(t)}var By=WC;function HC(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Nn=HC;const Bo=me(Nn);var VC=en,qC=Nn,KC="[object AsyncFunction]",GC="[object Function]",XC="[object GeneratorFunction]",YC="[object Proxy]";function QC(e){if(!qC(e))return!1;var t=VC(e);return t==GC||t==XC||t==KC||t==YC}var zy=QC;const J=me(zy);var ZC=Tr,JC=ZC["__core-js_shared__"],eN=JC,Ad=eN,O0=function(){var e=/[^.]+$/.exec(Ad&&Ad.keys&&Ad.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function tN(e){return!!O0&&O0 in e}var rN=tN,nN=Function.prototype,iN=nN.toString;function oN(e){if(e!=null){try{return iN.call(e)}catch{}try{return e+""}catch{}}return""}var pO=oN,aN=zy,sN=rN,lN=Nn,uN=pO,cN=/[\\^$.*+?()[\]{}|]/g,fN=/^\[object .+?Constructor\]$/,dN=Function.prototype,pN=Object.prototype,hN=dN.toString,mN=pN.hasOwnProperty,yN=RegExp("^"+hN.call(mN).replace(cN,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vN(e){if(!lN(e)||sN(e))return!1;var t=aN(e)?yN:fN;return t.test(uN(e))}var gN=vN;function bN(e,t){return e==null?void 0:e[t]}var xN=bN,wN=gN,SN=xN;function _N(e,t){var r=SN(e,t);return wN(r)?r:void 0}var bi=_N,ON=bi,PN=ON(Object,"create"),af=PN,P0=af;function AN(){this.__data__=P0?P0(null):{},this.size=0}var kN=AN;function EN(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var jN=EN,TN=af,$N="__lodash_hash_undefined__",CN=Object.prototype,NN=CN.hasOwnProperty;function MN(e){var t=this.__data__;if(TN){var r=t[e];return r===$N?void 0:r}return NN.call(t,e)?t[e]:void 0}var IN=MN,DN=af,RN=Object.prototype,LN=RN.hasOwnProperty;function BN(e){var t=this.__data__;return DN?t[e]!==void 0:LN.call(t,e)}var zN=BN,FN=af,UN="__lodash_hash_undefined__";function WN(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=FN&&t===void 0?UN:t,this}var HN=WN,VN=kN,qN=jN,KN=IN,GN=zN,XN=HN;function zo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}zo.prototype.clear=VN;zo.prototype.delete=qN;zo.prototype.get=KN;zo.prototype.has=GN;zo.prototype.set=XN;var YN=zo;function QN(){this.__data__=[],this.size=0}var ZN=QN;function JN(e,t){return e===t||e!==e&&t!==t}var Fy=JN,eM=Fy;function tM(e,t){for(var r=e.length;r--;)if(eM(e[r][0],t))return r;return-1}var sf=tM,rM=sf,nM=Array.prototype,iM=nM.splice;function oM(e){var t=this.__data__,r=rM(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():iM.call(t,r,1),--this.size,!0}var aM=oM,sM=sf;function lM(e){var t=this.__data__,r=sM(t,e);return r<0?void 0:t[r][1]}var uM=lM,cM=sf;function fM(e){return cM(this.__data__,e)>-1}var dM=fM,pM=sf;function hM(e,t){var r=this.__data__,n=pM(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var mM=hM,yM=ZN,vM=aM,gM=uM,bM=dM,xM=mM;function Fo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Fo.prototype.clear=yM;Fo.prototype.delete=vM;Fo.prototype.get=gM;Fo.prototype.has=bM;Fo.prototype.set=xM;var lf=Fo,wM=bi,SM=Tr,_M=wM(SM,"Map"),Uy=_M,A0=YN,OM=lf,PM=Uy;function AM(){this.size=0,this.__data__={hash:new A0,map:new(PM||OM),string:new A0}}var kM=AM;function EM(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var jM=EM,TM=jM;function $M(e,t){var r=e.__data__;return TM(t)?r[typeof t=="string"?"string":"hash"]:r.map}var uf=$M,CM=uf;function NM(e){var t=CM(this,e).delete(e);return this.size-=t?1:0,t}var MM=NM,IM=uf;function DM(e){return IM(this,e).get(e)}var RM=DM,LM=uf;function BM(e){return LM(this,e).has(e)}var zM=BM,FM=uf;function UM(e,t){var r=FM(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var WM=UM,HM=kM,VM=MM,qM=RM,KM=zM,GM=WM;function Uo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Uo.prototype.clear=HM;Uo.prototype.delete=VM;Uo.prototype.get=qM;Uo.prototype.has=KM;Uo.prototype.set=GM;var Wy=Uo,hO=Wy,XM="Expected a function";function Hy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(XM);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Hy.Cache||hO),r}Hy.Cache=hO;var mO=Hy;const YM=me(mO);var QM=mO,ZM=500;function JM(e){var t=QM(e,function(n){return r.size===ZM&&r.clear(),n}),r=t.cache;return t}var eI=JM,tI=eI,rI=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,nI=/\\(\\)?/g,iI=tI(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(rI,function(r,n,i,o){t.push(i?o.replace(nI,"$1"):n||r)}),t}),oI=iI;function aI(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}var Vy=aI,k0=Xs,sI=Vy,lI=Ot,uI=Lo,E0=k0?k0.prototype:void 0,j0=E0?E0.toString:void 0;function yO(e){if(typeof e=="string")return e;if(lI(e))return sI(e,yO)+"";if(uI(e))return j0?j0.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var cI=yO,fI=cI;function dI(e){return e==null?"":fI(e)}var vO=dI,pI=Ot,hI=By,mI=oI,yI=vO;function vI(e,t){return pI(e)?e:hI(e,t)?[e]:mI(yI(e))}var gO=vI,gI=Lo;function bI(e){if(typeof e=="string"||gI(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var cf=bI,xI=gO,wI=cf;function SI(e,t){t=xI(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[wI(t[r++])];return r&&r==n?e:void 0}var qy=SI,_I=qy;function OI(e,t,r){var n=e==null?void 0:_I(e,t);return n===void 0?r:n}var bO=OI;const Kt=me(bO);function PI(e){return e==null}var AI=PI;const ee=me(AI);var kI=en,EI=Ot,jI=tn,TI="[object String]";function $I(e){return typeof e=="string"||!EI(e)&&jI(e)&&kI(e)==TI}var CI=$I;const di=me(CI);var xO={exports:{}},pe={};/**
408
+ `),h=new Blob([d],{type:"text/csv"}),p=window.URL.createObjectURL(h),m=document.createElement("a");m.href=p,m.download=`lemma-metrics-${new Date().toISOString().split("T")[0]}.csv`,document.body.appendChild(m),m.click(),window.URL.revokeObjectURL(p),document.body.removeChild(m),ve.success("Metrics exported!")},c=()=>{l([]),ve.success("Event log cleared")};return e?v.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:v.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-md w-full mx-4",children:[v.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[v.jsx("h2",{className:"text-lg font-bold text-gray-900",children:"⚙️ Settings"}),v.jsx("button",{onClick:t,className:"p-1 hover:bg-gray-100 rounded transition",children:v.jsx(R_,{size:20,className:"text-gray-600"})})]}),v.jsxs("div",{className:"p-6 space-y-6",children:[v.jsxs("div",{children:[v.jsx("label",{className:"block text-sm font-semibold text-gray-900 mb-3",children:"📊 Dashboard Refresh Interval"}),v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsx("input",{type:"range",min:"2",max:"30",value:o,onChange:d=>a(Number(d.target.value)),className:"flex-1"}),v.jsxs("span",{className:"text-sm font-semibold text-gray-600 w-16 text-right",children:[o,"s"]})]}),v.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"How often to fetch updated metrics from the server"})]}),v.jsx("hr",{className:"border-gray-200"}),v.jsxs("button",{onClick:f,className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-50 hover:bg-blue-100 text-blue-600 rounded-lg font-medium transition",children:[v.jsx(iT,{size:16}),"📥 Export Metrics as CSV"]}),v.jsxs("button",{onClick:c,className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-red-50 hover:bg-red-100 text-red-600 rounded-lg font-medium transition",children:[v.jsx(gT,{size:16}),"🗑️ Clear Event Log (",s.length," events)"]}),v.jsx("hr",{className:"border-gray-200"}),v.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[v.jsx("h3",{className:"text-xs font-semibold text-gray-600 uppercase mb-2",children:"API Status"}),v.jsxs("div",{className:"space-y-1 text-xs text-gray-600",children:[v.jsxs("div",{children:["API: ",v.jsx("span",{className:"text-green-600 font-semibold",children:"http://localhost:3001"})]}),v.jsxs("div",{children:["WS: ",v.jsx("span",{className:"text-green-600 font-semibold",children:"ws://localhost:3001"})]}),v.jsxs("div",{children:["Dashboard: ",v.jsx("span",{className:"text-green-600 font-semibold",children:"localhost:5173"})]})]})]})]}),v.jsxs("div",{className:"px-6 py-4 border-t border-gray-200 flex gap-3",children:[v.jsx("button",{onClick:t,className:"flex-1 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-900 rounded font-medium transition",children:"Cancel"}),v.jsx("button",{onClick:u,className:"flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded font-medium transition",children:"Save Settings"})]})]})}):null},aC={idle:{label:"Standby",description:"Waiting to connect",dot:"bg-gray-400",badge:"bg-gray-100/20 border-gray-400/30 text-gray-200",pulse:!1},connecting:{label:"Connecting",description:"Establishing connection…",dot:"bg-amber-400",badge:"bg-amber-400/20 border-amber-300/40 text-amber-200",pulse:!0},connected:{label:"Live",description:"System is running",dot:"bg-emerald-400",badge:"bg-emerald-400/20 border-emerald-300/40 text-emerald-200",pulse:!0},disconnected:{label:"Offline",description:"Connection lost",dot:"bg-red-400",badge:"bg-red-400/20 border-red-400/40 text-red-200",pulse:!1}},sC={active:{label:"MCP: Active",dot:"bg-cyan-500",pulse:!0,badge:"bg-cyan-500/20 border-cyan-400/40 text-cyan-200"},idle:{label:"MCP: Idle",dot:"bg-gray-500",pulse:!1,badge:"bg-gray-500/20 border-gray-400/40 text-gray-300"},offline:{label:"MCP: Offline",dot:"bg-red-500",pulse:!1,badge:"bg-red-500/20 border-red-400/40 text-red-300"}},lC=()=>{const[e,t]=j.useState(!1),[r,n]=j.useState("offline"),i=re(u=>u.connectionStatus),o=re(u=>u.metrics),{clearCache:a}=of({enableSocket:!1});j.useEffect(()=>{const u=async()=>{try{const d=await(await fetch("/api/mcp-status")).json();n(d.status||"offline")}catch{n("offline")}};u();const f=setInterval(u,5e3);return()=>clearInterval(f)},[]);const s=aC[i],l=sC[r];return v.jsxs(v.Fragment,{children:[v.jsx("header",{className:"bg-slate-900/60 backdrop-blur-xl px-6 py-3 border-b border-white/5 relative overflow-hidden flex-shrink-0",children:v.jsxs("div",{className:"flex items-center justify-between relative",children:[v.jsxs("div",{className:"flex items-center gap-4",children:[v.jsx("div",{className:"w-9 h-9 bg-indigo-600/20 backdrop-blur rounded-lg flex items-center justify-center border border-indigo-500/30",children:v.jsx(M_,{className:"w-5 h-5 text-indigo-400"})}),v.jsxs("div",{children:[v.jsxs("h1",{className:"text-lg font-black text-white tracking-tight leading-none uppercase italic",children:["Lemma ",v.jsx("span",{className:"text-indigo-500 font-bold not-italic text-sm ml-1",children:"v0.7.7"})]}),v.jsx("p",{className:"text-[10px] text-slate-500 mt-1 font-bold uppercase tracking-widest",children:"Semantic Cache & AI Orchestrator"})]}),v.jsx("div",{className:"hidden sm:block h-6 w-px bg-white/5 mx-2"}),v.jsxs("div",{className:`hidden sm:flex items-center gap-2 px-3 py-1 rounded-full border ${s.badge} backdrop-blur-sm`,children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${s.dot} ${s.pulse?"animate-pulse":""}`}),v.jsx("span",{className:"text-[10px] font-black tracking-widest uppercase",children:s.label})]}),v.jsxs("div",{className:`hidden sm:flex items-center gap-2 px-3 py-1 rounded-full border ${l.badge} backdrop-blur-sm`,children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${l.dot} ${l.pulse?"animate-pulse":""}`}),v.jsx("span",{className:"text-[10px] font-black tracking-widest uppercase",children:l.label})]}),v.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[v.jsx("button",{onClick:()=>re.getState().setActiveSidePanel("agents"),className:`px-4 py-1.5 text-[10px] font-black uppercase tracking-widest rounded-md transition-all ${re(u=>u.activeSidePanel==="agents")?"bg-indigo-500/20 text-indigo-400 border border-indigo-500/30":"text-slate-500 hover:text-slate-300"}`,children:"The Hub"}),v.jsx("button",{onClick:()=>re.getState().setActiveSidePanel("tools"),className:`px-4 py-1.5 text-[10px] font-black uppercase tracking-widest rounded-md transition-all ${re(u=>u.activeSidePanel==="tools")?"bg-purple-500/20 text-purple-400 border border-purple-500/30":"text-slate-500 hover:text-slate-300"}`,children:"The Tools"}),v.jsx("button",{onClick:()=>re.getState().setActiveSidePanel("brain"),className:`px-4 py-1.5 text-[10px] font-black uppercase tracking-widest rounded-md transition-all ${re(u=>u.activeSidePanel==="brain")?"bg-indigo-500/20 text-indigo-400 border border-indigo-500/30":"text-slate-500 hover:text-slate-300"}`,children:"The Brain"})]})]}),v.jsxs("div",{className:"flex items-center gap-3",children:[(o==null?void 0:o.tier)==="pro"?v.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full border border-violet-500/30 bg-violet-500/10",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-violet-400 animate-pulse"}),v.jsx("span",{className:"text-[10px] font-black uppercase tracking-widest text-violet-300",children:"PRO"})]}):o?v.jsxs("a",{href:"https://lemma.nxus.studio/upgrade",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-1.5 text-[10px] font-black uppercase tracking-widest text-amber-300 bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 rounded-full transition-all duration-200 animate-pulse-neon",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"}),"Upgrade to Pro · $12/mo"]}):null,v.jsxs("button",{onClick:()=>a(),className:"hidden sm:inline-flex items-center gap-2 px-3 py-1.5 text-[10px] font-black uppercase tracking-widest text-slate-400 bg-white/5 hover:bg-white/10 border border-white/5 rounded-md transition-all duration-200",children:[v.jsx(fT,{className:"w-3 h-3"}),"Flush Cache"]}),v.jsx("button",{onClick:()=>t(!0),className:"p-2 text-slate-400 bg-white/5 hover:bg-white/10 border border-white/5 rounded-md transition-all duration-200",children:v.jsx(hT,{className:"w-4 h-4"})})]})]})}),v.jsx(oC,{isOpen:e,onClose:()=>t(!1)})]})},aa=({title:e,subtitle:t,value:r,icon:n,unit:i,color:o,loading:a,tooltip:s})=>{const l={blue:"from-blue-500/20 to-blue-600/5 border-blue-500/30 hover:border-blue-400 hover:shadow-[0_0_15px_rgba(59,130,246,0.3)]",green:"from-emerald-500/20 to-emerald-600/5 border-emerald-500/30 hover:border-emerald-400 hover:shadow-[0_0_15px_rgba(16,185,129,0.3)]",purple:"from-violet-500/20 to-violet-600/5 border-violet-500/30 hover:border-violet-400 hover:shadow-[0_0_15px_rgba(139,92,246,0.3)]",orange:"from-amber-500/20 to-amber-600/5 border-amber-500/30 hover:border-amber-400 hover:shadow-[0_0_15px_rgba(245,158,11,0.3)]"},u={blue:"from-blue-500 to-blue-600",green:"from-emerald-500 to-emerald-600",purple:"from-violet-500 to-violet-600",orange:"from-amber-500 to-amber-600"},f={blue:"text-blue-400",green:"text-emerald-400",purple:"text-violet-400",orange:"text-amber-400"};return v.jsx("div",{className:`bg-slate-900/40 ${l[o]} border rounded-2xl p-4 backdrop-blur-md transition-all duration-300 group relative overflow-hidden`,title:s,children:v.jsxs("div",{className:"flex items-center justify-between relative gap-3",children:[v.jsxs("div",{className:"flex-1 min-w-0",children:[v.jsx("p",{className:"text-[10px] font-bold text-slate-500 uppercase tracking-widest truncate",children:e}),a?v.jsx("div",{className:"mt-1.5 space-y-1.5",children:v.jsx("div",{className:"h-6 w-16 bg-white/5 rounded animate-pulse"})}):v.jsxs(v.Fragment,{children:[v.jsxs("p",{className:`text-2xl font-black ${f[o]} mt-1 leading-none tracking-tight`,children:[r,i&&v.jsx("span",{className:"text-xs font-semibold text-slate-500 ml-1",children:i})]}),v.jsx("p",{className:"text-[10px] text-slate-500 mt-1 leading-tight truncate uppercase font-medium",children:t})]})]}),v.jsx("div",{className:`bg-gradient-to-br ${u[o]} p-2 rounded-lg shadow-lg flex-shrink-0 opacity-80 group-hover:opacity-100 transition-opacity`,children:v.jsx("div",{className:"text-white",children:n})})]})})},uC=()=>{const e=re(l=>l.metrics),t=re(l=>l.isLoadingMetrics),[r,n]=j.useState(0);if(j.useEffect(()=>{n(0);const l=setInterval(()=>n(u=>u+1),1e3);return()=>clearInterval(l)},[e]),!e)return v.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(l=>v.jsx(aa,{title:"Syncing...",subtitle:"Secure bridge active",value:"-",icon:v.jsx(L_,{className:"w-4 h-4"}),color:"blue",loading:!0},l))});const i=e.hitRate*100,o=!e.secretsMasked||e.secretsMasked===0,a=e.tokensSaved>=1e3?`${(e.tokensSaved/1e3).toFixed(1)}k`:e.tokensSaved.toLocaleString(),s=e.averageLatency>0?(2500/e.averageLatency).toFixed(0):"80";return v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[v.jsx(aa,{title:"Privacy Shield",subtitle:o?"Zero leaks detected":"Secrets masked locally",value:o?"SECURE":e.secretsMasked??0,icon:v.jsx(mT,{className:"w-4 h-4"}),color:o?"green":"blue",loading:t,tooltip:"Lemma Privacy Firewall intercepts PII and secrets before they reach the cloud."}),v.jsx(aa,{title:"Budget Saved",subtitle:`Total Saved (All-Time) ~${a}`,value:e.costSaved<1?`$${e.costSaved.toFixed(4)}`:`$${e.costSaved.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`,icon:v.jsx(nT,{className:"w-4 h-4"}),color:"green",loading:t,tooltip:"Every time a cached response is reused, the system avoids paying the AI provider."}),v.jsx(aa,{title:"Global Hit Rate",subtitle:"Semantic memory efficiency",value:`${i.toFixed(1)}`,unit:"%",icon:v.jsx(yT,{className:"w-4 h-4"}),color:"orange",loading:t,tooltip:"When an AI agent asks the same question again, the system returns the cached answer instantly."}),v.jsx(aa,{title:"Response Time",subtitle:`vs. 2.5s direct LLM (${s}x speed)`,value:e.averageLatency.toFixed(0),unit:"ms",icon:v.jsx(oT,{className:"w-4 h-4"}),color:"blue",loading:t,tooltip:"How quickly the system responds. Lower is faster. Cached hits respond in <10ms."})]}),v.jsx("p",{className:"text-right text-xs text-gray-400 mt-1 pr-0.5",children:t?"Updating…":`Updated ${r===0?"just now":`${r}s ago`}`})]})},x0={active:{label:"Active",description:"Currently working",dot:"bg-emerald-500",badge:"bg-emerald-50 text-emerald-700 border-emerald-200",icon:v.jsx(o0,{className:"w-3.5 h-3.5"}),ring:"ring-emerald-200"},online:{label:"Active",description:"Currently working",dot:"bg-emerald-500",badge:"bg-emerald-50 text-emerald-700 border-emerald-200",icon:v.jsx(o0,{className:"w-3.5 h-3.5"}),ring:"ring-emerald-200"},idle:{label:"Idle",description:"Waiting for tasks",dot:"bg-amber-400",badge:"bg-amber-400/10 text-amber-400 border-amber-400/20",icon:v.jsx(I_,{className:"w-3.5 h-3.5"}),ring:"ring-amber-200"},error:{label:"Error",description:"Needs attention",dot:"bg-red-500",badge:"bg-red-500/10 text-red-400 border-red-500/20",icon:v.jsx(bT,{className:"w-3.5 h-3.5"}),ring:"ring-red-200"}},cC={llm:"Language AI",cache:"Caching",search:"Search",embedding:"Embeddings",tools:"Tools",memory:"Memory",vision:"Vision",audio:"Audio"},fC=e=>cC[e.toLowerCase()]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),dC=e=>e.substring(0,8).toUpperCase(),pC=()=>{const e=re(a=>a.agents),t=re(a=>a.selectedAgentId),r=re(a=>a.setSelectedAgent),n=e.filter(a=>a.status==="active").length,i=e.filter(a=>a.status==="idle").length,o=e.filter(a=>a.status==="error").length;return e.length===0?v.jsxs("div",{className:"flex flex-col items-center justify-center h-full bg-transparent px-6 text-center",children:[v.jsx("div",{className:"w-16 h-16 bg-white/5 rounded-2xl flex items-center justify-center mb-4 border border-white/5",children:v.jsx(i0,{className:"w-8 h-8 text-slate-600"})}),v.jsx("p",{className:"text-white font-bold text-base",children:"No agents connected"}),v.jsx("p",{className:"text-slate-500 text-sm mt-2 leading-relaxed max-w-[180px]",children:"Start an AI agent to see it appear here and begin processing requests."})]}):v.jsxs("div",{className:"h-full flex flex-col bg-transparent",children:[v.jsxs("div",{className:"px-5 py-4 border-b border-white/5 bg-white/5 sticky top-0 z-10",children:[v.jsx("div",{className:"flex items-center justify-between mb-3",children:v.jsxs("div",{children:[v.jsxs("h2",{className:"text-sm font-bold text-white flex items-center gap-2",children:[v.jsx(i0,{className:"w-4 h-4 text-indigo-400"}),"AI Agents"]}),v.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[e.length," connected right now"]})]})}),v.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[n>0&&v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-widest px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),n," Working"]}),i>0&&v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-widest px-2.5 py-1 rounded-full bg-amber-500/10 text-amber-400 border border-amber-500/20",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"}),i," Idle"]}),o>0&&v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-widest px-2.5 py-1 rounded-full bg-red-500/10 text-red-400 border border-red-500/20",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-red-500"}),o," Error"]})]})]}),v.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-2",children:e.map(a=>{const s=x0[a.status]||x0.idle,l=t===a.id,u=a.cacheHitRate,c=typeof u=="number"&&!isNaN(u)&&a.tasksCompleted>0?(u*100).toFixed(0):null;return v.jsxs("div",{onClick:()=>r(a.id),className:`p-4 rounded-xl border transition-all duration-200 cursor-pointer select-none ${l?"bg-indigo-600/10 border-indigo-500/40 shadow-[0_0_20px_rgba(79,70,229,0.15)]":"bg-white/5 border-white/5 hover:border-white/10 hover:bg-white/[0.08]"}`,children:[v.jsxs("div",{className:"flex items-start justify-between gap-2",children:[v.jsxs("div",{className:"flex items-start gap-2.5 min-w-0",children:[v.jsx("div",{className:`w-8 h-8 rounded-lg bg-gradient-to-br from-indigo-400 to-purple-500 flex items-center justify-center flex-shrink-0 text-white text-xs font-black ring-2 ${l?"ring-indigo-300":s.ring}`,children:a.name.charAt(0).toUpperCase()}),v.jsxs("div",{className:"min-w-0",children:[v.jsx("p",{className:"text-sm font-bold text-white truncate leading-tight",children:a.name}),v.jsxs("p",{className:"text-[10px] text-slate-500 font-mono truncate mt-0.5",children:["#",dC(a.id)]})]})]}),v.jsxs("span",{className:`inline-flex items-center gap-1 text-[10px] font-black uppercase tracking-tighter px-2 py-0.5 rounded-full border flex-shrink-0 ${s.badge}`,children:[s.icon,s.label]})]}),v.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[v.jsxs("div",{className:"flex-1 bg-black/20 rounded-lg px-3 py-1.5 text-center border border-white/5",children:[v.jsx("p",{className:"text-sm font-black text-white",children:a.tasksCompleted}),v.jsx("p",{className:"text-[10px] text-slate-500 uppercase font-bold tracking-tighter",children:"Tasks done"})]}),v.jsxs("div",{className:"flex-1 bg-black/20 rounded-lg px-3 py-1.5 text-center border border-white/5",children:[v.jsx("p",{className:`text-sm font-black ${c===null?"text-slate-500":parseInt(c)>=50?"text-emerald-400":"text-amber-400"}`,children:c===null?"—":`${c}%`}),v.jsx("p",{className:"text-[10px] text-slate-500 uppercase font-bold tracking-tighter",children:"Agent Hit Rate"})]})]}),a.errorCount>0&&v.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 text-red-600 bg-red-50 px-3 py-1.5 rounded-lg border border-red-100",children:[v.jsx(Jj,{className:"w-3.5 h-3.5 flex-shrink-0"}),v.jsxs("span",{className:"text-xs font-semibold",children:[a.errorCount," error",a.errorCount!==1?"s":""," — needs review"]})]}),a.capabilities.length>0&&v.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-2.5",children:[a.capabilities.slice(0,3).map(d=>v.jsx("span",{className:"text-[10px] font-black uppercase tracking-tighter bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 px-2 py-0.5 rounded-full",children:fC(d)},d)),a.capabilities.length>3&&v.jsxs("span",{className:"text-xs text-gray-400 font-medium self-center",children:["+",a.capabilities.length-3," more"]})]})]},a.id)})}),v.jsx("div",{className:"px-4 py-3 border-t border-white/5 bg-black/10",children:v.jsx("p",{className:"text-[10px] text-slate-600 text-center font-bold uppercase tracking-widest",children:"Tap an agent to focus its activity"})})]})};function cO(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=cO(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function le(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=cO(e))&&(n&&(n+=" "),n+=t);return n}var hC=Array.isArray,Ot=hC,mC=typeof al=="object"&&al&&al.Object===Object&&al,fO=mC,yC=fO,vC=typeof self=="object"&&self&&self.Object===Object&&self,gC=yC||vC||Function("return this")(),Tr=gC,bC=Tr,xC=bC.Symbol,Xs=xC,w0=Xs,dO=Object.prototype,wC=dO.hasOwnProperty,SC=dO.toString,sa=w0?w0.toStringTag:void 0;function _C(e){var t=wC.call(e,sa),r=e[sa];try{e[sa]=void 0;var n=!0}catch{}var i=SC.call(e);return n&&(t?e[sa]=r:delete e[sa]),i}var OC=_C,PC=Object.prototype,AC=PC.toString;function kC(e){return AC.call(e)}var EC=kC,S0=Xs,jC=OC,TC=EC,$C="[object Null]",CC="[object Undefined]",_0=S0?S0.toStringTag:void 0;function NC(e){return e==null?e===void 0?CC:$C:_0&&_0 in Object(e)?jC(e):TC(e)}var en=NC;function MC(e){return e!=null&&typeof e=="object"}var tn=MC,IC=en,DC=tn,RC="[object Symbol]";function LC(e){return typeof e=="symbol"||DC(e)&&IC(e)==RC}var Lo=LC,BC=Ot,zC=Lo,FC=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,UC=/^\w*$/;function WC(e,t){if(BC(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||zC(e)?!0:UC.test(e)||!FC.test(e)||t!=null&&e in Object(t)}var By=WC;function HC(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Nn=HC;const Bo=me(Nn);var VC=en,qC=Nn,KC="[object AsyncFunction]",GC="[object Function]",XC="[object GeneratorFunction]",YC="[object Proxy]";function QC(e){if(!qC(e))return!1;var t=VC(e);return t==GC||t==XC||t==KC||t==YC}var zy=QC;const J=me(zy);var ZC=Tr,JC=ZC["__core-js_shared__"],eN=JC,Ad=eN,O0=function(){var e=/[^.]+$/.exec(Ad&&Ad.keys&&Ad.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function tN(e){return!!O0&&O0 in e}var rN=tN,nN=Function.prototype,iN=nN.toString;function oN(e){if(e!=null){try{return iN.call(e)}catch{}try{return e+""}catch{}}return""}var pO=oN,aN=zy,sN=rN,lN=Nn,uN=pO,cN=/[\\^$.*+?()[\]{}|]/g,fN=/^\[object .+?Constructor\]$/,dN=Function.prototype,pN=Object.prototype,hN=dN.toString,mN=pN.hasOwnProperty,yN=RegExp("^"+hN.call(mN).replace(cN,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vN(e){if(!lN(e)||sN(e))return!1;var t=aN(e)?yN:fN;return t.test(uN(e))}var gN=vN;function bN(e,t){return e==null?void 0:e[t]}var xN=bN,wN=gN,SN=xN;function _N(e,t){var r=SN(e,t);return wN(r)?r:void 0}var bi=_N,ON=bi,PN=ON(Object,"create"),af=PN,P0=af;function AN(){this.__data__=P0?P0(null):{},this.size=0}var kN=AN;function EN(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var jN=EN,TN=af,$N="__lodash_hash_undefined__",CN=Object.prototype,NN=CN.hasOwnProperty;function MN(e){var t=this.__data__;if(TN){var r=t[e];return r===$N?void 0:r}return NN.call(t,e)?t[e]:void 0}var IN=MN,DN=af,RN=Object.prototype,LN=RN.hasOwnProperty;function BN(e){var t=this.__data__;return DN?t[e]!==void 0:LN.call(t,e)}var zN=BN,FN=af,UN="__lodash_hash_undefined__";function WN(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=FN&&t===void 0?UN:t,this}var HN=WN,VN=kN,qN=jN,KN=IN,GN=zN,XN=HN;function zo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}zo.prototype.clear=VN;zo.prototype.delete=qN;zo.prototype.get=KN;zo.prototype.has=GN;zo.prototype.set=XN;var YN=zo;function QN(){this.__data__=[],this.size=0}var ZN=QN;function JN(e,t){return e===t||e!==e&&t!==t}var Fy=JN,eM=Fy;function tM(e,t){for(var r=e.length;r--;)if(eM(e[r][0],t))return r;return-1}var sf=tM,rM=sf,nM=Array.prototype,iM=nM.splice;function oM(e){var t=this.__data__,r=rM(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():iM.call(t,r,1),--this.size,!0}var aM=oM,sM=sf;function lM(e){var t=this.__data__,r=sM(t,e);return r<0?void 0:t[r][1]}var uM=lM,cM=sf;function fM(e){return cM(this.__data__,e)>-1}var dM=fM,pM=sf;function hM(e,t){var r=this.__data__,n=pM(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var mM=hM,yM=ZN,vM=aM,gM=uM,bM=dM,xM=mM;function Fo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Fo.prototype.clear=yM;Fo.prototype.delete=vM;Fo.prototype.get=gM;Fo.prototype.has=bM;Fo.prototype.set=xM;var lf=Fo,wM=bi,SM=Tr,_M=wM(SM,"Map"),Uy=_M,A0=YN,OM=lf,PM=Uy;function AM(){this.size=0,this.__data__={hash:new A0,map:new(PM||OM),string:new A0}}var kM=AM;function EM(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var jM=EM,TM=jM;function $M(e,t){var r=e.__data__;return TM(t)?r[typeof t=="string"?"string":"hash"]:r.map}var uf=$M,CM=uf;function NM(e){var t=CM(this,e).delete(e);return this.size-=t?1:0,t}var MM=NM,IM=uf;function DM(e){return IM(this,e).get(e)}var RM=DM,LM=uf;function BM(e){return LM(this,e).has(e)}var zM=BM,FM=uf;function UM(e,t){var r=FM(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var WM=UM,HM=kM,VM=MM,qM=RM,KM=zM,GM=WM;function Uo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Uo.prototype.clear=HM;Uo.prototype.delete=VM;Uo.prototype.get=qM;Uo.prototype.has=KM;Uo.prototype.set=GM;var Wy=Uo,hO=Wy,XM="Expected a function";function Hy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(XM);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Hy.Cache||hO),r}Hy.Cache=hO;var mO=Hy;const YM=me(mO);var QM=mO,ZM=500;function JM(e){var t=QM(e,function(n){return r.size===ZM&&r.clear(),n}),r=t.cache;return t}var eI=JM,tI=eI,rI=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,nI=/\\(\\)?/g,iI=tI(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(rI,function(r,n,i,o){t.push(i?o.replace(nI,"$1"):n||r)}),t}),oI=iI;function aI(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}var Vy=aI,k0=Xs,sI=Vy,lI=Ot,uI=Lo,E0=k0?k0.prototype:void 0,j0=E0?E0.toString:void 0;function yO(e){if(typeof e=="string")return e;if(lI(e))return sI(e,yO)+"";if(uI(e))return j0?j0.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var cI=yO,fI=cI;function dI(e){return e==null?"":fI(e)}var vO=dI,pI=Ot,hI=By,mI=oI,yI=vO;function vI(e,t){return pI(e)?e:hI(e,t)?[e]:mI(yI(e))}var gO=vI,gI=Lo;function bI(e){if(typeof e=="string"||gI(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var cf=bI,xI=gO,wI=cf;function SI(e,t){t=xI(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[wI(t[r++])];return r&&r==n?e:void 0}var qy=SI,_I=qy;function OI(e,t,r){var n=e==null?void 0:_I(e,t);return n===void 0?r:n}var bO=OI;const Kt=me(bO);function PI(e){return e==null}var AI=PI;const ee=me(AI);var kI=en,EI=Ot,jI=tn,TI="[object String]";function $I(e){return typeof e=="string"||!EI(e)&&jI(e)&&kI(e)==TI}var CI=$I;const di=me(CI);var xO={exports:{}},pe={};/**
409
409
  * @license React
410
410
  * react-is.production.min.js
411
411
  *
@@ -478,4 +478,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
478
478
  `+(typeof l.response=="string"?l.response:JSON.stringify(l.response))),className:"p-2 hover:bg-white/5 rounded-lg text-slate-500 hover:text-white transition-colors",title:"Copy full interaction",children:v.jsx($y,{className:"w-4 h-4"})})]})]}),v.jsxs("div",{className:"space-y-4",children:[v.jsxs("div",{children:[v.jsx("h4",{className:"text-[10px] font-black text-slate-600 uppercase tracking-widest mb-2",children:"Prompt"}),v.jsx("div",{className:"bg-black/20 rounded-xl p-4 text-sm text-slate-300 font-medium border border-white/5 line-clamp-3 group-hover:line-clamp-none transition-all",children:l.prompt})]}),v.jsxs("div",{children:[v.jsx("h4",{className:"text-[10px] font-black text-slate-600 uppercase tracking-widest mb-2",children:"Response"}),v.jsx("div",{className:"bg-indigo-500/5 rounded-xl p-4 text-sm text-slate-200 border border-indigo-500/10 font-mono whitespace-pre-wrap",children:typeof l.response=="string"?l.response:((c=(f=(u=l.response)==null?void 0:u.content)==null?void 0:f[0])==null?void 0:c.text)||JSON.stringify(l.response,null,2)})]})]}),v.jsx("div",{className:"mt-4 pt-4 border-t border-white/5 flex justify-end",children:v.jsxs("button",{className:"flex items-center gap-1 text-[10px] font-black text-indigo-400 uppercase tracking-widest hover:text-indigo-300 transition-colors",children:["View Full Thread",v.jsx(Ty,{className:"w-3 h-3"})]})})]})},l.id)})})})]})},pJ=()=>{const e=re(l=>l.events),t=re(l=>l.metrics),[r,n]=j.useState([]),[i,o]=j.useState(0);j.useEffect(()=>{const l=e.filter(p=>p.type==="mcp_tool_call"||p.type==="brain_hit"||p.type==="brain_miss"),u={},f=l.filter(p=>p.type==="brain_hit"||p.tokensImpact&&p.tokensImpact>0).length,c=l.filter(p=>p.type==="brain_miss"||!p.tokensImpact||p.tokensImpact===0).length;l.forEach(p=>{const m=p.tool||(p.type==="brain_hit"?"Brain Hit":p.type==="brain_miss"?"Brain Miss":"Unknown");u[m]||(u[m]={name:m,calls:0,hits:0,tokensSaved:0,avgLatency:0}),u[m].calls++,(p.type==="brain_hit"||p.tokensImpact&&p.tokensImpact>0)&&u[m].hits++,u[m].tokensSaved+=p.tokensImpact||p.tokensSaved||0,u[m].avgLatency=(u[m].avgLatency*(u[m].calls-1)+(p.latency||0))/u[m].calls}),n(Object.values(u).sort((p,m)=>m.calls-p.calls));const d=f+c,h=d>0?f/d*100:0;o(h)},[e]);const a=e.filter(l=>l.type==="mcp_tool_call"||l.type==="brain_hit"||l.type==="brain_miss").length,s=r.reduce((l,u)=>l+u.tokensSaved,0);return v.jsxs("div",{className:"flex flex-col h-full bg-transparent overflow-hidden relative",children:[v.jsxs("div",{className:"px-4 py-3 border-b border-white/5 bg-white/5 flex-shrink-0",children:[v.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[v.jsx("div",{className:"w-6 h-6 bg-gradient-to-br from-purple-500 to-pink-600 rounded-lg flex items-center justify-center shadow-sm flex-shrink-0",children:v.jsx(es,{className:"w-3.5 h-3.5 text-white"})}),v.jsx("h2",{className:"text-[10px] font-black text-white uppercase tracking-widest",children:"MCP Live Feed"}),v.jsx("span",{className:"ml-auto text-[10px] font-black px-2 py-0.5 bg-purple-500/20 text-purple-400 rounded-full border border-purple-500/30",children:a})]}),v.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black px-2 py-0.5 rounded-full bg-cyan-500/10 text-cyan-400 border border-cyan-500/20",children:["🧠 ",i.toFixed(0),"% Brain Hit Rate"]}),v.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-black px-2 py-0.5 rounded-full bg-violet-500/10 text-violet-400 border border-violet-500/20",children:["⚡ ",s.toLocaleString()," tokens saved"]})]})]}),v.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:v.jsx("div",{className:"space-y-2 p-4",children:r.length===0?v.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-12",children:[v.jsx(es,{className:"w-8 h-8 text-slate-700 mb-2"}),v.jsx("p",{className:"text-white font-bold text-sm",children:"No MCP activity yet"}),v.jsx("p",{className:"text-slate-500 text-[10px] uppercase font-bold tracking-widest mt-2",children:"Tools will appear here as they execute"})]}):r.map(l=>v.jsxs("div",{className:"p-3 bg-white/5 hover:bg-white/10 border border-white/5 rounded-lg transition-all",children:[v.jsxs("div",{className:"flex items-center justify-between mb-2",children:[v.jsx("span",{className:"text-[10px] font-black uppercase tracking-widest text-white",children:l.name}),v.jsxs("span",{className:"text-[10px] text-slate-500 font-mono font-bold",children:[l.avgLatency.toFixed(0),"ms"]})]}),v.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[v.jsx("div",{className:"flex-1 h-1 bg-black/30 rounded-full overflow-hidden",children:v.jsx("div",{className:"h-full bg-gradient-to-r from-cyan-500 to-cyan-400",style:{width:`${l.hits>0?l.hits/l.calls*100:0}%`}})}),v.jsxs("span",{className:"text-[9px] text-slate-500 font-bold w-12 text-right",children:[l.hits,"/",l.calls]})]}),l.tokensSaved>0&&v.jsxs("div",{className:"flex items-center gap-1",children:[v.jsx(L_,{className:"w-3 h-3 text-violet-400"}),v.jsxs("span",{className:"text-[9px] font-black text-violet-400",children:[l.tokensSaved.toLocaleString()," tokens saved"]})]})]},l.name))})}),t&&t.tier!=="pro"&&v.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-transparent via-slate-900/40 to-slate-900/80 backdrop-blur-sm flex items-center justify-center rounded-2xl border border-white/5",children:v.jsxs("div",{className:"text-center max-w-xs px-6",children:[v.jsx(ts,{className:"w-12 h-12 text-purple-500 mx-auto mb-3"}),v.jsx("h3",{className:"text-sm font-black text-white mb-2",children:"Upgrade to Pro"}),v.jsx("p",{className:"text-[10px] text-slate-300 mb-4",children:"Unlock semantic cache to see brain hit rates and save 60-80% on token costs with intelligent memory."}),v.jsx("button",{className:"w-full px-4 py-2 bg-gradient-to-r from-purple-600 to-pink-600 text-white text-[10px] font-black uppercase rounded-lg hover:from-purple-500 hover:to-pink-500 transition-all",children:"Upgrade Now"})]})})]})},hJ=[{key:"clipboard",label:"Prompt Compression",emoji:"📋",color:"#22d3ee",bgColor:"rgba(34,211,238,0.1)"},{key:"contextSqueeze",label:"Context Optimization",emoji:"🗜️",color:"#a78bfa",bgColor:"rgba(167,139,250,0.1)"},{key:"historyPrune",label:"Memory Optimization",emoji:"📜",color:"#fb923c",bgColor:"rgba(251,146,60,0.1)"},{key:"complexityRouting",label:"Smart Model Routing",emoji:"🔀",color:"#34d399",bgColor:"rgba(52,211,153,0.1)"},{key:"cache",label:"Semantic Caching",emoji:"⚡",color:"#fbbf24",bgColor:"rgba(251,191,36,0.1)"}];function DA(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function mJ(e){return e===0?"$0.0000":e<1e-4?"<$0.0001":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}function yJ({stats:e,maxTokens:t,color:r,bgColor:n,label:i,emoji:o}){const a=t>0?Math.min(100,e.tokensSaved/t*100):0,s=e.tokensSaved>0;return v.jsxs("div",{style:{padding:"8px 10px",borderRadius:"8px",backgroundColor:s?n:"rgba(255,255,255,0.02)",border:`1px solid ${s?r+"30":"rgba(255,255,255,0.04)"}`,marginBottom:"6px",transition:"all 0.3s ease"},children:[v.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"4px"},children:[v.jsxs("span",{style:{fontSize:"11px",fontWeight:600,color:s?r:"#64748b",display:"flex",alignItems:"center",gap:"5px"},children:[v.jsx("span",{children:o}),v.jsx("span",{children:i})]}),v.jsx("span",{style:{fontSize:"10px",fontWeight:700,color:s?r:"rgba(16,185,129,0.6)",letterSpacing:s?"normal":"0.05em",textTransform:s?"none":"uppercase"},children:s?`${DA(e.tokensSaved)} tkns`:"Monitoring"})]}),v.jsx("div",{style:{height:"3px",borderRadius:"2px",backgroundColor:"rgba(255,255,255,0.06)",overflow:"hidden"},children:v.jsx("div",{style:{height:"100%",width:`${a}%`,backgroundColor:r,borderRadius:"2px",transition:"width 0.6s ease",boxShadow:s?`0 0 6px ${r}80`:"none"}})})]})}function vJ(){const e=re(o=>o.savingsBreakdown),t=re(o=>o.metrics),r=j.useMemo(()=>{if(!e)return null;if(e.total.tokensSaved===0&&t&&t.tokensSaved>0){const o=JSON.parse(JSON.stringify(e));return o.cache.tokensSaved=t.tokensSaved,o.cache.costSaved=t.costSaved,o.total.tokensSaved=t.tokensSaved,o.total.costSaved=t.costSaved,o}return e},[e,t]);if(!r)return v.jsxs("div",{style:{padding:"14px 16px"},children:[v.jsx("div",{style:{fontSize:"12px",fontWeight:700,color:"#94a3b8",letterSpacing:"0.08em",marginBottom:"10px",textTransform:"uppercase"},children:"💰 Savings Breakdown"}),v.jsx("div",{style:{fontSize:"11px",color:"#475569",textAlign:"center",padding:"16px 0"},children:"Waiting for first request…"})]});const n=r.total,i=Math.max(r.clipboard.tokensSaved,r.contextSqueeze.tokensSaved,r.historyPrune.tokensSaved,r.complexityRouting.tokensSaved,r.cache.tokensSaved,1);return v.jsxs("div",{style:{padding:"14px 16px"},children:[v.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"12px"},children:[v.jsxs("div",{children:[v.jsx("div",{style:{fontSize:"12px",fontWeight:700,color:"#94a3b8",letterSpacing:"0.08em",textTransform:"uppercase"},children:"💰 Savings Breakdown"}),v.jsx("div",{style:{fontSize:"10px",color:"#10b981",fontWeight:"bold",marginTop:"1px"},children:"Lifetime Savings · Synced"})]}),v.jsxs("div",{style:{textAlign:"right"},children:[v.jsx("div",{style:{fontSize:"16px",fontWeight:800,color:n.tokensSaved>0?"#22d3ee":"#475569",lineHeight:1,textShadow:n.tokensSaved>0?"0 0 12px rgba(34,211,238,0.4)":"none"},children:mJ(n.costSaved)}),v.jsxs("div",{style:{fontSize:"10px",color:"#64748b",marginTop:"2px"},children:[DA(n.tokensSaved)," total tokens"]})]})]}),v.jsx("div",{children:hJ.map(({key:o,label:a,emoji:s,color:l,bgColor:u})=>v.jsx(yJ,{stats:r[o],maxTokens:i,label:a,emoji:s,color:l,bgColor:u},o))}),n.events>0&&v.jsxs("div",{style:{fontSize:"10px",color:"#475569",textAlign:"center",marginTop:"6px"},children:[n.events," savings event",n.events!==1?"s":""," recorded"]})]})}const gJ=()=>{const{fetchMetrics:e,fetchAgents:t,fetchEvents:r,fetchCacheStats:n,fetchSavingsBreakdown:i}=of({enableSocket:!0}),o=re(l=>l.refreshIntervalSeconds);j.useEffect(()=>{(async()=>{await Promise.all([e(),t(),r(),n(),i()])})();const u=o*1e3,f=setInterval(()=>{e(),t(),r(),n(),i()},u);return()=>{clearInterval(f)}},[e,t,r,n,i,o]);const a=re(l=>l.activeSidePanel),s=re(l=>l.metrics);return v.jsxs("div",{className:"h-screen bg-transparent flex flex-col overflow-hidden text-slate-200",children:[v.jsx(lC,{}),v.jsx("div",{className:"px-5 py-3 bg-slate-900/20 backdrop-blur-md border-b border-white/5 flex-shrink-0",children:v.jsx(uC,{})}),s&&s.tier!=="pro"&&v.jsx("div",{className:"px-5 py-2.5 bg-gradient-to-r from-amber-500/5 via-amber-500/10 to-amber-500/5 border-b border-amber-500/20 flex-shrink-0",children:v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsx("span",{className:"text-lg",children:"💎"}),v.jsxs("div",{children:[v.jsx("p",{className:"text-xs font-bold text-amber-300 uppercase tracking-wider",children:"You're on the Free Plan"}),v.jsx("p",{className:"text-[10px] text-amber-500/80 mt-0.5",children:"Unlock semantic cache, cloud sync, autopilot healer, unlimited requests & more"})]})]}),v.jsx("a",{href:"https://lemma.nxus.studio/upgrade",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-2 text-[11px] font-black uppercase tracking-widest text-white bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-400 hover:to-orange-400 rounded-xl transition-all duration-200 shadow-lg shadow-amber-500/20",children:"Upgrade · $12/mo"})]})}),v.jsx("div",{className:"flex-1 overflow-hidden flex gap-4 p-4 min-h-0",children:a==="brain"?v.jsx("div",{className:"flex-1 panel-card overflow-hidden",children:v.jsx(dJ,{})}):a==="tools"?v.jsx("div",{className:"flex-1 panel-card overflow-hidden",children:v.jsx(pJ,{})}):v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"w-72 flex-shrink-0 overflow-hidden panel-card",children:v.jsx(pC,{})}),v.jsx("div",{className:"flex-1 overflow-y-auto space-y-4 pb-2 pr-0.5 min-h-0",children:v.jsx(aJ,{})}),v.jsxs("div",{className:"flex-shrink-0 flex flex-col gap-4 min-h-0",style:{width:"360px"},children:[v.jsx("div",{className:"panel-card flex-shrink-0",children:v.jsx(vJ,{})}),v.jsx("div",{className:"panel-card",style:{height:"30%"},children:v.jsx(lJ,{})}),v.jsx("div",{className:"flex-1 panel-card",children:v.jsx(cJ,{})})]})]})}),v.jsx(fJ,{}),v.jsx(Yj,{position:"top-right",toastOptions:{style:{background:"#1e293b",color:"#f1f5f9",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.08)",fontSize:"13px",fontWeight:"600"},success:{iconTheme:{primary:"#10b981",secondary:"#fff"}},error:{iconTheme:{primary:"#ef4444",secondary:"#fff"}}}})]})};class bJ extends k.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){console.error("Dashboard Error:",t,r)}render(){var t,r;return this.state.hasError?v.jsxs("div",{style:{width:"100vw",height:"100vh",background:"#0a0a0a",color:"white",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",fontFamily:"monospace",padding:"40px"},children:[v.jsx("h1",{style:{fontSize:"32px",marginBottom:"20px",color:"#ef4444"},children:"⚠️ Dashboard Error"}),v.jsxs("pre",{style:{background:"#1a1a1a",padding:"20px",borderRadius:"8px",maxWidth:"800px",overflow:"auto",fontSize:"14px",color:"#888"},children:[(t=this.state.error)==null?void 0:t.toString(),`
479
479
 
480
480
  `,(r=this.state.error)==null?void 0:r.stack]})]}):this.props.children}}tp.createRoot(document.getElementById("root")).render(v.jsx(k.StrictMode,{children:v.jsx(bJ,{children:v.jsx(gJ,{})})}));
481
- //# sourceMappingURL=index-DOfIKHLn.js.map
481
+ //# sourceMappingURL=index-DSYfE1bL.js.map